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