Unverified 提交 8a301b0c authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi 提交者: GitHub

Update modules structure and other minor improvements for Rust version (#558)

上级 54b2f4c5
...@@ -27,7 +27,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -27,7 +27,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([("useinbandfec", 1u32.into())]), parameters: RtpCodecParametersParameters::from([("useinbandfec", 1_u32.into())]),
rtcp_feedback: vec![RtcpFeedback::TransportCc], rtcp_feedback: vec![RtcpFeedback::TransportCc],
}, },
RtpCodecCapability::Video { RtpCodecCapability::Video {
...@@ -55,8 +55,9 @@ struct TransportOptions { ...@@ -55,8 +55,9 @@ struct TransportOptions {
ice_parameters: IceParameters, ice_parameters: IceParameters,
} }
#[derive(Serialize)] #[derive(Serialize, Message)]
#[serde(tag = "action")] #[serde(tag = "action")]
#[rtype(result = "()")]
enum ServerMessage { enum ServerMessage {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Init { Init {
...@@ -79,12 +80,9 @@ enum ServerMessage { ...@@ -79,12 +80,9 @@ enum ServerMessage {
}, },
} }
impl Message for ServerMessage { #[derive(Deserialize, Message)]
type Result = ();
}
#[derive(Deserialize)]
#[serde(tag = "action")] #[serde(tag = "action")]
#[rtype(result = "()")]
enum ClientMessage { enum ClientMessage {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
Init { rtp_capabilities: RtpCapabilities }, Init { rtp_capabilities: RtpCapabilities },
...@@ -103,20 +101,14 @@ enum ClientMessage { ...@@ -103,20 +101,14 @@ enum ClientMessage {
ConsumerResume { id: ConsumerId }, ConsumerResume { id: ConsumerId },
} }
impl Message for ClientMessage { #[derive(Message)]
type Result = (); #[rtype(result = "()")]
}
enum InternalMessage { enum InternalMessage {
SaveProducer(Producer), SaveProducer(Producer),
SaveConsumer(Consumer), SaveConsumer(Consumer),
Stop, Stop,
} }
impl Message for InternalMessage {
type Result = ();
}
struct Transports { struct Transports {
consumer: WebRtcTransport, consumer: WebRtcTransport,
producer: WebRtcTransport, producer: WebRtcTransport,
...@@ -331,8 +323,9 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -331,8 +323,9 @@ impl Handler<ClientMessage> for EchoServer {
} }
}); });
} }
ClientMessage::ConsumerResume { id } => match self.consumers.get(&id).cloned() { ClientMessage::ConsumerResume { id } => {
Some(consumer) => actix::spawn(async move { if let Some(consumer) = self.consumers.get(&id).cloned() {
actix::spawn(async move {
match consumer.resume().await { match consumer.resume().await {
Ok(_) => { Ok(_) => {
println!( println!(
...@@ -350,9 +343,9 @@ impl Handler<ClientMessage> for EchoServer { ...@@ -350,9 +343,9 @@ impl Handler<ClientMessage> for EchoServer {
); );
} }
} }
}), })
None => {} }
}, }
} }
} }
} }
...@@ -385,7 +378,7 @@ impl Handler<InternalMessage> for EchoServer { ...@@ -385,7 +378,7 @@ impl Handler<InternalMessage> for EchoServer {
} }
async fn ws_index( async fn ws_index(
r: HttpRequest, request: HttpRequest,
worker_manager: Data<WorkerManager>, worker_manager: Data<WorkerManager>,
stream: Payload, stream: Payload,
) -> Result<HttpResponse, Error> { ) -> Result<HttpResponse, Error> {
...@@ -395,7 +388,7 @@ async fn ws_index( ...@@ -395,7 +388,7 @@ async fn ws_index(
HttpResponse::InternalServerError().finish() HttpResponse::InternalServerError().finish()
})?; })?;
ws::start(echo_server, &r, stream) ws::start(echo_server, &request, stream)
} }
#[actix_web::main] #[actix_web::main]
......
...@@ -562,6 +562,21 @@ impl<'de> Deserialize<'de> for DtlsFingerprint { ...@@ -562,6 +562,21 @@ impl<'de> Deserialize<'de> for DtlsFingerprint {
where where
V: MapAccess<'de>, V: MapAccess<'de>,
{ {
fn parse_as_bytes(input: &str, output: &mut [u8]) -> Result<(), String> {
for (i, v) in output.iter_mut().enumerate() {
*v = u8::from_str_radix(&input[i * 3..(i * 3) + 2], 16).map_err(
|error| {
format!(
"Failed to parse value {} as series of hex bytes: {}",
input, error,
)
},
)?;
}
Ok(())
}
let mut algorithm = None::<Cow<'_, str>>; let mut algorithm = None::<Cow<'_, str>>;
let mut value = None::<Cow<'_, str>>; let mut value = None::<Cow<'_, str>>;
while let Some(key) = map.next_key()? { while let Some(key) = map.next_key()? {
...@@ -583,95 +598,80 @@ impl<'de> Deserialize<'de> for DtlsFingerprint { ...@@ -583,95 +598,80 @@ impl<'de> Deserialize<'de> for DtlsFingerprint {
let algorithm = algorithm.ok_or_else(|| de::Error::missing_field("algorithm"))?; let algorithm = algorithm.ok_or_else(|| de::Error::missing_field("algorithm"))?;
let value = value.ok_or_else(|| de::Error::missing_field("value"))?; let value = value.ok_or_else(|| de::Error::missing_field("value"))?;
fn parse_as_bytes(input: &str, output: &mut [u8]) -> Result<(), String> {
for (i, v) in output.iter_mut().enumerate() {
*v = u8::from_str_radix(&input[i * 3..(i * 3) + 2], 16).map_err(
|error| {
format!(
"Failed to parse value {} as series of hex bytes: {}",
input, error,
)
},
)?;
}
Ok(())
}
match algorithm.as_ref() { match algorithm.as_ref() {
"sha-1" => { "sha-1" => {
if value.len() != (20 * 3 - 1) { if value.len() == (20 * 3 - 1) {
Err(de::Error::custom( let mut value_result = [0_u8; 20];
"Value doesn't have correct length for SHA-1",
))
} else {
let mut value_result = [0u8; 20];
parse_as_bytes(value.as_ref(), &mut value_result) parse_as_bytes(value.as_ref(), &mut value_result)
.map_err(de::Error::custom)?; .map_err(de::Error::custom)?;
Ok(DtlsFingerprint::Sha1 { Ok(DtlsFingerprint::Sha1 {
value: value_result, value: value_result,
}) })
} else {
Err(de::Error::custom(
"Value doesn't have correct length for SHA-1",
))
} }
} }
"sha-224" => { "sha-224" => {
if value.len() != (28 * 3 - 1) { if value.len() == (28 * 3 - 1) {
Err(de::Error::custom( let mut value_result = [0_u8; 28];
"Value doesn't have correct length for SHA-224",
))
} else {
let mut value_result = [0u8; 28];
parse_as_bytes(value.as_ref(), &mut value_result) parse_as_bytes(value.as_ref(), &mut value_result)
.map_err(de::Error::custom)?; .map_err(de::Error::custom)?;
Ok(DtlsFingerprint::Sha224 { Ok(DtlsFingerprint::Sha224 {
value: value_result, value: value_result,
}) })
} else {
Err(de::Error::custom(
"Value doesn't have correct length for SHA-224",
))
} }
} }
"sha-256" => { "sha-256" => {
if value.len() != (32 * 3 - 1) { if value.len() == (32 * 3 - 1) {
Err(de::Error::custom( let mut value_result = [0_u8; 32];
"Value doesn't have correct length for SHA-256",
))
} else {
let mut value_result = [0u8; 32];
parse_as_bytes(value.as_ref(), &mut value_result) parse_as_bytes(value.as_ref(), &mut value_result)
.map_err(de::Error::custom)?; .map_err(de::Error::custom)?;
Ok(DtlsFingerprint::Sha256 { Ok(DtlsFingerprint::Sha256 {
value: value_result, value: value_result,
}) })
} else {
Err(de::Error::custom(
"Value doesn't have correct length for SHA-256",
))
} }
} }
"sha-384" => { "sha-384" => {
if value.len() != (48 * 3 - 1) { if value.len() == (48 * 3 - 1) {
Err(de::Error::custom( let mut value_result = [0_u8; 48];
"Value doesn't have correct length for SHA-384",
))
} else {
let mut value_result = [0u8; 48];
parse_as_bytes(value.as_ref(), &mut value_result) parse_as_bytes(value.as_ref(), &mut value_result)
.map_err(de::Error::custom)?; .map_err(de::Error::custom)?;
Ok(DtlsFingerprint::Sha384 { Ok(DtlsFingerprint::Sha384 {
value: value_result, value: value_result,
}) })
} else {
Err(de::Error::custom(
"Value doesn't have correct length for SHA-384",
))
} }
} }
"sha-512" => { "sha-512" => {
if value.len() != (64 * 3 - 1) { if value.len() == (64 * 3 - 1) {
Err(de::Error::custom( let mut value_result = [0_u8; 64];
"Value doesn't have correct length for SHA-512",
))
} else {
let mut value_result = [0u8; 64];
parse_as_bytes(value.as_ref(), &mut value_result) parse_as_bytes(value.as_ref(), &mut value_result)
.map_err(de::Error::custom)?; .map_err(de::Error::custom)?;
Ok(DtlsFingerprint::Sha512 { Ok(DtlsFingerprint::Sha512 {
value: value_result, value: value_result,
}) })
} else {
Err(de::Error::custom(
"Value doesn't have correct length for SHA-512",
))
} }
} }
algorithm => Err(de::Error::unknown_variant( algorithm => Err(de::Error::unknown_variant(
...@@ -749,7 +749,7 @@ impl WebRtcMessage { ...@@ -749,7 +749,7 @@ impl WebRtcMessage {
WebRtcMessage::String(string) => (51_u32, Bytes::from(string)), WebRtcMessage::String(string) => (51_u32, Bytes::from(string)),
WebRtcMessage::Binary(binary) => (53_u32, binary), WebRtcMessage::Binary(binary) => (53_u32, binary),
WebRtcMessage::EmptyString => (56_u32, Bytes::from_static(b" ")), WebRtcMessage::EmptyString => (56_u32, Bytes::from_static(b" ")),
WebRtcMessage::EmptyBinary => (57_u32, Bytes::from(vec![0u8])), WebRtcMessage::EmptyBinary => (57_u32, Bytes::from(vec![0_u8])),
} }
} }
} }
...@@ -51,6 +51,7 @@ ...@@ -51,6 +51,7 @@
pub mod data_structures; pub mod data_structures;
mod macros; mod macros;
mod messages; mod messages;
// TODO: Check public items in this module
mod ortc; mod ortc;
pub mod router; pub mod router;
pub mod rtp_parameters; pub mod rtp_parameters;
...@@ -62,68 +63,144 @@ pub mod worker; ...@@ -62,68 +63,144 @@ pub mod worker;
pub mod worker_manager; pub mod worker_manager;
// TODO: The mess below is because of https://github.com/rust-lang/rust/issues/59368 // TODO: The mess below is because of https://github.com/rust-lang/rust/issues/59368
#[cfg(not(doc))] pub mod audio_level_observer {
pub use router::audio_level_observer; //! An audio level observer monitors the volume of the selected audio producers.
#[cfg(doc)]
#[path = "router/audio_level_observer.rs"] pub use crate::router::audio_level_observer::*;
pub mod audio_level_observer; }
#[cfg(not(doc))] pub mod consumer {
pub use router::consumer; //! A consumer represents an audio or video source being forwarded from a mediasoup router to an
#[cfg(doc)] //! endpoint. It's created on top of a transport that defines how the media packets are carried.
#[path = "router/consumer.rs"]
pub mod consumer; pub use crate::router::consumer::*;
}
#[cfg(not(doc))]
pub use router::data_consumer; pub mod data_consumer {
#[cfg(doc)] //! A data consumer represents an endpoint capable of receiving data messages from a mediasoup
#[path = "router/data_consumer.rs"] //! [`Router`](router::Router).
pub mod data_consumer; //!
//! A data consumer can use [SCTP](https://tools.ietf.org/html/rfc4960) (AKA
#[cfg(not(doc))] //! DataChannel) to receive those messages, or can directly receive them in the Rust application
pub use router::producer; //! if the data consumer was created on top of a
#[cfg(doc)] //! [`DirectTransport`](direct_transport::DirectTransport).
#[path = "router/producer.rs"]
pub mod producer; #[cfg(doc)]
use super::*;
#[cfg(not(doc))] pub use crate::router::data_consumer::*;
pub use router::data_producer; }
#[cfg(doc)]
#[path = "router/data_producer.rs"] pub mod producer {
pub mod data_producer; //! A producer represents an audio or video source being injected into a mediasoup router. It's
//! created on top of a transport that defines how the media packets are carried.
#[cfg(not(doc))]
pub use router::transport; pub use crate::router::producer::*;
#[cfg(doc)] }
#[path = "router/transport.rs"]
pub mod transport; pub mod data_producer {
//! A data producer represents an endpoint capable of injecting data messages into a mediasoup
#[cfg(not(doc))] //! [`Router`](router::Router).
pub use router::direct_transport; //!
#[cfg(doc)] //! A data producer can use [SCTP](https://tools.ietf.org/html/rfc4960) (AKA DataChannel) to
#[path = "router/direct_transport.rs"] //! deliver those messages, or can directly send them from the Rust application if the data
pub mod direct_transport; //! producer was created on top of a [`DirectTransport`](direct_transport::DirectTransport).
#[cfg(not(doc))] #[cfg(doc)]
pub use router::pipe_transport; use super::*;
#[cfg(doc)] pub use crate::router::data_producer::*;
#[path = "router/pipe_transport.rs"] }
pub mod pipe_transport;
pub mod transport {
#[cfg(not(doc))] //! A transport connects an endpoint with a mediasoup router and enables transmission of media
pub use router::plain_transport; //! in both directions by means of [`Producer`](producer::Producer),
#[cfg(doc)] //! [`Consumer`](consumer::Consumer), [`DataProducer`](data_producer::DataProducer) and
#[path = "router/plain_transport.rs"] //! [`DataConsumer`](data_consumer::DataConsumer) instances created on it.
pub mod plain_transport; //!
//! mediasoup implements the following transports:
#[cfg(not(doc))] //! * [`WebRtcTransport`](webrtc_transport::WebRtcTransport)
pub use router::rtp_observer; //! * [`PlainTransport`](plain_transport::PlainTransport)
#[cfg(doc)] //! * [`PipeTransport`](pipe_transport::PipeTransport)
#[path = "router/rtp_observer.rs"] //! * [`DirectTransport`](direct_transport::DirectTransport)
pub mod rtp_observer;
#[cfg(doc)]
#[cfg(not(doc))] use super::*;
pub use router::webrtc_transport; pub use crate::router::transport::*;
#[cfg(doc)] }
#[path = "router/webrtc_transport.rs"]
pub mod webrtc_transport; pub mod direct_transport {
//! A direct transport represents a direct connection between the mediasoup Rust process and a
//! [`Router`](router::Router) instance in a mediasoup-worker thread.
//!
//! A direct transport can be used to directly send and receive data messages from/to Rust by
//! means of [`DataProducer`](data_producer::DataProducer)s and
//! [`DataConsumer`](data_consumer::DataConsumer)s of type `Direct` created on a direct
//! transport.
//! Direct messages sent by a [`DataProducer`](data_producer::DataProducer) in a direct
//! transport can be consumed by endpoints connected through a SCTP capable transport
//! ([`WebRtcTransport`](webrtc_transport::WebRtcTransport),
//! [`PlainTransport`](plain_transport::PlainTransport),
//! [`PipeTransport`](pipe_transport::PipeTransport) and also by the Rust application by means
//! of a [`DataConsumer`](data_consumer::DataConsumer) created on a [`DirectTransport`] (and
//! vice-versa: messages sent over SCTP/DataChannel can be consumed by the Rust application by
//! means of a [`DataConsumer`](data_consumer::DataConsumer) created on a [`DirectTransport`]).
//!
//! A direct transport can also be used to inject and directly consume RTP and RTCP packets in
//! Rust by using the [`DirectProducer::send`](producer::DirectProducer::send) and
//! [`Consumer::on_rtp`](consumer::Consumer::on_rtp) API (plus [`DirectTransport::send_rtcp`]
//! and [`DirectTransport::on_rtcp`] API).
#[cfg(doc)]
use super::*;
pub use crate::router::direct_transport::*;
}
pub mod pipe_transport {
//! A pipe transport represents a network path through which RTP, RTCP (optionally secured with
//! SRTP) and SCTP (DataChannel) is transmitted. Pipe transports are intended to
//! intercommunicate two [`Router`](router::Router) instances collocated on the same host or on
//! separate hosts.
//!
//! # Notes on usage
//! When calling [`PipeTransport::consume`](transport::Transport::consume), all RTP streams of
//! the [`Producer`](producer::Producer) are transmitted verbatim (in contrast to what happens
//! in [`WebRtcTransport`](webrtc_transport::WebRtcTransport) and
//! [`PlainTransport`](plain_transport::PlainTransport) in which a single and continuous RTP
//! stream is sent to the consuming endpoint).
#[cfg(doc)]
use super::*;
pub use crate::router::pipe_transport::*;
}
pub mod plain_transport {
//! A plain transport represents a network path through which RTP, RTCP (optionally secured with
//! SRTP) and SCTP (DataChannel) is transmitted.
pub use crate::router::plain_transport::*;
}
pub mod rtp_observer {
//! An RTP observer inspects the media received by a set of selected producers.
//!
//! mediasoup implements the following RTP observers:
//! * [`AudioLevelObserver`](audio_level_observer::AudioLevelObserver)
#[cfg(doc)]
use super::*;
pub use crate::router::rtp_observer::*;
}
pub mod webrtc_transport {
//! A WebRTC transport represents a network path negotiated by both, a WebRTC endpoint and
//! mediasoup, via ICE and DTLS procedures. A WebRTC transport may be used to receive media, to
//! send media or to both receive and send. There is no limitation in mediasoup. However, due to
//! their design, mediasoup-client and libmediasoupclient require separate WebRTC transports for
//! sending and receiving.
//!
//! # Notes on usage
//! The WebRTC transport implementation of mediasoup is
//! [ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not
//! initiate ICE connections but expects ICE Binding Requests from endpoints.
pub use crate::router::webrtc_transport::*;
}
...@@ -10,6 +10,7 @@ use crate::supported_rtp_capabilities; ...@@ -10,6 +10,7 @@ use crate::supported_rtp_capabilities;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::mem; use std::mem;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
use std::ops::Deref; use std::ops::Deref;
...@@ -116,21 +117,21 @@ pub enum ConsumerRtpParametersError { ...@@ -116,21 +117,21 @@ pub enum ConsumerRtpParametersError {
} }
fn generate_ssrc() -> u32 { fn generate_ssrc() -> u32 {
fastrand::u32(100000000..999999999) fastrand::u32(100_000_000..999_999_999)
} }
/// Validates RtpParameters. /// Validates [`RtpParameters`].
pub(crate) fn validate_rtp_parameters( pub(crate) fn validate_rtp_parameters(
rtp_parameters: &RtpParameters, rtp_parameters: &RtpParameters,
) -> Result<(), RtpParametersError> { ) -> Result<(), RtpParametersError> {
for codec in rtp_parameters.codecs.iter() { for codec in &rtp_parameters.codecs {
validate_rtp_codec_parameters(codec)?; validate_rtp_codec_parameters(codec)?;
} }
Ok(()) Ok(())
} }
/// Validates RtpCodecParameters. /// Validates [`RtpCodecParameters`].
fn validate_rtp_codec_parameters(codec: &RtpCodecParameters) -> Result<(), RtpParametersError> { fn validate_rtp_codec_parameters(codec: &RtpCodecParameters) -> Result<(), RtpParametersError> {
for (key, value) in codec.parameters().iter() { for (key, value) in codec.parameters().iter() {
// Specific parameters validation. // Specific parameters validation.
...@@ -149,7 +150,7 @@ fn validate_rtp_codec_parameters(codec: &RtpCodecParameters) -> Result<(), RtpPa ...@@ -149,7 +150,7 @@ fn validate_rtp_codec_parameters(codec: &RtpCodecParameters) -> Result<(), RtpPa
Ok(()) Ok(())
} }
// Validates RtpCodecCapability. // Validates [`RtpCodecCapability`].
fn validate_rtp_codec_capability(codec: &RtpCodecCapability) -> Result<(), RtpCapabilitiesError> { fn validate_rtp_codec_capability(codec: &RtpCodecCapability) -> Result<(), RtpCapabilitiesError> {
for (key, value) in codec.parameters().iter() { for (key, value) in codec.parameters().iter() {
// Specific parameters validation. // Specific parameters validation.
...@@ -168,11 +169,11 @@ fn validate_rtp_codec_capability(codec: &RtpCodecCapability) -> Result<(), RtpCa ...@@ -168,11 +169,11 @@ fn validate_rtp_codec_capability(codec: &RtpCodecCapability) -> Result<(), RtpCa
Ok(()) Ok(())
} }
/// Validates RtpCapabilities. /// Validates [`RtpCapabilities`].
pub(crate) fn validate_rtp_capabilities( pub(crate) fn validate_rtp_capabilities(
caps: &RtpCapabilities, caps: &RtpCapabilities,
) -> Result<(), RtpCapabilitiesError> { ) -> Result<(), RtpCapabilitiesError> {
for codec in caps.codecs.iter() { for codec in &caps.codecs {
validate_rtp_codec_capability(codec)?; validate_rtp_codec_capability(codec)?;
} }
...@@ -195,7 +196,7 @@ pub(crate) fn generate_router_rtp_capabilities( ...@@ -195,7 +196,7 @@ pub(crate) fn generate_router_rtp_capabilities(
fec_mechanisms: vec![], fec_mechanisms: vec![],
}; };
for media_codec in media_codecs.iter_mut() { for media_codec in &mut media_codecs {
validate_rtp_codec_capability(media_codec)?; validate_rtp_codec_capability(media_codec)?;
let codec = match supported_rtp_capabilities let codec = match supported_rtp_capabilities
...@@ -213,22 +214,20 @@ pub(crate) fn generate_router_rtp_capabilities( ...@@ -213,22 +214,20 @@ pub(crate) fn generate_router_rtp_capabilities(
}; };
let preferred_payload_type = match media_codec.preferred_payload_type() { let preferred_payload_type = match media_codec.preferred_payload_type() {
// If the given media codec has preferred_payload_type, keep it.
Some(preferred_payload_type) => { Some(preferred_payload_type) => {
// If the given media codec has preferred_payload_type, keep it.
// Also remove the payload_type from the list of available dynamic values. // Also remove the payload_type from the list of available dynamic values.
dynamic_payload_types.retain(|&pt| pt != preferred_payload_type); dynamic_payload_types.retain(|&pt| pt != preferred_payload_type);
preferred_payload_type preferred_payload_type
} }
None => { None => {
match codec.preferred_payload_type() { if let Some(preferred_payload_type) = codec.preferred_payload_type() {
// Otherwise if the supported codec has preferredPayloadType, use it. // Otherwise if the supported codec has preferredPayloadType, use it.
Some(preferred_payload_type) => {
// No need to remove it from the list since it's not a dynamic value. // No need to remove it from the list since it's not a dynamic value.
preferred_payload_type preferred_payload_type
} } else {
// Otherwise choose a dynamic one. // Otherwise choose a dynamic one.
None => {
if dynamic_payload_types.is_empty() { if dynamic_payload_types.is_empty() {
return Err(RtpCapabilitiesError::CannotAllocate); return Err(RtpCapabilitiesError::CannotAllocate);
} }
...@@ -236,11 +235,10 @@ pub(crate) fn generate_router_rtp_capabilities( ...@@ -236,11 +235,10 @@ pub(crate) fn generate_router_rtp_capabilities(
dynamic_payload_types.remove(0) dynamic_payload_types.remove(0)
} }
} }
}
}; };
// Ensure there is not duplicated preferredPayloadType values. // Ensure there is not duplicated preferredPayloadType values.
for codec in caps.codecs.iter() { for codec in &caps.codecs {
if codec.preferred_payload_type() == preferred_payload_type { if codec.preferred_payload_type() == preferred_payload_type {
return Err(RtpCapabilitiesError::DuplicatedPreferredPayloadType( return Err(RtpCapabilitiesError::DuplicatedPreferredPayloadType(
preferred_payload_type, preferred_payload_type,
...@@ -332,7 +330,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping( ...@@ -332,7 +330,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping(
let mut codec_to_cap_codec = let mut codec_to_cap_codec =
BTreeMap::<&RtpCodecParameters, Cow<'_, RtpCodecCapabilityFinalized>>::new(); BTreeMap::<&RtpCodecParameters, Cow<'_, RtpCodecCapabilityFinalized>>::new();
for codec in rtp_parameters.codecs.iter() { for codec in &rtp_parameters.codecs {
if codec.is_rtx() { if codec.is_rtx() {
continue; continue;
} }
...@@ -344,15 +342,13 @@ pub(crate) fn get_producer_rtp_parameters_mapping( ...@@ -344,15 +342,13 @@ pub(crate) fn get_producer_rtp_parameters_mapping(
.map(|profile_level_id| { .map(|profile_level_id| {
// This is rather ugly, but we need to fix `profile-level-id` and this was the // This is rather ugly, but we need to fix `profile-level-id` and this was the
// quickest way to do it // quickest way to do it
if let Some(profile_level_id) = profile_level_id { profile_level_id.map_or(Cow::Borrowed(cap_codec), |profile_level_id| {
let mut cap_codec = cap_codec.clone(); let mut cap_codec = cap_codec.clone();
cap_codec cap_codec
.parameters_mut() .parameters_mut()
.insert("profile-level-id", profile_level_id); .insert("profile-level-id", profile_level_id);
Cow::Owned(cap_codec) Cow::Owned(cap_codec)
} else { })
Cow::Borrowed(cap_codec)
}
}) })
}) { }) {
Some(matched_codec_capability) => { Some(matched_codec_capability) => {
...@@ -368,7 +364,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping( ...@@ -368,7 +364,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping(
} }
// Match parameters RTX codecs to capabilities RTX codecs. // Match parameters RTX codecs to capabilities RTX codecs.
for codec in rtp_parameters.codecs.iter() { for codec in &rtp_parameters.codecs {
if !codec.is_rtx() { if !codec.is_rtx() {
continue; continue;
} }
...@@ -380,7 +376,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping( ...@@ -380,7 +376,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping(
match codec_parameters_apt { match codec_parameters_apt {
Some(RtpCodecParametersParametersValue::Number(apt)) => { Some(RtpCodecParametersParametersValue::Number(apt)) => {
media_codec_payload_type as u32 == *apt u32::from(media_codec_payload_type) == *apt
} }
_ => false, _ => false,
} }
...@@ -399,7 +395,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping( ...@@ -399,7 +395,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping(
let cap_codec_parameters_apt = cap_codec.parameters().get(&"apt".to_string()); let cap_codec_parameters_apt = cap_codec.parameters().get(&"apt".to_string());
match cap_codec_parameters_apt { match cap_codec_parameters_apt {
Some(RtpCodecParametersParametersValue::Number(apt)) => { Some(RtpCodecParametersParametersValue::Number(apt)) => {
cap_media_codec.preferred_payload_type() as u32 == *apt u32::from(cap_media_codec.preferred_payload_type()) == *apt
} }
_ => false, _ => false,
} }
...@@ -435,7 +431,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping( ...@@ -435,7 +431,7 @@ pub(crate) fn get_producer_rtp_parameters_mapping(
// Generate encodings mapping. // Generate encodings mapping.
let mut mapped_ssrc: u32 = generate_ssrc(); let mut mapped_ssrc: u32 = generate_ssrc();
for encoding in rtp_parameters.encodings.iter() { for encoding in &rtp_parameters.encodings {
rtp_mapping.encodings.push(RtpMappingEncoding { rtp_mapping.encodings.push(RtpMappingEncoding {
ssrc: encoding.ssrc, ssrc: encoding.ssrc,
rid: encoding.rid.clone(), rid: encoding.rid.clone(),
...@@ -459,7 +455,7 @@ pub(crate) fn get_consumable_rtp_parameters( ...@@ -459,7 +455,7 @@ pub(crate) fn get_consumable_rtp_parameters(
) -> RtpParameters { ) -> RtpParameters {
let mut consumable_params = RtpParameters::default(); let mut consumable_params = RtpParameters::default();
for codec in params.codecs.iter() { for codec in &params.codecs {
if codec.is_rtx() { if codec.is_rtx() {
continue; continue;
} }
...@@ -522,7 +518,7 @@ pub(crate) fn get_consumable_rtp_parameters( ...@@ -522,7 +518,7 @@ pub(crate) fn get_consumable_rtp_parameters(
match cap_rtx_codec_parameters_apt { match cap_rtx_codec_parameters_apt {
Some(RtpCodecParametersParametersValue::Number(apt)) => { Some(RtpCodecParametersParametersValue::Number(apt)) => {
*apt as u8 == consumable_codec.payload_type() u8::try_from(*apt).map_or(false, |apt| apt == consumable_codec.payload_type())
} }
_ => false, _ => false,
} }
...@@ -566,7 +562,7 @@ pub(crate) fn get_consumable_rtp_parameters( ...@@ -566,7 +562,7 @@ pub(crate) fn get_consumable_rtp_parameters(
} }
} }
for cap_ext in caps.header_extensions.iter() { for cap_ext in &caps.header_extensions {
// Just take RTP header extension that can be used in Consumers. // Just take RTP header extension that can be used in Consumers.
match cap_ext.kind { match cap_ext.kind {
Some(cap_ext_kind) => { Some(cap_ext_kind) => {
...@@ -631,7 +627,7 @@ pub(crate) fn can_consume( ...@@ -631,7 +627,7 @@ pub(crate) fn can_consume(
let mut matching_codecs = Vec::<&RtpCodecParameters>::new(); let mut matching_codecs = Vec::<&RtpCodecParameters>::new();
for codec in consumable_params.codecs.iter() { for codec in &consumable_params.codecs {
if caps if caps
.codecs .codecs
.iter() .iter()
...@@ -655,7 +651,7 @@ pub(crate) fn can_consume( ...@@ -655,7 +651,7 @@ pub(crate) fn can_consume(
#[allow(clippy::suspicious_operation_groupings)] #[allow(clippy::suspicious_operation_groupings)]
pub(crate) fn get_consumer_rtp_parameters( pub(crate) fn get_consumer_rtp_parameters(
consumable_params: &RtpParameters, consumable_params: &RtpParameters,
caps: RtpCapabilities, caps: &RtpCapabilities,
pipe: bool, pipe: bool,
) -> Result<RtpParameters, ConsumerRtpParametersError> { ) -> Result<RtpParameters, ConsumerRtpParametersError> {
let mut consumer_params = RtpParameters { let mut consumer_params = RtpParameters {
...@@ -663,7 +659,7 @@ pub(crate) fn get_consumer_rtp_parameters( ...@@ -663,7 +659,7 @@ pub(crate) fn get_consumer_rtp_parameters(
..RtpParameters::default() ..RtpParameters::default()
}; };
for cap_codec in caps.codecs.iter() { for cap_codec in &caps.codecs {
validate_rtp_codec_capability(cap_codec) validate_rtp_codec_capability(cap_codec)
.map_err(ConsumerRtpParametersError::InvalidCapabilities)?; .map_err(ConsumerRtpParametersError::InvalidCapabilities)?;
} }
...@@ -688,7 +684,7 @@ pub(crate) fn get_consumer_rtp_parameters( ...@@ -688,7 +684,7 @@ pub(crate) fn get_consumer_rtp_parameters(
let associated_media_codec = consumer_params.codecs.iter().find(|media_codec| { let associated_media_codec = consumer_params.codecs.iter().find(|media_codec| {
match codec.parameters().get("apt") { match codec.parameters().get("apt") {
Some(RtpCodecParametersParametersValue::Number(apt)) => { Some(RtpCodecParametersParametersValue::Number(apt)) => {
media_codec.payload_type() as u32 == *apt u8::try_from(*apt).map_or(false, |apt| media_codec.payload_type() == apt)
} }
_ => false, _ => false,
} }
...@@ -727,7 +723,7 @@ pub(crate) fn get_consumer_rtp_parameters( ...@@ -727,7 +723,7 @@ pub(crate) fn get_consumer_rtp_parameters(
.iter() .iter()
.any(|ext| ext.uri == RtpHeaderExtensionUri::TransportWideCcDraft01) .any(|ext| ext.uri == RtpHeaderExtensionUri::TransportWideCcDraft01)
{ {
for codec in consumer_params.codecs.iter_mut() { for codec in &mut consumer_params.codecs {
codec codec
.rtcp_feedback_mut() .rtcp_feedback_mut()
.retain(|fb| fb != &RtcpFeedback::GoogRemb); .retain(|fb| fb != &RtcpFeedback::GoogRemb);
...@@ -737,13 +733,13 @@ pub(crate) fn get_consumer_rtp_parameters( ...@@ -737,13 +733,13 @@ pub(crate) fn get_consumer_rtp_parameters(
.iter() .iter()
.any(|ext| ext.uri == RtpHeaderExtensionUri::AbsSendTime) .any(|ext| ext.uri == RtpHeaderExtensionUri::AbsSendTime)
{ {
for codec in consumer_params.codecs.iter_mut() { for codec in &mut consumer_params.codecs {
codec codec
.rtcp_feedback_mut() .rtcp_feedback_mut()
.retain(|fb| fb != &RtcpFeedback::TransportCc); .retain(|fb| fb != &RtcpFeedback::TransportCc);
} }
} else { } else {
for codec in consumer_params.codecs.iter_mut() { for codec in &mut consumer_params.codecs {
codec codec
.rtcp_feedback_mut() .rtcp_feedback_mut()
.retain(|fb| !matches!(fb, RtcpFeedback::GoogRemb | RtcpFeedback::TransportCc)); .retain(|fb| !matches!(fb, RtcpFeedback::GoogRemb | RtcpFeedback::TransportCc));
...@@ -793,8 +789,7 @@ pub(crate) fn get_consumer_rtp_parameters( ...@@ -793,8 +789,7 @@ pub(crate) fn get_consumer_rtp_parameters(
consumable_params.encodings.len(), consumable_params.encodings.len(),
scalability_mode scalability_mode
.as_ref() .as_ref()
.map(|s| s.parse::<ScalabilityMode>().ok()) .and_then(|s| s.parse::<ScalabilityMode>().ok())
.flatten()
.unwrap_or_default() .unwrap_or_default()
.temporal_layers .temporal_layers
)); ));
...@@ -833,7 +828,7 @@ pub(crate) fn get_pipe_consumer_rtp_parameters( ...@@ -833,7 +828,7 @@ pub(crate) fn get_pipe_consumer_rtp_parameters(
rtcp: consumable_params.rtcp.clone(), rtcp: consumable_params.rtcp.clone(),
}; };
for codec in consumable_params.codecs.iter() { for codec in &consumable_params.codecs {
if !enable_rtx && codec.is_rtx() { if !enable_rtx && codec.is_rtx() {
continue; continue;
} }
......
...@@ -11,7 +11,7 @@ fn generate_router_rtp_capabilities_succeeds() { ...@@ -11,7 +11,7 @@ fn generate_router_rtp_capabilities_succeeds() {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -28,7 +28,7 @@ fn generate_router_rtp_capabilities_succeeds() { ...@@ -28,7 +28,7 @@ fn generate_router_rtp_capabilities_succeeds() {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("profile-level-id", "42e01f".into()), ("profile-level-id", "42e01f".into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
...@@ -48,7 +48,7 @@ fn generate_router_rtp_capabilities_succeeds() { ...@@ -48,7 +48,7 @@ fn generate_router_rtp_capabilities_succeeds() {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![RtcpFeedback::TransportCc], rtcp_feedback: vec![RtcpFeedback::TransportCc],
...@@ -78,8 +78,8 @@ fn generate_router_rtp_capabilities_succeeds() { ...@@ -78,8 +78,8 @@ fn generate_router_rtp_capabilities_succeeds() {
preferred_payload_type: 102, // 102 is the third available dynamic PT. preferred_payload_type: 102, // 102 is the third available dynamic PT.
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 0u32.into()), ("packetization-mode", 0_u32.into()),
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("profile-level-id", "42e01f".into()), ("profile-level-id", "42e01f".into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
...@@ -157,7 +157,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -157,7 +157,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -167,8 +167,8 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -167,8 +167,8 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
("foo", "lalala".into()), ("foo", "lalala".into()),
]), ]),
...@@ -188,7 +188,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -188,7 +188,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("foo", 1234u32.into()), ("foo", 1234u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -201,7 +201,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -201,7 +201,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
payload_type: 112, payload_type: 112,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 111u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 111_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
], ],
...@@ -289,7 +289,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -289,7 +289,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("foo", 1234u32.into()), ("foo", 1234u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -304,7 +304,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -304,7 +304,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
payload_type: 102, payload_type: 102,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
] ]
...@@ -395,7 +395,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -395,7 +395,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
preferred_payload_type: Some(101), preferred_payload_type: Some(101),
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
("baz", "LOLOLO".into()), ("baz", "LOLOLO".into()),
]), ]),
...@@ -409,7 +409,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -409,7 +409,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
preferred_payload_type: Some(102), preferred_payload_type: Some(102),
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
], ],
...@@ -461,7 +461,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -461,7 +461,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
}; };
let consumer_rtp_parameters = let consumer_rtp_parameters =
get_consumer_rtp_parameters(&consumable_rtp_parameters, remote_rtp_capabilities, false) get_consumer_rtp_parameters(&consumable_rtp_parameters, &remote_rtp_capabilities, false)
.expect("Failed to get consumer RTP parameters"); .expect("Failed to get consumer RTP parameters");
assert_eq!( assert_eq!(
...@@ -473,7 +473,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -473,7 +473,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("foo", 1234u32.into()), ("foo", 1234u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -486,7 +486,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -486,7 +486,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
payload_type: 102, payload_type: 102,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
] ]
...@@ -563,7 +563,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume ...@@ -563,7 +563,7 @@ fn get_producer_rtp_parameters_mapping_get_consumable_rtp_parameters_get_consume
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("foo", 1234u32.into()), ("foo", 1234u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![RtcpFeedback::NackPli, RtcpFeedback::CcmFir], rtcp_feedback: vec![RtcpFeedback::NackPli, RtcpFeedback::CcmFir],
...@@ -676,7 +676,7 @@ fn get_producer_rtp_parameters_mapping_unsupported() { ...@@ -676,7 +676,7 @@ fn get_producer_rtp_parameters_mapping_unsupported() {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "640032".into()), ("profile-level-id", "640032".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
......
...@@ -6,30 +6,19 @@ ...@@ -6,30 +6,19 @@
//! high level use cases (for instance, a "multi-party conference room" could involve various //! high level use cases (for instance, a "multi-party conference room" could involve various
//! mediasoup routers, even in different physicals hosts). //! mediasoup routers, even in different physicals hosts).
#[cfg(not(doc))] pub(super) mod audio_level_observer;
pub mod audio_level_observer; pub(super) mod consumer;
#[cfg(not(doc))] pub(super) mod data_consumer;
pub mod consumer; pub(super) mod data_producer;
#[cfg(not(doc))] pub(super) mod direct_transport;
pub mod data_consumer; pub(super) mod pipe_transport;
#[cfg(not(doc))] pub(super) mod plain_transport;
pub mod data_producer; pub(super) mod producer;
#[cfg(not(doc))] pub(super) mod rtp_observer;
pub mod direct_transport;
#[cfg(not(doc))]
pub mod pipe_transport;
#[cfg(not(doc))]
pub mod plain_transport;
#[cfg(not(doc))]
pub mod producer;
#[cfg(not(doc))]
pub mod rtp_observer;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
#[cfg(not(doc))] pub(super) mod transport;
pub mod transport; pub(super) mod webrtc_transport;
#[cfg(not(doc))]
pub mod webrtc_transport;
use crate::audio_level_observer::{AudioLevelObserver, AudioLevelObserverOptions}; use crate::audio_level_observer::{AudioLevelObserver, AudioLevelObserverOptions};
use crate::consumer::{Consumer, ConsumerId, ConsumerOptions}; use crate::consumer::{Consumer, ConsumerId, ConsumerOptions};
...@@ -51,7 +40,7 @@ use crate::pipe_transport::{ ...@@ -51,7 +40,7 @@ use crate::pipe_transport::{
PipeTransport, PipeTransportOptions, PipeTransportRemoteParameters, WeakPipeTransport, PipeTransport, PipeTransportOptions, PipeTransportRemoteParameters, WeakPipeTransport,
}; };
use crate::plain_transport::{PlainTransport, PlainTransportOptions}; use crate::plain_transport::{PlainTransport, PlainTransportOptions};
use crate::producer::{NonClosingProducer, Producer, ProducerId, ProducerOptions, WeakProducer}; use crate::producer::{PipedProducer, Producer, ProducerId, ProducerOptions, WeakProducer};
use crate::rtp_observer::RtpObserverId; use crate::rtp_observer::RtpObserverId;
use crate::rtp_parameters::{RtpCapabilities, RtpCapabilitiesFinalized, RtpCodecCapability}; use crate::rtp_parameters::{RtpCapabilities, RtpCapabilitiesFinalized, RtpCodecCapability};
use crate::sctp_parameters::NumSctpStreams; use crate::sctp_parameters::NumSctpStreams;
...@@ -66,7 +55,7 @@ use async_executor::Executor; ...@@ -66,7 +55,7 @@ use async_executor::Executor;
use async_lock::Mutex as AsyncMutex; use async_lock::Mutex as AsyncMutex;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use futures_lite::future; use futures_lite::future;
use log::*; use log::{debug, error};
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
...@@ -76,11 +65,11 @@ use std::sync::{Arc, Weak}; ...@@ -76,11 +65,11 @@ use std::sync::{Arc, Weak};
use thiserror::Error; use thiserror::Error;
uuid_based_wrapper_type!( uuid_based_wrapper_type!(
/// Router identifier. /// [`Router`] identifier.
RouterId RouterId
); );
/// Router options. /// [`Router`] options.
/// ///
/// # Notes on usage /// # Notes on usage
/// ///
...@@ -98,6 +87,7 @@ pub struct RouterOptions { ...@@ -98,6 +87,7 @@ pub struct RouterOptions {
impl RouterOptions { impl RouterOptions {
/// Create router options with given list of declared media codecs. /// Create router options with given list of declared media codecs.
#[must_use]
pub fn new(media_codecs: Vec<RtpCodecCapability>) -> Self { pub fn new(media_codecs: Vec<RtpCodecCapability>) -> Self {
Self { Self {
media_codecs, media_codecs,
...@@ -142,6 +132,7 @@ pub struct PipeToRouterOptions { ...@@ -142,6 +132,7 @@ pub struct PipeToRouterOptions {
impl PipeToRouterOptions { impl PipeToRouterOptions {
/// Crate pipe options for piping into given local router. /// Crate pipe options for piping into given local router.
#[must_use]
pub fn new(router: Router) -> Self { pub fn new(router: Router) -> Self {
Self { Self {
router, router,
...@@ -150,7 +141,7 @@ impl PipeToRouterOptions { ...@@ -150,7 +141,7 @@ impl PipeToRouterOptions {
announced_ip: None, announced_ip: None,
}, },
enable_sctp: true, enable_sctp: true,
num_sctp_streams: Default::default(), num_sctp_streams: NumSctpStreams::default(),
enable_rtx: false, enable_rtx: false,
enable_srtp: false, enable_srtp: false,
} }
...@@ -161,7 +152,7 @@ impl PipeToRouterOptions { ...@@ -161,7 +152,7 @@ impl PipeToRouterOptions {
/// ///
/// # Notes on usage /// # Notes on usage
/// Pipe consumer and Pipe producer will not be closed on drop, to control this manually get pipe /// Pipe consumer and Pipe producer will not be closed on drop, to control this manually get pipe
/// producer out of non-closing variant with [`NonClosingProducer::into_inner()`] call, /// producer out of non-closing variant with [`PipedProducer::into_inner()`] call,
/// otherwise pipe consumer and pipe producer lifetime will be tied to source producer lifetime. /// otherwise pipe consumer and pipe producer lifetime will be tied to source producer lifetime.
/// ///
/// Pipe consumer is always tied to the lifetime of pipe producer. /// Pipe consumer is always tied to the lifetime of pipe producer.
...@@ -170,8 +161,8 @@ pub struct PipeProducerToRouterPair { ...@@ -170,8 +161,8 @@ pub struct PipeProducerToRouterPair {
/// The Consumer created in the current Router. /// The Consumer created in the current Router.
pub pipe_consumer: Consumer, pub pipe_consumer: Consumer,
/// The Producer created in the target Router, get regular instance with /// The Producer created in the target Router, get regular instance with
/// [`NonClosingProducer::into_inner()`] call. /// [`PipedProducer::into_inner()`] call.
pub pipe_producer: NonClosingProducer, pub pipe_producer: PipedProducer,
} }
/// Error that caused [`Router::pipe_producer_to_router()`] to fail. /// Error that caused [`Router::pipe_producer_to_router()`] to fail.
...@@ -399,6 +390,7 @@ impl Inner { ...@@ -399,6 +390,7 @@ impl Inner {
/// high level use cases (for instance, a "multi-party conference room" could involve various /// high level use cases (for instance, a "multi-party conference room" could involve various
/// mediasoup routers, even in different physicals hosts). /// mediasoup routers, even in different physicals hosts).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Router will be closed on drop, make sure to keep it around for as long as needed"]
pub struct Router { pub struct Router {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -440,11 +432,7 @@ impl Router { ...@@ -440,11 +432,7 @@ impl Router {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
move || { move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.worker_close.call_simple(); inner.handlers.worker_close.call_simple();
if !inner.closed.swap(true, Ordering::SeqCst) { if !inner.closed.swap(true, Ordering::SeqCst) {
inner.handlers.close.call_simple(); inner.handlers.close.call_simple();
...@@ -474,16 +462,19 @@ impl Router { ...@@ -474,16 +462,19 @@ impl Router {
} }
/// Router id. /// Router id.
#[must_use]
pub fn id(&self) -> RouterId { pub fn id(&self) -> RouterId {
self.inner.id self.inner.id
} }
/// Custom application data. /// Custom application data.
#[must_use]
pub fn app_data(&self) -> &AppData { pub fn app_data(&self) -> &AppData {
&self.inner.app_data &self.inner.app_data
} }
/// Whether router is closed. /// Whether router is closed.
#[must_use]
pub fn closed(&self) -> bool { pub fn closed(&self) -> bool {
self.inner.closed.load(Ordering::SeqCst) self.inner.closed.load(Ordering::SeqCst)
} }
...@@ -496,6 +487,7 @@ impl Router { ...@@ -496,6 +487,7 @@ impl Router {
/// section for more details. /// section for more details.
/// * See also how to [filter these RTP capabilities](https://mediasoup.org/documentation/v3/tricks/#rtp-capabilities-filtering) /// * See also how to [filter these RTP capabilities](https://mediasoup.org/documentation/v3/tricks/#rtp-capabilities-filtering)
/// before using them into a client. /// before using them into a client.
#[must_use]
pub fn rtp_capabilities(&self) -> &RtpCapabilitiesFinalized { pub fn rtp_capabilities(&self) -> &RtpCapabilitiesFinalized {
&self.inner.rtp_capabilities &self.inner.rtp_capabilities
} }
...@@ -515,7 +507,7 @@ impl Router { ...@@ -515,7 +507,7 @@ impl Router {
.await .await
} }
/// Create a DirectTransport. /// Create a [`DirectTransport`].
/// ///
/// Router will be kept alive as long as at least one transport instance is alive. /// Router will be kept alive as long as at least one transport instance is alive.
/// ///
...@@ -567,7 +559,7 @@ impl Router { ...@@ -567,7 +559,7 @@ impl Router {
Ok(transport) Ok(transport)
} }
/// Create a `WebRtcTransport`. /// Create a [`WebRtcTransport`].
/// ///
/// Router will be kept alive as long as at least one transport instance is alive. /// Router will be kept alive as long as at least one transport instance is alive.
/// ///
...@@ -629,7 +621,7 @@ impl Router { ...@@ -629,7 +621,7 @@ impl Router {
Ok(transport) Ok(transport)
} }
/// Create a `PipeTransport`. /// Create a [`PipeTransport`].
/// ///
/// Router will be kept alive as long as at least one transport instance is alive. /// Router will be kept alive as long as at least one transport instance is alive.
/// ///
...@@ -689,7 +681,7 @@ impl Router { ...@@ -689,7 +681,7 @@ impl Router {
Ok(transport) Ok(transport)
} }
/// Create a `PlainTransport`. /// Create a [`PlainTransport`].
/// ///
/// Router will be kept alive as long as at least one transport instance is alive. /// Router will be kept alive as long as at least one transport instance is alive.
/// ///
...@@ -749,7 +741,7 @@ impl Router { ...@@ -749,7 +741,7 @@ impl Router {
Ok(transport) Ok(transport)
} }
/// Create an `AudioLevelObserver`. /// Create an [`AudioLevelObserver`].
/// ///
/// Router will be kept alive as long as at least one observer instance is alive. /// Router will be kept alive as long as at least one observer instance is alive.
/// ///
...@@ -812,7 +804,7 @@ impl Router { ...@@ -812,7 +804,7 @@ impl Router {
Ok(audio_level_observer) Ok(audio_level_observer)
} }
/// Pipes `Producer` with the given `producer_id` into another `Router` on same host. /// Pipes [`Producer`] with the given `producer_id` into another [`Router`] on same host.
/// ///
/// # Example /// # Example
/// ```rust /// ```rust
...@@ -844,7 +836,7 @@ impl Router { ...@@ -844,7 +836,7 @@ impl Router {
/// clock_rate: NonZeroU32::new(48000).unwrap(), /// clock_rate: NonZeroU32::new(48000).unwrap(),
/// channels: NonZeroU8::new(2).unwrap(), /// channels: NonZeroU8::new(2).unwrap(),
/// parameters: RtpCodecParametersParameters::from([ /// parameters: RtpCodecParametersParameters::from([
/// ("useinbandfec", 1u32.into()), /// ("useinbandfec", 1_u32.into()),
/// ]), /// ]),
/// rtcp_feedback: vec![], /// rtcp_feedback: vec![],
/// }, /// },
...@@ -872,8 +864,8 @@ impl Router { ...@@ -872,8 +864,8 @@ impl Router {
/// clock_rate: NonZeroU32::new(48000).unwrap(), /// clock_rate: NonZeroU32::new(48000).unwrap(),
/// channels: NonZeroU8::new(2).unwrap(), /// channels: NonZeroU8::new(2).unwrap(),
/// parameters: RtpCodecParametersParameters::from([ /// parameters: RtpCodecParametersParameters::from([
/// ("useinbandfec", 1u32.into()), /// ("useinbandfec", 1_u32.into()),
/// ("usedtx", 1u32.into()), /// ("usedtx", 1_u32.into()),
/// ]), /// ]),
/// rtcp_feedback: vec![], /// rtcp_feedback: vec![],
/// }], /// }],
...@@ -980,7 +972,7 @@ impl Router { ...@@ -980,7 +972,7 @@ impl Router {
move || { move || {
if let Some(pipe_producer) = pipe_producer_weak.upgrade() { if let Some(pipe_producer) = pipe_producer_weak.upgrade() {
let _ = pipe_producer.close(); pipe_producer.close();
} }
} }
}) })
...@@ -1031,12 +1023,12 @@ impl Router { ...@@ -1031,12 +1023,12 @@ impl Router {
}) })
.detach(); .detach();
let pipe_producer = NonClosingProducer::new(pipe_producer, { let pipe_producer = PipedProducer::new(pipe_producer, {
let weak_producer = producer.downgrade(); let weak_producer = producer.downgrade();
move |pipe_producer| { move |pipe_producer| {
if let Some(producer) = weak_producer.upgrade() { if let Some(producer) = weak_producer.upgrade() {
// In case `NonClosingProducer` was dropped without transforming into regular // In case `PipedProducer` was dropped without transforming into regular
// `Producer` first, we need to tie underlying pipe producer lifetime to the // `Producer` first, we need to tie underlying pipe producer lifetime to the
// lifetime of original source producer in another router // lifetime of original source producer in another router
producer producer
...@@ -1054,7 +1046,8 @@ impl Router { ...@@ -1054,7 +1046,8 @@ impl Router {
}) })
} }
/// Pipes `DataProducer` with the given `data_producer_id` into another `Router` on same host. /// Pipes [`DataProducer`] with the given `data_producer_id` into another [`Router`] on same
/// host.
/// ///
/// # Example /// # Example
/// ```rust /// ```rust
...@@ -1163,6 +1156,7 @@ impl Router { ...@@ -1163,6 +1156,7 @@ impl Router {
.produce_data({ .produce_data({
let mut producer_options = DataProducerOptions::new_pipe_transport( let mut producer_options = DataProducerOptions::new_pipe_transport(
data_producer_id, data_producer_id,
// We've created `DataConsumer` with SCTP above, so this should never panic
pipe_data_consumer.sctp_stream_parameters().unwrap(), pipe_data_consumer.sctp_stream_parameters().unwrap(),
); );
producer_options.label = pipe_data_consumer.label().clone(); producer_options.label = pipe_data_consumer.label().clone();
...@@ -1180,7 +1174,7 @@ impl Router { ...@@ -1180,7 +1174,7 @@ impl Router {
move || { move || {
if let Some(pipe_data_producer) = pipe_data_producer_weak.upgrade() { if let Some(pipe_data_producer) = pipe_data_producer_weak.upgrade() {
let _ = pipe_data_producer.close(); pipe_data_producer.close();
} }
} }
}) })
...@@ -1222,13 +1216,13 @@ impl Router { ...@@ -1222,13 +1216,13 @@ impl Router {
} }
/// Check whether the given RTP capabilities are valid to consume the given producer. /// Check whether the given RTP capabilities are valid to consume the given producer.
#[must_use]
pub fn can_consume( pub fn can_consume(
&self, &self,
producer_id: &ProducerId, producer_id: &ProducerId,
rtp_capabilities: &RtpCapabilities, rtp_capabilities: &RtpCapabilities,
) -> bool { ) -> bool {
match self.get_producer(producer_id) { if let Some(producer) = self.get_producer(producer_id) {
Some(producer) => {
match ortc::can_consume(producer.consumable_rtp_parameters(), rtp_capabilities) { match ortc::can_consume(producer.consumable_rtp_parameters(), rtp_capabilities) {
Ok(result) => result, Ok(result) => result,
Err(error) => { Err(error) => {
...@@ -1236,8 +1230,7 @@ impl Router { ...@@ -1236,8 +1230,7 @@ impl Router {
false false
} }
} }
} } else {
None => {
error!( error!(
"can_consume() | Producer with id \"{}\" not found", "can_consume() | Producer with id \"{}\" not found",
producer_id producer_id
...@@ -1245,7 +1238,6 @@ impl Router { ...@@ -1245,7 +1238,6 @@ impl Router {
false false
} }
} }
}
/// Callback is called when a new transport is created. /// Callback is called when a new transport is created.
pub fn on_new_transport<F: Fn(NewTransport<'_>) + Send + Sync + 'static>( pub fn on_new_transport<F: Fn(NewTransport<'_>) + Send + Sync + 'static>(
...@@ -1341,7 +1333,7 @@ impl Router { ...@@ -1341,7 +1333,7 @@ impl Router {
num_sctp_streams, num_sctp_streams,
enable_rtx, enable_rtx,
enable_srtp, enable_srtp,
app_data: Default::default(), app_data: AppData::default(),
..PipeTransportOptions::new(listen_ip) ..PipeTransportOptions::new(listen_ip)
}; };
let local_pipe_transport_fut = self.create_pipe_transport(transport_options.clone()); let local_pipe_transport_fut = self.create_pipe_transport(transport_options.clone());
...@@ -1357,8 +1349,8 @@ impl Router { ...@@ -1357,8 +1349,8 @@ impl Router {
local_ip, local_ip,
local_port, local_port,
.. ..
} => (local_ip, local_port), }
TransportTuple::WithRemote { | TransportTuple::WithRemote {
local_ip, local_ip,
local_port, local_port,
.. ..
...@@ -1378,8 +1370,8 @@ impl Router { ...@@ -1378,8 +1370,8 @@ impl Router {
local_ip, local_ip,
local_port, local_port,
.. ..
} => (local_ip, local_port), }
TransportTuple::WithRemote { | TransportTuple::WithRemote {
local_ip, local_ip,
local_port, local_port,
.. ..
......
//! An audio level observer monitors the volume of the selected audio producers.
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -24,7 +22,7 @@ use std::num::NonZeroU16; ...@@ -24,7 +22,7 @@ use std::num::NonZeroU16;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
/// AudioLevelObserver options /// [`AudioLevelObserver`] options
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct AudioLevelObserverOptions { pub struct AudioLevelObserverOptions {
...@@ -149,6 +147,7 @@ impl Inner { ...@@ -149,6 +147,7 @@ impl Inner {
/// Audio levels are read from an RTP header extension. No decoding of audio data is done. See /// Audio levels are read from an RTP header extension. No decoding of audio data is done. See
/// [RFC6464](https://tools.ietf.org/html/rfc6464) for more information. /// [RFC6464](https://tools.ietf.org/html/rfc6464) for more information.
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Audio level observer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct AudioLevelObserver { pub struct AudioLevelObserver {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -362,11 +361,7 @@ impl AudioLevelObserver { ...@@ -362,11 +361,7 @@ impl AudioLevelObserver {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
move || { move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.router_close.call_simple(); inner.handlers.router_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -407,6 +402,7 @@ impl AudioLevelObserver { ...@@ -407,6 +402,7 @@ impl AudioLevelObserver {
} }
/// Downgrade `AudioLevelObserver` to [`WeakAudioLevelObserver`] instance. /// Downgrade `AudioLevelObserver` to [`WeakAudioLevelObserver`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakAudioLevelObserver { pub fn downgrade(&self) -> WeakAudioLevelObserver {
WeakAudioLevelObserver { WeakAudioLevelObserver {
inner: Arc::downgrade(&self.inner), inner: Arc::downgrade(&self.inner),
...@@ -440,6 +436,7 @@ impl fmt::Debug for WeakAudioLevelObserver { ...@@ -440,6 +436,7 @@ impl fmt::Debug for WeakAudioLevelObserver {
impl WeakAudioLevelObserver { impl WeakAudioLevelObserver {
/// Attempts to upgrade `WeakAudioLevelObserver` to [`AudioLevelObserver`] if last instance of one wasn't /// Attempts to upgrade `WeakAudioLevelObserver` to [`AudioLevelObserver`] if last instance of one wasn't
/// dropped yet. /// dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<AudioLevelObserver> { pub fn upgrade(&self) -> Option<AudioLevelObserver> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A consumer represents an audio or video source being forwarded from a mediasoup router to an
//! endpoint. It's created on top of a transport that defines how the media packets are carried.
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -21,7 +18,7 @@ use crate::worker::{ ...@@ -21,7 +18,7 @@ use crate::worker::{
use async_executor::Executor; use async_executor::Executor;
use bytes::Bytes; use bytes::Bytes;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
...@@ -31,7 +28,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; ...@@ -31,7 +28,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
uuid_based_wrapper_type!( uuid_based_wrapper_type!(
/// Consumer identifier. /// [`Consumer`] identifier.
ConsumerId ConsumerId
); );
...@@ -60,7 +57,7 @@ pub struct ConsumerScore { ...@@ -60,7 +57,7 @@ pub struct ConsumerScore {
pub producer_scores: Vec<u8>, pub producer_scores: Vec<u8>,
} }
/// Consumer options. /// [`Consumer`] options.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct ConsumerOptions { pub struct ConsumerOptions {
...@@ -90,6 +87,7 @@ pub struct ConsumerOptions { ...@@ -90,6 +87,7 @@ pub struct ConsumerOptions {
impl ConsumerOptions { impl ConsumerOptions {
/// Create consumer options with given producer ID and RTP capabilities. /// Create consumer options with given producer ID and RTP capabilities.
#[must_use]
pub fn new(producer_id: ProducerId, rtp_capabilities: RtpCapabilities) -> Self { pub fn new(producer_id: ProducerId, rtp_capabilities: RtpCapabilities) -> Self {
Self { Self {
producer_id, producer_id,
...@@ -421,6 +419,7 @@ impl Inner { ...@@ -421,6 +419,7 @@ impl Inner {
/// A consumer represents an audio or video source being forwarded from a mediasoup router to an /// A consumer represents an audio or video source being forwarded from a mediasoup router to an
/// endpoint. It's created on top of a transport that defines how the media packets are carried. /// endpoint. It's created on top of a transport that defines how the media packets are carried.
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Consumer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct Consumer { pub struct Consumer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -456,7 +455,7 @@ impl Consumer { ...@@ -456,7 +455,7 @@ impl Consumer {
paused: bool, paused: bool,
executor: Arc<Executor<'static>>, executor: Arc<Executor<'static>>,
channel: Channel, channel: Channel,
payload_channel: PayloadChannel, payload_channel: &PayloadChannel,
producer_paused: bool, producer_paused: bool,
score: ConsumerScore, score: ConsumerScore,
preferred_layers: Option<ConsumerLayers>, preferred_layers: Option<ConsumerLayers>,
...@@ -487,10 +486,7 @@ impl Consumer { ...@@ -487,10 +486,7 @@ impl Consumer {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::ProducerClose => { Notification::ProducerClose => {
handlers.producer_close.call_simple(); handlers.producer_close.call_simple();
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade)
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{ {
inner.close(false); inner.close(false);
} }
...@@ -567,11 +563,7 @@ impl Consumer { ...@@ -567,11 +563,7 @@ impl Consumer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
Box::new(move || { Box::new(move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.transport_close.call_simple(); inner.handlers.transport_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -585,7 +577,7 @@ impl Consumer { ...@@ -585,7 +577,7 @@ impl Consumer {
rtp_parameters, rtp_parameters,
paused, paused,
producer_paused, producer_paused,
priority: Mutex::new(1u8), priority: Mutex::new(1_u8),
score, score,
preferred_layers: Mutex::new(preferred_layers), preferred_layers: Mutex::new(preferred_layers),
current_layers, current_layers,
...@@ -605,16 +597,19 @@ impl Consumer { ...@@ -605,16 +597,19 @@ impl Consumer {
} }
/// Consumer id. /// Consumer id.
#[must_use]
pub fn id(&self) -> ConsumerId { pub fn id(&self) -> ConsumerId {
self.inner.id self.inner.id
} }
/// Associated Producer id. /// Associated Producer id.
#[must_use]
pub fn producer_id(&self) -> ProducerId { pub fn producer_id(&self) -> ProducerId {
self.inner.producer_id self.inner.producer_id
} }
/// Media kind. /// Media kind.
#[must_use]
pub fn kind(&self) -> MediaKind { pub fn kind(&self) -> MediaKind {
self.inner.kind self.inner.kind
} }
...@@ -624,38 +619,45 @@ impl Consumer { ...@@ -624,38 +619,45 @@ impl Consumer {
/// Check the /// Check the
/// [RTP Parameters and Capabilities](https://mediasoup.org/documentation/v3/mediasoup/rtp-parameters-and-capabilities/) /// [RTP Parameters and Capabilities](https://mediasoup.org/documentation/v3/mediasoup/rtp-parameters-and-capabilities/)
/// section for more details (TypeScript-oriented, but concepts apply here as well). /// section for more details (TypeScript-oriented, but concepts apply here as well).
#[must_use]
pub fn rtp_parameters(&self) -> &RtpParameters { pub fn rtp_parameters(&self) -> &RtpParameters {
&self.inner.rtp_parameters &self.inner.rtp_parameters
} }
/// Consumer type. /// Consumer type.
#[must_use]
pub fn r#type(&self) -> ConsumerType { pub fn r#type(&self) -> ConsumerType {
self.inner.r#type self.inner.r#type
} }
/// Whether the consumer is paused. It does not take into account whether the associated /// Whether the consumer is paused. It does not take into account whether the associated
/// producer is paused. /// producer is paused.
#[must_use]
pub fn paused(&self) -> bool { pub fn paused(&self) -> bool {
*self.inner.paused.lock() *self.inner.paused.lock()
} }
/// Whether the associate Producer is paused. /// Whether the associate Producer is paused.
#[must_use]
pub fn producer_paused(&self) -> bool { pub fn producer_paused(&self) -> bool {
*self.inner.producer_paused.lock() *self.inner.producer_paused.lock()
} }
/// Consumer priority (see [`Consumer::set_priority`] method). /// Consumer priority (see [`Consumer::set_priority`] method).
#[must_use]
pub fn priority(&self) -> u8 { pub fn priority(&self) -> u8 {
*self.inner.priority.lock() *self.inner.priority.lock()
} }
/// The score of the RTP stream being sent, representing its transmission quality. /// The score of the RTP stream being sent, representing its transmission quality.
#[must_use]
pub fn score(&self) -> ConsumerScore { pub fn score(&self) -> ConsumerScore {
self.inner.score.lock().clone() self.inner.score.lock().clone()
} }
/// Preferred spatial and temporal layers (see [`Consumer::set_preferred_layers`] method). For /// Preferred spatial and temporal layers (see [`Consumer::set_preferred_layers`] method). For
/// simulcast and SVC consumers, `None` otherwise. /// simulcast and SVC consumers, `None` otherwise.
#[must_use]
pub fn preferred_layers(&self) -> Option<ConsumerLayers> { pub fn preferred_layers(&self) -> Option<ConsumerLayers> {
*self.inner.preferred_layers.lock() *self.inner.preferred_layers.lock()
} }
...@@ -663,16 +665,19 @@ impl Consumer { ...@@ -663,16 +665,19 @@ impl Consumer {
/// Currently active spatial and temporal layers (for `Simulcast` and `SVC` consumers only). /// Currently active spatial and temporal layers (for `Simulcast` and `SVC` consumers only).
/// It's `None` if no layers are being sent to the consuming endpoint at this time (or if the /// It's `None` if no layers are being sent to the consuming endpoint at this time (or if the
/// consumer is consuming from a `Simulcast` or `SVC` producer). /// consumer is consuming from a `Simulcast` or `SVC` producer).
#[must_use]
pub fn current_layers(&self) -> Option<ConsumerLayers> { pub fn current_layers(&self) -> Option<ConsumerLayers> {
*self.inner.current_layers.lock() *self.inner.current_layers.lock()
} }
/// Custom application data. /// Custom application data.
#[must_use]
pub fn app_data(&self) -> &AppData { pub fn app_data(&self) -> &AppData {
&self.inner.app_data &self.inner.app_data
} }
/// Whether the consumer is closed. /// Whether the consumer is closed.
#[must_use]
pub fn closed(&self) -> bool { pub fn closed(&self) -> bool {
self.inner.closed.load(Ordering::SeqCst) self.inner.closed.load(Ordering::SeqCst)
} }
...@@ -935,6 +940,7 @@ impl Consumer { ...@@ -935,6 +940,7 @@ impl Consumer {
} }
/// Downgrade `Consumer` to [`WeakConsumer`] instance. /// Downgrade `Consumer` to [`WeakConsumer`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakConsumer { pub fn downgrade(&self) -> WeakConsumer {
WeakConsumer { WeakConsumer {
inner: Arc::downgrade(&self.inner), inner: Arc::downgrade(&self.inner),
...@@ -969,6 +975,7 @@ impl fmt::Debug for WeakConsumer { ...@@ -969,6 +975,7 @@ impl fmt::Debug for WeakConsumer {
impl WeakConsumer { impl WeakConsumer {
/// Attempts to upgrade `WeakConsumer` to [`Consumer`] if last instance of one wasn't dropped /// Attempts to upgrade `WeakConsumer` to [`Consumer`] if last instance of one wasn't dropped
/// yet. /// yet.
#[must_use]
pub fn upgrade(&self) -> Option<Consumer> { pub fn upgrade(&self) -> Option<Consumer> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A data consumer represents an endpoint capable of receiving data messages from a mediasoup
//! [`Router`](crate::router::Router).
//!
//! A data consumer can use [SCTP](https://tools.ietf.org/html/rfc4960) (AKA
//! DataChannel) to receive those messages, or can directly receive them in the Rust application if
//! the data consumer was created on top of a
//! [`DirectTransport`](crate::direct_transport::DirectTransport).
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -25,7 +17,7 @@ use crate::worker::{ ...@@ -25,7 +17,7 @@ use crate::worker::{
}; };
use async_executor::Executor; use async_executor::Executor;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
...@@ -34,15 +26,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; ...@@ -34,15 +26,15 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
uuid_based_wrapper_type!( uuid_based_wrapper_type!(
/// Data consumer identifier. /// [`DataConsumer`] identifier.
DataConsumerId DataConsumerId
); );
/// Data consumer options. /// [`DataConsumer`] options.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct DataConsumerOptions { pub struct DataConsumerOptions {
// The id of the DataProducer to consume. // The id of the [`DataProducer`](crate::data_producer::DataProducer) to consume.
pub(super) data_producer_id: DataProducerId, pub(super) data_producer_id: DataProducerId,
/// Just if consuming over SCTP. /// Just if consuming over SCTP.
/// Whether data messages must be received in order. If true the messages will be sent reliably. /// Whether data messages must be received in order. If true the messages will be sent reliably.
...@@ -57,15 +49,17 @@ pub struct DataConsumerOptions { ...@@ -57,15 +49,17 @@ pub struct DataConsumerOptions {
pub(super) max_packet_life_time: Option<u16>, pub(super) max_packet_life_time: Option<u16>,
/// Just if consuming over SCTP. /// Just if consuming over SCTP.
/// When ordered is false indicates the maximum number of times a packet will be retransmitted. /// When ordered is false indicates the maximum number of times a packet will be retransmitted.
/// Defaults to the value in the DataProducer if it has type `Sctp` or unset if it has type /// Defaults to the value in the [`DataProducer`](crate::data_producer::DataProducer) if it
/// `Direct`. /// has type `Sctp` or unset if it has type `Direct`.
pub(super) max_retransmits: Option<u16>, pub(super) max_retransmits: Option<u16>,
/// Custom application data. /// Custom application data.
pub app_data: AppData, pub app_data: AppData,
} }
impl DataConsumerOptions { impl DataConsumerOptions {
/// Inherits parameters of corresponding DataProducer. /// Inherits parameters of corresponding
/// [`DataProducer`](crate::data_producer::DataProducer).
#[must_use]
pub fn new_sctp(data_producer_id: DataProducerId) -> Self { pub fn new_sctp(data_producer_id: DataProducerId) -> Self {
Self { Self {
data_producer_id, data_producer_id,
...@@ -76,7 +70,8 @@ impl DataConsumerOptions { ...@@ -76,7 +70,8 @@ impl DataConsumerOptions {
} }
} }
/// For DirectTransport. /// For [`DirectTransport`](crate::direct_transport::DirectTransport).
#[must_use]
pub fn new_direct(data_producer_id: DataProducerId) -> Self { pub fn new_direct(data_producer_id: DataProducerId) -> Self {
Self { Self {
data_producer_id, data_producer_id,
...@@ -88,6 +83,7 @@ impl DataConsumerOptions { ...@@ -88,6 +83,7 @@ impl DataConsumerOptions {
} }
/// Messages will be sent reliably in order. /// Messages will be sent reliably in order.
#[must_use]
pub fn new_sctp_ordered(data_producer_id: DataProducerId) -> Self { pub fn new_sctp_ordered(data_producer_id: DataProducerId) -> Self {
Self { Self {
data_producer_id, data_producer_id,
...@@ -100,6 +96,7 @@ impl DataConsumerOptions { ...@@ -100,6 +96,7 @@ impl DataConsumerOptions {
/// Messages will be sent unreliably with time (in milliseconds) after which a SCTP packet will /// Messages will be sent unreliably with time (in milliseconds) after which a SCTP packet will
/// stop being retransmitted. /// stop being retransmitted.
#[must_use]
pub fn new_sctp_unordered_with_life_time( pub fn new_sctp_unordered_with_life_time(
data_producer_id: DataProducerId, data_producer_id: DataProducerId,
max_packet_life_time: u16, max_packet_life_time: u16,
...@@ -114,6 +111,7 @@ impl DataConsumerOptions { ...@@ -114,6 +111,7 @@ impl DataConsumerOptions {
} }
/// Messages will be sent unreliably with a limited number of retransmission attempts. /// Messages will be sent unreliably with a limited number of retransmission attempts.
#[must_use]
pub fn new_sctp_unordered_with_retransmits( pub fn new_sctp_unordered_with_retransmits(
data_producer_id: DataProducerId, data_producer_id: DataProducerId,
max_retransmits: u16, max_retransmits: u16,
...@@ -257,6 +255,7 @@ impl Inner { ...@@ -257,6 +255,7 @@ impl Inner {
/// Data consumer created on transport other than /// Data consumer created on transport other than
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Data consumer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct RegularDataConsumer { pub struct RegularDataConsumer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -284,6 +283,7 @@ impl From<RegularDataConsumer> for DataConsumer { ...@@ -284,6 +283,7 @@ impl From<RegularDataConsumer> for DataConsumer {
/// Data consumer created on [`DirectTransport`](crate::direct_transport::DirectTransport). /// Data consumer created on [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Data consumer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct DirectDataConsumer { pub struct DirectDataConsumer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -318,6 +318,7 @@ impl From<DirectDataConsumer> for DataConsumer { ...@@ -318,6 +318,7 @@ impl From<DirectDataConsumer> for DataConsumer {
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[non_exhaustive] #[non_exhaustive]
#[must_use = "Data consumer will be closed on drop, make sure to keep it around for as long as needed"]
pub enum DataConsumer { pub enum DataConsumer {
/// Data consumer created on transport other than /// Data consumer created on transport other than
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
...@@ -365,10 +366,7 @@ impl DataConsumer { ...@@ -365,10 +366,7 @@ impl DataConsumer {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::DataProducerClose => { Notification::DataProducerClose => {
handlers.data_producer_close.call_simple(); handlers.data_producer_close.call_simple();
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade)
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{ {
inner.close(false); inner.close(false);
} }
...@@ -420,11 +418,7 @@ impl DataConsumer { ...@@ -420,11 +418,7 @@ impl DataConsumer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
Box::new(move || { Box::new(move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.transport_close.call_simple(); inner.handlers.transport_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -459,41 +453,49 @@ impl DataConsumer { ...@@ -459,41 +453,49 @@ impl DataConsumer {
} }
/// Data consumer identifier. /// Data consumer identifier.
#[must_use]
pub fn id(&self) -> DataConsumerId { pub fn id(&self) -> DataConsumerId {
self.inner().id self.inner().id
} }
/// The associated data producer identifier. /// The associated data producer identifier.
#[must_use]
pub fn data_producer_id(&self) -> DataProducerId { pub fn data_producer_id(&self) -> DataProducerId {
self.inner().data_producer_id self.inner().data_producer_id
} }
/// The type of the data consumer. /// The type of the data consumer.
#[must_use]
pub fn r#type(&self) -> DataConsumerType { pub fn r#type(&self) -> DataConsumerType {
self.inner().r#type self.inner().r#type
} }
/// The SCTP stream parameters (just if the data consumer type is `Sctp`). /// The SCTP stream parameters (just if the data consumer type is `Sctp`).
#[must_use]
pub fn sctp_stream_parameters(&self) -> Option<SctpStreamParameters> { pub fn sctp_stream_parameters(&self) -> Option<SctpStreamParameters> {
self.inner().sctp_stream_parameters self.inner().sctp_stream_parameters
} }
/// The data consumer label. /// The data consumer label.
#[must_use]
pub fn label(&self) -> &String { pub fn label(&self) -> &String {
&self.inner().label &self.inner().label
} }
/// The data consumer sub-protocol. /// The data consumer sub-protocol.
#[must_use]
pub fn protocol(&self) -> &String { pub fn protocol(&self) -> &String {
&self.inner().protocol &self.inner().protocol
} }
/// Custom application data. /// Custom application data.
#[must_use]
pub fn app_data(&self) -> &AppData { pub fn app_data(&self) -> &AppData {
&self.inner().app_data &self.inner().app_data
} }
/// Whether the data consumer is closed. /// Whether the data consumer is closed.
#[must_use]
pub fn closed(&self) -> bool { pub fn closed(&self) -> bool {
self.inner().closed.load(Ordering::SeqCst) self.inner().closed.load(Ordering::SeqCst)
} }
...@@ -635,6 +637,7 @@ impl DataConsumer { ...@@ -635,6 +637,7 @@ impl DataConsumer {
} }
/// Downgrade `DataConsumer` to [`WeakDataConsumer`] instance. /// Downgrade `DataConsumer` to [`WeakDataConsumer`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakDataConsumer { pub fn downgrade(&self) -> WeakDataConsumer {
WeakDataConsumer { WeakDataConsumer {
inner: Arc::downgrade(&self.inner()), inner: Arc::downgrade(&self.inner()),
...@@ -699,6 +702,7 @@ impl fmt::Debug for WeakDataConsumer { ...@@ -699,6 +702,7 @@ impl fmt::Debug for WeakDataConsumer {
impl WeakDataConsumer { impl WeakDataConsumer {
/// Attempts to upgrade `WeakDataConsumer` to [`DataConsumer`] if last instance of one wasn't /// Attempts to upgrade `WeakDataConsumer` to [`DataConsumer`] if last instance of one wasn't
/// dropped yet. /// dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<DataConsumer> { pub fn upgrade(&self) -> Option<DataConsumer> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A data producer represents an endpoint capable of injecting data messages into a mediasoup
//! [`Router`](crate::router::Router).
//!
//! A data producer can use [SCTP](https://tools.ietf.org/html/rfc4960) (AKA DataChannel) to deliver
//! those messages, or can directly send them from the Rust application if the data producer was
//! created on top of a [`DirectTransport`](crate::direct_transport::DirectTransport).
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -19,7 +12,7 @@ use crate::uuid_based_wrapper_type; ...@@ -19,7 +12,7 @@ use crate::uuid_based_wrapper_type;
use crate::worker::{Channel, NotificationError, PayloadChannel, RequestError}; use crate::worker::{Channel, NotificationError, PayloadChannel, RequestError};
use async_executor::Executor; use async_executor::Executor;
use event_listener_primitives::{BagOnce, HandlerId}; use event_listener_primitives::{BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
...@@ -28,11 +21,11 @@ use std::sync::atomic::{AtomicBool, Ordering}; ...@@ -28,11 +21,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
uuid_based_wrapper_type!( uuid_based_wrapper_type!(
/// Data producer identifier. /// [`DataProducer`] identifier.
DataProducerId DataProducerId
); );
/// Data producer options. /// [`DataProducer`] options.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct DataProducerOptions { pub struct DataProducerOptions {
...@@ -53,6 +46,7 @@ pub struct DataProducerOptions { ...@@ -53,6 +46,7 @@ pub struct DataProducerOptions {
} }
impl DataProducerOptions { impl DataProducerOptions {
#[must_use]
pub(super) fn new_pipe_transport( pub(super) fn new_pipe_transport(
data_producer_id: DataProducerId, data_producer_id: DataProducerId,
sctp_stream_parameters: SctpStreamParameters, sctp_stream_parameters: SctpStreamParameters,
...@@ -67,6 +61,7 @@ impl DataProducerOptions { ...@@ -67,6 +61,7 @@ impl DataProducerOptions {
} }
/// Data producer options for non-Direct transport. /// Data producer options for non-Direct transport.
#[must_use]
pub fn new_sctp(sctp_stream_parameters: SctpStreamParameters) -> Self { pub fn new_sctp(sctp_stream_parameters: SctpStreamParameters) -> Self {
Self { Self {
id: None, id: None,
...@@ -78,6 +73,7 @@ impl DataProducerOptions { ...@@ -78,6 +73,7 @@ impl DataProducerOptions {
} }
/// Data producer options for Direct transport. /// Data producer options for Direct transport.
#[must_use]
pub fn new_direct() -> Self { pub fn new_direct() -> Self {
Self { Self {
id: None, id: None,
...@@ -190,6 +186,7 @@ impl Inner { ...@@ -190,6 +186,7 @@ impl Inner {
/// Data producer created on transport other than /// Data producer created on transport other than
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Data producer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct RegularDataProducer { pub struct RegularDataProducer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -216,6 +213,7 @@ impl From<RegularDataProducer> for DataProducer { ...@@ -216,6 +213,7 @@ impl From<RegularDataProducer> for DataProducer {
/// Data producer created on [`DirectTransport`](crate::direct_transport::DirectTransport). /// Data producer created on [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Data producer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct DirectDataProducer { pub struct DirectDataProducer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -248,6 +246,7 @@ impl From<DirectDataProducer> for DataProducer { ...@@ -248,6 +246,7 @@ impl From<DirectDataProducer> for DataProducer {
/// created on top of a [`DirectTransport`](crate::direct_transport::DirectTransport). /// created on top of a [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[non_exhaustive] #[non_exhaustive]
#[must_use = "Data producer will be closed on drop, make sure to keep it around for as long as needed"]
pub enum DataProducer { pub enum DataProducer {
/// Data producer created on transport other than /// Data producer created on transport other than
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
...@@ -289,11 +288,7 @@ impl DataProducer { ...@@ -289,11 +288,7 @@ impl DataProducer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
Box::new(move || { Box::new(move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.transport_close.call_simple(); inner.handlers.transport_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -326,36 +321,43 @@ impl DataProducer { ...@@ -326,36 +321,43 @@ impl DataProducer {
} }
/// Data producer identifier. /// Data producer identifier.
#[must_use]
pub fn id(&self) -> DataProducerId { pub fn id(&self) -> DataProducerId {
self.inner().id self.inner().id
} }
/// The type of the data producer. /// The type of the data producer.
#[must_use]
pub fn r#type(&self) -> DataProducerType { pub fn r#type(&self) -> DataProducerType {
self.inner().r#type self.inner().r#type
} }
/// The SCTP stream parameters (just if the data producer type is `Sctp`). /// The SCTP stream parameters (just if the data producer type is `Sctp`).
#[must_use]
pub fn sctp_stream_parameters(&self) -> Option<SctpStreamParameters> { pub fn sctp_stream_parameters(&self) -> Option<SctpStreamParameters> {
self.inner().sctp_stream_parameters self.inner().sctp_stream_parameters
} }
/// The data producer label. /// The data producer label.
#[must_use]
pub fn label(&self) -> &String { pub fn label(&self) -> &String {
&self.inner().label &self.inner().label
} }
/// The data producer sub-protocol. /// The data producer sub-protocol.
#[must_use]
pub fn protocol(&self) -> &String { pub fn protocol(&self) -> &String {
&self.inner().protocol &self.inner().protocol
} }
/// Custom application data. /// Custom application data.
#[must_use]
pub fn app_data(&self) -> &AppData { pub fn app_data(&self) -> &AppData {
&self.inner().app_data &self.inner().app_data
} }
/// Whether the data producer is closed. /// Whether the data producer is closed.
#[must_use]
pub fn closed(&self) -> bool { pub fn closed(&self) -> bool {
self.inner().closed.load(Ordering::SeqCst) self.inner().closed.load(Ordering::SeqCst)
} }
...@@ -414,6 +416,7 @@ impl DataProducer { ...@@ -414,6 +416,7 @@ impl DataProducer {
} }
/// Downgrade `DataProducer` to [`WeakDataProducer`] instance. /// Downgrade `DataProducer` to [`WeakDataProducer`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakDataProducer { pub fn downgrade(&self) -> WeakDataProducer {
WeakDataProducer { WeakDataProducer {
inner: Arc::downgrade(&self.inner()), inner: Arc::downgrade(&self.inner()),
...@@ -522,6 +525,7 @@ impl fmt::Debug for WeakDataProducer { ...@@ -522,6 +525,7 @@ impl fmt::Debug for WeakDataProducer {
impl WeakDataProducer { impl WeakDataProducer {
/// Attempts to upgrade `WeakDataProducer` to [`DataProducer`] if last instance of one wasn't /// Attempts to upgrade `WeakDataProducer` to [`DataProducer`] if last instance of one wasn't
/// dropped yet. /// dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<DataProducer> { pub fn upgrade(&self) -> Option<DataProducer> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A direct transport represents a direct connection between the mediasoup Rust process and a
//! [`Router`] instance in a mediasoup-worker thread.
//!
//! A direct transport can be used to directly send and receive data messages from/to Rust by means
//! of [`DataProducer`]s and [`DataConsumer`]s of type `Direct` created on a direct transport.
//! Direct messages sent by a [`DataProducer`] in a direct transport can be consumed by endpoints
//! connected through a SCTP capable transport ([`WebRtcTransport`](crate::webrtc_transport::WebRtcTransport),
//! [`PlainTransport`](crate::plain_transport::PlainTransport), [`PipeTransport`](crate::pipe_transport::PipeTransport)
//! and also by the Rust application by means of a [`DataConsumer`] created on a [`DirectTransport`]
//! (and vice-versa: messages sent over SCTP/DataChannel can be consumed by the Rust application by
//! means of a [`DataConsumer`] created on a [`DirectTransport`]).
//!
//! A direct transport can also be used to inject and directly consume RTP and RTCP packets in Rust
//! by using the [`DirectProducer::send`](crate::producer::DirectProducer::send) and
//! [`Consumer::on_rtp`] API (plus [`DirectTransport::send_rtcp`] and [`DirectTransport::on_rtcp`]
//! API).
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -24,12 +7,13 @@ use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, Da ...@@ -24,12 +7,13 @@ use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, Da
use crate::data_structures::{AppData, SctpState}; use crate::data_structures::{AppData, SctpState};
use crate::messages::{TransportCloseRequest, TransportInternal, TransportSendRtcpNotification}; use crate::messages::{TransportCloseRequest, TransportInternal, TransportSendRtcpNotification};
use crate::producer::{Producer, ProducerId, ProducerOptions}; use crate::producer::{Producer, ProducerId, ProducerOptions};
use crate::router::transport::{TransportImpl, TransportType};
use crate::router::{Router, RouterId}; use crate::router::{Router, RouterId};
use crate::sctp_parameters::SctpParameters; use crate::sctp_parameters::SctpParameters;
use crate::transport::{ use crate::transport::{
ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions, ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions,
RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportImpl, RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportTraceEventData,
TransportTraceEventData, TransportTraceEventType, TransportType, TransportTraceEventType,
}; };
use crate::worker::{ use crate::worker::{
Channel, NotificationError, NotificationMessage, PayloadChannel, RequestError, Channel, NotificationError, NotificationMessage, PayloadChannel, RequestError,
...@@ -39,7 +23,7 @@ use async_executor::Executor; ...@@ -39,7 +23,7 @@ use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use bytes::Bytes; use bytes::Bytes;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
...@@ -47,7 +31,7 @@ use std::fmt; ...@@ -47,7 +31,7 @@ use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
/// Direct transport options. /// [`DirectTransport`] options.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct DirectTransportOptions { pub struct DirectTransportOptions {
...@@ -220,6 +204,7 @@ impl Inner { ...@@ -220,6 +204,7 @@ impl Inner {
/// [`Consumer::on_rtp`] API (plus [`DirectTransport::send_rtcp`] and [`DirectTransport::on_rtcp`] /// [`Consumer::on_rtp`] API (plus [`DirectTransport::send_rtcp`] and [`DirectTransport::on_rtcp`]
/// API). /// API).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Transport will be closed on drop, make sure to keep it around for as long as needed"]
pub struct DirectTransport { pub struct DirectTransport {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -510,11 +495,7 @@ impl DirectTransport { ...@@ -510,11 +495,7 @@ impl DirectTransport {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
move || { move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.router_close.call_simple(); inner.handlers.router_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -562,6 +543,7 @@ impl DirectTransport { ...@@ -562,6 +543,7 @@ impl DirectTransport {
} }
/// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance. /// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakDirectTransport { pub fn downgrade(&self) -> WeakDirectTransport {
WeakDirectTransport { WeakDirectTransport {
inner: Arc::downgrade(&self.inner), inner: Arc::downgrade(&self.inner),
...@@ -594,6 +576,7 @@ impl fmt::Debug for WeakDirectTransport { ...@@ -594,6 +576,7 @@ impl fmt::Debug for WeakDirectTransport {
impl WeakDirectTransport { impl WeakDirectTransport {
/// Attempts to upgrade `WeakDirectTransport` to [`DirectTransport`] if last instance of one /// Attempts to upgrade `WeakDirectTransport` to [`DirectTransport`] if last instance of one
/// wasn't dropped yet. /// wasn't dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<DirectTransport> { pub fn upgrade(&self) -> Option<DirectTransport> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A pipe transport represents a network path through which RTP, RTCP (optionally secured with
//! SRTP) and SCTP (DataChannel) is transmitted. Pipe transports are intended to intercommunicate
//! two [`Router`] instances collocated on the same host or on separate hosts.
//!
//! # Notes on usage
//! When calling [`PipeTransport::consume`], all RTP streams of the [`Producer`] are transmitted
//! verbatim (in contrast to what happens in [`WebRtcTransport`](crate::webrtc_transport::WebRtcTransport)
//! and [`PlainTransport`](crate::plain_transport::PlainTransport) in which a single and continuous
//! RTP stream is sent to the consuming endpoint).
use crate::consumer::{Consumer, ConsumerId, ConsumerOptions}; use crate::consumer::{Consumer, ConsumerId, ConsumerOptions};
use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, DataConsumerType}; use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, DataConsumerType};
use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, DataProducerType}; use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, DataProducerType};
...@@ -17,19 +7,20 @@ use crate::messages::{ ...@@ -17,19 +7,20 @@ use crate::messages::{
TransportConnectRequestPipeData, TransportInternal, TransportConnectRequestPipeData, TransportInternal,
}; };
use crate::producer::{Producer, ProducerId, ProducerOptions}; use crate::producer::{Producer, ProducerId, ProducerOptions};
use crate::router::transport::{TransportImpl, TransportType};
use crate::router::{Router, RouterId}; use crate::router::{Router, RouterId};
use crate::sctp_parameters::{NumSctpStreams, SctpParameters}; use crate::sctp_parameters::{NumSctpStreams, SctpParameters};
use crate::srtp_parameters::SrtpParameters; use crate::srtp_parameters::SrtpParameters;
use crate::transport::{ use crate::transport::{
ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions, ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions,
RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportImpl, RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportTraceEventData,
TransportTraceEventData, TransportTraceEventType, TransportType, TransportTraceEventType,
}; };
use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler}; use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
use async_executor::Executor; use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
...@@ -38,7 +29,7 @@ use std::net::IpAddr; ...@@ -38,7 +29,7 @@ use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
/// Pipe transport options. /// [`PipeTransport`] options.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct PipeTransportOptions { pub struct PipeTransportOptions {
...@@ -70,6 +61,7 @@ pub struct PipeTransportOptions { ...@@ -70,6 +61,7 @@ pub struct PipeTransportOptions {
impl PipeTransportOptions { impl PipeTransportOptions {
/// Create Pipe transport options with given listen IP. /// Create Pipe transport options with given listen IP.
#[must_use]
pub fn new(listen_ip: TransportListenIp) -> Self { pub fn new(listen_ip: TransportListenIp) -> Self {
Self { Self {
listen_ip, listen_ip,
...@@ -248,6 +240,7 @@ impl Inner { ...@@ -248,6 +240,7 @@ impl Inner {
/// and [`PlainTransport`](crate::plain_transport::PlainTransport) in which a single and continuous /// and [`PlainTransport`](crate::plain_transport::PlainTransport) in which a single and continuous
/// RTP stream is sent to the consuming endpoint). /// RTP stream is sent to the consuming endpoint).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Transport will be closed on drop, make sure to keep it around for as long as needed"]
pub struct PipeTransport { pub struct PipeTransport {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -517,11 +510,7 @@ impl PipeTransport { ...@@ -517,11 +510,7 @@ impl PipeTransport {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
move || { move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.router_close.call_simple(); inner.handlers.router_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -549,7 +538,7 @@ impl PipeTransport { ...@@ -549,7 +538,7 @@ impl PipeTransport {
Self { inner } Self { inner }
} }
/// Provide the PipeTransport with remote parameters. /// Provide the [`PipeTransport`] with remote parameters.
pub async fn connect( pub async fn connect(
&self, &self,
remote_parameters: PipeTransportRemoteParameters, remote_parameters: PipeTransportRemoteParameters,
...@@ -590,16 +579,19 @@ impl PipeTransport { ...@@ -590,16 +579,19 @@ impl PipeTransport {
/// its `local_ip`, `local_port` and `protocol`. /// its `local_ip`, `local_port` and `protocol`.
/// * Information about `remote_ip` and `remote_port` will be set after calling `connect()` /// * Information about `remote_ip` and `remote_port` will be set after calling `connect()`
/// method. /// method.
#[must_use]
pub fn tuple(&self) -> TransportTuple { pub fn tuple(&self) -> TransportTuple {
*self.inner.data.tuple.lock() *self.inner.data.tuple.lock()
} }
/// Local SCTP parameters. Or `None` if SCTP is not enabled. /// Local SCTP parameters. Or `None` if SCTP is not enabled.
#[must_use]
pub fn sctp_parameters(&self) -> Option<SctpParameters> { pub fn sctp_parameters(&self) -> Option<SctpParameters> {
self.inner.data.sctp_parameters self.inner.data.sctp_parameters
} }
/// Current SCTP state. Or `None` if SCTP is not enabled. /// Current SCTP state. Or `None` if SCTP is not enabled.
#[must_use]
pub fn sctp_state(&self) -> Option<SctpState> { pub fn sctp_state(&self) -> Option<SctpState> {
*self.inner.data.sctp_state.lock() *self.inner.data.sctp_state.lock()
} }
...@@ -607,6 +599,7 @@ impl PipeTransport { ...@@ -607,6 +599,7 @@ impl PipeTransport {
/// Local SRTP parameters representing the crypto suite and key material used to encrypt sending /// Local SRTP parameters representing the crypto suite and key material used to encrypt sending
/// RTP and SRTP. Those parameters must be given to the paired `PipeTransport` in the /// RTP and SRTP. Those parameters must be given to the paired `PipeTransport` in the
/// `connect()` method. /// `connect()` method.
#[must_use]
pub fn srtp_parameters(&self) -> Option<SrtpParameters> { pub fn srtp_parameters(&self) -> Option<SrtpParameters> {
self.inner.data.srtp_parameters.lock().clone() self.inner.data.srtp_parameters.lock().clone()
} }
...@@ -632,6 +625,7 @@ impl PipeTransport { ...@@ -632,6 +625,7 @@ impl PipeTransport {
} }
/// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance. /// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakPipeTransport { pub fn downgrade(&self) -> WeakPipeTransport {
WeakPipeTransport { WeakPipeTransport {
inner: Arc::downgrade(&self.inner), inner: Arc::downgrade(&self.inner),
...@@ -664,6 +658,7 @@ impl fmt::Debug for WeakPipeTransport { ...@@ -664,6 +658,7 @@ impl fmt::Debug for WeakPipeTransport {
impl WeakPipeTransport { impl WeakPipeTransport {
/// Attempts to upgrade `WeakPipeTransport` to [`PipeTransport`] if last instance of one /// Attempts to upgrade `WeakPipeTransport` to [`PipeTransport`] if last instance of one
/// wasn't dropped yet. /// wasn't dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<PipeTransport> { pub fn upgrade(&self) -> Option<PipeTransport> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A plain transport represents a network path through which RTP, RTCP (optionally secured with
//! SRTP) and SCTP (DataChannel) is transmitted.
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -13,19 +10,20 @@ use crate::messages::{ ...@@ -13,19 +10,20 @@ use crate::messages::{
TransportConnectRequestPlainData, TransportInternal, TransportConnectRequestPlainData, TransportInternal,
}; };
use crate::producer::{Producer, ProducerId, ProducerOptions}; use crate::producer::{Producer, ProducerId, ProducerOptions};
use crate::router::transport::{TransportImpl, TransportType};
use crate::router::{Router, RouterId}; use crate::router::{Router, RouterId};
use crate::sctp_parameters::{NumSctpStreams, SctpParameters}; use crate::sctp_parameters::{NumSctpStreams, SctpParameters};
use crate::srtp_parameters::{SrtpCryptoSuite, SrtpParameters}; use crate::srtp_parameters::{SrtpCryptoSuite, SrtpParameters};
use crate::transport::{ use crate::transport::{
ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions, ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions,
RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportImpl, RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportTraceEventData,
TransportTraceEventData, TransportTraceEventType, TransportType, TransportTraceEventType,
}; };
use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler}; use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
use async_executor::Executor; use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
...@@ -34,7 +32,7 @@ use std::net::IpAddr; ...@@ -34,7 +32,7 @@ use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
/// Plain transport options. /// [`PlainTransport`] options.
/// ///
/// # Notes on usage /// # Notes on usage
/// * Note that `comedia` mode just makes sense when the remote endpoint is gonna produce RTP on /// * Note that `comedia` mode just makes sense when the remote endpoint is gonna produce RTP on
...@@ -80,6 +78,7 @@ pub struct PlainTransportOptions { ...@@ -80,6 +78,7 @@ pub struct PlainTransportOptions {
impl PlainTransportOptions { impl PlainTransportOptions {
/// Create Plain transport options with given listen IP. /// Create Plain transport options with given listen IP.
#[must_use]
pub fn new(listen_ip: TransportListenIp) -> Self { pub fn new(listen_ip: TransportListenIp) -> Self {
Self { Self {
listen_ip, listen_ip,
...@@ -87,8 +86,8 @@ impl PlainTransportOptions { ...@@ -87,8 +86,8 @@ impl PlainTransportOptions {
comedia: false, comedia: false,
enable_sctp: false, enable_sctp: false,
num_sctp_streams: NumSctpStreams::default(), num_sctp_streams: NumSctpStreams::default(),
max_sctp_message_size: 262144, max_sctp_message_size: 262_144,
sctp_send_buffer_size: 262144, sctp_send_buffer_size: 262_144,
enable_srtp: false, enable_srtp: false,
srtp_crypto_suite: SrtpCryptoSuite::default(), srtp_crypto_suite: SrtpCryptoSuite::default(),
app_data: AppData::default(), app_data: AppData::default(),
...@@ -270,6 +269,7 @@ impl Inner { ...@@ -270,6 +269,7 @@ impl Inner {
/// A plain transport represents a network path through which RTP, RTCP (optionally secured with /// A plain transport represents a network path through which RTP, RTCP (optionally secured with
/// SRTP) and SCTP (DataChannel) is transmitted. /// SRTP) and SCTP (DataChannel) is transmitted.
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Transport will be closed on drop, make sure to keep it around for as long as needed"]
pub struct PlainTransport { pub struct PlainTransport {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -553,11 +553,7 @@ impl PlainTransport { ...@@ -553,11 +553,7 @@ impl PlainTransport {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
move || { move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.router_close.call_simple(); inner.handlers.router_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -585,7 +581,7 @@ impl PlainTransport { ...@@ -585,7 +581,7 @@ impl PlainTransport {
Self { inner } Self { inner }
} }
/// Provide the PlainTransport with remote parameters. /// Provide the [`PlainTransport`] with remote parameters.
/// ///
/// # Notes on usage /// # Notes on usage
/// * If `comedia` is enabled in this plain transport and SRTP is not, `connect()` must not be /// * If `comedia` is enabled in this plain transport and SRTP is not, `connect()` must not be
...@@ -737,6 +733,7 @@ impl PlainTransport { ...@@ -737,6 +733,7 @@ impl PlainTransport {
/// * Information about `remote_ip` and `remote_port` will be set: /// * Information about `remote_ip` and `remote_port` will be set:
/// * after calling `connect()` method, or /// * after calling `connect()` method, or
/// * via dynamic remote address detection when using `comedia` mode. /// * via dynamic remote address detection when using `comedia` mode.
#[must_use]
pub fn tuple(&self) -> TransportTuple { pub fn tuple(&self) -> TransportTuple {
*self.inner.data.tuple.lock() *self.inner.data.tuple.lock()
} }
...@@ -750,16 +747,19 @@ impl PlainTransport { ...@@ -750,16 +747,19 @@ impl PlainTransport {
/// * Information about `remote_ip` and `remote_port` will be set: /// * Information about `remote_ip` and `remote_port` will be set:
/// * after calling `connect()` method, or /// * after calling `connect()` method, or
/// * via dynamic remote address detection when using `comedia` mode. /// * via dynamic remote address detection when using `comedia` mode.
#[must_use]
pub fn rtcp_tuple(&self) -> Option<TransportTuple> { pub fn rtcp_tuple(&self) -> Option<TransportTuple> {
*self.inner.data.rtcp_tuple.lock() *self.inner.data.rtcp_tuple.lock()
} }
/// Current SCTP state. Or `None` if SCTP is not enabled. /// Current SCTP state. Or `None` if SCTP is not enabled.
#[must_use]
pub fn sctp_parameters(&self) -> Option<SctpParameters> { pub fn sctp_parameters(&self) -> Option<SctpParameters> {
self.inner.data.sctp_parameters self.inner.data.sctp_parameters
} }
/// Current SCTP state. Or `None` if SCTP is not enabled. /// Current SCTP state. Or `None` if SCTP is not enabled.
#[must_use]
pub fn sctp_state(&self) -> Option<SctpState> { pub fn sctp_state(&self) -> Option<SctpState> {
*self.inner.data.sctp_state.lock() *self.inner.data.sctp_state.lock()
} }
...@@ -768,6 +768,7 @@ impl PlainTransport { ...@@ -768,6 +768,7 @@ impl PlainTransport {
/// RTP and SRTP. Note that, if `comedia` mode is set, these local SRTP parameters may change /// RTP and SRTP. Note that, if `comedia` mode is set, these local SRTP parameters may change
/// after calling `connect()` with the remote SRTP parameters (to override the local SRTP crypto /// after calling `connect()` with the remote SRTP parameters (to override the local SRTP crypto
/// suite with the one given in `connect()`). /// suite with the one given in `connect()`).
#[must_use]
pub fn srtp_parameters(&self) -> Option<SrtpParameters> { pub fn srtp_parameters(&self) -> Option<SrtpParameters> {
self.inner.data.srtp_parameters.lock().clone() self.inner.data.srtp_parameters.lock().clone()
} }
...@@ -802,6 +803,7 @@ impl PlainTransport { ...@@ -802,6 +803,7 @@ impl PlainTransport {
} }
/// Downgrade `PlainTransport` to [`WeakPlainTransport`] instance. /// Downgrade `PlainTransport` to [`WeakPlainTransport`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakPlainTransport { pub fn downgrade(&self) -> WeakPlainTransport {
WeakPlainTransport { WeakPlainTransport {
inner: Arc::downgrade(&self.inner), inner: Arc::downgrade(&self.inner),
...@@ -834,6 +836,7 @@ impl fmt::Debug for WeakPlainTransport { ...@@ -834,6 +836,7 @@ impl fmt::Debug for WeakPlainTransport {
impl WeakPlainTransport { impl WeakPlainTransport {
/// Attempts to upgrade `WeakPlainTransport` to [`PlainTransport`] if last instance of one /// Attempts to upgrade `WeakPlainTransport` to [`PlainTransport`] if last instance of one
/// wasn't dropped yet. /// wasn't dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<PlainTransport> { pub fn upgrade(&self) -> Option<PlainTransport> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! A producer represents an audio or video source being injected into a mediasoup router. It's
//! created on top of a transport that defines how the media packets are carried.
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -21,7 +18,7 @@ use crate::worker::{ ...@@ -21,7 +18,7 @@ use crate::worker::{
use async_executor::Executor; use async_executor::Executor;
use bytes::Bytes; use bytes::Bytes;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
...@@ -33,11 +30,11 @@ use std::sync::atomic::{AtomicBool, Ordering}; ...@@ -33,11 +30,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
uuid_based_wrapper_type!( uuid_based_wrapper_type!(
/// Producer identifier. /// [`Producer`] identifier.
ProducerId ProducerId
); );
/// Producer options. /// [`Producer`] options.
/// ///
/// # Notes on usage /// # Notes on usage
/// Check the /// Check the
...@@ -65,6 +62,7 @@ pub struct ProducerOptions { ...@@ -65,6 +62,7 @@ pub struct ProducerOptions {
impl ProducerOptions { impl ProducerOptions {
/// Create producer options that will be used with Pipe transport /// Create producer options that will be used with Pipe transport
#[must_use]
pub fn new_pipe_transport( pub fn new_pipe_transport(
producer_id: ProducerId, producer_id: ProducerId,
kind: MediaKind, kind: MediaKind,
...@@ -81,6 +79,7 @@ impl ProducerOptions { ...@@ -81,6 +79,7 @@ impl ProducerOptions {
} }
/// Create producer options that will be used with non-Pipe transport /// Create producer options that will be used with non-Pipe transport
#[must_use]
pub fn new(kind: MediaKind, rtp_parameters: RtpParameters) -> Self { pub fn new(kind: MediaKind, rtp_parameters: RtpParameters) -> Self {
Self { Self {
id: None, id: None,
...@@ -362,6 +361,7 @@ impl Inner { ...@@ -362,6 +361,7 @@ impl Inner {
/// Producer created on transport other than /// Producer created on transport other than
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Producer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct RegularProducer { pub struct RegularProducer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -393,6 +393,7 @@ impl From<RegularProducer> for Producer { ...@@ -393,6 +393,7 @@ impl From<RegularProducer> for Producer {
/// Producer created on [`DirectTransport`](crate::direct_transport::DirectTransport). /// Producer created on [`DirectTransport`](crate::direct_transport::DirectTransport).
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Producer will be closed on drop, make sure to keep it around for as long as needed"]
pub struct DirectProducer { pub struct DirectProducer {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -426,6 +427,7 @@ impl From<DirectProducer> for Producer { ...@@ -426,6 +427,7 @@ impl From<DirectProducer> for Producer {
/// created on top of a transport that defines how the media packets are carried. /// created on top of a transport that defines how the media packets are carried.
#[derive(Clone)] #[derive(Clone)]
#[non_exhaustive] #[non_exhaustive]
#[must_use = "Producer will be closed on drop, make sure to keep it around for as long as needed"]
pub enum Producer { pub enum Producer {
/// Producer created on transport other than /// Producer created on transport other than
/// [`DirectTransport`](crate::direct_transport::DirectTransport). /// [`DirectTransport`](crate::direct_transport::DirectTransport).
...@@ -500,11 +502,7 @@ impl Producer { ...@@ -500,11 +502,7 @@ impl Producer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
Box::new(move || { Box::new(move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.transport_close.call_simple(); inner.handlers.transport_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -540,11 +538,13 @@ impl Producer { ...@@ -540,11 +538,13 @@ impl Producer {
} }
/// Producer identifier. /// Producer identifier.
#[must_use]
pub fn id(&self) -> ProducerId { pub fn id(&self) -> ProducerId {
self.inner().id self.inner().id
} }
/// Media kind. /// Media kind.
#[must_use]
pub fn kind(&self) -> MediaKind { pub fn kind(&self) -> MediaKind {
self.inner().kind self.inner().kind
} }
...@@ -554,31 +554,37 @@ impl Producer { ...@@ -554,31 +554,37 @@ impl Producer {
/// Check the /// Check the
/// [RTP Parameters and Capabilities](https://mediasoup.org/documentation/v3/mediasoup/rtp-parameters-and-capabilities/) /// [RTP Parameters and Capabilities](https://mediasoup.org/documentation/v3/mediasoup/rtp-parameters-and-capabilities/)
/// section for more details (TypeScript-oriented, but concepts apply here as well). /// section for more details (TypeScript-oriented, but concepts apply here as well).
#[must_use]
pub fn rtp_parameters(&self) -> &RtpParameters { pub fn rtp_parameters(&self) -> &RtpParameters {
&self.inner().rtp_parameters &self.inner().rtp_parameters
} }
/// Producer type. /// Producer type.
#[must_use]
pub fn r#type(&self) -> ProducerType { pub fn r#type(&self) -> ProducerType {
self.inner().r#type self.inner().r#type
} }
/// Whether the Producer is paused. /// Whether the Producer is paused.
#[must_use]
pub fn paused(&self) -> bool { pub fn paused(&self) -> bool {
self.inner().paused.load(Ordering::SeqCst) self.inner().paused.load(Ordering::SeqCst)
} }
/// The score of each RTP stream being received, representing their transmission quality. /// The score of each RTP stream being received, representing their transmission quality.
#[must_use]
pub fn score(&self) -> Vec<ProducerScore> { pub fn score(&self) -> Vec<ProducerScore> {
self.inner().score.lock().clone() self.inner().score.lock().clone()
} }
/// Custom application data. /// Custom application data.
#[must_use]
pub fn app_data(&self) -> &AppData { pub fn app_data(&self) -> &AppData {
&self.inner().app_data &self.inner().app_data
} }
/// Whether the producer is closed. /// Whether the producer is closed.
#[must_use]
pub fn closed(&self) -> bool { pub fn closed(&self) -> bool {
self.inner().closed.load(Ordering::SeqCst) self.inner().closed.load(Ordering::SeqCst)
} }
...@@ -734,6 +740,7 @@ impl Producer { ...@@ -734,6 +740,7 @@ impl Producer {
/// Consumable RTP parameters. /// Consumable RTP parameters.
// This is used in tests, otherwise would have been `pub(super)` // This is used in tests, otherwise would have been `pub(super)`
#[doc(hidden)] #[doc(hidden)]
#[must_use]
pub fn consumable_rtp_parameters(&self) -> &RtpParameters { pub fn consumable_rtp_parameters(&self) -> &RtpParameters {
&self.inner().consumable_rtp_parameters &self.inner().consumable_rtp_parameters
} }
...@@ -743,6 +750,7 @@ impl Producer { ...@@ -743,6 +750,7 @@ impl Producer {
} }
/// Downgrade `Producer` to [`WeakProducer`] instance. /// Downgrade `Producer` to [`WeakProducer`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakProducer { pub fn downgrade(&self) -> WeakProducer {
WeakProducer { WeakProducer {
inner: Arc::downgrade(&self.inner()), inner: Arc::downgrade(&self.inner()),
...@@ -784,24 +792,33 @@ impl DirectProducer { ...@@ -784,24 +792,33 @@ impl DirectProducer {
} }
} }
// TODO: Remove with next major version
#[deprecated(note = "Please use `PipedProducer` instead, it is an alias to the same type")]
#[doc(hidden)]
pub type NonClosingProducer = PipedProducer;
/// Same as [`Producer`], but will not be closed when dropped. /// Same as [`Producer`], but will not be closed when dropped.
/// ///
/// Use [`NonClosingProducer::into_inner()`] method to get regular [`Producer`] instead and restore /// The idea here is that [`ProducerId`] of both original [`Producer`] and `PipedProducer` is the
/// same and lifetime of piped producer is also tied to original producer, so you may not need to
/// store `PipedProducer` at all.
///
/// Use [`PipedProducer::into_inner()`] method to get regular [`Producer`] instead and restore
/// regular behavior of [`Drop`] implementation. /// regular behavior of [`Drop`] implementation.
pub struct NonClosingProducer { pub struct PipedProducer {
producer: Producer, producer: Producer,
on_drop: Option<Box<dyn FnOnce(Producer) + Send + 'static>>, on_drop: Option<Box<dyn FnOnce(Producer) + Send + 'static>>,
} }
impl fmt::Debug for NonClosingProducer { impl fmt::Debug for PipedProducer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NonClosingProducer") f.debug_struct("PipedProducer")
.field("producer", &self.producer) .field("producer", &self.producer)
.finish() .finish()
} }
} }
impl Drop for NonClosingProducer { impl Drop for PipedProducer {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(on_drop) = self.on_drop.take() { if let Some(on_drop) = self.on_drop.take() {
on_drop(self.producer.clone()) on_drop(self.producer.clone())
...@@ -809,7 +826,7 @@ impl Drop for NonClosingProducer { ...@@ -809,7 +826,7 @@ impl Drop for NonClosingProducer {
} }
} }
impl NonClosingProducer { impl PipedProducer {
/// * `on_drop` - Callback that takes last `Producer` instance and must do something with it to /// * `on_drop` - Callback that takes last `Producer` instance and must do something with it to
/// prevent dropping and thus closing /// prevent dropping and thus closing
pub(crate) fn new<F: FnOnce(Producer) + Send + 'static>( pub(crate) fn new<F: FnOnce(Producer) + Send + 'static>(
...@@ -822,7 +839,7 @@ impl NonClosingProducer { ...@@ -822,7 +839,7 @@ impl NonClosingProducer {
} }
} }
/// Get inner [`Producer`] (which will close on drop in contrast to `NonClosingProducer`). /// Get inner [`Producer`] (which will close on drop in contrast to `PipedProducer`).
pub fn into_inner(mut self) -> Producer { pub fn into_inner(mut self) -> Producer {
self.on_drop.take(); self.on_drop.take();
self.producer.clone() self.producer.clone()
...@@ -847,6 +864,7 @@ impl fmt::Debug for WeakProducer { ...@@ -847,6 +864,7 @@ impl fmt::Debug for WeakProducer {
impl WeakProducer { impl WeakProducer {
/// Attempts to upgrade `WeakProducer` to [`Producer`] if last instance of one wasn't dropped /// Attempts to upgrade `WeakProducer` to [`Producer`] if last instance of one wasn't dropped
/// yet. /// yet.
#[must_use]
pub fn upgrade(&self) -> Option<Producer> { pub fn upgrade(&self) -> Option<Producer> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
//! An RTP observer inspects the media received by a set of selected producers.
//!
//! mediasoup implements the following RTP observers:
//! * [`AudioLevelObserver`](crate::audio_level_observer::AudioLevelObserver)
use crate::data_structures::AppData; use crate::data_structures::AppData;
use crate::producer::{Producer, ProducerId}; use crate::producer::{Producer, ProducerId};
use crate::uuid_based_wrapper_type; use crate::uuid_based_wrapper_type;
...@@ -11,11 +6,11 @@ use async_trait::async_trait; ...@@ -11,11 +6,11 @@ use async_trait::async_trait;
use event_listener_primitives::HandlerId; use event_listener_primitives::HandlerId;
uuid_based_wrapper_type!( uuid_based_wrapper_type!(
/// RTP observer identifier. /// [`RtpObserver`] identifier.
RtpObserverId RtpObserverId
); );
/// Options for adding producer to RTP observer /// Options for adding producer to `[RtpObserver`]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct RtpObserverAddProducerOptions { pub struct RtpObserverAddProducerOptions {
...@@ -24,7 +19,8 @@ pub struct RtpObserverAddProducerOptions { ...@@ -24,7 +19,8 @@ pub struct RtpObserverAddProducerOptions {
} }
impl RtpObserverAddProducerOptions { impl RtpObserverAddProducerOptions {
/// * `producer_id` - The id of the Producer to be added. /// * `producer_id` - The id of the [`Producer`] to be added.
#[must_use]
pub fn new(producer_id: ProducerId) -> Self { pub fn new(producer_id: ProducerId) -> Self {
Self { producer_id } Self { producer_id }
} }
...@@ -37,15 +33,19 @@ impl RtpObserverAddProducerOptions { ...@@ -37,15 +33,19 @@ impl RtpObserverAddProducerOptions {
#[async_trait(?Send)] #[async_trait(?Send)]
pub trait RtpObserver { pub trait RtpObserver {
/// RtpObserver id. /// RtpObserver id.
#[must_use]
fn id(&self) -> RtpObserverId; fn id(&self) -> RtpObserverId;
/// Whether the RtpObserver is paused. /// Whether the RtpObserver is paused.
#[must_use]
fn paused(&self) -> bool; fn paused(&self) -> bool;
/// Custom application data. /// Custom application data.
#[must_use]
fn app_data(&self) -> &AppData; fn app_data(&self) -> &AppData;
/// Whether the RTP observer is closed. /// Whether the RTP observer is closed.
#[must_use]
fn closed(&self) -> bool; fn closed(&self) -> bool;
/// Pauses the RTP observer. No RTP is inspected until resume() is called. /// Pauses the RTP observer. No RTP is inspected until resume() is called.
......
//! A transport connects an endpoint with a mediasoup router and enables transmission of media in
//! both directions by means of [`Producer`], [`Consumer`], [`DataProducer`] and [`DataConsumer`]
//! instances created on it.
//!
//! mediasoup implements the following transports:
//! * [`WebRtcTransport`](crate::webrtc_transport::WebRtcTransport)
//! * [`PlainTransport`](crate::plain_transport::PlainTransport)
//! * [`PipeTransport`](crate::pipe_transport::PipeTransport)
//! * [`DirectTransport`](crate::direct_transport::DirectTransport)
use crate::consumer::{Consumer, ConsumerId, ConsumerOptions, ConsumerType}; use crate::consumer::{Consumer, ConsumerId, ConsumerOptions, ConsumerType};
use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, DataConsumerType}; use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, DataConsumerType};
use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, DataProducerType}; use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, DataProducerType};
...@@ -32,7 +22,7 @@ use crate::{ortc, uuid_based_wrapper_type}; ...@@ -32,7 +22,7 @@ use crate::{ortc, uuid_based_wrapper_type};
use async_executor::Executor; use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use event_listener_primitives::HandlerId; use event_listener_primitives::HandlerId;
use log::*; use log::{error, warn};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
...@@ -142,15 +132,19 @@ pub(super) enum TransportType { ...@@ -142,15 +132,19 @@ pub(super) enum TransportType {
#[async_trait(?Send)] #[async_trait(?Send)]
pub trait Transport: Debug + Send + Sync + CloneTransport { pub trait Transport: Debug + Send + Sync + CloneTransport {
/// Transport id. /// Transport id.
#[must_use]
fn id(&self) -> TransportId; fn id(&self) -> TransportId;
/// Router id. /// Router id.
#[must_use]
fn router_id(&self) -> RouterId; fn router_id(&self) -> RouterId;
/// Custom application data. /// Custom application data.
#[must_use]
fn app_data(&self) -> &AppData; fn app_data(&self) -> &AppData;
/// Whether the transport is closed. /// Whether the transport is closed.
#[must_use]
fn closed(&self) -> bool; fn closed(&self) -> bool;
/// Instructs the router to receive audio or video RTP (or SRTP depending on the transport). /// Instructs the router to receive audio or video RTP (or SRTP depending on the transport).
...@@ -585,7 +579,7 @@ pub(super) trait TransportImpl: TransportGeneric { ...@@ -585,7 +579,7 @@ pub(super) trait TransportImpl: TransportGeneric {
} else { } else {
let mut rtp_parameters = ortc::get_consumer_rtp_parameters( let mut rtp_parameters = ortc::get_consumer_rtp_parameters(
producer.consumable_rtp_parameters(), producer.consumable_rtp_parameters(),
rtp_capabilities, &rtp_capabilities,
pipe, pipe,
) )
.map_err(ConsumeError::BadConsumerRtpParameters)?; .map_err(ConsumeError::BadConsumerRtpParameters)?;
...@@ -647,7 +641,7 @@ pub(super) trait TransportImpl: TransportGeneric { ...@@ -647,7 +641,7 @@ pub(super) trait TransportImpl: TransportGeneric {
response.paused, response.paused,
Arc::clone(self.executor()), Arc::clone(self.executor()),
self.channel().clone(), self.channel().clone(),
self.payload_channel().clone(), self.payload_channel(),
response.producer_paused, response.producer_paused,
response.score, response.score,
response.preferred_layers, response.preferred_layers,
......
//! A WebRTC transport represents a network path negotiated by both, a WebRTC endpoint and
//! mediasoup, via ICE and DTLS procedures. A WebRTC transport may be used to receive media, to send
//! media or to both receive and send. There is no limitation in mediasoup. However, due to their
//! design, mediasoup-client and libmediasoupclient require separate WebRTC transports for sending
//! and receiving.
//!
//! # Notes on usage
//! The WebRTC transport implementation of mediasoup is
//! [ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not initiate
//! ICE connections but expects ICE Binding Requests from endpoints.
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
...@@ -24,18 +13,20 @@ use crate::messages::{ ...@@ -24,18 +13,20 @@ use crate::messages::{
TransportInternal, TransportRestartIceRequest, WebRtcTransportData, TransportInternal, TransportRestartIceRequest, WebRtcTransportData,
}; };
use crate::producer::{Producer, ProducerId, ProducerOptions}; use crate::producer::{Producer, ProducerId, ProducerOptions};
use crate::router::transport::{TransportImpl, TransportType};
use crate::router::{Router, RouterId}; use crate::router::{Router, RouterId};
use crate::sctp_parameters::{NumSctpStreams, SctpParameters}; use crate::sctp_parameters::{NumSctpStreams, SctpParameters};
use crate::transport::{ use crate::transport::{
ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions, ConsumeDataError, ConsumeError, ProduceDataError, ProduceError, RecvRtpHeaderExtensions,
RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportImpl, RtpListener, SctpListener, Transport, TransportGeneric, TransportId, TransportTraceEventData,
TransportTraceEventData, TransportTraceEventType, TransportType, TransportTraceEventType,
}; };
use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler}; use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
use async_executor::Executor; use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::*; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
...@@ -52,11 +43,13 @@ pub struct TransportListenIps(Vec<TransportListenIp>); ...@@ -52,11 +43,13 @@ pub struct TransportListenIps(Vec<TransportListenIp>);
impl TransportListenIps { impl TransportListenIps {
/// Create transport listen IPs with given IP populated initially. /// Create transport listen IPs with given IP populated initially.
#[must_use]
pub fn new(listen_ip: TransportListenIp) -> Self { pub fn new(listen_ip: TransportListenIp) -> Self {
Self(vec![listen_ip]) Self(vec![listen_ip])
} }
/// Insert another listen IP. /// Insert another listen IP.
#[must_use]
pub fn insert(mut self, listen_ip: TransportListenIp) -> Self { pub fn insert(mut self, listen_ip: TransportListenIp) -> Self {
self.0.push(listen_ip); self.0.push(listen_ip);
self self
...@@ -88,7 +81,7 @@ impl TryFrom<Vec<TransportListenIp>> for TransportListenIps { ...@@ -88,7 +81,7 @@ impl TryFrom<Vec<TransportListenIp>> for TransportListenIps {
} }
} }
/// Plain transport options. /// [`WebRtcTransport`] options.
/// ///
/// # Notes on usage /// # Notes on usage
/// * Do not use "0.0.0.0" into `listen_ips`. Values in `listen_ips` must be specific bindable IPs /// * Do not use "0.0.0.0" into `listen_ips`. Values in `listen_ips` must be specific bindable IPs
...@@ -132,7 +125,8 @@ pub struct WebRtcTransportOptions { ...@@ -132,7 +125,8 @@ pub struct WebRtcTransportOptions {
} }
impl WebRtcTransportOptions { impl WebRtcTransportOptions {
/// Create WebRtc transport options with given listen IPs. /// Create [`WebRtcTransport`] options with given listen IPs.
#[must_use]
pub fn new(listen_ips: TransportListenIps) -> Self { pub fn new(listen_ips: TransportListenIps) -> Self {
Self { Self {
listen_ips, listen_ips,
...@@ -143,8 +137,8 @@ impl WebRtcTransportOptions { ...@@ -143,8 +137,8 @@ impl WebRtcTransportOptions {
initial_available_outgoing_bitrate: 600_000, initial_available_outgoing_bitrate: 600_000,
enable_sctp: false, enable_sctp: false,
num_sctp_streams: NumSctpStreams::default(), num_sctp_streams: NumSctpStreams::default(),
max_sctp_message_size: 262144, max_sctp_message_size: 262_144,
sctp_send_buffer_size: 262144, sctp_send_buffer_size: 262_144,
app_data: AppData::default(), app_data: AppData::default(),
} }
} }
...@@ -181,7 +175,7 @@ pub struct WebRtcTransportDump { ...@@ -181,7 +175,7 @@ pub struct WebRtcTransportDump {
pub ice_selected_tuple: Option<TransportTuple>, pub ice_selected_tuple: Option<TransportTuple>,
} }
/// RTC statistics of the WebRTC transport. /// RTC statistics of the [`WebRtcTransport`].
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)] #[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
#[non_exhaustive] #[non_exhaustive]
...@@ -220,7 +214,7 @@ pub struct WebRtcTransportStat { ...@@ -220,7 +214,7 @@ pub struct WebRtcTransportStat {
pub dtls_state: DtlsState, pub dtls_state: DtlsState,
} }
/// Remote parameters for WebRTC transport. /// Remote parameters for [`WebRtcTransport`].
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)] #[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct WebRtcTransportRemoteParameters { pub struct WebRtcTransportRemoteParameters {
...@@ -323,17 +317,18 @@ impl Inner { ...@@ -323,17 +317,18 @@ impl Inner {
} }
} }
/// A WebRTC transport represents a network path negotiated by both, a WebRTC endpoint and /// A [`WebRtcTransport`] represents a network path negotiated by both, a WebRTC endpoint and
/// mediasoup, via ICE and DTLS procedures. A WebRTC transport may be used to receive media, to send /// mediasoup, via ICE and DTLS procedures. A [`WebRtcTransport`] may be used to receive media, to
/// media or to both receive and send. There is no limitation in mediasoup. However, due to their /// send media or to both receive and send. There is no limitation in mediasoup. However, due to
/// design, mediasoup-client and libmediasoupclient require separate WebRTC transports for sending /// their design, mediasoup-client and libmediasoupclient require separate [`WebRtcTransport`]s for
/// and receiving. /// sending and receiving.
/// ///
/// # Notes on usage /// # Notes on usage
/// The WebRTC transport implementation of mediasoup is /// The [`WebRtcTransport`] implementation of mediasoup is
/// [ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not initiate /// [ICE Lite](https://tools.ietf.org/html/rfc5245#section-2.7), meaning that it does not initiate
/// ICE connections but expects ICE Binding Requests from endpoints. /// ICE connections but expects ICE Binding Requests from endpoints.
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Transport will be closed on drop, make sure to keep it around for as long as needed"]
pub struct WebRtcTransport { pub struct WebRtcTransport {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -629,11 +624,7 @@ impl WebRtcTransport { ...@@ -629,11 +624,7 @@ impl WebRtcTransport {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
move || { move || {
if let Some(inner) = inner_weak if let Some(inner) = inner_weak.lock().as_ref().and_then(Weak::upgrade) {
.lock()
.as_ref()
.and_then(|weak_inner| weak_inner.upgrade())
{
inner.handlers.router_close.call_simple(); inner.handlers.router_close.call_simple();
inner.close(false); inner.close(false);
} }
...@@ -661,7 +652,7 @@ impl WebRtcTransport { ...@@ -661,7 +652,7 @@ impl WebRtcTransport {
Self { inner } Self { inner }
} }
/// Provide the WebRtcTransport with remote parameters. /// Provide the [`WebRtcTransport`] with remote parameters.
/// ///
/// # Example /// # Example
/// ```rust /// ```rust
...@@ -722,37 +713,44 @@ impl WebRtcTransport { ...@@ -722,37 +713,44 @@ impl WebRtcTransport {
} }
/// Local ICE role. Due to the mediasoup ICE Lite design, this is always `Controlled`. /// Local ICE role. Due to the mediasoup ICE Lite design, this is always `Controlled`.
#[must_use]
pub fn ice_role(&self) -> IceRole { pub fn ice_role(&self) -> IceRole {
self.inner.data.ice_role self.inner.data.ice_role
} }
/// Local ICE parameters. /// Local ICE parameters.
#[must_use]
pub fn ice_parameters(&self) -> &IceParameters { pub fn ice_parameters(&self) -> &IceParameters {
&self.inner.data.ice_parameters &self.inner.data.ice_parameters
} }
/// Local ICE candidates. /// Local ICE candidates.
#[must_use]
pub fn ice_candidates(&self) -> &Vec<IceCandidate> { pub fn ice_candidates(&self) -> &Vec<IceCandidate> {
&self.inner.data.ice_candidates &self.inner.data.ice_candidates
} }
/// Current ICE state. /// Current ICE state.
#[must_use]
pub fn ice_state(&self) -> IceState { pub fn ice_state(&self) -> IceState {
*self.inner.data.ice_state.lock() *self.inner.data.ice_state.lock()
} }
/// The selected transport tuple if ICE is in `Connected` or `Completed` state. It is `None` if /// The selected transport tuple if ICE is in `Connected` or `Completed` state. It is `None` if
/// ICE is not established (no working candidate pair was found). /// ICE is not established (no working candidate pair was found).
#[must_use]
pub fn ice_selected_tuple(&self) -> Option<TransportTuple> { pub fn ice_selected_tuple(&self) -> Option<TransportTuple> {
*self.inner.data.ice_selected_tuple.lock() *self.inner.data.ice_selected_tuple.lock()
} }
/// Local DTLS parameters. /// Local DTLS parameters.
#[must_use]
pub fn dtls_parameters(&self) -> DtlsParameters { pub fn dtls_parameters(&self) -> DtlsParameters {
self.inner.data.dtls_parameters.lock().clone() self.inner.data.dtls_parameters.lock().clone()
} }
/// Current DTLS state. /// Current DTLS state.
#[must_use]
pub fn dtls_state(&self) -> DtlsState { pub fn dtls_state(&self) -> DtlsState {
*self.inner.data.dtls_state.lock() *self.inner.data.dtls_state.lock()
} }
...@@ -762,16 +760,19 @@ impl WebRtcTransport { ...@@ -762,16 +760,19 @@ impl WebRtcTransport {
/// # Notes on usage /// # Notes on usage
/// The application may want to inspect the remote certificate for authorization purposes by /// The application may want to inspect the remote certificate for authorization purposes by
/// using some certificates utility. /// using some certificates utility.
#[must_use]
pub fn dtls_remote_cert(&self) -> Option<String> { pub fn dtls_remote_cert(&self) -> Option<String> {
self.inner.data.dtls_remote_cert.lock().clone() self.inner.data.dtls_remote_cert.lock().clone()
} }
/// Local SCTP parameters. Or `None` if SCTP is not enabled. /// Local SCTP parameters. Or `None` if SCTP is not enabled.
#[must_use]
pub fn sctp_parameters(&self) -> Option<SctpParameters> { pub fn sctp_parameters(&self) -> Option<SctpParameters> {
self.inner.data.sctp_parameters self.inner.data.sctp_parameters
} }
/// Current SCTP state. Or `None` if SCTP is not enabled. /// Current SCTP state. Or `None` if SCTP is not enabled.
#[must_use]
pub fn sctp_state(&self) -> Option<SctpState> { pub fn sctp_state(&self) -> Option<SctpState> {
*self.inner.data.sctp_state.lock() *self.inner.data.sctp_state.lock()
} }
...@@ -835,6 +836,7 @@ impl WebRtcTransport { ...@@ -835,6 +836,7 @@ impl WebRtcTransport {
} }
/// Downgrade `WebRtcTransport` to [`WeakWebRtcTransport`] instance. /// Downgrade `WebRtcTransport` to [`WeakWebRtcTransport`] instance.
#[must_use]
pub fn downgrade(&self) -> WeakWebRtcTransport { pub fn downgrade(&self) -> WeakWebRtcTransport {
WeakWebRtcTransport { WeakWebRtcTransport {
inner: Arc::downgrade(&self.inner), inner: Arc::downgrade(&self.inner),
...@@ -849,8 +851,9 @@ impl WebRtcTransport { ...@@ -849,8 +851,9 @@ impl WebRtcTransport {
} }
} }
/// [`WeakWebRtcTransport`] doesn't own WebRTC transport instance on mediasoup-worker and will not /// [`WeakWebRtcTransport`] doesn't own [`WebRtcTransport`] instance on mediasoup-worker and will
/// prevent one from being destroyed once last instance of regular [`WebRtcTransport`] is dropped. /// not prevent one from being destroyed once last instance of regular [`WebRtcTransport`] is
/// dropped.
/// ///
/// [`WeakWebRtcTransport`] vs [`WebRtcTransport`] is similar to [`Weak`] vs [`Arc`]. /// [`WeakWebRtcTransport`] vs [`WebRtcTransport`] is similar to [`Weak`] vs [`Arc`].
#[derive(Clone)] #[derive(Clone)]
...@@ -867,6 +870,7 @@ impl fmt::Debug for WeakWebRtcTransport { ...@@ -867,6 +870,7 @@ impl fmt::Debug for WeakWebRtcTransport {
impl WeakWebRtcTransport { impl WeakWebRtcTransport {
/// Attempts to upgrade `WeakWebRtcTransport` to [`WebRtcTransport`] if last instance of one /// Attempts to upgrade `WeakWebRtcTransport` to [`WebRtcTransport`] if last instance of one
/// wasn't dropped yet. /// wasn't dropped yet.
#[must_use]
pub fn upgrade(&self) -> Option<WebRtcTransport> { pub fn upgrade(&self) -> Option<WebRtcTransport> {
let inner = self.inner.upgrade()?; let inner = self.inner.upgrade()?;
......
...@@ -30,6 +30,7 @@ impl RtpCodecParametersParameters { ...@@ -30,6 +30,7 @@ impl RtpCodecParametersParameters {
} }
/// Iterate over parameters in collection. /// Iterate over parameters in collection.
#[must_use]
pub fn iter( pub fn iter(
&self, &self,
) -> std::collections::btree_map::Iter<'_, String, RtpCodecParametersParametersValue> { ) -> std::collections::btree_map::Iter<'_, String, RtpCodecParametersParametersValue> {
...@@ -37,6 +38,7 @@ impl RtpCodecParametersParameters { ...@@ -37,6 +38,7 @@ impl RtpCodecParametersParameters {
} }
/// Get specific parameter from collection. /// Get specific parameter from collection.
#[must_use]
pub fn get(&self, key: &str) -> Option<&RtpCodecParametersParametersValue> { pub fn get(&self, key: &str) -> Option<&RtpCodecParametersParametersValue> {
self.0.get(key) self.0.get(key)
} }
...@@ -86,16 +88,17 @@ where ...@@ -86,16 +88,17 @@ where
/// Provides information on the capabilities of a codec within the RTP capabilities. The list of /// Provides information on the capabilities of a codec within the RTP capabilities. The list of
/// media codecs supported by mediasoup and their settings is defined in the /// media codecs supported by mediasoup and their settings is defined in the
/// supported_rtp_capabilities.rs file. /// `supported_rtp_capabilities.rs` file.
/// ///
/// Exactly one RtpCodecCapabilityFinalized will be present for each supported combination of parameters that /// Exactly one [`RtpCodecCapabilityFinalized`] will be present for each supported combination of
/// requires a distinct value of preferred_payload_type. For example: /// parameters that requires a distinct value of `preferred_payload_type`. For example:
/// ///
/// - Multiple H264 codecs, each with their own distinct `packetization-mode` and `profile-level-id` /// - Multiple H264 codecs, each with their own distinct `packetization-mode` and `profile-level-id`
/// values. /// values.
/// - Multiple VP9 codecs, each with their own distinct `profile-id` value. /// - Multiple VP9 codecs, each with their own distinct `profile-id` value.
/// ///
/// This is similar to RtpCodecCapability, but with preferred_payload_type field being required /// This is similar to [`RtpCodecCapability`], but with `preferred_payload_type` field being
/// required.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")] #[serde(tag = "kind", rename_all = "lowercase")]
#[non_exhaustive] #[non_exhaustive]
...@@ -145,22 +148,19 @@ impl RtpCodecCapabilityFinalized { ...@@ -145,22 +148,19 @@ impl RtpCodecCapabilityFinalized {
pub(crate) fn clock_rate(&self) -> NonZeroU32 { pub(crate) fn clock_rate(&self) -> NonZeroU32 {
match self { match self {
Self::Audio { clock_rate, .. } => *clock_rate, Self::Audio { clock_rate, .. } | Self::Video { clock_rate, .. } => *clock_rate,
Self::Video { clock_rate, .. } => *clock_rate,
} }
} }
pub(crate) fn parameters(&self) -> &RtpCodecParametersParameters { pub(crate) fn parameters(&self) -> &RtpCodecParametersParameters {
match self { match self {
Self::Audio { parameters, .. } => parameters, Self::Audio { parameters, .. } | Self::Video { parameters, .. } => parameters,
Self::Video { parameters, .. } => parameters,
} }
} }
pub(crate) fn parameters_mut(&mut self) -> &mut RtpCodecParametersParameters { pub(crate) fn parameters_mut(&mut self) -> &mut RtpCodecParametersParameters {
match self { match self {
Self::Audio { parameters, .. } => parameters, Self::Audio { parameters, .. } | Self::Video { parameters, .. } => parameters,
Self::Video { parameters, .. } => parameters,
} }
} }
...@@ -169,8 +169,8 @@ impl RtpCodecCapabilityFinalized { ...@@ -169,8 +169,8 @@ impl RtpCodecCapabilityFinalized {
Self::Audio { Self::Audio {
preferred_payload_type, preferred_payload_type,
.. ..
} => *preferred_payload_type, }
Self::Video { | Self::Video {
preferred_payload_type, preferred_payload_type,
.. ..
} => *preferred_payload_type, } => *preferred_payload_type,
...@@ -279,18 +279,18 @@ pub enum MimeTypeVideo { ...@@ -279,18 +279,18 @@ pub enum MimeTypeVideo {
/// Provides information on the capabilities of a codec within the RTP capabilities. The list of /// Provides information on the capabilities of a codec within the RTP capabilities. The list of
/// media codecs supported by mediasoup and their settings is defined in the /// media codecs supported by mediasoup and their settings is defined in the
/// supported_rtp_capabilities.rs file. /// `supported_rtp_capabilities.rs` file.
/// ///
/// Exactly one RtpCodecCapability will be present for each supported combination of parameters that /// Exactly one [`RtpCodecCapability`] will be present for each supported combination of parameters
/// requires a distinct value of preferred_payload_type. For example: /// that requires a distinct value of `preferred_payload_type`. For example:
/// ///
/// - Multiple H264 codecs, each with their own distinct `packetization-mode` and `profile-level-id` /// - Multiple H264 codecs, each with their own distinct `packetization-mode` and `profile-level-id`
/// values. /// values.
/// - Multiple VP9 codecs, each with their own distinct `profile-id` value. /// - Multiple VP9 codecs, each with their own distinct `profile-id` value.
/// ///
/// RtpCodecCapability entries in the mediaCodecs array of RouterOptions do not require /// [`RtpCodecCapability`] entries in the `media_codecs` vector of
/// preferred_payload_type field (if unset, mediasoup will choose a random one). If given, make sure /// [`RouterOptions`](crate::router::RouterOptions) do not require `preferred_payload_type` field
/// it's in the 96-127 range. /// (if unset, mediasoup will choose a random one). If given, make sure it's in the 96-127 range.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")] #[serde(tag = "kind", rename_all = "lowercase")]
pub enum RtpCodecCapability { pub enum RtpCodecCapability {
...@@ -341,15 +341,13 @@ impl RtpCodecCapability { ...@@ -341,15 +341,13 @@ impl RtpCodecCapability {
pub(crate) fn parameters(&self) -> &RtpCodecParametersParameters { pub(crate) fn parameters(&self) -> &RtpCodecParametersParameters {
match self { match self {
Self::Audio { parameters, .. } => parameters, Self::Audio { parameters, .. } | Self::Video { parameters, .. } => parameters,
Self::Video { parameters, .. } => parameters,
} }
} }
pub(crate) fn parameters_mut(&mut self) -> &mut RtpCodecParametersParameters { pub(crate) fn parameters_mut(&mut self) -> &mut RtpCodecParametersParameters {
match self { match self {
Self::Audio { parameters, .. } => parameters, Self::Audio { parameters, .. } | Self::Video { parameters, .. } => parameters,
Self::Video { parameters, .. } => parameters,
} }
} }
...@@ -358,8 +356,8 @@ impl RtpCodecCapability { ...@@ -358,8 +356,8 @@ impl RtpCodecCapability {
Self::Audio { Self::Audio {
preferred_payload_type, preferred_payload_type,
.. ..
} => *preferred_payload_type, }
Self::Video { | Self::Video {
preferred_payload_type, preferred_payload_type,
.. ..
} => *preferred_payload_type, } => *preferred_payload_type,
...@@ -368,8 +366,7 @@ impl RtpCodecCapability { ...@@ -368,8 +366,7 @@ impl RtpCodecCapability {
pub(crate) fn rtcp_feedback(&self) -> &Vec<RtcpFeedback> { pub(crate) fn rtcp_feedback(&self) -> &Vec<RtcpFeedback> {
match self { match self {
Self::Audio { rtcp_feedback, .. } => rtcp_feedback, Self::Audio { rtcp_feedback, .. } | Self::Video { rtcp_feedback, .. } => rtcp_feedback,
Self::Video { rtcp_feedback, .. } => rtcp_feedback,
} }
} }
} }
...@@ -447,7 +444,9 @@ pub enum RtpHeaderExtensionUri { ...@@ -447,7 +444,9 @@ pub enum RtpHeaderExtensionUri {
} }
impl RtpHeaderExtensionUri { impl RtpHeaderExtensionUri {
// TODO: Replace `&self` with `self` in next major version
/// RTP header extension as a string /// RTP header extension as a string
#[must_use]
pub fn as_str(&self) -> &'static str { pub fn as_str(&self) -> &'static str {
match self { match self {
RtpHeaderExtensionUri::Mid => "urn:ietf:params:rtp-hdrext:sdes:mid", RtpHeaderExtensionUri::Mid => "urn:ietf:params:rtp-hdrext:sdes:mid",
...@@ -474,10 +473,11 @@ impl RtpHeaderExtensionUri { ...@@ -474,10 +473,11 @@ impl RtpHeaderExtensionUri {
} }
/// Provides information relating to supported header extensions. The list of RTP header extensions /// Provides information relating to supported header extensions. The list of RTP header extensions
/// supported by mediasoup is defined in the supported_rtp_capabilities.rs file. /// supported by mediasoup is defined in the `supported_rtp_capabilities.rs` file.
/// ///
/// mediasoup does not currently support encrypted RTP header extensions. The direction field is /// mediasoup does not currently support encrypted RTP header extensions. The direction field is
/// just present in mediasoup RTP capabilities (retrieved via `mediasoup::router::Router::rtp_capabilities()` or /// just present in mediasoup RTP capabilities (retrieved via
/// `mediasoup::router::Router::rtp_capabilities()` or
/// `mediasoup::supported_rtp_capabilities::get_supported_rtp_capabilities()`. It's ignored if /// `mediasoup::supported_rtp_capabilities::get_supported_rtp_capabilities()`. It's ignored if
/// present in endpoints' RTP capabilities. /// present in endpoints' RTP capabilities.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
...@@ -523,8 +523,8 @@ pub struct RtpHeaderExtension { ...@@ -523,8 +523,8 @@ pub struct RtpHeaderExtension {
/// consumer.setPreferredLayers(). /// consumer.setPreferredLayers().
/// ///
/// As an exception, previous bullet is not true when consuming a stream over a /// As an exception, previous bullet is not true when consuming a stream over a
/// PipeTransport, in which all RTP streams from the associated producer are /// [`PipeTransport`](crate::pipe_transport::PipeTransport), in which all RTP streams from the
/// forwarded verbatim through the consumer. /// associated producer are forwarded verbatim through the consumer.
/// ///
/// The RTP receive parameters will always have their ssrc values randomly /// The RTP receive parameters will always have their ssrc values randomly
/// generated for all of its encodings (and optional rtx: { ssrc: XXXX } if the /// generated for all of its encodings (and optional rtx: { ssrc: XXXX } if the
...@@ -571,13 +571,13 @@ impl From<&str> for RtpCodecParametersParametersValue { ...@@ -571,13 +571,13 @@ impl From<&str> for RtpCodecParametersParametersValue {
impl From<u8> for RtpCodecParametersParametersValue { impl From<u8> for RtpCodecParametersParametersValue {
fn from(n: u8) -> Self { fn from(n: u8) -> Self {
Self::Number(n as u32) Self::Number(u32::from(n))
} }
} }
impl From<u16> for RtpCodecParametersParametersValue { impl From<u16> for RtpCodecParametersParametersValue {
fn from(n: u16) -> Self { fn from(n: u16) -> Self {
Self::Number(n as u32) Self::Number(u32::from(n))
} }
} }
...@@ -589,7 +589,7 @@ impl From<u32> for RtpCodecParametersParametersValue { ...@@ -589,7 +589,7 @@ impl From<u32> for RtpCodecParametersParametersValue {
/// Provides information on codec settings within the RTP parameters. The list /// Provides information on codec settings within the RTP parameters. The list
/// of media codecs supported by mediasoup and their settings is defined in the /// of media codecs supported by mediasoup and their settings is defined in the
/// supported_rtp_capabilities.rs file. /// `supported_rtp_capabilities.rs` file.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
#[serde(untagged, rename_all = "lowercase")] #[serde(untagged, rename_all = "lowercase")]
pub enum RtpCodecParameters { pub enum RtpCodecParameters {
...@@ -647,29 +647,26 @@ impl RtpCodecParameters { ...@@ -647,29 +647,26 @@ impl RtpCodecParameters {
pub(crate) fn payload_type(&self) -> u8 { pub(crate) fn payload_type(&self) -> u8 {
match self { match self {
Self::Audio { payload_type, .. } => *payload_type, Self::Audio { payload_type, .. } | Self::Video { payload_type, .. } => *payload_type,
Self::Video { payload_type, .. } => *payload_type,
} }
} }
pub(crate) fn parameters(&self) -> &RtpCodecParametersParameters { pub(crate) fn parameters(&self) -> &RtpCodecParametersParameters {
match self { match self {
Self::Audio { parameters, .. } => parameters, Self::Audio { parameters, .. } | Self::Video { parameters, .. } => parameters,
Self::Video { parameters, .. } => parameters,
} }
} }
pub(crate) fn rtcp_feedback_mut(&mut self) -> &mut Vec<RtcpFeedback> { pub(crate) fn rtcp_feedback_mut(&mut self) -> &mut Vec<RtcpFeedback> {
match self { match self {
Self::Audio { rtcp_feedback, .. } => rtcp_feedback, Self::Audio { rtcp_feedback, .. } | Self::Video { rtcp_feedback, .. } => rtcp_feedback,
Self::Video { rtcp_feedback, .. } => rtcp_feedback,
} }
} }
} }
/// Provides information on RTCP feedback messages for a specific codec. Those messages can be /// Provides information on RTCP feedback messages for a specific codec. Those messages can be
/// transport layer feedback messages or codec-specific feedback messages. The list of RTCP /// transport layer feedback messages or codec-specific feedback messages. The list of RTCP
/// feedbacks supported by mediasoup is defined in the supported_rtp_capabilities.rs file. /// feedbacks supported by mediasoup is defined in the `supported_rtp_capabilities.rs` file.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum RtcpFeedback { pub enum RtcpFeedback {
/// NACK /// NACK
...@@ -830,7 +827,7 @@ pub struct RtpEncodingParameters { ...@@ -830,7 +827,7 @@ pub struct RtpEncodingParameters {
} }
/// Defines a RTP header extension within the RTP parameters. The list of RTP /// Defines a RTP header extension within the RTP parameters. The list of RTP
/// header extensions supported by mediasoup is defined in the supported_rtp_capabilities.rs file. /// header extensions supported by mediasoup is defined in the `supported_rtp_capabilities.rs` file.
/// ///
/// mediasoup does not currently support encrypted RTP header extensions and no /// mediasoup does not currently support encrypted RTP header extensions and no
/// parameters are currently considered. /// parameters are currently considered.
...@@ -853,7 +850,7 @@ pub struct RtpHeaderExtensionParameters { ...@@ -853,7 +850,7 @@ pub struct RtpHeaderExtensionParameters {
/// If no cname is given in a producer's RTP parameters, the mediasoup transport will choose a /// If no cname is given in a producer's RTP parameters, the mediasoup transport will choose a
/// random one that will be used into RTCP SDES messages sent to all its associated consumers. /// random one that will be used into RTCP SDES messages sent to all its associated consumers.
/// ///
/// mediasoup assumes reduced_size to always be true. /// mediasoup assumes `reduced_size` to always be true.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct RtcpParameters { pub struct RtcpParameters {
......
...@@ -5,19 +5,21 @@ use serde::{Deserialize, Serialize}; ...@@ -5,19 +5,21 @@ use serde::{Deserialize, Serialize};
/// Number of SCTP streams. /// Number of SCTP streams.
/// ///
/// Both OS and MIS are part of the SCTP INIT+ACK handshake. OS refers to the initial number of /// Both OS and MIS are part of the SCTP INIT+ACK handshake. OS refers to the initial number of
/// outgoing SCTP streams that the server side transport creates (to be used by DataConsumers), /// outgoing SCTP streams that the server side transport creates (to be used by
/// while MIS refers to the maximum number of incoming SCTP streams that the server side transport /// [DataConsumer](crate::data_consumer::DataConsumer)s), while MIS refers to the maximum number of
/// can receive (to be used by DataProducers). So, if the server side transport will just be used to /// incoming SCTP streams that the server side transport can receive (to be used by
/// create data producers (but no data consumers), OS can be low (~1). However, if data consumers /// [DataProducer](crate::data_producer::DataProducer)s). So, if the server side transport will just
/// are desired on the server side transport, OS must have a proper value and such a proper value /// be used to create data producers (but no data consumers), OS can be low (~1). However, if data
/// depends on whether the remote endpoint supports SCTP_ADD_STREAMS extension or not. /// consumers are desired on the server side transport, OS must have a proper value and such a
/// proper value depends on whether the remote endpoint supports `SCTP_ADD_STREAMS` extension or
/// not.
/// ///
/// libwebrtc (Chrome, Safari, etc) does not enable SCTP_ADD_STREAMS so, if data consumers are /// libwebrtc (Chrome, Safari, etc) does not enable `SCTP_ADD_STREAMS` so, if data consumers are
/// required, OS should be 1024 (the maximum number of DataChannels that libwebrtc enables). /// required, OS should be 1024 (the maximum number of DataChannels that libwebrtc enables).
/// ///
/// Firefox does enable SCTP_ADD_STREAMS so, if data consumers are required, OS can be lower (16 for /// Firefox does enable `SCTP_ADD_STREAMS` so, if data consumers are required, OS can be lower (16
/// instance). The mediasoup transport will allocate and announce more outgoing SCTP streams when /// for instance). The mediasoup transport will allocate and announce more outgoing SCTP streams
/// needed. /// when needed.
/// ///
/// mediasoup-client provides specific per browser/version OS and MIS values via the /// mediasoup-client provides specific per browser/version OS and MIS values via the
/// device.sctpCapabilities getter. /// device.sctpCapabilities getter.
...@@ -58,8 +60,8 @@ pub struct SctpParameters { ...@@ -58,8 +60,8 @@ pub struct SctpParameters {
/// SCTP stream parameters describe the reliability of a certain SCTP stream. /// SCTP stream parameters describe the reliability of a certain SCTP stream.
/// ///
/// If ordered is true then max_packet_life_time and max_retransmits must be false. /// If ordered is true then `max_packet_life_time` and `max_retransmits` must be `false`.
/// If ordered if false, only one of max_packet_life_time or max_retransmits can be true. /// If ordered if false, only one of `max_packet_life_time` or max_retransmits can be `true`.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Serialize)] #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SctpStreamParameters { pub struct SctpStreamParameters {
...@@ -81,24 +83,28 @@ pub struct SctpStreamParameters { ...@@ -81,24 +83,28 @@ pub struct SctpStreamParameters {
impl SctpStreamParameters { impl SctpStreamParameters {
/// SCTP stream id. /// SCTP stream id.
#[must_use]
pub fn stream_id(&self) -> u16 { pub fn stream_id(&self) -> u16 {
self.stream_id self.stream_id
} }
/// Whether data messages must be received in order. If `true` the messages will be sent /// Whether data messages must be received in order. If `true` the messages will be sent
/// reliably. /// reliably.
#[must_use]
pub fn ordered(&self) -> bool { pub fn ordered(&self) -> bool {
self.ordered self.ordered
} }
/// When `ordered` is `false` indicates the time (in milliseconds) after which a SCTP packet /// When `ordered` is `false` indicates the time (in milliseconds) after which a SCTP packet
/// will stop being retransmitted. /// will stop being retransmitted.
#[must_use]
pub fn max_packet_life_time(&self) -> Option<u16> { pub fn max_packet_life_time(&self) -> Option<u16> {
self.max_packet_life_time self.max_packet_life_time
} }
/// When `ordered` is `false` indicates the maximum number of times a packet will be /// When `ordered` is `false` indicates the maximum number of times a packet will be
/// retransmitted. /// retransmitted.
#[must_use]
pub fn max_retransmits(&self) -> Option<u16> { pub fn max_retransmits(&self) -> Option<u16> {
self.max_retransmits self.max_retransmits
} }
...@@ -106,6 +112,7 @@ impl SctpStreamParameters { ...@@ -106,6 +112,7 @@ impl SctpStreamParameters {
impl SctpStreamParameters { impl SctpStreamParameters {
/// Messages will be sent reliably in order. /// Messages will be sent reliably in order.
#[must_use]
pub fn new_ordered(stream_id: u16) -> Self { pub fn new_ordered(stream_id: u16) -> Self {
Self { Self {
stream_id, stream_id,
...@@ -117,6 +124,7 @@ impl SctpStreamParameters { ...@@ -117,6 +124,7 @@ impl SctpStreamParameters {
/// Messages will be sent unreliably with time (in milliseconds) after which a SCTP packet will /// Messages will be sent unreliably with time (in milliseconds) after which a SCTP packet will
/// stop being retransmitted. /// stop being retransmitted.
#[must_use]
pub fn new_unordered_with_life_time(stream_id: u16, max_packet_life_time: u16) -> Self { pub fn new_unordered_with_life_time(stream_id: u16, max_packet_life_time: u16) -> Self {
Self { Self {
stream_id, stream_id,
...@@ -127,6 +135,7 @@ impl SctpStreamParameters { ...@@ -127,6 +135,7 @@ impl SctpStreamParameters {
} }
/// Messages will be sent unreliably with a limited number of retransmission attempts. /// Messages will be sent unreliably with a limited number of retransmission attempts.
#[must_use]
pub fn new_unordered_with_retransmits(stream_id: u16, max_retransmits: u16) -> Self { pub fn new_unordered_with_retransmits(stream_id: u16, max_retransmits: u16) -> Self {
Self { Self {
stream_id, stream_id,
......
...@@ -12,9 +12,11 @@ use std::num::{NonZeroU32, NonZeroU8}; ...@@ -12,9 +12,11 @@ use std::num::{NonZeroU32, NonZeroU8};
/// # Notes on usage /// # Notes on usage
/// Those are NOT the RTP capabilities needed by mediasoup-client's /// Those are NOT the RTP capabilities needed by mediasoup-client's
/// [device.load()](https://mediasoup.org/documentation/v3/mediasoup-client/api/#device-load) and /// [device.load()](https://mediasoup.org/documentation/v3/mediasoup-client/api/#device-load) and
/// libmediasoupclient's [device.Load()](https://mediasoup.org/documentation/v3/libmediasoupclient/api/#device-Load) /// libmediasoupclient's
/// methods. There you must use [`Router::rtp_capabilities`](crate::router::Router::rtp_capabilities) /// [device.Load()](https://mediasoup.org/documentation/v3/libmediasoupclient/api/#device-Load)
/// getter instead. /// methods. There you must use
/// [`Router::rtp_capabilities`](crate::router::Router::rtp_capabilities) getter instead.
#[must_use]
pub fn get_supported_rtp_capabilities() -> RtpCapabilities { pub fn get_supported_rtp_capabilities() -> RtpCapabilities {
RtpCapabilities { RtpCapabilities {
codecs: vec![ codecs: vec![
...@@ -193,8 +195,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities { ...@@ -193,8 +195,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
RtcpFeedback::Nack, RtcpFeedback::Nack,
...@@ -209,8 +211,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities { ...@@ -209,8 +211,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 0u32.into()), ("packetization-mode", 0_u32.into()),
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
RtcpFeedback::Nack, RtcpFeedback::Nack,
...@@ -225,8 +227,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities { ...@@ -225,8 +227,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
RtcpFeedback::Nack, RtcpFeedback::Nack,
...@@ -241,8 +243,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities { ...@@ -241,8 +243,8 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 0u32.into()), ("packetization-mode", 0_u32.into()),
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
RtcpFeedback::Nack, RtcpFeedback::Nack,
......
...@@ -23,7 +23,7 @@ pub(crate) use channel::Channel; ...@@ -23,7 +23,7 @@ pub(crate) use channel::Channel;
pub(crate) use common::{SubscriptionHandler, SubscriptionTarget}; pub(crate) use common::{SubscriptionHandler, SubscriptionTarget};
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use futures_lite::FutureExt; use futures_lite::FutureExt;
use log::*; use log::{debug, error, warn};
use parking_lot::Mutex; use parking_lot::Mutex;
pub(crate) use payload_channel::{NotificationError, NotificationMessage, PayloadChannel}; pub(crate) use payload_channel::{NotificationError, NotificationMessage, PayloadChannel};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
...@@ -98,7 +98,7 @@ impl Default for WorkerLogLevel { ...@@ -98,7 +98,7 @@ impl Default for WorkerLogLevel {
} }
impl WorkerLogLevel { impl WorkerLogLevel {
fn as_str(&self) -> &'static str { fn as_str(self) -> &'static str {
match self { match self {
Self::Debug => "debug", Self::Debug => "debug",
Self::Warn => "warn", Self::Warn => "warn",
...@@ -142,7 +142,7 @@ pub enum WorkerLogTag { ...@@ -142,7 +142,7 @@ pub enum WorkerLogTag {
} }
impl WorkerLogTag { impl WorkerLogTag {
fn as_str(&self) -> &'static str { fn as_str(self) -> &'static str {
match self { match self {
Self::Info => "info", Self::Info => "info",
Self::Ice => "ice", Self::Ice => "ice",
...@@ -497,6 +497,7 @@ impl Inner { ...@@ -497,6 +497,7 @@ impl Inner {
/// A worker represents a mediasoup C++ thread that runs on a single CPU core and handles /// A worker represents a mediasoup C++ thread that runs on a single CPU core and handles
/// [`Router`] instances. /// [`Router`] instances.
#[derive(Clone)] #[derive(Clone)]
#[must_use = "Worker will be destroyed on drop, make sure to keep it around for as long as needed"]
pub struct Worker { pub struct Worker {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
...@@ -522,16 +523,19 @@ impl Worker { ...@@ -522,16 +523,19 @@ impl Worker {
} }
/// Worker id. /// Worker id.
#[must_use]
pub fn id(&self) -> WorkerId { pub fn id(&self) -> WorkerId {
self.inner.id self.inner.id
} }
/// Custom application data. /// Custom application data.
#[must_use]
pub fn app_data(&self) -> &AppData { pub fn app_data(&self) -> &AppData {
&self.inner.app_data &self.inner.app_data
} }
/// Whether the worker is closed. /// Whether the worker is closed.
#[must_use]
pub fn closed(&self) -> bool { pub fn closed(&self) -> bool {
self.inner.closed.load(Ordering::SeqCst) self.inner.closed.load(Ordering::SeqCst)
} }
......
...@@ -6,7 +6,7 @@ use async_fs::File; ...@@ -6,7 +6,7 @@ use async_fs::File;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures_lite::io::BufReader; use futures_lite::io::BufReader;
use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
use log::*; use log::{debug, trace, warn};
use lru::LruCache; use lru::LruCache;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
...@@ -134,7 +134,7 @@ pub(crate) struct Channel { ...@@ -134,7 +134,7 @@ pub(crate) struct Channel {
} }
impl Channel { impl Channel {
pub(super) fn new(executor: Arc<Executor<'static>>, reader: File, mut writer: File) -> Self { pub(super) fn new(executor: &Executor<'static>, reader: File, mut writer: File) -> Self {
let requests_container = Arc::<Mutex<RequestsContainer>>::default(); let requests_container = Arc::<Mutex<RequestsContainer>>::default();
let requests_container_weak = Arc::downgrade(&requests_container); let requests_container_weak = Arc::downgrade(&requests_container);
let buffered_notifications_for = let buffered_notifications_for =
...@@ -179,7 +179,7 @@ impl Channel { ...@@ -179,7 +179,7 @@ impl Channel {
bytes.resize(length + 1, 0); bytes.resize(length + 1, 0);
} }
// +1 because of netstring `,` at the very end // +1 because of netstring `,` at the very end
reader.read_exact(&mut bytes[..(length + 1)]).await?; reader.read_exact(&mut bytes[..=length]).await?;
trace!( trace!(
"received raw message: {}", "received raw message: {}",
...@@ -227,8 +227,7 @@ impl Channel { ...@@ -227,8 +227,7 @@ impl Channel {
}) })
}); });
match target_id { if let Some(target_id) = target_id {
Some(target_id) => {
if !non_buffered_notifications.contains(&target_id) { if !non_buffered_notifications.contains(&target_id) {
let mut buffer_notifications_for = let mut buffer_notifications_for =
buffered_notifications_for.lock(); buffered_notifications_for.lock();
...@@ -239,24 +238,21 @@ impl Channel { ...@@ -239,24 +238,21 @@ impl Channel {
{ {
list.push(notification); list.push(notification);
continue; continue;
} else { }
// Remember we don't need to buffer these // Remember we don't need to buffer these
non_buffered_notifications.put(target_id, ()); non_buffered_notifications.put(target_id, ());
} }
}
event_handlers event_handlers
.call_callbacks_with_value(&target_id, notification); .call_callbacks_with_value(&target_id, notification);
} } else {
None => { let unexpected_message =
let unexpected_message = InternalMessage::Unexpected( InternalMessage::Unexpected(Vec::from(&bytes[..length]));
Vec::from(&bytes[..length]),
);
if sender.send(unexpected_message).await.is_err() { if sender.send(unexpected_message).await.is_err() {
break; break;
} }
} }
} }
}
ChannelReceiveMessage::Event(event_message) => { ChannelReceiveMessage::Event(event_message) => {
if sender.send(event_message).await.is_err() { if sender.send(event_message).await.is_err() {
break; break;
......
...@@ -6,7 +6,7 @@ use async_fs::File; ...@@ -6,7 +6,7 @@ use async_fs::File;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures_lite::io::BufReader; use futures_lite::io::BufReader;
use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
use log::*; use log::{debug, error, trace, warn};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
...@@ -111,7 +111,7 @@ pub(crate) struct PayloadChannel { ...@@ -111,7 +111,7 @@ pub(crate) struct PayloadChannel {
} }
impl PayloadChannel { impl PayloadChannel {
pub(super) fn new(executor: Arc<Executor<'static>>, reader: File, mut writer: File) -> Self { pub(super) fn new(executor: &Executor<'static>, reader: File, mut writer: File) -> Self {
let requests_container = Arc::<Mutex<RequestsContainer>>::default(); let requests_container = Arc::<Mutex<RequestsContainer>>::default();
let requests_container_weak = Arc::downgrade(&requests_container); let requests_container_weak = Arc::downgrade(&requests_container);
let event_handlers = EventHandlers::new(); let event_handlers = EventHandlers::new();
...@@ -149,7 +149,7 @@ impl PayloadChannel { ...@@ -149,7 +149,7 @@ impl PayloadChannel {
bytes.resize(length + 1, 0); bytes.resize(length + 1, 0);
} }
// +1 because of netstring `,` at the very end // +1 because of netstring `,` at the very end
reader.read_exact(&mut bytes[..(length + 1)]).await?; reader.read_exact(&mut bytes[..=length]).await?;
trace!( trace!(
"received raw message: {}", "received raw message: {}",
...@@ -216,14 +216,13 @@ impl PayloadChannel { ...@@ -216,14 +216,13 @@ impl PayloadChannel {
len_bytes.clear(); len_bytes.clear();
// +1 because of netstring `,` at the very end // +1 because of netstring `,` at the very end
reader.read_exact(&mut bytes[..(length + 1)]).await?; reader.read_exact(&mut bytes[..=length]).await?;
trace!("received notification payload of {} bytes", length); trace!("received notification payload of {} bytes", length);
let payload = Bytes::copy_from_slice(&bytes[..length]); let payload = Bytes::copy_from_slice(&bytes[..length]);
match target_id { if let Some(target_id) = target_id {
Some(target_id) => {
event_handlers.call_callbacks_with_value( event_handlers.call_callbacks_with_value(
&target_id, &target_id,
NotificationMessage { NotificationMessage {
...@@ -231,8 +230,7 @@ impl PayloadChannel { ...@@ -231,8 +230,7 @@ impl PayloadChannel {
payload, payload,
}, },
); );
} } else {
None => {
let unexpected_message = InternalMessage::UnexpectedData( let unexpected_message = InternalMessage::UnexpectedData(
Vec::from(&bytes[..length]), Vec::from(&bytes[..length]),
); );
...@@ -241,7 +239,6 @@ impl PayloadChannel { ...@@ -241,7 +239,6 @@ impl PayloadChannel {
} }
} }
} }
}
PayloadChannelReceiveMessage::Internal(internal_message) => { PayloadChannelReceiveMessage::Internal(internal_message) => {
if sender.send(internal_message).await.is_err() { if sender.send(internal_message).await.is_err() {
break; break;
......
...@@ -35,7 +35,7 @@ fn pipe() -> [c_int; 2] { ...@@ -35,7 +35,7 @@ fn pipe() -> [c_int; 2] {
unsafe { unsafe {
let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit(); let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit();
if libc::pipe(fds.as_mut_ptr() as *mut c_int) != 0 { if libc::pipe(fds.as_mut_ptr().cast::<c_int>()) != 0 {
panic!( panic!(
"libc::pipe() failed with code {}", "libc::pipe() failed with code {}",
*libc::__errno_location() *libc::__errno_location()
...@@ -69,9 +69,9 @@ pub(super) fn run_worker_with_channels( ...@@ -69,9 +69,9 @@ pub(super) fn run_worker_with_channels(
let producer_payload_file = unsafe { File::from_raw_fd(producer_payload_fd_write) }; let producer_payload_file = unsafe { File::from_raw_fd(producer_payload_fd_write) };
let consumer_payload_file = unsafe { File::from_raw_fd(consumer_payload_fd_read) }; let consumer_payload_file = unsafe { File::from_raw_fd(consumer_payload_fd_read) };
let channel = Channel::new(Arc::clone(&executor), consumer_file, producer_file); let channel = Channel::new(&executor, consumer_file, producer_file);
let payload_channel = let payload_channel =
PayloadChannel::new(executor, consumer_payload_file, producer_payload_file); PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file);
let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into()); let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into());
std::thread::Builder::new() std::thread::Builder::new()
...@@ -84,7 +84,7 @@ pub(super) fn run_worker_with_channels( ...@@ -84,7 +84,7 @@ pub(super) fn run_worker_with_channels(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let argv = args_cstring let argv = args_cstring
.iter() .iter()
.map(|arg| arg.as_ptr() as *const c_char) .map(|arg| arg.as_ptr().cast::<c_char>())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap(); let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap();
let status_code = unsafe { let status_code = unsafe {
......
...@@ -48,6 +48,7 @@ struct Inner { ...@@ -48,6 +48,7 @@ struct Inner {
/// multi-threaded executor, [`WorkerManager::with_executor()`] can be used to create an instance /// multi-threaded executor, [`WorkerManager::with_executor()`] can be used to create an instance
/// instead. /// instead.
#[derive(Clone)] #[derive(Clone)]
#[must_use]
pub struct WorkerManager { pub struct WorkerManager {
inner: Arc<Inner>, inner: Arc<Inner>,
} }
......
...@@ -18,7 +18,7 @@ fn worker_manager_test() { ...@@ -18,7 +18,7 @@ fn worker_manager_test() {
let worker_manager = WorkerManager::new(); let worker_manager = WorkerManager::new();
future::block_on(async move { future::block_on(async move {
worker_manager let _ = worker_manager
.create_worker(WorkerSettings::default()) .create_worker(WorkerSettings::default())
.await .await
.unwrap(); .unwrap();
......
...@@ -19,7 +19,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -19,7 +19,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
......
...@@ -57,8 +57,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -57,8 +57,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
...@@ -78,8 +78,8 @@ fn audio_producer_options() -> ProducerOptions { ...@@ -78,8 +78,8 @@ fn audio_producer_options() -> ProducerOptions {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("usedtx", 1u32.into()), ("usedtx", 1_u32.into()),
("foo", "222.222".into()), ("foo", "222.222".into()),
("bar", "333".into()), ("bar", "333".into()),
]), ]),
...@@ -124,7 +124,7 @@ fn video_producer_options() -> ProducerOptions { ...@@ -124,7 +124,7 @@ fn video_producer_options() -> ProducerOptions {
payload_type: 112, payload_type: 112,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -203,8 +203,8 @@ fn consumer_device_capabilities() -> RtpCapabilities { ...@@ -203,8 +203,8 @@ fn consumer_device_capabilities() -> RtpCapabilities {
preferred_payload_type: Some(101), preferred_payload_type: Some(101),
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -218,7 +218,7 @@ fn consumer_device_capabilities() -> RtpCapabilities { ...@@ -218,7 +218,7 @@ fn consumer_device_capabilities() -> RtpCapabilities {
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
preferred_payload_type: Some(102), preferred_payload_type: Some(102),
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
], ],
...@@ -387,8 +387,8 @@ fn consume_succeeds() { ...@@ -387,8 +387,8 @@ fn consume_succeeds() {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("usedtx", 1u32.into()), ("usedtx", 1_u32.into()),
("foo", "222.222".into()), ("foo", "222.222".into()),
("bar", "333".into()), ("bar", "333".into()),
]), ]),
...@@ -474,7 +474,7 @@ fn consume_succeeds() { ...@@ -474,7 +474,7 @@ fn consume_succeeds() {
payload_type: 103, payload_type: 103,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -579,7 +579,7 @@ fn consume_succeeds() { ...@@ -579,7 +579,7 @@ fn consume_succeeds() {
payload_type: 103, payload_type: 103,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -796,8 +796,8 @@ fn dump_succeeds() { ...@@ -796,8 +796,8 @@ fn dump_succeeds() {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("usedtx", 1u32.into()), ("usedtx", 1_u32.into()),
("foo", "222.222".into()), ("foo", "222.222".into()),
("bar", "333".into()), ("bar", "333".into()),
]), ]),
...@@ -897,7 +897,7 @@ fn dump_succeeds() { ...@@ -897,7 +897,7 @@ fn dump_succeeds() {
payload_type: 103, payload_type: 103,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
......
...@@ -36,10 +36,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -36,10 +36,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::default(),
("useinbandfec", 1u32.into()),
("foo", "bar".into()),
]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
RtpCodecCapability::Video { RtpCodecCapability::Video {
...@@ -63,7 +60,7 @@ fn audio_producer_options() -> ProducerOptions { ...@@ -63,7 +60,7 @@ fn audio_producer_options() -> ProducerOptions {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar1".into()), ("foo", "bar1".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -185,7 +182,7 @@ fn consumer_device_capabilities() -> RtpCapabilities { ...@@ -185,7 +182,7 @@ fn consumer_device_capabilities() -> RtpCapabilities {
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
preferred_payload_type: Some(102), preferred_payload_type: Some(102),
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
], ],
...@@ -313,7 +310,7 @@ fn pipe_to_router_succeeds_with_audio() { ...@@ -313,7 +310,7 @@ fn pipe_to_router_succeeds_with_audio() {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar1".into()), ("foo", "bar1".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -351,7 +348,7 @@ fn pipe_to_router_succeeds_with_audio() { ...@@ -351,7 +348,7 @@ fn pipe_to_router_succeeds_with_audio() {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar1".into()), ("foo", "bar1".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -604,7 +601,7 @@ fn create_with_enable_rtx_succeeds() { ...@@ -604,7 +601,7 @@ fn create_with_enable_rtx_succeeds() {
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
payload_type: 102, payload_type: 102,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
], ],
...@@ -783,7 +780,7 @@ fn consume_for_pipe_producer_succeeds() { ...@@ -783,7 +780,7 @@ fn consume_for_pipe_producer_succeeds() {
mime_type: MimeTypeVideo::Rtx, mime_type: MimeTypeVideo::Rtx,
payload_type: 102, payload_type: 102,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([("apt", 101u32.into())]), parameters: RtpCodecParametersParameters::from([("apt", 101_u32.into())]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
], ],
......
...@@ -31,7 +31,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -31,7 +31,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -48,8 +48,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -48,8 +48,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
...@@ -168,7 +168,7 @@ fn create_succeeds() { ...@@ -168,7 +168,7 @@ fn create_succeeds() {
port: 5000, port: 5000,
os: 1024, os: 1024,
mis: 1024, mis: 1024,
max_message_size: 262144, max_message_size: 262_144,
}), }),
); );
assert_eq!(transport1.sctp_state(), Some(SctpState::New)); assert_eq!(transport1.sctp_state(), Some(SctpState::New));
......
...@@ -46,8 +46,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -46,8 +46,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
...@@ -67,8 +67,8 @@ fn audio_producer_options() -> ProducerOptions { ...@@ -67,8 +67,8 @@ fn audio_producer_options() -> ProducerOptions {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("usedtx", 1u32.into()), ("usedtx", 1_u32.into()),
("foo", "222.222".into()), ("foo", "222.222".into()),
("bar", "333".into()), ("bar", "333".into()),
]), ]),
...@@ -111,7 +111,7 @@ fn video_producer_options() -> ProducerOptions { ...@@ -111,7 +111,7 @@ fn video_producer_options() -> ProducerOptions {
payload_type: 112, payload_type: 112,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![ rtcp_feedback: vec![
...@@ -387,7 +387,7 @@ fn produce_wrong_arguments() { ...@@ -387,7 +387,7 @@ fn produce_wrong_arguments() {
payload_type: 112, payload_type: 112,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -425,7 +425,7 @@ fn produce_wrong_arguments() { ...@@ -425,7 +425,7 @@ fn produce_wrong_arguments() {
payload_type: 112, payload_type: 112,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -436,7 +436,7 @@ fn produce_wrong_arguments() { ...@@ -436,7 +436,7 @@ fn produce_wrong_arguments() {
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([( parameters: RtpCodecParametersParameters::from([(
"apt", "apt",
111u32.into(), 111_u32.into(),
)]), )]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
}, },
...@@ -506,7 +506,7 @@ fn produce_unsupported_codecs() { ...@@ -506,7 +506,7 @@ fn produce_unsupported_codecs() {
payload_type: 112, payload_type: 112,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "CHICKEN".into()), ("profile-level-id", "CHICKEN".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
......
...@@ -20,7 +20,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -20,7 +20,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -37,8 +37,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -37,8 +37,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
]), ]),
rtcp_feedback: vec![], // Will be ignored. rtcp_feedback: vec![], // Will be ignored.
......
...@@ -34,7 +34,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -34,7 +34,7 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
clock_rate: NonZeroU32::new(48000).unwrap(), clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(2).unwrap(), channels: NonZeroU8::new(2).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1u32.into()), ("useinbandfec", 1_u32.into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
rtcp_feedback: vec![], rtcp_feedback: vec![],
...@@ -51,8 +51,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> { ...@@ -51,8 +51,8 @@ fn media_codecs() -> Vec<RtpCodecCapability> {
preferred_payload_type: None, preferred_payload_type: None,
clock_rate: NonZeroU32::new(90000).unwrap(), clock_rate: NonZeroU32::new(90000).unwrap(),
parameters: RtpCodecParametersParameters::from([ parameters: RtpCodecParametersParameters::from([
("level-asymmetry-allowed", 1u32.into()), ("level-asymmetry-allowed", 1_u32.into()),
("packetization-mode", 1u32.into()), ("packetization-mode", 1_u32.into()),
("profile-level-id", "4d0032".into()), ("profile-level-id", "4d0032".into()),
("foo", "bar".into()), ("foo", "bar".into()),
]), ]),
......
...@@ -293,9 +293,12 @@ inline void Worker::OnChannelClosed(Channel::UnixStreamSocket* /*socket*/) ...@@ -293,9 +293,12 @@ inline void Worker::OnChannelClosed(Channel::UnixStreamSocket* /*socket*/)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
// Only needed for executable, library user can close channel earlier and it is fine.
#ifdef MS_EXECUTABLE
// If the pipe is remotely closed it may mean that mediasoup Node process // If the pipe is remotely closed it may mean that mediasoup Node process
// abruptly died (SIGKILL?) so we must die. // abruptly died (SIGKILL?) so we must die.
MS_ERROR_STD("channel remotely closed, closing myself"); MS_ERROR_STD("channel remotely closed, closing myself");
#endif
Close(); Close();
} }
...@@ -333,9 +336,12 @@ inline void Worker::OnPayloadChannelClosed(PayloadChannel::UnixStreamSocket* /*p ...@@ -333,9 +336,12 @@ inline void Worker::OnPayloadChannelClosed(PayloadChannel::UnixStreamSocket* /*p
{ {
MS_TRACE(); MS_TRACE();
// Only needed for executable, library user can close channel earlier and it is fine.
#ifdef MS_EXECUTABLE
// If the pipe is remotely closed it may mean that mediasoup Node process // If the pipe is remotely closed it may mean that mediasoup Node process
// abruptly died (SIGKILL?) so we must die. // abruptly died (SIGKILL?) so we must die.
MS_ERROR_STD("payloadChannel remotely closed, closing myself"); MS_ERROR_STD("payloadChannel remotely closed, closing myself");
#endif
Close(); Close();
} }
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论