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

Merge pull request #666 from nazar-pc/rust-next

Rust updates and optimizations around communication performance
...@@ -22,11 +22,6 @@ jobs: ...@@ -22,11 +22,6 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Rust toolchain - name: Rust toolchain
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
......
...@@ -207,7 +207,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -207,7 +207,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// the response, destroying the ordered delivery. So we must wait a bit // the response, destroying the ordered delivery. So we must wait a bit
// here. // here.
// See https://github.com/versatica/mediasoup/issues/510 // See https://github.com/versatica/mediasoup/issues/510
setImmediate(() => this.emit(msg.targetId, msg.event, msg.data)); setImmediate(() => this.emit(String(msg.targetId), msg.event, msg.data));
} }
// Otherwise unexpected message. // Otherwise unexpected message.
else { else {
......
...@@ -213,7 +213,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -213,7 +213,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
else if (msg.targetId && msg.event) { else if (msg.targetId && msg.event) {
this.#ongoingNotification = this.#ongoingNotification =
{ {
targetId: msg.targetId, targetId: String(msg.targetId),
event: msg.event, event: msg.event,
data: msg.data data: msg.data
}; };
......
...@@ -330,7 +330,7 @@ export class Channel extends EnhancedEventEmitter ...@@ -330,7 +330,7 @@ export class Channel extends EnhancedEventEmitter
// the response, destroying the ordered delivery. So we must wait a bit // the response, destroying the ordered delivery. So we must wait a bit
// here. // here.
// See https://github.com/versatica/mediasoup/issues/510 // See https://github.com/versatica/mediasoup/issues/510
setImmediate(() => this.emit(msg.targetId, msg.event, msg.data)); setImmediate(() => this.emit(String(msg.targetId), msg.event, msg.data));
} }
// Otherwise unexpected message. // Otherwise unexpected message.
else else
......
...@@ -354,7 +354,7 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -354,7 +354,7 @@ export class PayloadChannel extends EnhancedEventEmitter
{ {
this.#ongoingNotification = this.#ongoingNotification =
{ {
targetId : msg.targetId, targetId : String(msg.targetId),
event : msg.event, event : msg.event,
data : msg.data data : msg.data
}; };
......
...@@ -3,6 +3,11 @@ ...@@ -3,6 +3,11 @@
# Unreleased # Unreleased
* Fix for receiving data over payload channel * Fix for receiving data over payload channel
* Support thread initializer function for worker threads, can be used for pinning worker threads to CPU cores
* Significant worker communication optimizations (especially latency)
* Switch from file descriptors to function calls when communicating with worker
* Various optimizations that caused minor breaking changes to public API
* Requests no longer have internal timeout, but they can now be cancelled, add your own timeouts on top if needed
# 0.8.5 # 0.8.5
......
...@@ -22,33 +22,32 @@ targets = [] ...@@ -22,33 +22,32 @@ targets = []
[dependencies] [dependencies]
async-channel = "1.6.1" async-channel = "1.6.1"
async-executor = "1.4.1" async-executor = "1.4.1"
async-fs = "1.5.0"
async-io = "1.6.0"
async-lock = "2.4.0" async-lock = "2.4.0"
async-oneshot = "0.5.0" async-oneshot = "0.5.0"
async-trait = "0.1.50" async-trait = "0.1.51"
bytes = "1.0.1" atomic-take = "1.0.0"
event-listener-primitives = "1.0.0" event-listener-primitives = "2.0.1"
fastrand = "1.5.0" fastrand = "1.5.0"
futures-lite = "1.12.0" futures-lite = "1.12.0"
h264-profile-level-id = "0.1.1" h264-profile-level-id = "0.1.1"
hash_hasher = "2.0.3"
log = "0.4.14" log = "0.4.14"
libc = "0.2.98" nohash-hasher = "0.2.0"
once_cell = "1.8.0" once_cell = "1.8.0"
serde_json = "1.0.64" serde_json = "1.0.67"
serde_repr = "0.1.7" serde_repr = "0.1.7"
thiserror = "1.0.26" thiserror = "1.0.28"
[dependencies.lru] [dependencies.lru]
default-features = false default-features = false
version = "0.6.5" version = "0.6.6"
[dependencies.mediasoup-sys] [dependencies.mediasoup-sys]
path = "../worker" path = "../worker"
version = "0.2.5" version = "0.2.5"
[dependencies.parking_lot] [dependencies.parking_lot]
version = "0.11.1" version = "0.11.2"
features = ["serde"] features = ["serde"]
[dependencies.regex] [dependencies.regex]
...@@ -58,7 +57,7 @@ version = "1.5.4" ...@@ -58,7 +57,7 @@ version = "1.5.4"
[dependencies.serde] [dependencies.serde]
features = ["derive"] features = ["derive"]
version = "1.0.126" version = "1.0.130"
[dependencies.uuid] [dependencies.uuid]
features = ["serde", "v4"] features = ["serde", "v4"]
...@@ -66,13 +65,14 @@ version = "0.8.2" ...@@ -66,13 +65,14 @@ version = "0.8.2"
[dev-dependencies] [dev-dependencies]
actix = "0.12.0" actix = "0.12.0"
actix-web = "4.0.0-beta.8"
actix-web-actors = "4.0.0-beta.6" actix-web-actors = "4.0.0-beta.6"
async-io = "1.6.0"
criterion = "0.3.5"
env_logger = "0.9.0" env_logger = "0.9.0"
[dev-dependencies.criterion] [dev-dependencies.actix-web]
version = "0.3.5" default-features = false
features = ["async_futures"] version = "4.0.0-beta.8"
[[bench]] [[bench]]
name = "direct_data" name = "direct_data"
......
use bytes::Bytes;
use criterion::async_executor::FuturesExecutor;
use criterion::{criterion_group, criterion_main, Criterion}; use criterion::{criterion_group, criterion_main, Criterion};
use futures_lite::StreamExt;
use mediasoup::prelude::*; use mediasoup::prelude::*;
use std::borrow::Cow;
use std::sync::mpsc;
async fn create_data_producer_consumer_pair( async fn create_data_producer_consumer_pair(
) -> Result<(DataProducer, DataConsumer), Box<dyn std::error::Error>> { ) -> Result<(DataProducer, DataConsumer), Box<dyn std::error::Error>> {
...@@ -29,32 +28,10 @@ async fn create_data_producer_consumer_pair( ...@@ -29,32 +28,10 @@ async fn create_data_producer_consumer_pair(
pub fn criterion_benchmark(c: &mut Criterion) { pub fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("direct_data"); let mut group = c.benchmark_group("direct_data");
let data = Bytes::from( let data = std::iter::repeat_with(|| fastrand::u8(..))
std::iter::repeat_with(|| fastrand::u8(..))
.take(512) .take(512)
.collect::<Vec<u8>>(), .collect::<Vec<u8>>();
);
{
let (data_producer, _data_consumer) = futures_lite::future::block_on(async {
create_data_producer_consumer_pair().await.unwrap()
});
let direct_data_producer =
if let DataProducer::Direct(direct_data_producer) = data_producer.clone() {
direct_data_producer
} else {
unreachable!()
};
group.bench_with_input("send", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async {
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.await;
})
});
}
{ {
let (data_producer, data_consumer) = futures_lite::future::block_on(async { let (data_producer, data_consumer) = futures_lite::future::block_on(async {
create_data_producer_consumer_pair().await.unwrap() create_data_producer_consumer_pair().await.unwrap()
...@@ -68,17 +45,15 @@ pub fn criterion_benchmark(c: &mut Criterion) { ...@@ -68,17 +45,15 @@ pub fn criterion_benchmark(c: &mut Criterion) {
}; };
group.bench_with_input("recv", &data, |b, data| { group.bench_with_input("recv", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async { b.iter(|| {
let (sender, mut receiver) = async_channel::unbounded::<()>(); let (sender, receiver) = mpsc::sync_channel(1);
let _handler_id = data_consumer.on_message(move |_message| { let _handler_id = data_consumer.on_message(move |_message| {
let _ = sender.try_send(()); let _ = sender.send(());
}); });
let _ = direct_data_producer let _ = direct_data_producer.send(WebRtcMessage::Binary(Cow::from(data)));
.send(WebRtcMessage::Binary(data.clone()))
.await;
let _ = receiver.next().await; let _ = receiver.recv();
}) })
}); });
} }
......
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path'); const path = require('path');
module.exports = { module.exports = {
...@@ -22,6 +21,9 @@ module.exports = { ...@@ -22,6 +21,9 @@ module.exports = {
}, },
devServer : { devServer : {
liveReload : false, liveReload : false,
port : 3001 port : 3001,
static : {
directory: __dirname
}
} }
}; };
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path'); const path = require('path');
module.exports = { module.exports = {
...@@ -22,6 +21,9 @@ module.exports = { ...@@ -22,6 +21,9 @@ module.exports = {
}, },
devServer : { devServer : {
liveReload : false, liveReload : false,
port : 3001 port : 3001,
static : {
directory: __dirname
}
} }
}; };
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path'); const path = require('path');
module.exports = { module.exports = {
...@@ -22,6 +21,9 @@ module.exports = { ...@@ -22,6 +21,9 @@ module.exports = {
}, },
devServer : { devServer : {
liveReload : false, liveReload : false,
port : 3001 port : 3001,
static : {
directory: __dirname
}
} }
}; };
...@@ -37,8 +37,10 @@ mod room { ...@@ -37,8 +37,10 @@ mod room {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
producer_add: Bag<Box<dyn Fn(&ParticipantId, &Producer) + Send + Sync>>, producer_add:
producer_remove: Bag<Box<dyn Fn(&ParticipantId, &ProducerId) + Send + Sync>>, Bag<Arc<dyn Fn(&ParticipantId, &Producer) + Send + Sync>, ParticipantId, Producer>,
producer_remove:
Bag<Arc<dyn Fn(&ParticipantId, &ProducerId) + Send + Sync>, ParticipantId, ProducerId>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -146,9 +148,10 @@ mod room { ...@@ -146,9 +148,10 @@ mod room {
.or_default() .or_default()
.push(producer.clone()); .push(producer.clone());
self.inner.handlers.producer_add.call(|callback| { self.inner
callback(&participant_id, &producer); .handlers
}); .producer_add
.call_simple(&participant_id, &producer);
} }
/// Remove participant and all of its associated producers /// Remove participant and all of its associated producers
...@@ -157,9 +160,10 @@ mod room { ...@@ -157,9 +160,10 @@ mod room {
for producer in producers.unwrap_or_default() { for producer in producers.unwrap_or_default() {
let producer_id = &producer.id(); let producer_id = &producer.id();
self.inner.handlers.producer_remove.call(|callback| { self.inner
callback(participant_id, producer_id); .handlers
}); .producer_remove
.call_simple(participant_id, producer_id);
} }
} }
...@@ -185,7 +189,7 @@ mod room { ...@@ -185,7 +189,7 @@ mod room {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.producer_add.add(Box::new(callback)) self.inner.handlers.producer_add.add(Arc::new(callback))
} }
/// Subscribe to notifications when producer is removed from the room /// Subscribe to notifications when producer is removed from the room
...@@ -193,7 +197,7 @@ mod room { ...@@ -193,7 +197,7 @@ mod room {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.producer_remove.add(Box::new(callback)) self.inner.handlers.producer_remove.add(Arc::new(callback))
} }
/// Subscribe to notification when room is closed /// Subscribe to notification when room is closed
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
use bytes::Bytes;
use serde::de::{MapAccess, Visitor}; use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeStruct; use serde::ser::SerializeStruct;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
...@@ -770,18 +769,18 @@ pub enum TraceEventDirection { ...@@ -770,18 +769,18 @@ pub enum TraceEventDirection {
/// Container used for sending/receiving messages using `DirectTransport` data producers and data /// Container used for sending/receiving messages using `DirectTransport` data producers and data
/// consumers. /// consumers.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum WebRtcMessage { pub enum WebRtcMessage<'a> {
/// String /// String
String(String), String(String),
/// Binary /// Binary
Binary(Bytes), Binary(Cow<'a, [u8]>),
/// EmptyString /// EmptyString
EmptyString, EmptyString,
/// EmptyBinary /// EmptyBinary
EmptyBinary, EmptyBinary,
} }
impl WebRtcMessage { impl<'a> WebRtcMessage<'a> {
// +------------------------------------+-----------+ // +------------------------------------+-----------+
// | Value | SCTP PPID | // | Value | SCTP PPID |
// +------------------------------------+-----------+ // +------------------------------------+-----------+
...@@ -793,7 +792,7 @@ impl WebRtcMessage { ...@@ -793,7 +792,7 @@ impl WebRtcMessage {
// | WebRTC Binary Empty | 57 | // | WebRTC Binary Empty | 57 |
// +------------------------------------+-----------+ // +------------------------------------+-----------+
pub(crate) fn new(ppid: u32, payload: Bytes) -> Result<Self, u32> { pub(crate) fn new(ppid: u32, payload: Cow<'a, [u8]>) -> Result<Self, u32> {
match ppid { match ppid {
51 => Ok(WebRtcMessage::String( 51 => Ok(WebRtcMessage::String(
String::from_utf8(payload.to_vec()).unwrap(), String::from_utf8(payload.to_vec()).unwrap(),
...@@ -805,12 +804,12 @@ impl WebRtcMessage { ...@@ -805,12 +804,12 @@ impl WebRtcMessage {
} }
} }
pub(crate) fn into_ppid_and_payload(self) -> (u32, Bytes) { pub(crate) fn into_ppid_and_payload(self) -> (u32, Cow<'a, [u8]>) {
match self { match self {
WebRtcMessage::String(string) => (51_u32, Bytes::from(string)), WebRtcMessage::String(string) => (51_u32, Cow::from(string.into_bytes())),
WebRtcMessage::Binary(binary) => (53_u32, binary), WebRtcMessage::Binary(binary) => (53_u32, binary),
WebRtcMessage::EmptyString => (56_u32, Bytes::from_static(b" ")), WebRtcMessage::EmptyString => (56_u32, Cow::from(b" ".as_ref())),
WebRtcMessage::EmptyBinary => (57_u32, Bytes::from(vec![0_u8])), WebRtcMessage::EmptyBinary => (57_u32, Cow::from(vec![0_u8])),
} }
} }
} }
......
...@@ -28,8 +28,8 @@ use crate::worker::{WorkerDump, WorkerUpdateSettings}; ...@@ -28,8 +28,8 @@ use crate::worker::{WorkerDump, WorkerUpdateSettings};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt::Debug; use std::fmt::Debug;
use std::marker::PhantomData;
use std::net::IpAddr; use std::net::IpAddr;
use std::num::NonZeroU16; use std::num::NonZeroU16;
...@@ -149,32 +149,6 @@ macro_rules! request_response { ...@@ -149,32 +149,6 @@ macro_rules! request_response {
}; };
} }
macro_rules! request_response_generic {
(
$method: literal,
$request_struct_name: ident { $( $request_field_name: ident: $request_field_type: ty$(,)? )* },
$generic_response: ident,
) => {
#[derive(Debug, Serialize)]
pub(crate) struct $request_struct_name<$generic_response>
where
$generic_response: Debug + DeserializeOwned,
{
$( pub(crate) $request_field_name: $request_field_type, )*
#[serde(skip)]
pub(crate) phantom_data: PhantomData<$generic_response>,
}
impl<$generic_response: Debug + DeserializeOwned> Request for $request_struct_name<$generic_response> {
type Response = $generic_response;
fn as_method(&self) -> &'static str {
$method
}
}
};
}
request_response!("worker.close", WorkerCloseRequest {}); request_response!("worker.close", WorkerCloseRequest {});
request_response!("worker.dump", WorkerDumpRequest {}, WorkerDump); request_response!("worker.dump", WorkerDumpRequest {}, WorkerDump);
...@@ -333,8 +307,9 @@ request_response!( ...@@ -333,8 +307,9 @@ request_response!(
data: RouterCreatePlainTransportData, data: RouterCreatePlainTransportData,
}, },
PlainTransportData { PlainTransportData {
rtcp_mux: bool, // The following fields are present, but unused
comedia: bool, // rtcp_mux: bool,
// comedia: bool,
tuple: Mutex<TransportTuple>, tuple: Mutex<TransportTuple>,
rtcp_tuple: Mutex<Option<TransportTuple>>, rtcp_tuple: Mutex<Option<TransportTuple>>,
sctp_parameters: Option<SctpParameters>, sctp_parameters: Option<SctpParameters>,
...@@ -446,20 +421,20 @@ request_response!( ...@@ -446,20 +421,20 @@ request_response!(
}, },
); );
request_response_generic!( request_response!(
"transport.dump", "transport.dump",
TransportDumpRequest { TransportDumpRequest {
internal: TransportInternal, internal: TransportInternal,
}, },
Dump, Value,
); );
request_response_generic!( request_response!(
"transport.getStats", "transport.getStats",
TransportGetStatsRequest { TransportGetStatsRequest {
internal: TransportInternal, internal: TransportInternal,
}, },
Stats, Value,
); );
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
...@@ -470,7 +445,7 @@ pub(crate) struct TransportConnectRequestWebRtcData { ...@@ -470,7 +445,7 @@ pub(crate) struct TransportConnectRequestWebRtcData {
request_response!( request_response!(
"transport.connect", "transport.connect",
TransportConnectRequestWebRtc { TransportConnectWebRtcRequest {
internal: TransportInternal, internal: TransportInternal,
data: TransportConnectRequestWebRtcData, data: TransportConnectRequestWebRtcData,
}, },
...@@ -490,7 +465,7 @@ pub(crate) struct TransportConnectRequestPipeData { ...@@ -490,7 +465,7 @@ pub(crate) struct TransportConnectRequestPipeData {
request_response!( request_response!(
"transport.connect", "transport.connect",
TransportConnectRequestPipe { TransportConnectPipeRequest {
internal: TransportInternal, internal: TransportInternal,
data: TransportConnectRequestPipeData, data: TransportConnectRequestPipeData,
}, },
...@@ -514,7 +489,7 @@ pub(crate) struct TransportConnectRequestPlainData { ...@@ -514,7 +489,7 @@ pub(crate) struct TransportConnectRequestPlainData {
request_response!( request_response!(
"transport.connect", "transport.connect",
TransportConnectRequestPlain { TransportConnectPlainRequest {
internal: TransportInternal, internal: TransportInternal,
data: TransportConnectRequestPlainData, data: TransportConnectRequestPlainData,
}, },
......
...@@ -59,10 +59,10 @@ use async_executor::Executor; ...@@ -59,10 +59,10 @@ use async_executor::Executor;
use async_lock::Mutex as AsyncMutex; use async_lock::Mutex as AsyncMutex;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use futures_lite::future; use futures_lite::future;
use hash_hasher::{HashedMap, HashedSet};
use log::{debug, error}; use log::{debug, error};
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt; use std::fmt;
use std::ops::Deref; use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
...@@ -270,13 +270,14 @@ impl From<ProduceDataError> for PipeDataProducerToRouterError { ...@@ -270,13 +270,14 @@ impl From<ProduceDataError> for PipeDataProducerToRouterError {
#[non_exhaustive] #[non_exhaustive]
pub struct RouterDump { pub struct RouterDump {
pub id: RouterId, pub id: RouterId,
pub map_consumer_id_producer_id: HashMap<ConsumerId, ProducerId>, pub map_consumer_id_producer_id: HashedMap<ConsumerId, ProducerId>,
pub map_data_consumer_id_data_producer_id: HashMap<DataConsumerId, DataProducerId>, pub map_data_consumer_id_data_producer_id: HashedMap<DataConsumerId, DataProducerId>,
pub map_data_producer_id_data_consumer_ids: HashMap<DataProducerId, HashSet<DataConsumerId>>, pub map_data_producer_id_data_consumer_ids:
pub map_producer_id_consumer_ids: HashMap<ProducerId, HashSet<ConsumerId>>, HashedMap<DataProducerId, HashedSet<DataConsumerId>>,
pub map_producer_id_observer_ids: HashMap<ProducerId, HashSet<RtpObserverId>>, pub map_producer_id_consumer_ids: HashedMap<ProducerId, HashedSet<ConsumerId>>,
pub rtp_observer_ids: HashSet<RtpObserverId>, pub map_producer_id_observer_ids: HashedMap<ProducerId, HashedSet<RtpObserverId>>,
pub transport_ids: HashSet<TransportId>, pub rtp_observer_ids: HashedSet<RtpObserverId>,
pub transport_ids: HashedSet<TransportId>,
} }
/// New transport that was just created. /// New transport that was just created.
...@@ -355,8 +356,8 @@ impl WeakPipeTransportPair { ...@@ -355,8 +356,8 @@ impl WeakPipeTransportPair {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
new_transport: Bag<Box<dyn Fn(NewTransport<'_>) + Send + Sync>>, new_transport: Bag<Arc<dyn Fn(NewTransport<'_>) + Send + Sync>>,
new_rtp_observer: Bag<Box<dyn Fn(NewRtpObserver<'_>) + Send + Sync>>, new_rtp_observer: Bag<Arc<dyn Fn(NewRtpObserver<'_>) + Send + Sync>>,
worker_close: BagOnce<Box<dyn FnOnce() + Send>>, worker_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -369,11 +370,11 @@ struct Inner { ...@@ -369,11 +370,11 @@ struct Inner {
payload_channel: PayloadChannel, payload_channel: PayloadChannel,
handlers: Arc<Handlers>, handlers: Arc<Handlers>,
app_data: AppData, app_data: AppData,
producers: Arc<RwLock<HashMap<ProducerId, WeakProducer>>>, producers: Arc<RwLock<HashedMap<ProducerId, WeakProducer>>>,
data_producers: Arc<RwLock<HashMap<DataProducerId, WeakDataProducer>>>, data_producers: Arc<RwLock<HashedMap<DataProducerId, WeakDataProducer>>>,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
mapped_pipe_transports: mapped_pipe_transports:
Arc<Mutex<HashMap<RouterId, Arc<AsyncMutex<Option<WeakPipeTransportPair>>>>>>, Arc<Mutex<HashedMap<RouterId, Arc<AsyncMutex<Option<WeakPipeTransportPair>>>>>>,
// Make sure worker is not dropped until this router is not dropped // Make sure worker is not dropped until this router is not dropped
worker: Option<Worker>, worker: Option<Worker>,
closed: AtomicBool, closed: AtomicBool,
...@@ -449,10 +450,10 @@ impl Router { ...@@ -449,10 +450,10 @@ impl Router {
) -> Self { ) -> Self {
debug!("new()"); debug!("new()");
let producers = Arc::<RwLock<HashMap<ProducerId, WeakProducer>>>::default(); let producers = Arc::<RwLock<HashedMap<ProducerId, WeakProducer>>>::default();
let data_producers = Arc::<RwLock<HashMap<DataProducerId, WeakDataProducer>>>::default(); let data_producers = Arc::<RwLock<HashedMap<DataProducerId, WeakDataProducer>>>::default();
let mapped_pipe_transports = Arc::< let mapped_pipe_transports = Arc::<
Mutex<HashMap<RouterId, Arc<AsyncMutex<Option<WeakPipeTransportPair>>>>>, Mutex<HashedMap<RouterId, Arc<AsyncMutex<Option<WeakPipeTransportPair>>>>>,
>::default(); >::default();
let handlers = Arc::<Handlers>::default(); let handlers = Arc::<Handlers>::default();
let inner_weak = Arc::<Mutex<Option<Weak<Inner>>>>::default(); let inner_weak = Arc::<Mutex<Option<Weak<Inner>>>>::default();
...@@ -1314,7 +1315,7 @@ impl Router { ...@@ -1314,7 +1315,7 @@ impl Router {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_transport.add(Box::new(callback)) self.inner.handlers.new_transport.add(Arc::new(callback))
} }
/// Callback is called when a new RTP observer is created. /// Callback is called when a new RTP observer is created.
...@@ -1322,7 +1323,7 @@ impl Router { ...@@ -1322,7 +1323,7 @@ impl Router {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_rtp_observer.add(Box::new(callback)) self.inner.handlers.new_rtp_observer.add(Arc::new(callback))
} }
/// Callback is called when the worker this router belongs to is closed for whatever reason. /// Callback is called when the worker this router belongs to is closed for whatever reason.
...@@ -1351,7 +1352,7 @@ impl Router { ...@@ -1351,7 +1352,7 @@ impl Router {
// destination Routers. We just want to keep a PipeTransport pair for each // destination Routers. We just want to keep a PipeTransport pair for each
// pair of Routers. Since this operation is async, it may happen that two // pair of Routers. Since this operation is async, it may happen that two
// simultaneous calls piping to the same router would end up generating two pairs of // simultaneous calls piping to the same router would end up generating two pairs of
// `PipeTransport`. To prevent that, we have `HashMap` with mapping behind `Mutex` and // `PipeTransport`. To prevent that, we have `HashedMap` with mapping behind `Mutex` and
// another `Mutex` on the pair of `PipeTransport`. // another `Mutex` on the pair of `PipeTransport`.
let mut mapped_pipe_transports = self.inner.mapped_pipe_transports.lock(); let mut mapped_pipe_transports = self.inner.mapped_pipe_transports.lock();
...@@ -1465,7 +1466,7 @@ impl Router { ...@@ -1465,7 +1466,7 @@ impl Router {
{ {
let producers_weak = Arc::downgrade(&self.inner.producers); let producers_weak = Arc::downgrade(&self.inner.producers);
transport transport
.on_new_producer(Box::new(move |producer| { .on_new_producer(Arc::new(move |producer| {
let producer_id = producer.id(); let producer_id = producer.id();
if let Some(producers) = producers_weak.upgrade() { if let Some(producers) = producers_weak.upgrade() {
producers.write().insert(producer_id, producer.downgrade()); producers.write().insert(producer_id, producer.downgrade());
...@@ -1486,7 +1487,7 @@ impl Router { ...@@ -1486,7 +1487,7 @@ impl Router {
{ {
let data_producers_weak = Arc::downgrade(&self.inner.data_producers); let data_producers_weak = Arc::downgrade(&self.inner.data_producers);
transport transport
.on_new_data_producer(Box::new(move |data_producer| { .on_new_data_producer(Arc::new(move |data_producer| {
let data_producer_id = data_producer.id(); let data_producer_id = data_producer.id();
if let Some(data_producers) = data_producers_weak.upgrade() { if let Some(data_producers) = data_producers_weak.upgrade() {
data_producers data_producers
......
...@@ -50,11 +50,14 @@ pub struct ActiveSpeakerObserverDominantSpeaker { ...@@ -50,11 +50,14 @@ pub struct ActiveSpeakerObserverDominantSpeaker {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
dominant_speaker: Bag<Box<dyn Fn(&ActiveSpeakerObserverDominantSpeaker) + Send + Sync>>, dominant_speaker: Bag<
pause: Bag<Box<dyn Fn() + Send + Sync>>, Arc<dyn Fn(&ActiveSpeakerObserverDominantSpeaker) + Send + Sync>,
resume: Bag<Box<dyn Fn() + Send + Sync>>, ActiveSpeakerObserverDominantSpeaker,
add_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, >,
remove_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, pause: Bag<Arc<dyn Fn() + Send + Sync>>,
resume: Bag<Arc<dyn Fn() + Send + Sync>>,
add_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
remove_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
router_close: BagOnce<Box<dyn FnOnce() + Send>>, router_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -220,9 +223,7 @@ impl RtpObserver for ActiveSpeakerObserver { ...@@ -220,9 +223,7 @@ impl RtpObserver for ActiveSpeakerObserver {
}) })
.await?; .await?;
self.inner.handlers.add_producer.call(|callback| { self.inner.handlers.add_producer.call_simple(&producer);
callback(&producer);
});
Ok(()) Ok(())
} }
...@@ -242,33 +243,31 @@ impl RtpObserver for ActiveSpeakerObserver { ...@@ -242,33 +243,31 @@ impl RtpObserver for ActiveSpeakerObserver {
}) })
.await?; .await?;
self.inner.handlers.remove_producer.call(|callback| { self.inner.handlers.remove_producer.call_simple(&producer);
callback(&producer);
});
Ok(()) Ok(())
} }
fn on_pause(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId { fn on_pause(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId {
self.inner.handlers.pause.add(Box::new(callback)) self.inner.handlers.pause.add(Arc::new(callback))
} }
fn on_resume(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId { fn on_resume(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId {
self.inner.handlers.resume.add(Box::new(callback)) self.inner.handlers.resume.add(Arc::new(callback))
} }
fn on_add_producer( fn on_add_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.add_producer.add(Box::new(callback)) self.inner.handlers.add_producer.add(Arc::new(callback))
} }
fn on_remove_producer( fn on_remove_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.remove_producer.add(Box::new(callback)) self.inner.handlers.remove_producer.add(Arc::new(callback))
} }
fn on_router_close(&self, callback: Box<dyn FnOnce() + Send + 'static>) -> HandlerId { fn on_router_close(&self, callback: Box<dyn FnOnce() + Send + 'static>) -> HandlerId {
...@@ -302,7 +301,7 @@ impl ActiveSpeakerObserver { ...@@ -302,7 +301,7 @@ impl ActiveSpeakerObserver {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::DominantSpeaker(dominant_speaker) => { Notification::DominantSpeaker(dominant_speaker) => {
let DominantSpeakerNotification { producer_id } = dominant_speaker; let DominantSpeakerNotification { producer_id } = dominant_speaker;
...@@ -311,9 +310,7 @@ impl ActiveSpeakerObserver { ...@@ -311,9 +310,7 @@ impl ActiveSpeakerObserver {
let dominant_speaker = let dominant_speaker =
ActiveSpeakerObserverDominantSpeaker { producer }; ActiveSpeakerObserverDominantSpeaker { producer };
handlers.dominant_speaker.call(|callback| { handlers.dominant_speaker.call_simple(&dominant_speaker);
callback(&dominant_speaker);
});
} }
None => { None => {
error!( error!(
...@@ -367,7 +364,7 @@ impl ActiveSpeakerObserver { ...@@ -367,7 +364,7 @@ impl ActiveSpeakerObserver {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.dominant_speaker.add(Box::new(callback)) self.inner.handlers.dominant_speaker.add(Arc::new(callback))
} }
/// Downgrade `ActiveSpeakerObserver` to [`WeakActiveSpeakerObserver`] instance. /// Downgrade `ActiveSpeakerObserver` to [`WeakActiveSpeakerObserver`] instance.
......
...@@ -61,12 +61,12 @@ pub struct AudioLevelObserverVolume { ...@@ -61,12 +61,12 @@ pub struct AudioLevelObserverVolume {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
volumes: Bag<Box<dyn Fn(&Vec<AudioLevelObserverVolume>) + Send + Sync>>, volumes: Bag<Arc<dyn Fn(&[AudioLevelObserverVolume]) + Send + Sync>>,
silence: Bag<Box<dyn Fn() + Send + Sync>>, silence: Bag<Arc<dyn Fn() + Send + Sync>>,
pause: Bag<Box<dyn Fn() + Send + Sync>>, pause: Bag<Arc<dyn Fn() + Send + Sync>>,
resume: Bag<Box<dyn Fn() + Send + Sync>>, resume: Bag<Arc<dyn Fn() + Send + Sync>>,
add_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, add_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
remove_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, remove_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
router_close: BagOnce<Box<dyn FnOnce() + Send>>, router_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -234,9 +234,7 @@ impl RtpObserver for AudioLevelObserver { ...@@ -234,9 +234,7 @@ impl RtpObserver for AudioLevelObserver {
}) })
.await?; .await?;
self.inner.handlers.add_producer.call(|callback| { self.inner.handlers.add_producer.call_simple(&producer);
callback(&producer);
});
Ok(()) Ok(())
} }
...@@ -256,33 +254,31 @@ impl RtpObserver for AudioLevelObserver { ...@@ -256,33 +254,31 @@ impl RtpObserver for AudioLevelObserver {
}) })
.await?; .await?;
self.inner.handlers.remove_producer.call(|callback| { self.inner.handlers.remove_producer.call_simple(&producer);
callback(&producer);
});
Ok(()) Ok(())
} }
fn on_pause(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId { fn on_pause(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId {
self.inner.handlers.pause.add(Box::new(callback)) self.inner.handlers.pause.add(Arc::new(callback))
} }
fn on_resume(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId { fn on_resume(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId {
self.inner.handlers.resume.add(Box::new(callback)) self.inner.handlers.resume.add(Arc::new(callback))
} }
fn on_add_producer( fn on_add_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.add_producer.add(Box::new(callback)) self.inner.handlers.add_producer.add(Arc::new(callback))
} }
fn on_remove_producer( fn on_remove_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.remove_producer.add(Box::new(callback)) self.inner.handlers.remove_producer.add(Arc::new(callback))
} }
fn on_router_close(&self, callback: Box<dyn FnOnce() + Send + 'static>) -> HandlerId { fn on_router_close(&self, callback: Box<dyn FnOnce() + Send + 'static>) -> HandlerId {
...@@ -316,21 +312,24 @@ impl AudioLevelObserver { ...@@ -316,21 +312,24 @@ impl AudioLevelObserver {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Volumes(volumes) => { Notification::Volumes(volumes) => {
let volumes = volumes let volumes = volumes
.into_iter() .iter()
.filter_map(|notification| { .filter_map(|notification| {
let VolumeNotification { let VolumeNotification {
producer_id, producer_id,
volume, volume,
} = notification; } = notification;
router.get_producer(&producer_id).map(|producer| { router.get_producer(producer_id).map(|producer| {
AudioLevelObserverVolume { producer, volume } AudioLevelObserverVolume {
producer,
volume: *volume,
}
}) })
}) })
.collect(); .collect::<Vec<_>>();
handlers.volumes.call(|callback| { handlers.volumes.call(|callback| {
callback(&volumes); callback(&volumes);
...@@ -379,17 +378,17 @@ impl AudioLevelObserver { ...@@ -379,17 +378,17 @@ impl AudioLevelObserver {
/// Callback is called at most every interval (see [`AudioLevelObserverOptions`]). /// Callback is called at most every interval (see [`AudioLevelObserverOptions`]).
/// ///
/// Audio volumes entries ordered by volume (louder ones go first). /// Audio volumes entries ordered by volume (louder ones go first).
pub fn on_volumes<F: Fn(&Vec<AudioLevelObserverVolume>) + Send + Sync + 'static>( pub fn on_volumes<F: Fn(&[AudioLevelObserverVolume]) + Send + Sync + 'static>(
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.volumes.add(Box::new(callback)) self.inner.handlers.volumes.add(Arc::new(callback))
} }
/// Callback is called when no one of the producers in this RTP observer is generating audio with a volume /// Callback is called when no one of the producers in this RTP observer is generating audio with a volume
/// beyond the given threshold. /// beyond the given threshold.
pub fn on_silence<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_silence<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.silence.add(Box::new(callback)) self.inner.handlers.silence.add(Arc::new(callback))
} }
/// Downgrade `AudioLevelObserver` to [`WeakAudioLevelObserver`] instance. /// Downgrade `AudioLevelObserver` to [`WeakAudioLevelObserver`] instance.
......
...@@ -13,11 +13,8 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters} ...@@ -13,11 +13,8 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters}
use crate::scalability_modes::ScalabilityMode; use crate::scalability_modes::ScalabilityMode;
use crate::transport::Transport; use crate::transport::Transport;
use crate::uuid_based_wrapper_type; use crate::uuid_based_wrapper_type;
use crate::worker::{ use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
Channel, NotificationMessage, PayloadChannel, RequestError, SubscriptionHandler,
};
use async_executor::Executor; use async_executor::Executor;
use bytes::Bytes;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error}; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
...@@ -347,14 +344,15 @@ enum PayloadNotification { ...@@ -347,14 +344,15 @@ enum PayloadNotification {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
rtp: Bag<Box<dyn Fn(&Bytes) + Send + Sync>>, rtp: Bag<Arc<dyn Fn(&[u8]) + Send + Sync>>,
pause: Bag<Box<dyn Fn() + Send + Sync>>, pause: Bag<Arc<dyn Fn() + Send + Sync>>,
resume: Bag<Box<dyn Fn() + Send + Sync>>, resume: Bag<Arc<dyn Fn() + Send + Sync>>,
producer_pause: Bag<Box<dyn Fn() + Send + Sync>>, producer_pause: Bag<Arc<dyn Fn() + Send + Sync>>,
producer_resume: Bag<Box<dyn Fn() + Send + Sync>>, producer_resume: Bag<Arc<dyn Fn() + Send + Sync>>,
score: Bag<Box<dyn Fn(&ConsumerScore) + Send + Sync>>, score: Bag<Arc<dyn Fn(&ConsumerScore) + Send + Sync>, ConsumerScore>,
layers_change: Bag<Box<dyn Fn(&Option<ConsumerLayers>) + Send + Sync>>, #[allow(clippy::type_complexity)]
trace: Bag<Box<dyn Fn(&ConsumerTraceEventData) + Send + Sync>>, layers_change: Bag<Arc<dyn Fn(&Option<ConsumerLayers>) + Send + Sync>, Option<ConsumerLayers>>,
trace: Bag<Arc<dyn Fn(&ConsumerTraceEventData) + Send + Sync>, ConsumerTraceEventData>,
producer_close: BagOnce<Box<dyn FnOnce() + Send>>, producer_close: BagOnce<Box<dyn FnOnce() + Send>>,
transport_close: BagOnce<Box<dyn FnOnce() + Send>>, transport_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
...@@ -492,7 +490,7 @@ impl Consumer { ...@@ -492,7 +490,7 @@ impl Consumer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::ProducerClose => { Notification::ProducerClose => {
if !closed.load(Ordering::SeqCst) { if !closed.load(Ordering::SeqCst) {
...@@ -529,20 +527,14 @@ impl Consumer { ...@@ -529,20 +527,14 @@ impl Consumer {
} }
Notification::Score(consumer_score) => { Notification::Score(consumer_score) => {
*score.lock() = consumer_score.clone(); *score.lock() = consumer_score.clone();
handlers.score.call(|callback| { handlers.score.call_simple(&consumer_score);
callback(&consumer_score);
});
} }
Notification::LayersChange(consumer_layers) => { Notification::LayersChange(consumer_layers) => {
*current_layers.lock() = consumer_layers; *current_layers.lock() = consumer_layers;
handlers.layers_change.call(|callback| { handlers.layers_change.call_simple(&consumer_layers);
callback(&consumer_layers);
});
} }
Notification::Trace(trace_event_data) => { Notification::Trace(trace_event_data) => {
handlers.trace.call(|callback| { handlers.trace.call_simple(&trace_event_data);
callback(&trace_event_data);
});
} }
}, },
Err(error) => { Err(error) => {
...@@ -555,13 +547,12 @@ impl Consumer { ...@@ -555,13 +547,12 @@ impl Consumer {
let payload_subscription_handler = { let payload_subscription_handler = {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
payload_channel.subscribe_to_notifications(id.into(), move |notification| { payload_channel.subscribe_to_notifications(id.into(), move |message, payload| {
let NotificationMessage { message, payload } = notification; match serde_json::from_slice::<PayloadNotification>(message) {
match serde_json::from_value::<PayloadNotification>(message) {
Ok(notification) => match notification { Ok(notification) => match notification {
PayloadNotification::Rtp => { PayloadNotification::Rtp => {
handlers.rtp.call(|callback| { handlers.rtp.call(|callback| {
callback(&payload); callback(payload);
}); });
} }
}, },
...@@ -864,30 +855,30 @@ impl Consumer { ...@@ -864,30 +855,30 @@ impl Consumer {
/// # Notes on usage /// # Notes on usage
/// Just available in direct transports, this is, those created via /// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport). /// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub fn on_rtp<F: Fn(&Bytes) + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_rtp<F: Fn(&[u8]) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.rtp.add(Box::new(callback)) self.inner.handlers.rtp.add(Arc::new(callback))
} }
/// Callback is called when the consumer or its associated producer is paused and, as result, /// Callback is called when the consumer or its associated producer is paused and, as result,
/// the consumer becomes paused. /// the consumer becomes paused.
pub fn on_pause<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_pause<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.pause.add(Box::new(callback)) self.inner.handlers.pause.add(Arc::new(callback))
} }
/// Callback is called when the consumer or its associated producer is resumed and, as result, /// Callback is called when the consumer or its associated producer is resumed and, as result,
/// the consumer is no longer paused. /// the consumer is no longer paused.
pub fn on_resume<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_resume<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.resume.add(Box::new(callback)) self.inner.handlers.resume.add(Arc::new(callback))
} }
/// Callback is called when the associated producer is paused. /// Callback is called when the associated producer is paused.
pub fn on_producer_pause<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_producer_pause<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.producer_pause.add(Box::new(callback)) self.inner.handlers.producer_pause.add(Arc::new(callback))
} }
/// Callback is called when the associated producer is resumed. /// Callback is called when the associated producer is resumed.
pub fn on_producer_resume<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_producer_resume<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.producer_resume.add(Box::new(callback)) self.inner.handlers.producer_resume.add(Arc::new(callback))
} }
/// Callback is called when the consumer score changes. /// Callback is called when the consumer score changes.
...@@ -895,7 +886,7 @@ impl Consumer { ...@@ -895,7 +886,7 @@ impl Consumer {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.score.add(Box::new(callback)) self.inner.handlers.score.add(Arc::new(callback))
} }
/// Callback is called when the spatial/temporal layers being sent to the endpoint change. Just /// Callback is called when the spatial/temporal layers being sent to the endpoint change. Just
...@@ -919,7 +910,7 @@ impl Consumer { ...@@ -919,7 +910,7 @@ impl Consumer {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.layers_change.add(Box::new(callback)) self.inner.handlers.layers_change.add(Arc::new(callback))
} }
/// See [`Consumer::enable_trace_event`] method. /// See [`Consumer::enable_trace_event`] method.
...@@ -927,7 +918,7 @@ impl Consumer { ...@@ -927,7 +918,7 @@ impl Consumer {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.trace.add(Box::new(callback)) self.inner.handlers.trace.add(Arc::new(callback))
} }
/// Callback is called when the associated producer is closed for whatever reason. The consumer /// Callback is called when the associated producer is closed for whatever reason. The consumer
......
...@@ -12,14 +12,13 @@ use crate::messages::{ ...@@ -12,14 +12,13 @@ use crate::messages::{
use crate::sctp_parameters::SctpStreamParameters; use crate::sctp_parameters::SctpStreamParameters;
use crate::transport::Transport; use crate::transport::Transport;
use crate::uuid_based_wrapper_type; use crate::uuid_based_wrapper_type;
use crate::worker::{ use crate::worker::{Channel, PayloadChannel, RequestError, SubscriptionHandler};
Channel, NotificationMessage, PayloadChannel, RequestError, SubscriptionHandler,
};
use async_executor::Executor; use async_executor::Executor;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error}; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::fmt; use std::fmt;
use std::fmt::Debug; use std::fmt::Debug;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
...@@ -184,9 +183,9 @@ enum PayloadNotification { ...@@ -184,9 +183,9 @@ enum PayloadNotification {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
message: Bag<Box<dyn Fn(&WebRtcMessage) + Send + Sync>>, message: Bag<Arc<dyn Fn(&WebRtcMessage<'_>) + Send + Sync>>,
sctp_send_buffer_full: Bag<Box<dyn Fn() + Send + Sync>>, sctp_send_buffer_full: Bag<Arc<dyn Fn() + Send + Sync>>,
buffered_amount_low: Bag<Box<dyn Fn(u32) + Send + Sync>>, buffered_amount_low: Bag<Arc<dyn Fn(u32) + Send + Sync>>,
data_producer_close: BagOnce<Box<dyn FnOnce() + Send>>, data_producer_close: BagOnce<Box<dyn FnOnce() + Send>>,
transport_close: BagOnce<Box<dyn FnOnce() + Send>>, transport_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
...@@ -366,7 +365,7 @@ impl DataConsumer { ...@@ -366,7 +365,7 @@ impl DataConsumer {
let inner_weak = Arc::clone(&inner_weak); let inner_weak = Arc::clone(&inner_weak);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::DataProducerClose => { Notification::DataProducerClose => {
if !closed.load(Ordering::SeqCst) { if !closed.load(Ordering::SeqCst) {
...@@ -397,12 +396,11 @@ impl DataConsumer { ...@@ -397,12 +396,11 @@ impl DataConsumer {
let payload_subscription_handler = { let payload_subscription_handler = {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
payload_channel.subscribe_to_notifications(id.into(), move |notification| { payload_channel.subscribe_to_notifications(id.into(), move |message, payload| {
let NotificationMessage { message, payload } = notification; match serde_json::from_slice::<PayloadNotification>(message) {
match serde_json::from_value::<PayloadNotification>(message) {
Ok(notification) => match notification { Ok(notification) => match notification {
PayloadNotification::Message { ppid } => { PayloadNotification::Message { ppid } => {
match WebRtcMessage::new(ppid, payload) { match WebRtcMessage::new(ppid, Cow::from(payload)) {
Ok(message) => { Ok(message) => {
handlers.message.call(|callback| { handlers.message.call(|callback| {
callback(&message); callback(&message);
...@@ -582,11 +580,11 @@ impl DataConsumer { ...@@ -582,11 +580,11 @@ impl DataConsumer {
/// # Notes on usage /// # Notes on usage
/// Just available in direct transports, this is, those created via /// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport). /// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub fn on_message<F: Fn(&WebRtcMessage) + Send + Sync + 'static>( pub fn on_message<F: Fn(&WebRtcMessage<'_>) + Send + Sync + 'static>(
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner().handlers.message.add(Box::new(callback)) self.inner().handlers.message.add(Arc::new(callback))
} }
/// Callback is called when a message could not be sent because the SCTP send buffer was full. /// Callback is called when a message could not be sent because the SCTP send buffer was full.
...@@ -597,7 +595,7 @@ impl DataConsumer { ...@@ -597,7 +595,7 @@ impl DataConsumer {
self.inner() self.inner()
.handlers .handlers
.sctp_send_buffer_full .sctp_send_buffer_full
.add(Box::new(callback)) .add(Arc::new(callback))
} }
/// Emitted when the underlying SCTP association buffered bytes drop down to the value set with /// Emitted when the underlying SCTP association buffered bytes drop down to the value set with
...@@ -612,7 +610,7 @@ impl DataConsumer { ...@@ -612,7 +610,7 @@ impl DataConsumer {
self.inner() self.inner()
.handlers .handlers
.buffered_amount_low .buffered_amount_low
.add(Box::new(callback)) .add(Arc::new(callback))
} }
/// Callback is called when the associated data producer is closed for whatever reason. The data /// Callback is called when the associated data producer is closed for whatever reason. The data
...@@ -671,7 +669,7 @@ impl DataConsumer { ...@@ -671,7 +669,7 @@ impl DataConsumer {
impl DirectDataConsumer { impl DirectDataConsumer {
/// Sends direct messages from the Rust process. /// Sends direct messages from the Rust process.
pub async fn send(&self, message: WebRtcMessage) -> Result<(), RequestError> { pub async fn send(&self, message: WebRtcMessage<'_>) -> Result<(), RequestError> {
let (ppid, payload) = message.into_ppid_and_payload(); let (ppid, payload) = message.into_ppid_and_payload();
self.inner self.inner
...@@ -686,7 +684,7 @@ impl DirectDataConsumer { ...@@ -686,7 +684,7 @@ impl DirectDataConsumer {
}, },
data: DataConsumerSendRequestData { ppid }, data: DataConsumerSendRequestData { ppid },
}, },
payload, payload.into_owned(),
) )
.await .await
} }
......
...@@ -437,13 +437,11 @@ impl DataProducer { ...@@ -437,13 +437,11 @@ impl DataProducer {
} }
impl DirectDataProducer { impl DirectDataProducer {
/// Sends direct messages from the Rust process. /// Sends direct messages from the Rust to the worker.
pub async fn send(&self, message: WebRtcMessage) -> Result<(), NotificationError> { pub fn send(&self, message: WebRtcMessage<'_>) -> Result<(), NotificationError> {
let (ppid, payload) = message.into_ppid_and_payload(); let (ppid, payload) = message.into_ppid_and_payload();
self.inner self.inner.payload_channel.notify(
.payload_channel
.notify(
DataProducerSendNotification { DataProducerSendNotification {
internal: DataProducerInternal { internal: DataProducerInternal {
router_id: self.inner.transport.router_id(), router_id: self.inner.transport.router_id(),
...@@ -452,9 +450,8 @@ impl DirectDataProducer { ...@@ -452,9 +450,8 @@ impl DirectDataProducer {
}, },
data: DataProducerSendData { ppid }, data: DataProducerSendData { ppid },
}, },
payload, payload.into_owned(),
) )
.await
} }
} }
......
...@@ -16,17 +16,15 @@ use crate::transport::{ ...@@ -16,17 +16,15 @@ use crate::transport::{
TransportTraceEventType, TransportTraceEventType,
}; };
use crate::worker::{ use crate::worker::{
Channel, NotificationError, NotificationMessage, PayloadChannel, RequestError, Channel, NotificationError, PayloadChannel, RequestError, SubscriptionHandler,
SubscriptionHandler,
}; };
use async_executor::Executor; use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use bytes::Bytes;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error}; use log::{debug, error};
use nohash_hasher::IntMap;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
...@@ -61,8 +59,8 @@ pub struct DirectTransportDump { ...@@ -61,8 +59,8 @@ pub struct DirectTransportDump {
pub direct: bool, pub direct: bool,
pub producer_ids: Vec<ProducerId>, pub producer_ids: Vec<ProducerId>,
pub consumer_ids: Vec<ConsumerId>, pub consumer_ids: Vec<ConsumerId>,
pub map_ssrc_consumer_id: HashMap<u32, ConsumerId>, pub map_ssrc_consumer_id: IntMap<u32, ConsumerId>,
pub map_rtx_ssrc_consumer_id: HashMap<u32, ConsumerId>, pub map_rtx_ssrc_consumer_id: IntMap<u32, ConsumerId>,
pub data_producer_ids: Vec<DataProducerId>, pub data_producer_ids: Vec<DataProducerId>,
pub data_consumer_ids: Vec<DataConsumerId>, pub data_consumer_ids: Vec<DataConsumerId>,
pub recv_rtp_header_extensions: RecvRtpHeaderExtensions, pub recv_rtp_header_extensions: RecvRtpHeaderExtensions,
...@@ -113,12 +111,12 @@ pub struct DirectTransportStat { ...@@ -113,12 +111,12 @@ pub struct DirectTransportStat {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
rtcp: Bag<Box<dyn Fn(&Bytes) + Send + Sync>>, rtcp: Bag<Arc<dyn Fn(&[u8]) + Send + Sync>>,
new_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, new_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
new_consumer: Bag<Box<dyn Fn(&Consumer) + Send + Sync>>, new_consumer: Bag<Arc<dyn Fn(&Consumer) + Send + Sync>, Consumer>,
new_data_producer: Bag<Box<dyn Fn(&DataProducer) + Send + Sync>>, new_data_producer: Bag<Arc<dyn Fn(&DataProducer) + Send + Sync>, DataProducer>,
new_data_consumer: Bag<Box<dyn Fn(&DataConsumer) + Send + Sync>>, new_data_consumer: Bag<Arc<dyn Fn(&DataConsumer) + Send + Sync>, DataConsumer>,
trace: Bag<Box<dyn Fn(&TransportTraceEventData) + Send + Sync>>, trace: Bag<Arc<dyn Fn(&TransportTraceEventData) + Send + Sync>, TransportTraceEventData>,
router_close: BagOnce<Box<dyn FnOnce() + Send>>, router_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -138,7 +136,7 @@ enum PayloadNotification { ...@@ -138,7 +136,7 @@ enum PayloadNotification {
struct Inner { struct Inner {
id: TransportId, id: TransportId,
next_mid_for_consumers: AtomicUsize, next_mid_for_consumers: AtomicUsize,
used_sctp_stream_ids: Mutex<HashMap<u16, bool>>, used_sctp_stream_ids: Mutex<IntMap<u16, bool>>,
cname_for_producers: Mutex<Option<String>>, cname_for_producers: Mutex<Option<String>>,
executor: Arc<Executor<'static>>, executor: Arc<Executor<'static>>,
channel: Channel, channel: Channel,
...@@ -253,9 +251,7 @@ impl Transport for DirectTransport { ...@@ -253,9 +251,7 @@ impl Transport for DirectTransport {
.produce_impl(producer_options, TransportType::Direct) .produce_impl(producer_options, TransportType::Direct)
.await?; .await?;
self.inner.handlers.new_producer.call(|callback| { self.inner.handlers.new_producer.call_simple(&producer);
callback(&producer);
});
Ok(producer) Ok(producer)
} }
...@@ -270,9 +266,7 @@ impl Transport for DirectTransport { ...@@ -270,9 +266,7 @@ impl Transport for DirectTransport {
.consume_impl(consumer_options, TransportType::Direct, false) .consume_impl(consumer_options, TransportType::Direct, false)
.await?; .await?;
self.inner.handlers.new_consumer.call(|callback| { self.inner.handlers.new_consumer.call_simple(&consumer);
callback(&consumer);
});
Ok(consumer) Ok(consumer)
} }
...@@ -294,9 +288,10 @@ impl Transport for DirectTransport { ...@@ -294,9 +288,10 @@ impl Transport for DirectTransport {
) )
.await?; .await?;
self.inner.handlers.new_data_producer.call(|callback| { self.inner
callback(&data_producer); .handlers
}); .new_data_producer
.call_simple(&data_producer);
Ok(data_producer) Ok(data_producer)
} }
...@@ -318,9 +313,10 @@ impl Transport for DirectTransport { ...@@ -318,9 +313,10 @@ impl Transport for DirectTransport {
) )
.await?; .await?;
self.inner.handlers.new_data_consumer.call(|callback| { self.inner
callback(&data_consumer); .handlers
}); .new_data_consumer
.call_simple(&data_consumer);
Ok(data_consumer) Ok(data_consumer)
} }
...@@ -336,35 +332,35 @@ impl Transport for DirectTransport { ...@@ -336,35 +332,35 @@ impl Transport for DirectTransport {
fn on_new_producer( fn on_new_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_producer.add(callback) self.inner.handlers.new_producer.add(callback)
} }
fn on_new_consumer( fn on_new_consumer(
&self, &self,
callback: Box<dyn Fn(&Consumer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&Consumer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_consumer.add(callback) self.inner.handlers.new_consumer.add(callback)
} }
fn on_new_data_producer( fn on_new_data_producer(
&self, &self,
callback: Box<dyn Fn(&DataProducer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&DataProducer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_data_producer.add(callback) self.inner.handlers.new_data_producer.add(callback)
} }
fn on_new_data_consumer( fn on_new_data_consumer(
&self, &self,
callback: Box<dyn Fn(&DataConsumer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&DataConsumer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_data_consumer.add(callback) self.inner.handlers.new_data_consumer.add(callback)
} }
fn on_trace( fn on_trace(
&self, &self,
callback: Box<dyn Fn(&TransportTraceEventData) + Send + Sync + 'static>, callback: Arc<dyn Fn(&TransportTraceEventData) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.trace.add(callback) self.inner.handlers.trace.add(callback)
} }
...@@ -392,7 +388,11 @@ impl TransportGeneric for DirectTransport { ...@@ -392,7 +388,11 @@ impl TransportGeneric for DirectTransport {
async fn dump(&self) -> Result<Self::Dump, RequestError> { async fn dump(&self) -> Result<Self::Dump, RequestError> {
debug!("dump()"); debug!("dump()");
self.dump_impl().await serde_json::from_value(self.dump_impl().await?).map_err(|error| {
RequestError::FailedToParse {
error: error.to_string(),
}
})
} }
/// Returns current RTC statistics of the transport. /// Returns current RTC statistics of the transport.
...@@ -402,7 +402,11 @@ impl TransportGeneric for DirectTransport { ...@@ -402,7 +402,11 @@ impl TransportGeneric for DirectTransport {
async fn get_stats(&self) -> Result<Vec<Self::Stat>, RequestError> { async fn get_stats(&self) -> Result<Vec<Self::Stat>, RequestError> {
debug!("get_stats()"); debug!("get_stats()");
self.get_stats_impl().await serde_json::from_value(self.get_stats_impl().await?).map_err(|error| {
RequestError::FailedToParse {
error: error.to_string(),
}
})
} }
} }
...@@ -427,7 +431,7 @@ impl TransportImpl for DirectTransport { ...@@ -427,7 +431,7 @@ impl TransportImpl for DirectTransport {
&self.inner.next_mid_for_consumers &self.inner.next_mid_for_consumers
} }
fn used_sctp_stream_ids(&self) -> &Mutex<HashMap<u16, bool>> { fn used_sctp_stream_ids(&self) -> &Mutex<IntMap<u16, bool>> {
&self.inner.used_sctp_stream_ids &self.inner.used_sctp_stream_ids
} }
...@@ -453,12 +457,10 @@ impl DirectTransport { ...@@ -453,12 +457,10 @@ impl DirectTransport {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Trace(trace_event_data) => { Notification::Trace(trace_event_data) => {
handlers.trace.call(|callback| { handlers.trace.call_simple(&trace_event_data);
callback(&trace_event_data);
});
} }
}, },
Err(error) => { Err(error) => {
...@@ -471,13 +473,12 @@ impl DirectTransport { ...@@ -471,13 +473,12 @@ impl DirectTransport {
let payload_subscription_handler = { let payload_subscription_handler = {
let handlers = Arc::clone(&handlers); let handlers = Arc::clone(&handlers);
payload_channel.subscribe_to_notifications(id.into(), move |notification| { payload_channel.subscribe_to_notifications(id.into(), move |message, payload| {
let NotificationMessage { message, payload } = notification; match serde_json::from_slice::<PayloadNotification>(message) {
match serde_json::from_value::<PayloadNotification>(message) {
Ok(notification) => match notification { Ok(notification) => match notification {
PayloadNotification::Rtcp => { PayloadNotification::Rtcp => {
handlers.rtcp.call(|callback| { handlers.rtcp.call(|callback| {
callback(&payload); callback(payload);
}); });
} }
}, },
...@@ -489,7 +490,7 @@ impl DirectTransport { ...@@ -489,7 +490,7 @@ impl DirectTransport {
}; };
let next_mid_for_consumers = AtomicUsize::default(); let next_mid_for_consumers = AtomicUsize::default();
let used_sctp_stream_ids = Mutex::new(HashMap::new()); let used_sctp_stream_ids = Mutex::new(IntMap::default());
let cname_for_producers = Mutex::new(None); let cname_for_producers = Mutex::new(None);
let inner_weak = Arc::<Mutex<Option<Weak<Inner>>>>::default(); let inner_weak = Arc::<Mutex<Option<Weak<Inner>>>>::default();
let on_router_close_handler = router.on_close({ let on_router_close_handler = router.on_close({
...@@ -526,21 +527,18 @@ impl DirectTransport { ...@@ -526,21 +527,18 @@ impl DirectTransport {
/// Send a RTCP packet from the Rust process. /// Send a RTCP packet from the Rust process.
/// ///
/// * `rtcp_packet` - Bytes containing a valid RTCP packet (can be a compound packet). /// * `rtcp_packet` - Bytes containing a valid RTCP packet (can be a compound packet).
pub async fn send_rtcp(&self, rtcp_packet: Bytes) -> Result<(), NotificationError> { pub fn send_rtcp(&self, rtcp_packet: Vec<u8>) -> Result<(), NotificationError> {
self.inner self.inner.payload_channel.notify(
.payload_channel
.notify(
TransportSendRtcpNotification { TransportSendRtcpNotification {
internal: self.get_internal(), internal: self.get_internal(),
}, },
rtcp_packet, rtcp_packet,
) )
.await
} }
/// Callback is called when the direct transport receives a RTCP packet from its router. /// Callback is called when the direct transport receives a RTCP packet from its router.
pub fn on_rtcp<F: Fn(&Bytes) + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_rtcp<F: Fn(&[u8]) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.rtcp.add(Box::new(callback)) self.inner.handlers.rtcp.add(Arc::new(callback))
} }
/// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance. /// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance.
......
...@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da ...@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da
use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, DataProducerType}; use crate::data_producer::{DataProducer, DataProducerId, DataProducerOptions, DataProducerType};
use crate::data_structures::{AppData, SctpState, TransportListenIp, TransportTuple}; use crate::data_structures::{AppData, SctpState, TransportListenIp, TransportTuple};
use crate::messages::{ use crate::messages::{
PipeTransportData, TransportCloseRequest, TransportConnectRequestPipe, PipeTransportData, TransportCloseRequest, TransportConnectPipeRequest,
TransportConnectRequestPipeData, TransportInternal, TransportConnectRequestPipeData, TransportInternal,
}; };
use crate::producer::{Producer, ProducerId, ProducerOptions}; use crate::producer::{Producer, ProducerId, ProducerOptions};
...@@ -24,9 +24,9 @@ use async_executor::Executor; ...@@ -24,9 +24,9 @@ use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error}; use log::{debug, error};
use nohash_hasher::IntMap;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::net::IpAddr; use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
...@@ -92,8 +92,8 @@ pub struct PipeTransportDump { ...@@ -92,8 +92,8 @@ pub struct PipeTransportDump {
pub direct: bool, pub direct: bool,
pub producer_ids: Vec<ProducerId>, pub producer_ids: Vec<ProducerId>,
pub consumer_ids: Vec<ConsumerId>, pub consumer_ids: Vec<ConsumerId>,
pub map_ssrc_consumer_id: HashMap<u32, ConsumerId>, pub map_ssrc_consumer_id: IntMap<u32, ConsumerId>,
pub map_rtx_ssrc_consumer_id: HashMap<u32, ConsumerId>, pub map_rtx_ssrc_consumer_id: IntMap<u32, ConsumerId>,
pub data_producer_ids: Vec<DataProducerId>, pub data_producer_ids: Vec<DataProducerId>,
pub data_consumer_ids: Vec<DataConsumerId>, pub data_consumer_ids: Vec<DataConsumerId>,
pub recv_rtp_header_extensions: RecvRtpHeaderExtensions, pub recv_rtp_header_extensions: RecvRtpHeaderExtensions,
...@@ -162,13 +162,13 @@ pub struct PipeTransportRemoteParameters { ...@@ -162,13 +162,13 @@ pub struct PipeTransportRemoteParameters {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
new_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, new_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
new_consumer: Bag<Box<dyn Fn(&Consumer) + Send + Sync>>, new_consumer: Bag<Arc<dyn Fn(&Consumer) + Send + Sync>, Consumer>,
new_data_producer: Bag<Box<dyn Fn(&DataProducer) + Send + Sync>>, new_data_producer: Bag<Arc<dyn Fn(&DataProducer) + Send + Sync>, DataProducer>,
new_data_consumer: Bag<Box<dyn Fn(&DataConsumer) + Send + Sync>>, new_data_consumer: Bag<Arc<dyn Fn(&DataConsumer) + Send + Sync>, DataConsumer>,
tuple: Bag<Box<dyn Fn(&TransportTuple) + Send + Sync>>, tuple: Bag<Arc<dyn Fn(&TransportTuple) + Send + Sync>, TransportTuple>,
sctp_state_change: Bag<Box<dyn Fn(SctpState) + Send + Sync>>, sctp_state_change: Bag<Arc<dyn Fn(SctpState) + Send + Sync>>,
trace: Bag<Box<dyn Fn(&TransportTraceEventData) + Send + Sync>>, trace: Bag<Arc<dyn Fn(&TransportTraceEventData) + Send + Sync>, TransportTraceEventData>,
router_close: BagOnce<Box<dyn FnOnce() + Send>>, router_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -186,7 +186,7 @@ enum Notification { ...@@ -186,7 +186,7 @@ enum Notification {
struct Inner { struct Inner {
id: TransportId, id: TransportId,
next_mid_for_consumers: AtomicUsize, next_mid_for_consumers: AtomicUsize,
used_sctp_stream_ids: Mutex<HashMap<u16, bool>>, used_sctp_stream_ids: Mutex<IntMap<u16, bool>>,
cname_for_producers: Mutex<Option<String>>, cname_for_producers: Mutex<Option<String>>,
executor: Arc<Executor<'static>>, executor: Arc<Executor<'static>>,
channel: Channel, channel: Channel,
...@@ -290,9 +290,7 @@ impl Transport for PipeTransport { ...@@ -290,9 +290,7 @@ impl Transport for PipeTransport {
.produce_impl(producer_options, TransportType::Pipe) .produce_impl(producer_options, TransportType::Pipe)
.await?; .await?;
self.inner.handlers.new_producer.call(|callback| { self.inner.handlers.new_producer.call_simple(&producer);
callback(&producer);
});
Ok(producer) Ok(producer)
} }
...@@ -304,9 +302,7 @@ impl Transport for PipeTransport { ...@@ -304,9 +302,7 @@ impl Transport for PipeTransport {
.consume_impl(consumer_options, TransportType::Pipe, self.inner.data.rtx) .consume_impl(consumer_options, TransportType::Pipe, self.inner.data.rtx)
.await?; .await?;
self.inner.handlers.new_consumer.call(|callback| { self.inner.handlers.new_consumer.call_simple(&consumer);
callback(&consumer);
});
Ok(consumer) Ok(consumer)
} }
...@@ -325,9 +321,10 @@ impl Transport for PipeTransport { ...@@ -325,9 +321,10 @@ impl Transport for PipeTransport {
) )
.await?; .await?;
self.inner.handlers.new_data_producer.call(|callback| { self.inner
callback(&data_producer); .handlers
}); .new_data_producer
.call_simple(&data_producer);
Ok(data_producer) Ok(data_producer)
} }
...@@ -346,9 +343,10 @@ impl Transport for PipeTransport { ...@@ -346,9 +343,10 @@ impl Transport for PipeTransport {
) )
.await?; .await?;
self.inner.handlers.new_data_consumer.call(|callback| { self.inner
callback(&data_consumer); .handlers
}); .new_data_consumer
.call_simple(&data_consumer);
Ok(data_consumer) Ok(data_consumer)
} }
...@@ -364,35 +362,35 @@ impl Transport for PipeTransport { ...@@ -364,35 +362,35 @@ impl Transport for PipeTransport {
fn on_new_producer( fn on_new_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_producer.add(callback) self.inner.handlers.new_producer.add(callback)
} }
fn on_new_consumer( fn on_new_consumer(
&self, &self,
callback: Box<dyn Fn(&Consumer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&Consumer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_consumer.add(callback) self.inner.handlers.new_consumer.add(callback)
} }
fn on_new_data_producer( fn on_new_data_producer(
&self, &self,
callback: Box<dyn Fn(&DataProducer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&DataProducer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_data_producer.add(callback) self.inner.handlers.new_data_producer.add(callback)
} }
fn on_new_data_consumer( fn on_new_data_consumer(
&self, &self,
callback: Box<dyn Fn(&DataConsumer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&DataConsumer) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.new_data_consumer.add(callback) self.inner.handlers.new_data_consumer.add(callback)
} }
fn on_trace( fn on_trace(
&self, &self,
callback: Box<dyn Fn(&TransportTraceEventData) + Send + Sync + 'static>, callback: Arc<dyn Fn(&TransportTraceEventData) + Send + Sync + 'static>,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.trace.add(callback) self.inner.handlers.trace.add(callback)
} }
...@@ -419,13 +417,21 @@ impl TransportGeneric for PipeTransport { ...@@ -419,13 +417,21 @@ impl TransportGeneric for PipeTransport {
async fn dump(&self) -> Result<Self::Dump, RequestError> { async fn dump(&self) -> Result<Self::Dump, RequestError> {
debug!("dump()"); debug!("dump()");
self.dump_impl().await serde_json::from_value(self.dump_impl().await?).map_err(|error| {
RequestError::FailedToParse {
error: error.to_string(),
}
})
} }
async fn get_stats(&self) -> Result<Vec<Self::Stat>, RequestError> { async fn get_stats(&self) -> Result<Vec<Self::Stat>, RequestError> {
debug!("get_stats()"); debug!("get_stats()");
self.get_stats_impl().await serde_json::from_value(self.get_stats_impl().await?).map_err(|error| {
RequestError::FailedToParse {
error: error.to_string(),
}
})
} }
} }
...@@ -450,7 +456,7 @@ impl TransportImpl for PipeTransport { ...@@ -450,7 +456,7 @@ impl TransportImpl for PipeTransport {
&self.inner.next_mid_for_consumers &self.inner.next_mid_for_consumers
} }
fn used_sctp_stream_ids(&self) -> &Mutex<HashMap<u16, bool>> { fn used_sctp_stream_ids(&self) -> &Mutex<IntMap<u16, bool>> {
&self.inner.used_sctp_stream_ids &self.inner.used_sctp_stream_ids
} }
...@@ -479,7 +485,7 @@ impl PipeTransport { ...@@ -479,7 +485,7 @@ impl PipeTransport {
let data = Arc::clone(&data); let data = Arc::clone(&data);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::SctpStateChange { sctp_state } => { Notification::SctpStateChange { sctp_state } => {
data.sctp_state.lock().replace(sctp_state); data.sctp_state.lock().replace(sctp_state);
...@@ -489,9 +495,7 @@ impl PipeTransport { ...@@ -489,9 +495,7 @@ impl PipeTransport {
}); });
} }
Notification::Trace(trace_event_data) => { Notification::Trace(trace_event_data) => {
handlers.trace.call(|callback| { handlers.trace.call_simple(&trace_event_data);
callback(&trace_event_data);
});
} }
}, },
Err(error) => { Err(error) => {
...@@ -503,7 +507,7 @@ impl PipeTransport { ...@@ -503,7 +507,7 @@ impl PipeTransport {
let next_mid_for_consumers = AtomicUsize::default(); let next_mid_for_consumers = AtomicUsize::default();
let used_sctp_stream_ids = Mutex::new({ let used_sctp_stream_ids = Mutex::new({
let mut used_used_sctp_stream_ids = HashMap::new(); let mut used_used_sctp_stream_ids = IntMap::default();
if let Some(sctp_parameters) = &data.sctp_parameters { if let Some(sctp_parameters) = &data.sctp_parameters {
for i in 0..sctp_parameters.mis { for i in 0..sctp_parameters.mis {
used_used_sctp_stream_ids.insert(i, false); used_used_sctp_stream_ids.insert(i, false);
...@@ -555,7 +559,7 @@ impl PipeTransport { ...@@ -555,7 +559,7 @@ impl PipeTransport {
let response = self let response = self
.inner .inner
.channel .channel
.request(TransportConnectRequestPipe { .request(TransportConnectPipeRequest {
internal: self.get_internal(), internal: self.get_internal(),
data: TransportConnectRequestPipeData { data: TransportConnectRequestPipeData {
ip: remote_parameters.ip, ip: remote_parameters.ip,
...@@ -617,7 +621,7 @@ impl PipeTransport { ...@@ -617,7 +621,7 @@ impl PipeTransport {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner.handlers.tuple.add(Box::new(callback)) self.inner.handlers.tuple.add(Arc::new(callback))
} }
/// Callback is called when the transport SCTP state changes. /// Callback is called when the transport SCTP state changes.
...@@ -628,7 +632,7 @@ impl PipeTransport { ...@@ -628,7 +632,7 @@ impl PipeTransport {
self.inner self.inner
.handlers .handlers
.sctp_state_change .sctp_state_change
.add(Box::new(callback)) .add(Arc::new(callback))
} }
/// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance. /// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance.
......
...@@ -16,13 +16,12 @@ use crate::worker::{ ...@@ -16,13 +16,12 @@ use crate::worker::{
Channel, NotificationError, PayloadChannel, RequestError, SubscriptionHandler, Channel, NotificationError, PayloadChannel, RequestError, SubscriptionHandler,
}; };
use async_executor::Executor; use async_executor::Executor;
use bytes::Bytes;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use hash_hasher::HashedMap;
use log::{debug, error}; use log::{debug, error};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr}; use serde_repr::{Deserialize_repr, Serialize_repr};
use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::fmt::Debug; use std::fmt::Debug;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
...@@ -101,7 +100,7 @@ pub struct RtpStreamRecv { ...@@ -101,7 +100,7 @@ pub struct RtpStreamRecv {
pub packet_count: usize, pub packet_count: usize,
pub byte_count: usize, pub byte_count: usize,
pub bitrate: u32, pub bitrate: u32,
pub bitrate_by_layer: Option<HashMap<String, u32>>, pub bitrate_by_layer: Option<HashedMap<String, u32>>,
} }
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
...@@ -202,7 +201,7 @@ pub struct ProducerStat { ...@@ -202,7 +201,7 @@ pub struct ProducerStat {
pub rtx_packets_discarded: Option<u32>, pub rtx_packets_discarded: Option<u32>,
// RtpStreamRecv specific. // RtpStreamRecv specific.
pub jitter: u32, pub jitter: u32,
pub bitrate_by_layer: Option<HashMap<String, u32>>, pub bitrate_by_layer: Option<HashedMap<String, u32>>,
} }
/// 'trace' event data. /// 'trace' event data.
...@@ -280,11 +279,11 @@ enum Notification { ...@@ -280,11 +279,11 @@ enum Notification {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
score: Bag<Box<dyn Fn(&Vec<ProducerScore>) + Send + Sync>>, score: Bag<Arc<dyn Fn(&[ProducerScore]) + Send + Sync>>,
video_orientation_change: Bag<Box<dyn Fn(ProducerVideoOrientation) + Send + Sync>>, video_orientation_change: Bag<Arc<dyn Fn(ProducerVideoOrientation) + Send + Sync>>,
pause: Bag<Box<dyn Fn() + Send + Sync>>, pause: Bag<Arc<dyn Fn() + Send + Sync>>,
resume: Bag<Box<dyn Fn() + Send + Sync>>, resume: Bag<Arc<dyn Fn() + Send + Sync>>,
trace: Bag<Box<dyn Fn(&ProducerTraceEventData) + Send + Sync>>, trace: Bag<Arc<dyn Fn(&ProducerTraceEventData) + Send + Sync>, ProducerTraceEventData>,
transport_close: BagOnce<Box<dyn FnOnce() + Send>>, transport_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
} }
...@@ -459,7 +458,7 @@ impl Producer { ...@@ -459,7 +458,7 @@ impl Producer {
let score = Arc::clone(&score); let score = Arc::clone(&score);
channel.subscribe_to_notifications(id.into(), move |notification| { channel.subscribe_to_notifications(id.into(), move |notification| {
match serde_json::from_value::<Notification>(notification) { match serde_json::from_slice::<Notification>(notification) {
Ok(notification) => match notification { Ok(notification) => match notification {
Notification::Score(scores) => { Notification::Score(scores) => {
*score.lock() = scores.clone(); *score.lock() = scores.clone();
...@@ -473,9 +472,7 @@ impl Producer { ...@@ -473,9 +472,7 @@ impl Producer {
}); });
} }
Notification::Trace(trace_event_data) => { Notification::Trace(trace_event_data) => {
handlers.trace.call(|callback| { handlers.trace.call_simple(&trace_event_data);
callback(&trace_event_data);
});
} }
}, },
Err(error) => { Err(error) => {
...@@ -666,11 +663,11 @@ impl Producer { ...@@ -666,11 +663,11 @@ impl Producer {
} }
/// Callback is called when the producer score changes. /// Callback is called when the producer score changes.
pub fn on_score<F: Fn(&Vec<ProducerScore>) + Send + Sync + 'static>( pub fn on_score<F: Fn(&[ProducerScore]) + Send + Sync + 'static>(
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner().handlers.score.add(Box::new(callback)) self.inner().handlers.score.add(Arc::new(callback))
} }
/// Callback is called when the video orientation changes. This is just possible if the /// Callback is called when the video orientation changes. This is just possible if the
...@@ -683,17 +680,17 @@ impl Producer { ...@@ -683,17 +680,17 @@ impl Producer {
self.inner() self.inner()
.handlers .handlers
.video_orientation_change .video_orientation_change
.add(Box::new(callback)) .add(Arc::new(callback))
} }
/// Callback is called when the producer is paused. /// Callback is called when the producer is paused.
pub fn on_pause<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_pause<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner().handlers.pause.add(Box::new(callback)) self.inner().handlers.pause.add(Arc::new(callback))
} }
/// Callback is called when the producer is resumed. /// Callback is called when the producer is resumed.
pub fn on_resume<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_resume<F: Fn() + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner().handlers.resume.add(Box::new(callback)) self.inner().handlers.resume.add(Arc::new(callback))
} }
/// See [`Producer::enable_trace_event`] method. /// See [`Producer::enable_trace_event`] method.
...@@ -701,7 +698,7 @@ impl Producer { ...@@ -701,7 +698,7 @@ impl Producer {
&self, &self,
callback: F, callback: F,
) -> HandlerId { ) -> HandlerId {
self.inner().handlers.trace.add(Box::new(callback)) self.inner().handlers.trace.add(Arc::new(callback))
} }
/// Callback is called when the transport this producer belongs to is closed for whatever /// Callback is called when the transport this producer belongs to is closed for whatever
...@@ -763,10 +760,8 @@ impl Producer { ...@@ -763,10 +760,8 @@ impl Producer {
impl DirectProducer { impl DirectProducer {
/// Sends a RTP packet from the Rust process. /// Sends a RTP packet from the Rust process.
pub async fn send(&self, rtp_packet: Bytes) -> Result<(), NotificationError> { pub fn send(&self, rtp_packet: Vec<u8>) -> Result<(), NotificationError> {
self.inner self.inner.payload_channel.notify(
.payload_channel
.notify(
ProducerSendNotification { ProducerSendNotification {
internal: ProducerInternal { internal: ProducerInternal {
router_id: self.inner.transport.router_id(), router_id: self.inner.transport.router_id(),
...@@ -776,7 +771,6 @@ impl DirectProducer { ...@@ -776,7 +771,6 @@ impl DirectProducer {
}, },
rtp_packet, rtp_packet,
) )
.await
} }
} }
......
...@@ -23,13 +23,14 @@ use crate::{ortc, uuid_based_wrapper_type}; ...@@ -23,13 +23,14 @@ use crate::{ortc, uuid_based_wrapper_type};
use async_executor::Executor; use async_executor::Executor;
use async_trait::async_trait; use async_trait::async_trait;
use event_listener_primitives::HandlerId; use event_listener_primitives::HandlerId;
use hash_hasher::HashedMap;
use log::{error, warn}; use log::{error, warn};
use nohash_hasher::IntMap;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use serde_json::Value;
use std::fmt::Debug; use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
use thiserror::Error; use thiserror::Error;
...@@ -103,11 +104,11 @@ pub enum TransportTraceEventType { ...@@ -103,11 +104,11 @@ pub enum TransportTraceEventType {
#[doc(hidden)] #[doc(hidden)]
pub struct RtpListener { pub struct RtpListener {
/// Map from Ssrc (as string) to producer ID /// Map from Ssrc (as string) to producer ID
pub mid_table: HashMap<String, ProducerId>, pub mid_table: HashedMap<String, ProducerId>,
/// Map from Ssrc (as string) to producer ID /// Map from Ssrc (as string) to producer ID
pub rid_table: HashMap<String, ProducerId>, pub rid_table: HashedMap<String, ProducerId>,
/// Map from Ssrc (as string) to producer ID /// Map from Ssrc (as string) to producer ID
pub ssrc_table: HashMap<String, ProducerId>, pub ssrc_table: HashedMap<String, ProducerId>,
} }
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Serialize)] #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Serialize)]
...@@ -126,7 +127,7 @@ pub struct RecvRtpHeaderExtensions { ...@@ -126,7 +127,7 @@ pub struct RecvRtpHeaderExtensions {
#[doc(hidden)] #[doc(hidden)]
pub struct SctpListener { pub struct SctpListener {
/// Map from stream ID (as string) to data producer ID /// Map from stream ID (as string) to data producer ID
stream_id_table: HashMap<String, DataProducerId>, stream_id_table: HashedMap<String, DataProducerId>,
} }
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
...@@ -236,31 +237,31 @@ pub trait Transport: Debug + Send + Sync + private::CloneTransport { ...@@ -236,31 +237,31 @@ pub trait Transport: Debug + Send + Sync + private::CloneTransport {
/// Callback is called when a new producer is created. /// Callback is called when a new producer is created.
fn on_new_producer( fn on_new_producer(
&self, &self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId; ) -> HandlerId;
/// Callback is called when a new consumer is created. /// Callback is called when a new consumer is created.
fn on_new_consumer( fn on_new_consumer(
&self, &self,
callback: Box<dyn Fn(&Consumer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&Consumer) + Send + Sync + 'static>,
) -> HandlerId; ) -> HandlerId;
/// Callback is called when a new data producer is created. /// Callback is called when a new data producer is created.
fn on_new_data_producer( fn on_new_data_producer(
&self, &self,
callback: Box<dyn Fn(&DataProducer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&DataProducer) + Send + Sync + 'static>,
) -> HandlerId; ) -> HandlerId;
/// Callback is called when a new data consumer is created. /// Callback is called when a new data consumer is created.
fn on_new_data_consumer( fn on_new_data_consumer(
&self, &self,
callback: Box<dyn Fn(&DataConsumer) + Send + Sync + 'static>, callback: Arc<dyn Fn(&DataConsumer) + Send + Sync + 'static>,
) -> HandlerId; ) -> HandlerId;
/// See [`Transport::enable_trace_event()`] /// See [`Transport::enable_trace_event()`]
fn on_trace( fn on_trace(
&self, &self,
callback: Box<dyn Fn(&TransportTraceEventData) + Send + Sync + 'static>, callback: Arc<dyn Fn(&TransportTraceEventData) + Send + Sync + 'static>,
) -> HandlerId; ) -> HandlerId;
/// Callback is called when the router this transport belongs to is closed for whatever reason. /// Callback is called when the router this transport belongs to is closed for whatever reason.
...@@ -371,7 +372,7 @@ pub(super) trait TransportImpl: TransportGeneric { ...@@ -371,7 +372,7 @@ pub(super) trait TransportImpl: TransportGeneric {
fn next_mid_for_consumers(&self) -> &AtomicUsize; fn next_mid_for_consumers(&self) -> &AtomicUsize;
fn used_sctp_stream_ids(&self) -> &Mutex<HashMap<u16, bool>>; fn used_sctp_stream_ids(&self) -> &Mutex<IntMap<u16, bool>>;
fn cname_for_producers(&self) -> &Mutex<Option<String>>; fn cname_for_producers(&self) -> &Mutex<Option<String>>;
...@@ -395,26 +396,24 @@ pub(super) trait TransportImpl: TransportGeneric { ...@@ -395,26 +396,24 @@ pub(super) trait TransportImpl: TransportGeneric {
} }
} }
async fn dump_impl(&self) -> Result<Self::Dump, RequestError> { async fn dump_impl(&self) -> Result<Value, RequestError> {
self.channel() self.channel()
.request(TransportDumpRequest { .request(TransportDumpRequest {
internal: TransportInternal { internal: TransportInternal {
router_id: self.router().id(), router_id: self.router().id(),
transport_id: self.id(), transport_id: self.id(),
}, },
phantom_data: PhantomData {},
}) })
.await .await
} }
async fn get_stats_impl(&self) -> Result<Vec<Self::Stat>, RequestError> { async fn get_stats_impl(&self) -> Result<Value, RequestError> {
self.channel() self.channel()
.request(TransportGetStatsRequest { .request(TransportGetStatsRequest {
internal: TransportInternal { internal: TransportInternal {
router_id: self.router().id(), router_id: self.router().id(),
transport_id: self.id(), transport_id: self.id(),
}, },
phantom_data: PhantomData {},
}) })
.await .await
} }
......
//! A worker represents a mediasoup C++ thread that runs on a single CPU core and handles //! A worker represents a mediasoup C++ thread that runs on a single CPU core and handles
//! [`Router`] instances. //! [`Router`] instances.
// TODO: This is Unix-specific and doesn't support Windows in any way
mod channel; mod channel;
mod common; mod common;
mod payload_channel; mod payload_channel;
...@@ -25,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId}; ...@@ -25,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId};
use futures_lite::FutureExt; use futures_lite::FutureExt;
use log::{debug, error, warn}; use log::{debug, error, warn};
use parking_lot::Mutex; use parking_lot::Mutex;
pub(crate) use payload_channel::{NotificationError, NotificationMessage, PayloadChannel}; pub(crate) use payload_channel::{NotificationError, PayloadChannel};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::ops::RangeInclusive; use std::ops::RangeInclusive;
use std::path::PathBuf; use std::path::PathBuf;
...@@ -40,18 +39,12 @@ uuid_based_wrapper_type!( ...@@ -40,18 +39,12 @@ uuid_based_wrapper_type!(
WorkerId WorkerId
); );
/// Error that caused request to mediasoup-worker thread to fail. /// Error that caused request to mediasoup-worker request to fail.
#[derive(Debug, Error, Eq, PartialEq)] #[derive(Debug, Error, Eq, PartialEq)]
pub enum RequestError { pub enum RequestError {
/// Channel already closed. /// Channel already closed.
#[error("Channel already closed")] #[error("Channel already closed")]
ChannelClosed, ChannelClosed,
/// Message is too long.
#[error("Message is too long")]
MessageTooLong,
/// Payload is too long.
#[error("Payload is too long")]
PayloadTooLong,
/// Request timed out. /// Request timed out.
#[error("Request timed out")] #[error("Request timed out")]
TimedOut, TimedOut,
...@@ -171,7 +164,7 @@ pub struct WorkerDtlsFiles { ...@@ -171,7 +164,7 @@ pub struct WorkerDtlsFiles {
} }
/// Settings for worker to be created with. /// Settings for worker to be created with.
#[derive(Debug, Clone)] #[derive(Clone)]
#[non_exhaustive] #[non_exhaustive]
pub struct WorkerSettings { pub struct WorkerSettings {
/// Logging level for logs generated by the media worker thread. /// Logging level for logs generated by the media worker thread.
...@@ -187,6 +180,9 @@ pub struct WorkerSettings { ...@@ -187,6 +180,9 @@ pub struct WorkerSettings {
/// ///
/// If `None`, a certificate is dynamically created. /// If `None`, a certificate is dynamically created.
pub dtls_files: Option<WorkerDtlsFiles>, pub dtls_files: Option<WorkerDtlsFiles>,
/// Function that will be called under worker thread before worker starts, can be used for
/// pinning worker threads to CPU cores.
pub thread_initializer: Option<Arc<dyn Fn() + Send + Sync>>,
/// Custom application data. /// Custom application data.
pub app_data: AppData, pub app_data: AppData,
} }
...@@ -198,11 +194,37 @@ impl Default for WorkerSettings { ...@@ -198,11 +194,37 @@ impl Default for WorkerSettings {
log_tags: Vec::new(), log_tags: Vec::new(),
rtc_ports_range: 10000..=59999, rtc_ports_range: 10000..=59999,
dtls_files: None, dtls_files: None,
thread_initializer: None,
app_data: AppData::default(), app_data: AppData::default(),
} }
} }
} }
impl fmt::Debug for WorkerSettings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let WorkerSettings {
log_level,
log_tags,
rtc_ports_range,
dtls_files,
thread_initializer,
app_data,
} = self;
f.debug_struct("WorkerSettings")
.field("log_level", &log_level)
.field("log_tags", &log_tags)
.field("rtc_ports_range", &rtc_ports_range)
.field("dtls_files", &dtls_files)
.field(
"thread_initializer",
&thread_initializer.as_ref().map(|_| "ThreadInitializer"),
)
.field("app_data", &app_data)
.finish()
}
}
/// Worker settings that can be updated in runtime. /// Worker settings that can be updated in runtime.
#[derive(Default, Debug, Clone, Serialize)] #[derive(Default, Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
...@@ -241,7 +263,7 @@ pub enum CreateRouterError { ...@@ -241,7 +263,7 @@ pub enum CreateRouterError {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
new_router: Bag<Box<dyn Fn(&Router) + Send + Sync>>, new_router: Bag<Arc<dyn Fn(&Router) + Send + Sync>, Router>,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
dead: BagOnce<Box<dyn FnOnce(Result<(), ExitError>) + Send>>, dead: BagOnce<Box<dyn FnOnce(Result<(), ExitError>) + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>, close: BagOnce<Box<dyn FnOnce() + Send>>,
...@@ -271,11 +293,12 @@ impl Inner { ...@@ -271,11 +293,12 @@ impl Inner {
async fn new<OE: FnOnce() + Send + 'static>( async fn new<OE: FnOnce() + Send + 'static>(
executor: Arc<Executor<'static>>, executor: Arc<Executor<'static>>,
WorkerSettings { WorkerSettings {
app_data,
log_level, log_level,
log_tags, log_tags,
rtc_ports_range, rtc_ports_range,
dtls_files, dtls_files,
thread_initializer,
app_data,
}: WorkerSettings, }: WorkerSettings,
worker_manager: WorkerManager, worker_manager: WorkerManager,
on_exit: OE, on_exit: OE,
...@@ -327,7 +350,7 @@ impl Inner { ...@@ -327,7 +350,7 @@ impl Inner {
channel, channel,
payload_channel, payload_channel,
buffer_worker_messages_guard, buffer_worker_messages_guard,
} = utils::run_worker_with_channels(id, Arc::clone(&executor), spawn_args, move |result| { } = utils::run_worker_with_channels(id, thread_initializer, spawn_args, move |result| {
let _ = status_sender.send(result); let _ = status_sender.send(result);
on_exit(); on_exit();
}); });
...@@ -405,7 +428,7 @@ impl Inner { ...@@ -405,7 +428,7 @@ impl Inner {
let _handler = self.channel.subscribe_to_notifications( let _handler = self.channel.subscribe_to_notifications(
std::process::id().into(), std::process::id().into(),
move |notification| { move |notification| {
let result = match serde_json::from_value(notification.clone()) { let result = match serde_json::from_slice(notification) {
Ok(Notification::Running) => { Ok(Notification::Running) => {
debug!("worker thread running [id:{}]", id); debug!("worker thread running [id:{}]", id);
Ok(()) Ok(())
...@@ -601,16 +624,14 @@ impl Worker { ...@@ -601,16 +624,14 @@ impl Worker {
self.clone(), self.clone(),
); );
self.inner.handlers.new_router.call(|callback| { self.inner.handlers.new_router.call_simple(&router);
callback(&router);
});
Ok(router) Ok(router)
} }
/// Callback is called when a new router is created. /// Callback is called when a new router is created.
pub fn on_new_router<F: Fn(&Router) + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_new_router<F: Fn(&Router) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.new_router.add(Box::new(callback)) self.inner.handlers.new_router.add(Arc::new(callback))
} }
/// Callback is called when the worker thread unexpectedly dies. /// Callback is called when the worker thread unexpectedly dies.
......
差异被折叠。
use hash_hasher::HashedMap;
use nohash_hasher::IntMap;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::collections::HashMap; use serde::Deserialize;
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use uuid::Uuid; use uuid::Uuid;
struct EventHandlersList<V: Clone + 'static> { struct EventHandlersList<F> {
index: usize, index: usize,
#[allow(clippy::type_complexity)] callbacks: IntMap<usize, F>,
callbacks: HashMap<usize, Arc<Box<dyn Fn(V) + Send + Sync>>>,
} }
impl<V: Clone + 'static> Default for EventHandlersList<V> { impl<F> Default for EventHandlersList<F> {
fn default() -> Self { fn default() -> Self {
Self { Self {
index: 0, index: 0,
callbacks: HashMap::new(), callbacks: IntMap::default(),
} }
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub(super) struct EventHandlers<V: Clone + 'static> { pub(super) struct EventHandlers<F> {
handlers: Arc<Mutex<HashMap<SubscriptionTarget, EventHandlersList<V>>>>, handlers: Arc<Mutex<HashedMap<SubscriptionTarget, EventHandlersList<F>>>>,
} }
impl<V: Clone + 'static> EventHandlers<V> { impl<F: Sized + Send + Sync + 'static> EventHandlers<F> {
pub(super) fn new() -> Self { pub(super) fn new() -> Self {
let handlers = Arc::<Mutex<HashMap<SubscriptionTarget, EventHandlersList<V>>>>::default(); let handlers = Arc::<Mutex<HashedMap<SubscriptionTarget, EventHandlersList<F>>>>::default();
Self { handlers } Self { handlers }
} }
pub(super) fn add( pub(super) fn add(&self, target_id: SubscriptionTarget, callback: F) -> SubscriptionHandler {
&self,
target_id: SubscriptionTarget,
callback: Box<dyn Fn(V) + Send + Sync + 'static>,
) -> SubscriptionHandler {
let index; let index;
{ {
let mut event_handlers = self.handlers.lock(); let mut event_handlers = self.handlers.lock();
...@@ -42,7 +39,7 @@ impl<V: Clone + 'static> EventHandlers<V> { ...@@ -42,7 +39,7 @@ impl<V: Clone + 'static> EventHandlers<V> {
.or_insert_with(EventHandlersList::default); .or_insert_with(EventHandlersList::default);
index = list.index; index = list.index;
list.index += 1; list.index += 1;
list.callbacks.insert(index, Arc::new(Box::new(callback))); list.callbacks.insert(index, callback);
drop(event_handlers); drop(event_handlers);
} }
...@@ -75,54 +72,72 @@ impl<V: Clone + 'static> EventHandlers<V> { ...@@ -75,54 +72,72 @@ impl<V: Clone + 'static> EventHandlers<V> {
}) })
} }
pub(super) fn call_callbacks_with_value(&self, target_id: &SubscriptionTarget, value: V) { pub(super) fn downgrade(&self) -> WeakEventHandlers<F> {
WeakEventHandlers {
handlers: Arc::downgrade(&self.handlers),
}
}
}
impl<V: ?Sized> EventHandlers<Arc<dyn Fn(&V) + Send + Sync + 'static>> {
pub(super) fn call_callbacks_with_single_value(
&self,
target_id: &SubscriptionTarget,
value: &V,
) {
let handlers = self.handlers.lock(); let handlers = self.handlers.lock();
if let Some(list) = handlers.get(target_id) { if let Some(list) = handlers.get(target_id) {
// Tiny optimization that avoids cloning `value` unless necessary for callback in list.callbacks.values() {
if list.callbacks.len() == 1 {
let callback = list.callbacks.values().next().cloned().unwrap();
// Drop mutex guard before running callbacks to avoid deadlocks
drop(handlers);
callback(value); callback(value);
} else {
let callbacks = list.callbacks.values().cloned().collect::<Vec<_>>();
// Drop mutex guard before running callbacks to avoid deadlocks
drop(handlers);
for callback in callbacks {
callback(value.clone());
}
} }
} }
} }
}
pub(super) fn downgrade(&self) -> WeakEventHandlers<V> { impl<V1: ?Sized, V2: ?Sized> EventHandlers<Arc<dyn Fn(&V1, &V2) + Send + Sync + 'static>> {
WeakEventHandlers { pub(super) fn call_callbacks_with_two_values(
handlers: Arc::downgrade(&self.handlers), &self,
target_id: &SubscriptionTarget,
value1: &V1,
value2: &V2,
) {
let handlers = self.handlers.lock();
if let Some(list) = handlers.get(target_id) {
for callback in list.callbacks.values() {
callback(value1, value2);
}
} }
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub(super) struct WeakEventHandlers<V: Clone + 'static> { pub(super) struct WeakEventHandlers<F> {
handlers: Weak<Mutex<HashMap<SubscriptionTarget, EventHandlersList<V>>>>, handlers: Weak<Mutex<HashedMap<SubscriptionTarget, EventHandlersList<F>>>>,
} }
impl<V: Clone + 'static> WeakEventHandlers<V> { impl<F> WeakEventHandlers<F> {
pub(super) fn upgrade(&self) -> Option<EventHandlers<V>> { pub(super) fn upgrade(&self) -> Option<EventHandlers<F>> {
self.handlers self.handlers
.upgrade() .upgrade()
.map(|handlers| EventHandlers { handlers }) .map(|handlers| EventHandlers { handlers })
} }
} }
#[derive(Copy, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Deserialize)]
#[serde(untagged)]
pub(crate) enum SubscriptionTarget { pub(crate) enum SubscriptionTarget {
Uuid(Uuid), Uuid(Uuid),
Number(u32), Number(u64),
} }
impl From<u32> for SubscriptionTarget { impl From<u32> for SubscriptionTarget {
fn from(number: u32) -> Self { fn from(number: u32) -> Self {
Self::Number(u64::from(number))
}
}
impl From<u64> for SubscriptionTarget {
fn from(number: u64) -> Self {
Self::Number(number) Self::Number(number)
} }
} }
......
// Contents of this module is inspired by https://github.com/Srinivasa314/alcro/tree/master/src/chrome mod channel_read_fn;
mod channel_write_fn;
use crate::worker::channel::BufferMessagesGuard; use crate::worker::channel::BufferMessagesGuard;
use crate::worker::{Channel, PayloadChannel, WorkerId}; use crate::worker::{Channel, PayloadChannel, WorkerId};
use async_executor::Executor; pub(super) use channel_read_fn::{
use async_fs::File; prepare_channel_read_fn, prepare_payload_channel_read_fn, PreparedChannelRead,
PreparedPayloadChannelRead,
};
pub(super) use channel_write_fn::{
prepare_channel_write_fn, prepare_payload_channel_write_fn, PreparedChannelWrite,
PreparedPayloadChannelWrite,
};
use std::ffi::CString; use std::ffi::CString;
use std::mem;
use std::os::raw::{c_char, c_int}; use std::os::raw::{c_char, c_int};
use std::os::unix::io::FromRawFd;
use std::sync::Arc; use std::sync::Arc;
use thiserror::Error; use thiserror::Error;
...@@ -30,18 +36,6 @@ pub enum ExitError { ...@@ -30,18 +36,6 @@ pub enum ExitError {
Unexpected, Unexpected,
} }
fn pipe() -> [c_int; 2] {
unsafe {
let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit();
if libc::pipe(fds.as_mut_ptr().cast::<c_int>()) != 0 {
panic!("libc::pipe() failed: {:?}", std::io::Error::last_os_error());
}
fds.assume_init()
}
}
pub(super) struct WorkerRunResult { pub(super) struct WorkerRunResult {
pub(super) channel: Channel, pub(super) channel: Channel,
pub(super) payload_channel: PayloadChannel, pub(super) payload_channel: PayloadChannel,
...@@ -50,31 +44,24 @@ pub(super) struct WorkerRunResult { ...@@ -50,31 +44,24 @@ pub(super) struct WorkerRunResult {
pub(super) fn run_worker_with_channels<OE>( pub(super) fn run_worker_with_channels<OE>(
id: WorkerId, id: WorkerId,
executor: Arc<Executor<'static>>, thread_initializer: Option<Arc<dyn Fn() + Send + Sync>>,
args: Vec<String>, args: Vec<String>,
on_exit: OE, on_exit: OE,
) -> WorkerRunResult ) -> WorkerRunResult
where where
OE: FnOnce(Result<(), ExitError>) + Send + 'static, OE: FnOnce(Result<(), ExitError>) + Send + 'static,
{ {
let [producer_fd_read, producer_fd_write] = pipe(); let (channel, prepared_channel_read, prepared_channel_write) = Channel::new();
let [consumer_fd_read, consumer_fd_write] = pipe(); let (payload_channel, prepared_payload_channel_read, prepared_payload_channel_write) =
let [producer_payload_fd_read, producer_payload_fd_write] = pipe(); PayloadChannel::new();
let [consumer_payload_fd_read, consumer_payload_fd_write] = pipe();
let producer_file = unsafe { File::from_raw_fd(producer_fd_write) };
let consumer_file = unsafe { File::from_raw_fd(consumer_fd_read) };
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(&executor, consumer_file, producer_file);
let payload_channel =
PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file);
let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into()); let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into());
std::thread::Builder::new() std::thread::Builder::new()
.name(format!("mediasoup-worker-{}", id)) .name(format!("mediasoup-worker-{}", id))
.spawn(move || { .spawn(move || {
if let Some(thread_initializer) = thread_initializer {
thread_initializer();
}
let argc = args.len() as c_int; let argc = args.len() as c_int;
let args_cstring = args let args_cstring = args
.into_iter() .into_iter()
...@@ -85,15 +72,39 @@ where ...@@ -85,15 +72,39 @@ where
.map(|arg| arg.as_ptr().cast::<c_char>()) .map(|arg| arg.as_ptr().cast::<c_char>())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap(); let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap();
let status_code = unsafe { let status_code = unsafe {
mediasoup_sys::run_worker( let (channel_read_fn, channel_read_ctx, _channel_write_callback) =
prepared_channel_read.deconstruct();
let (channel_write_fn, channel_write_ctx, _channel_read_callback) =
prepared_channel_write.deconstruct();
let (
payload_channel_read_fn,
payload_channel_read_ctx,
_payload_channel_write_callback,
) = prepared_payload_channel_read.deconstruct();
let (
payload_channel_write_fn,
payload_channel_write_ctx,
_payload_channel_read_callback,
) = prepared_payload_channel_write.deconstruct();
mediasoup_sys::mediasoup_worker_run(
argc, argc,
argv.as_ptr(), argv.as_ptr(),
version.as_ptr(), version.as_ptr(),
producer_fd_read, 0,
consumer_fd_write, 0,
producer_payload_fd_read, 0,
consumer_payload_fd_write, 0,
channel_read_fn,
channel_read_ctx,
channel_write_fn,
channel_write_ctx,
payload_channel_read_fn,
payload_channel_read_ctx,
payload_channel_write_fn,
payload_channel_write_ctx,
) )
}; };
......
pub(super) use mediasoup_sys::{
ChannelReadCtx, ChannelReadFn, PayloadChannelReadCtx, PayloadChannelReadFn,
};
use mediasoup_sys::{ChannelReadFreeFn, PayloadChannelReadFreeFn, UvAsyncT};
use std::mem;
use std::os::raw::c_void;
unsafe extern "C" fn free_vec(message: *mut u8, message_len: u32, message_capacity: usize) {
Vec::from_raw_parts(message, message_len as usize, message_capacity);
}
pub(super) struct ChannelReadCallback(
Box<dyn (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static>,
);
pub(crate) struct PreparedChannelRead {
channel_read_fn: ChannelReadFn,
channel_read_ctx: ChannelReadCtx,
write_callback: ChannelReadCallback,
}
unsafe impl Send for PreparedChannelRead {}
impl PreparedChannelRead {
/// SAFETY:
/// 1) `ChannelReadCallback` returned must be dropped AFTER last usage of returned function and
/// context pointers
/// 2) `ChannelReadCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(self) -> (ChannelReadFn, ChannelReadCtx, ChannelReadCallback) {
let Self {
channel_read_fn,
channel_read_ctx,
write_callback,
} = self;
(channel_read_fn, channel_read_ctx, write_callback)
}
}
/// Given callback function, prepares a pair of channel read function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it wants to
/// read something from Rust (so it is reading from C++ point of view and writing from Rust).
pub(crate) fn prepare_channel_read_fn<F>(read_callback: F) -> PreparedChannelRead
where
F: (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *mut *mut u8,
message_len: *mut u32,
message_capacity: *mut usize,
handle: UvAsyncT,
ChannelReadCtx(ctx): ChannelReadCtx,
) -> ChannelReadFreeFn
where
F: (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static,
{
// Call Rust and try to get a new message (if there is any)
let mut new_message = (*(ctx as *mut F))(handle)?;
// Set pointers, give out control over memory to C++
*message = new_message.as_mut_ptr();
*message_len = new_message.len() as u32;
*message_capacity = new_message.capacity();
// Forget about vector in Rust
mem::forget(new_message);
// Function pointer that C++ can use to free vector later
Some(free_vec)
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedChannelRead {
channel_read_fn: wrapper::<F>,
channel_read_ctx: ChannelReadCtx(read_callback.as_ref() as *const F as *const c_void),
write_callback: ChannelReadCallback(read_callback),
}
}
#[allow(clippy::type_complexity)]
pub(super) struct PayloadChannelReadCallback(
Box<dyn (FnMut(UvAsyncT) -> Option<(Vec<u8>, Vec<u8>)>) + Send + 'static>,
);
pub(crate) struct PreparedPayloadChannelRead {
payload_channel_read_fn: PayloadChannelReadFn,
payload_channel_read_ctx: PayloadChannelReadCtx,
write_callback: PayloadChannelReadCallback,
}
unsafe impl Send for PreparedPayloadChannelRead {}
impl PreparedPayloadChannelRead {
/// SAFETY:
/// 1) `PayloadChannelReadCallback` returned must be dropped AFTER last usage of returned
/// function and context pointers
/// 2) `PayloadChannelReadCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
) -> (
PayloadChannelReadFn,
PayloadChannelReadCtx,
PayloadChannelReadCallback,
) {
let Self {
payload_channel_read_fn,
payload_channel_read_ctx,
write_callback,
} = self;
(
payload_channel_read_fn,
payload_channel_read_ctx,
write_callback,
)
}
}
/// Given callback function, prepares a pair of channel read function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it wants to
/// read something from Rust (so it is reading from C++ point of view and writing from Rust).
pub(crate) fn prepare_payload_channel_read_fn<F>(read_callback: F) -> PreparedPayloadChannelRead
where
F: (FnMut(UvAsyncT) -> Option<(Vec<u8>, Vec<u8>)>) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *mut *mut u8,
message_len: *mut u32,
message_capacity: *mut usize,
payload: *mut *mut u8,
payload_len: *mut u32,
payload_capacity: *mut usize,
handle: UvAsyncT,
PayloadChannelReadCtx(ctx): PayloadChannelReadCtx,
) -> PayloadChannelReadFreeFn
where
F: (FnMut(UvAsyncT) -> Option<(Vec<u8>, Vec<u8>)>) + Send + 'static,
{
// Call Rust and try to get a new message (if there is any)
let (mut new_message, mut new_payload) = (*(ctx as *mut F))(handle)?;
// Set pointers, give out control over memory to C++
*message = new_message.as_mut_ptr();
*message_len = new_message.len() as u32;
*message_capacity = new_message.capacity();
*payload = new_payload.as_mut_ptr();
*payload_len = new_payload.len() as u32;
*payload_capacity = new_payload.capacity();
// Forget about vectors in Rust
mem::forget(new_message);
mem::forget(new_payload);
// Function pointer that C++ can use to free vectors later
Some(free_vec)
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedPayloadChannelRead {
payload_channel_read_fn: wrapper::<F>,
payload_channel_read_ctx: PayloadChannelReadCtx(
read_callback.as_ref() as *const F as *const c_void
),
write_callback: PayloadChannelReadCallback(read_callback),
}
}
pub(super) use mediasoup_sys::{
ChannelWriteCtx, ChannelWriteFn, PayloadChannelWriteCtx, PayloadChannelWriteFn,
};
use std::os::raw::c_void;
use std::slice;
pub(super) struct ChannelReadCallback(Box<dyn FnMut(&[u8]) + Send + 'static>);
pub(crate) struct PreparedChannelWrite {
channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx,
read_callback: ChannelReadCallback,
}
unsafe impl Send for PreparedChannelWrite {}
impl PreparedChannelWrite {
/// SAFETY:
/// 1) `ChannelReadCallback` returned must be dropped AFTER last usage of returned function and
/// context pointers
/// 2) `ChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
) -> (ChannelWriteFn, ChannelWriteCtx, ChannelReadCallback) {
let Self {
channel_write_fn,
channel_write_ctx,
read_callback,
} = self;
(channel_write_fn, channel_write_ctx, read_callback)
}
}
/// Given callback function, prepares a pair of channel write function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it needs to
/// send something to Rust (so it is writing from C++ point of view and reading from Rust).
pub(crate) fn prepare_channel_write_fn<F>(read_callback: F) -> PreparedChannelWrite
where
F: FnMut(&[u8]) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *const u8,
message_len: u32,
ChannelWriteCtx(ctx): ChannelWriteCtx,
) where
F: FnMut(&[u8]) + Send + 'static,
{
let message = slice::from_raw_parts(message, message_len as usize);
(*(ctx as *mut F))(message);
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: ChannelWriteCtx(read_callback.as_ref() as *const F as *const c_void),
read_callback: ChannelReadCallback(read_callback),
}
}
pub(super) struct PayloadChannelReadCallback(Box<dyn FnMut(&[u8], &[u8]) + Send + 'static>);
pub(crate) struct PreparedPayloadChannelWrite {
channel_write_fn: PayloadChannelWriteFn,
channel_write_ctx: PayloadChannelWriteCtx,
read_callback: PayloadChannelReadCallback,
}
unsafe impl Send for PreparedPayloadChannelWrite {}
impl PreparedPayloadChannelWrite {
/// SAFETY:
/// 1) `PayloadChannelReadCallback` returned must be dropped AFTER last usage of returned
/// function and context pointers
/// 2) `PayloadChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
) -> (
PayloadChannelWriteFn,
PayloadChannelWriteCtx,
PayloadChannelReadCallback,
) {
let Self {
channel_write_fn,
channel_write_ctx,
read_callback,
} = self;
(channel_write_fn, channel_write_ctx, read_callback)
}
}
/// Given callback function, prepares a pair of channel write function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it needs to
/// send something to Rust (so it is writing from C++ point of view and reading from Rust).
pub(crate) fn prepare_payload_channel_write_fn<F>(read_callback: F) -> PreparedPayloadChannelWrite
where
F: FnMut(&[u8], &[u8]) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *const u8,
message_len: u32,
payload: *const u8,
payload_len: u32,
PayloadChannelWriteCtx(ctx): PayloadChannelWriteCtx,
) where
F: FnMut(&[u8], &[u8]) + Send + 'static,
{
let message = slice::from_raw_parts(message, message_len as usize);
let payload = if payload_len == 0 {
&[]
} else {
slice::from_raw_parts(payload, payload_len as usize)
};
(*(ctx as *mut F))(message, payload);
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedPayloadChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: PayloadChannelWriteCtx(
read_callback.as_ref() as *const F as *const c_void
),
read_callback: PayloadChannelReadCallback(read_callback),
}
}
...@@ -18,7 +18,7 @@ use std::{fmt, io, mem}; ...@@ -18,7 +18,7 @@ use std::{fmt, io, mem};
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
new_worker: Bag<Box<dyn Fn(&Worker) + Send + Sync>>, new_worker: Bag<Arc<dyn Fn(&Worker) + Send + Sync>, Worker>,
} }
struct Inner { struct Inner {
...@@ -145,9 +145,7 @@ impl WorkerManager { ...@@ -145,9 +145,7 @@ impl WorkerManager {
) )
.await?; .await?;
self.inner.handlers.new_worker.call(|callback| { self.inner.handlers.new_worker.call_simple(&worker);
callback(&worker);
});
id.lock().replace(worker.id()); id.lock().replace(worker.id());
...@@ -158,6 +156,6 @@ impl WorkerManager { ...@@ -158,6 +156,6 @@ impl WorkerManager {
/// Callback is called when a new worker is created. /// Callback is called when a new worker is created.
pub fn on_new_worker<F: Fn(&Worker) + Send + Sync + 'static>(&self, callback: F) -> HandlerId { pub fn on_new_worker<F: Fn(&Worker) + Send + Sync + 'static>(&self, callback: F) -> HandlerId {
self.inner.handlers.new_worker.add(Box::new(callback)) self.inner.handlers.new_worker.add(Arc::new(callback))
} }
} }
use async_io::Timer; use async_io::Timer;
use futures_lite::future; use futures_lite::future;
use hash_hasher::{HashedMap, HashedSet};
use mediasoup::consumer::{ use mediasoup::consumer::{
ConsumableRtpEncoding, ConsumerLayers, ConsumerOptions, ConsumerScore, ConsumerType, ConsumableRtpEncoding, ConsumerLayers, ConsumerOptions, ConsumerScore, ConsumerType,
}; };
...@@ -20,7 +21,6 @@ use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTra ...@@ -20,7 +21,6 @@ use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTra
use mediasoup::worker::{Worker, WorkerSettings}; use mediasoup::worker::{Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::collections::{HashMap, HashSet};
use std::env; use std::env;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
...@@ -350,7 +350,7 @@ fn consume_succeeds() { ...@@ -350,7 +350,7 @@ fn consume_succeeds() {
.on_new_consumer({ .on_new_consumer({
let new_consumer_count = Arc::clone(&new_consumer_count); let new_consumer_count = Arc::clone(&new_consumer_count);
Box::new(move |_consumer| { Arc::new(move |_consumer| {
new_consumer_count.fetch_add(1, Ordering::SeqCst); new_consumer_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -421,13 +421,13 @@ fn consume_succeeds() { ...@@ -421,13 +421,13 @@ fn consume_succeeds() {
let router_dump = router.dump().await.expect("Failed to get router dump"); let router_dump = router.dump().await.expect("Failed to get router dump");
assert_eq!(router_dump.map_producer_id_consumer_ids, { assert_eq!(router_dump.map_producer_id_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(audio_producer.id(), { map.insert(audio_producer.id(), {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(audio_consumer.id()); set.insert(audio_consumer.id());
set set
}); });
map.insert(video_producer.id(), HashSet::new()); map.insert(video_producer.id(), HashedSet::default());
map map
}); });
...@@ -525,14 +525,14 @@ fn consume_succeeds() { ...@@ -525,14 +525,14 @@ fn consume_succeeds() {
let router_dump = router.dump().await.expect("Failed to get router dump"); let router_dump = router.dump().await.expect("Failed to get router dump");
assert_eq!(router_dump.map_producer_id_consumer_ids, { assert_eq!(router_dump.map_producer_id_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(audio_producer.id(), { map.insert(audio_producer.id(), {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(audio_consumer.id()); set.insert(audio_consumer.id());
set set
}); });
map.insert(video_producer.id(), { map.insert(video_producer.id(), {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(video_consumer.id()); set.insert(video_consumer.id());
set set
}); });
...@@ -620,14 +620,14 @@ fn consume_succeeds() { ...@@ -620,14 +620,14 @@ fn consume_succeeds() {
let router_dump = router.dump().await.expect("Failed to get router dump"); let router_dump = router.dump().await.expect("Failed to get router dump");
assert_eq!(router_dump.map_producer_id_consumer_ids, { assert_eq!(router_dump.map_producer_id_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(audio_producer.id(), { map.insert(audio_producer.id(), {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(audio_consumer.id()); set.insert(audio_consumer.id());
set set
}); });
map.insert(video_producer.id(), { map.insert(video_producer.id(), {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(video_consumer.id()); set.insert(video_consumer.id());
set.insert(video_pipe_consumer.id()); set.insert(video_pipe_consumer.id());
set set
...@@ -1387,11 +1387,11 @@ fn close_event() { ...@@ -1387,11 +1387,11 @@ fn close_event() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_producer_id_consumer_ids, { assert_eq!(dump.map_producer_id_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(audio_producer.id(), HashSet::new()); map.insert(audio_producer.id(), HashedSet::default());
map map
}); });
assert_eq!(dump.map_consumer_id_producer_id, HashMap::new()); assert_eq!(dump.map_consumer_id_producer_id, HashedMap::default());
} }
{ {
......
use async_io::Timer; use async_io::Timer;
use futures_lite::future; use futures_lite::future;
use hash_hasher::{HashedMap, HashedSet};
use mediasoup::data_consumer::{DataConsumerOptions, DataConsumerType}; use mediasoup::data_consumer::{DataConsumerOptions, DataConsumerType};
use mediasoup::data_producer::{DataProducer, DataProducerOptions}; use mediasoup::data_producer::{DataProducer, DataProducerOptions};
use mediasoup::data_structures::{AppData, TransportListenIp}; use mediasoup::data_structures::{AppData, TransportListenIp};
...@@ -11,7 +12,6 @@ use mediasoup::sctp_parameters::SctpStreamParameters; ...@@ -11,7 +12,6 @@ use mediasoup::sctp_parameters::SctpStreamParameters;
use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions}; use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions};
use mediasoup::worker::{Worker, WorkerSettings}; use mediasoup::worker::{Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use std::collections::{HashMap, HashSet};
use std::env; use std::env;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
...@@ -105,7 +105,7 @@ fn consume_data_succeeds() { ...@@ -105,7 +105,7 @@ fn consume_data_succeeds() {
.on_new_data_consumer({ .on_new_data_consumer({
let new_data_consumer_count = Arc::clone(&new_data_consumer_count); let new_data_consumer_count = Arc::clone(&new_data_consumer_count);
Box::new(move |_data_consumer| { Arc::new(move |_data_consumer| {
new_data_consumer_count.fetch_add(1, Ordering::SeqCst); new_data_consumer_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -154,16 +154,16 @@ fn consume_data_succeeds() { ...@@ -154,16 +154,16 @@ fn consume_data_succeeds() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_data_producer_id_data_consumer_ids, { assert_eq!(dump.map_data_producer_id_data_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(data_producer.id(), { map.insert(data_producer.id(), {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(data_consumer.id()); set.insert(data_consumer.id());
set set
}); });
map map
}); });
assert_eq!(dump.map_data_consumer_id_data_producer_id, { assert_eq!(dump.map_data_consumer_id_data_producer_id, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(data_consumer.id(), data_producer.id()); map.insert(data_consumer.id(), data_producer.id());
map map
}); });
...@@ -316,7 +316,7 @@ fn consume_data_on_direct_transport_succeeds() { ...@@ -316,7 +316,7 @@ fn consume_data_on_direct_transport_succeeds() {
.on_new_data_consumer({ .on_new_data_consumer({
let new_data_consumer_count = Arc::clone(&new_data_consumer_count); let new_data_consumer_count = Arc::clone(&new_data_consumer_count);
Box::new(move |_data_consumer| { Arc::new(move |_data_consumer| {
new_data_consumer_count.fetch_add(1, Ordering::SeqCst); new_data_consumer_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -478,11 +478,14 @@ fn close_event() { ...@@ -478,11 +478,14 @@ fn close_event() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_data_producer_id_data_consumer_ids, { assert_eq!(dump.map_data_producer_id_data_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(data_producer.id(), HashSet::new()); map.insert(data_producer.id(), HashedSet::default());
map map
}); });
assert_eq!(dump.map_data_consumer_id_data_producer_id, HashMap::new()); assert_eq!(
dump.map_data_consumer_id_data_producer_id,
HashedMap::default()
);
} }
{ {
......
use async_io::Timer; use async_io::Timer;
use futures_lite::future; use futures_lite::future;
use hash_hasher::{HashedMap, HashedSet};
use mediasoup::data_producer::{DataProducerOptions, DataProducerType}; use mediasoup::data_producer::{DataProducerOptions, DataProducerType};
use mediasoup::data_structures::{AppData, TransportListenIp}; use mediasoup::data_structures::{AppData, TransportListenIp};
use mediasoup::plain_transport::{PlainTransport, PlainTransportOptions}; use mediasoup::plain_transport::{PlainTransport, PlainTransportOptions};
...@@ -10,7 +11,6 @@ use mediasoup::transport::ProduceDataError; ...@@ -10,7 +11,6 @@ use mediasoup::transport::ProduceDataError;
use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions}; use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions};
use mediasoup::worker::{RequestError, Worker, WorkerSettings}; use mediasoup::worker::{RequestError, Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use std::collections::{HashMap, HashSet};
use std::env; use std::env;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
...@@ -86,7 +86,7 @@ fn transport_1_produce_data_succeeds() { ...@@ -86,7 +86,7 @@ fn transport_1_produce_data_succeeds() {
.on_new_data_producer({ .on_new_data_producer({
let new_data_producer_count = Arc::clone(&new_data_producer_count); let new_data_producer_count = Arc::clone(&new_data_producer_count);
Box::new(move |_data_producer| { Arc::new(move |_data_producer| {
new_data_producer_count.fetch_add(1, Ordering::SeqCst); new_data_producer_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -131,11 +131,14 @@ fn transport_1_produce_data_succeeds() { ...@@ -131,11 +131,14 @@ fn transport_1_produce_data_succeeds() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_data_producer_id_data_consumer_ids, { assert_eq!(dump.map_data_producer_id_data_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(data_producer1.id(), HashSet::new()); map.insert(data_producer1.id(), HashedSet::default());
map map
}); });
assert_eq!(dump.map_data_consumer_id_data_producer_id, HashMap::new()); assert_eq!(
dump.map_data_consumer_id_data_producer_id,
HashedMap::default()
);
} }
{ {
...@@ -159,7 +162,7 @@ fn transport_2_produce_data_succeeds() { ...@@ -159,7 +162,7 @@ fn transport_2_produce_data_succeeds() {
.on_new_data_producer({ .on_new_data_producer({
let new_data_producer_count = Arc::clone(&new_data_producer_count); let new_data_producer_count = Arc::clone(&new_data_producer_count);
Box::new(move |_data_producer| { Arc::new(move |_data_producer| {
new_data_producer_count.fetch_add(1, Ordering::SeqCst); new_data_producer_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -205,11 +208,14 @@ fn transport_2_produce_data_succeeds() { ...@@ -205,11 +208,14 @@ fn transport_2_produce_data_succeeds() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_data_producer_id_data_consumer_ids, { assert_eq!(dump.map_data_producer_id_data_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(data_producer2.id(), HashSet::new()); map.insert(data_producer2.id(), HashedSet::default());
map map
}); });
assert_eq!(dump.map_data_consumer_id_data_producer_id, HashMap::new()); assert_eq!(
dump.map_data_consumer_id_data_producer_id,
HashedMap::default()
);
} }
{ {
...@@ -447,8 +453,14 @@ fn close_event() { ...@@ -447,8 +453,14 @@ fn close_event() {
{ {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_data_producer_id_data_consumer_ids, HashMap::new()); assert_eq!(
assert_eq!(dump.map_data_consumer_id_data_producer_id, HashMap::new()); dump.map_data_producer_id_data_consumer_ids,
HashedMap::default()
);
assert_eq!(
dump.map_data_consumer_id_data_producer_id,
HashedMap::default()
);
} }
{ {
......
use bytes::Bytes;
use futures_lite::future; use futures_lite::future;
use hash_hasher::HashedSet;
use mediasoup::data_consumer::DataConsumerOptions; use mediasoup::data_consumer::DataConsumerOptions;
use mediasoup::data_producer::{DataProducer, DataProducerOptions}; use mediasoup::data_producer::{DataProducer, DataProducerOptions};
use mediasoup::data_structures::{AppData, WebRtcMessage}; use mediasoup::data_structures::{AppData, WebRtcMessage};
...@@ -9,7 +9,7 @@ use mediasoup::router::{Router, RouterOptions}; ...@@ -9,7 +9,7 @@ use mediasoup::router::{Router, RouterOptions};
use mediasoup::worker::{Worker, WorkerSettings}; use mediasoup::worker::{Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::collections::HashSet; use std::borrow::Cow;
use std::env; use std::env;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc; use std::sync::Arc;
...@@ -56,7 +56,7 @@ fn create_succeeds() { ...@@ -56,7 +56,7 @@ fn create_succeeds() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.transport_ids, { assert_eq!(dump.transport_ids, {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(transport.id()); set.insert(transport.id());
set set
}); });
...@@ -240,14 +240,13 @@ fn send_succeeds() { ...@@ -240,14 +240,13 @@ fn send_succeeds() {
sent_message_bytes += content.len(); sent_message_bytes += content.len();
WebRtcMessage::String(content) WebRtcMessage::String(content)
} else { } else {
let content = Bytes::from(id.to_string().into_bytes()); let content = id.to_string().into_bytes();
sent_message_bytes += content.len(); sent_message_bytes += content.len();
WebRtcMessage::Binary(content) WebRtcMessage::Binary(Cow::from(content))
}; };
direct_data_producer direct_data_producer
.send(message) .send(message)
.await
.expect("Failed to send message"); .expect("Failed to send message");
if id == num_messages { if id == num_messages {
......
use futures_lite::future; use futures_lite::future;
use hash_hasher::HashedSet;
use mediasoup::data_structures::{ use mediasoup::data_structures::{
AppData, SctpState, TransportListenIp, TransportProtocol, TransportTuple, AppData, SctpState, TransportListenIp, TransportProtocol, TransportTuple,
}; };
...@@ -12,7 +13,6 @@ use mediasoup::sctp_parameters::SctpParameters; ...@@ -12,7 +13,6 @@ use mediasoup::sctp_parameters::SctpParameters;
use mediasoup::srtp_parameters::{SrtpCryptoSuite, SrtpParameters}; use mediasoup::srtp_parameters::{SrtpCryptoSuite, SrtpParameters};
use mediasoup::worker::{RequestError, Worker, WorkerSettings}; use mediasoup::worker::{RequestError, Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use std::collections::HashSet;
use std::env; use std::env;
use std::net::IpAddr; use std::net::IpAddr;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
...@@ -104,7 +104,7 @@ fn create_succeeds() { ...@@ -104,7 +104,7 @@ fn create_succeeds() {
let router_dump = router.dump().await.expect("Failed to dump router"); let router_dump = router.dump().await.expect("Failed to dump router");
assert_eq!(router_dump.transport_ids, { assert_eq!(router_dump.transport_ids, {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(transport.id()); set.insert(transport.id());
set set
}); });
......
use async_io::Timer; use async_io::Timer;
use futures_lite::future; use futures_lite::future;
use hash_hasher::{HashedMap, HashedSet};
use mediasoup::data_structures::{AppData, TransportListenIp}; use mediasoup::data_structures::{AppData, TransportListenIp};
use mediasoup::prelude::*; use mediasoup::prelude::*;
use mediasoup::producer::{ProducerOptions, ProducerTraceEventType, ProducerType}; use mediasoup::producer::{ProducerOptions, ProducerTraceEventType, ProducerType};
...@@ -14,7 +15,6 @@ use mediasoup::transport::ProduceError; ...@@ -14,7 +15,6 @@ use mediasoup::transport::ProduceError;
use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions}; use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions};
use mediasoup::worker::{Worker, WorkerSettings}; use mediasoup::worker::{Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use std::collections::{HashMap, HashSet};
use std::env; use std::env;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
...@@ -229,7 +229,7 @@ fn produce_succeeds() { ...@@ -229,7 +229,7 @@ fn produce_succeeds() {
.on_new_producer({ .on_new_producer({
let new_producers_count = Arc::clone(&new_producers_count); let new_producers_count = Arc::clone(&new_producers_count);
Box::new(move |_producer| { Arc::new(move |_producer| {
new_producers_count.fetch_add(1, Ordering::SeqCst); new_producers_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -266,11 +266,14 @@ fn produce_succeeds() { ...@@ -266,11 +266,14 @@ fn produce_succeeds() {
let router_dump = router.dump().await.expect("Failed to get router dump"); let router_dump = router.dump().await.expect("Failed to get router dump");
assert_eq!(router_dump.map_producer_id_consumer_ids, { assert_eq!(router_dump.map_producer_id_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(audio_producer.id(), HashSet::new()); map.insert(audio_producer.id(), HashedSet::default());
map map
}); });
assert_eq!(router_dump.map_consumer_id_producer_id, HashMap::new()); assert_eq!(
router_dump.map_consumer_id_producer_id,
HashedMap::default()
);
let transport_1_dump = transport_1 let transport_1_dump = transport_1
.dump() .dump()
...@@ -279,6 +282,19 @@ fn produce_succeeds() { ...@@ -279,6 +282,19 @@ fn produce_succeeds() {
assert_eq!(transport_1_dump.producer_ids, vec![audio_producer.id()]); assert_eq!(transport_1_dump.producer_ids, vec![audio_producer.id()]);
assert_eq!(transport_1_dump.consumer_ids, vec![]); assert_eq!(transport_1_dump.consumer_ids, vec![]);
let (mut tx, rx) = async_oneshot::oneshot::<()>();
transport_1
.on_close(Box::new(move || {
let _ = tx.send(());
}))
.detach();
drop(audio_producer);
drop(transport_1);
// This means producer was definitely dropped
rx.await.expect("Failed to receive transport close event");
} }
{ {
...@@ -288,7 +304,7 @@ fn produce_succeeds() { ...@@ -288,7 +304,7 @@ fn produce_succeeds() {
.on_new_producer({ .on_new_producer({
let new_producers_count = Arc::clone(&new_producers_count); let new_producers_count = Arc::clone(&new_producers_count);
Box::new(move |_producer| { Arc::new(move |_producer| {
new_producers_count.fetch_add(1, Ordering::SeqCst); new_producers_count.fetch_add(1, Ordering::SeqCst);
}) })
}) })
...@@ -325,11 +341,14 @@ fn produce_succeeds() { ...@@ -325,11 +341,14 @@ fn produce_succeeds() {
let router_dump = router.dump().await.expect("Failed to get router dump"); let router_dump = router.dump().await.expect("Failed to get router dump");
assert_eq!(router_dump.map_producer_id_consumer_ids, { assert_eq!(router_dump.map_producer_id_consumer_ids, {
let mut map = HashMap::new(); let mut map = HashedMap::default();
map.insert(video_producer.id(), HashSet::new()); map.insert(video_producer.id(), HashedSet::default());
map map
}); });
assert_eq!(router_dump.map_consumer_id_producer_id, HashMap::new()); assert_eq!(
router_dump.map_consumer_id_producer_id,
HashedMap::default()
);
let transport_2_dump = transport_2 let transport_2_dump = transport_2
.dump() .dump()
...@@ -903,8 +922,8 @@ fn close_event() { ...@@ -903,8 +922,8 @@ fn close_event() {
{ {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.map_producer_id_consumer_ids, HashMap::new()); assert_eq!(dump.map_producer_id_consumer_ids, HashedMap::default());
assert_eq!(dump.map_consumer_id_producer_id, HashMap::new()); assert_eq!(dump.map_consumer_id_producer_id, HashedMap::default());
} }
{ {
......
use futures_lite::future; use futures_lite::future;
use hash_hasher::{HashedMap, HashedSet};
use mediasoup::data_structures::AppData; use mediasoup::data_structures::AppData;
use mediasoup::router::RouterOptions; use mediasoup::router::RouterOptions;
use mediasoup::rtp_parameters::{ use mediasoup::rtp_parameters::{
...@@ -6,7 +7,6 @@ use mediasoup::rtp_parameters::{ ...@@ -6,7 +7,6 @@ use mediasoup::rtp_parameters::{
}; };
use mediasoup::worker::{Worker, WorkerSettings}; use mediasoup::worker::{Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use std::collections::{HashMap, HashSet};
use std::env; use std::env;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
...@@ -106,13 +106,19 @@ fn create_router_succeeds() { ...@@ -106,13 +106,19 @@ fn create_router_succeeds() {
let dump = router.dump().await.expect("Failed to dump router"); let dump = router.dump().await.expect("Failed to dump router");
assert_eq!(dump.id, router.id()); assert_eq!(dump.id, router.id());
assert_eq!(dump.transport_ids, HashSet::new()); assert_eq!(dump.transport_ids, HashedSet::default());
assert_eq!(dump.rtp_observer_ids, HashSet::new()); assert_eq!(dump.rtp_observer_ids, HashedSet::default());
assert_eq!(dump.map_producer_id_consumer_ids, HashMap::new()); assert_eq!(dump.map_producer_id_consumer_ids, HashedMap::default());
assert_eq!(dump.map_consumer_id_producer_id, HashMap::new()); assert_eq!(dump.map_consumer_id_producer_id, HashedMap::default());
assert_eq!(dump.map_producer_id_observer_ids, HashMap::new()); assert_eq!(dump.map_producer_id_observer_ids, HashedMap::default());
assert_eq!(dump.map_data_producer_id_data_consumer_ids, HashMap::new()); assert_eq!(
assert_eq!(dump.map_data_consumer_id_data_producer_id, HashMap::new()); dump.map_data_producer_id_data_consumer_ids,
HashedMap::default()
);
assert_eq!(
dump.map_data_consumer_id_data_producer_id,
HashedMap::default()
);
}); });
} }
......
use futures_lite::future; use futures_lite::future;
use hash_hasher::HashedSet;
use mediasoup::data_structures::{ use mediasoup::data_structures::{
AppData, DtlsFingerprint, DtlsParameters, DtlsRole, DtlsState, IceCandidateTcpType, AppData, DtlsFingerprint, DtlsParameters, DtlsRole, DtlsState, IceCandidateTcpType,
IceCandidateType, IceRole, IceState, SctpState, TransportListenIp, TransportProtocol, IceCandidateType, IceRole, IceState, SctpState, TransportListenIp, TransportProtocol,
...@@ -15,7 +16,6 @@ use mediasoup::webrtc_transport::{ ...@@ -15,7 +16,6 @@ use mediasoup::webrtc_transport::{
}; };
use mediasoup::worker::{RequestError, Worker, WorkerSettings}; use mediasoup::worker::{RequestError, Worker, WorkerSettings};
use mediasoup::worker_manager::WorkerManager; use mediasoup::worker_manager::WorkerManager;
use std::collections::HashSet;
use std::convert::TryInto; use std::convert::TryInto;
use std::env; use std::env;
use std::net::IpAddr; use std::net::IpAddr;
...@@ -104,7 +104,7 @@ fn create_succeeds() { ...@@ -104,7 +104,7 @@ fn create_succeeds() {
let router_dump = router.dump().await.expect("Failed to dump router"); let router_dump = router.dump().await.expect("Failed to dump router");
assert_eq!(router_dump.transport_ids, { assert_eq!(router_dump.transport_ids, {
let mut set = HashSet::new(); let mut set = HashedSet::default();
set.insert(transport.id()); set.insert(transport.id());
set set
}); });
......
...@@ -7,6 +7,12 @@ fn main() { ...@@ -7,6 +7,12 @@ fn main() {
return; return;
} }
let build_type = if cfg!(debug_assertions) {
"Debug"
} else {
"Release"
};
let out_dir = env::var("OUT_DIR").unwrap(); let out_dir = env::var("OUT_DIR").unwrap();
// Add C++ std lib // Add C++ std lib
...@@ -79,9 +85,8 @@ fn main() { ...@@ -79,9 +85,8 @@ fn main() {
// Build // Build
if !Command::new("make") if !Command::new("make")
.arg("libmediasoup-worker") .arg("libmediasoup-worker")
.env("PYTHONDONTWRITEBYTECODE", "1")
.env("MEDIASOUP_OUT_DIR", &out_dir) .env("MEDIASOUP_OUT_DIR", &out_dir)
.env("MEDIASOUP_BUILDTYPE", "Release") .env("MEDIASOUP_BUILDTYPE", &build_type)
.spawn() .spawn()
.expect("Failed to start") .expect("Failed to start")
.wait() .wait()
...@@ -95,7 +100,6 @@ fn main() { ...@@ -95,7 +100,6 @@ fn main() {
// Clean // Clean
if !Command::new("make") if !Command::new("make")
.arg("clean-all") .arg("clean-all")
.env("PYTHONDONTWRITEBYTECODE", "1")
.spawn() .spawn()
.expect("Failed to start") .expect("Failed to start")
.wait() .wait()
...@@ -108,6 +112,5 @@ fn main() { ...@@ -108,6 +112,5 @@ fn main() {
} }
println!("cargo:rustc-link-lib=static=mediasoup-worker"); println!("cargo:rustc-link-lib=static=mediasoup-worker");
println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-search=native={}/{}", out_dir, build_type);
println!("cargo:rustc-link-search=native={}/Release", out_dir);
} }
...@@ -12,6 +12,7 @@ namespace Channel ...@@ -12,6 +12,7 @@ namespace Channel
{ {
public: public:
static void ClassInit(Channel::ChannelSocket* channel); static void ClassInit(Channel::ChannelSocket* channel);
static void Emit(uint64_t targetId, const char* event);
static void Emit(const std::string& targetId, const char* event); static void Emit(const std::string& targetId, const char* event);
static void Emit(const std::string& targetId, const char* event, json& data); static void Emit(const std::string& targetId, const char* event, json& data);
......
...@@ -64,16 +64,22 @@ namespace Channel ...@@ -64,16 +64,22 @@ namespace Channel
public: public:
explicit ChannelSocket(int consumerFd, int producerFd); explicit ChannelSocket(int consumerFd, int producerFd);
explicit ChannelSocket(
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx);
virtual ~ChannelSocket(); virtual ~ChannelSocket();
public: public:
void Close(); void Close();
void SetListener(Listener* listener); void SetListener(Listener* listener);
bool CallbackRead();
void Send(json& jsonMessage); void Send(json& jsonMessage);
void SendLog(char* message, uint32_t messageLen); void SendLog(const char* message, uint32_t messageLen);
private: private:
void SendImpl(const void* payload, uint32_t payloadLen); void SendImpl(const uint8_t* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */ /* Pure virtual methods inherited from ConsumerSocket::Listener. */
public: public:
...@@ -85,9 +91,14 @@ namespace Channel ...@@ -85,9 +91,14 @@ namespace Channel
Listener* listener{ nullptr }; Listener* listener{ nullptr };
// Others. // Others.
bool closed{ false }; bool closed{ false };
ConsumerSocket consumerSocket; ConsumerSocket* consumerSocket{ nullptr };
ProducerSocket producerSocket; ProducerSocket* producerSocket{ nullptr };
uint8_t* writeBuffer; ChannelReadFn channelReadFn{ nullptr };
ChannelReadCtx channelReadCtx{ nullptr };
ChannelWriteFn channelWriteFn{ nullptr };
ChannelWriteCtx channelWriteCtx{ nullptr };
uv_async_t* uvReadHandle{ nullptr };
uint8_t* writeBuffer{ nullptr };
}; };
} // namespace Channel } // namespace Channel
......
...@@ -132,7 +132,7 @@ public: ...@@ -132,7 +132,7 @@ public:
static void ClassInit(Channel::ChannelSocket* channel); static void ClassInit(Channel::ChannelSocket* channel);
public: public:
static const int64_t pid; static const uint64_t pid;
thread_local static Channel::ChannelSocket* channel; thread_local static Channel::ChannelSocket* channel;
static const size_t bufferSize {50000}; static const size_t bufferSize {50000};
thread_local static char buffer[]; thread_local static char buffer[];
......
...@@ -71,16 +71,24 @@ namespace PayloadChannel ...@@ -71,16 +71,24 @@ namespace PayloadChannel
public: public:
explicit PayloadChannelSocket(int consumerFd, int producerFd); explicit PayloadChannelSocket(int consumerFd, int producerFd);
explicit PayloadChannelSocket(
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx);
virtual ~PayloadChannelSocket(); virtual ~PayloadChannelSocket();
public: public:
void Close(); void Close();
void SetListener(Listener* listener); void SetListener(Listener* listener);
bool CallbackRead();
void Send(json& jsonMessage, const uint8_t* payload, size_t payloadLen); void Send(json& jsonMessage, const uint8_t* payload, size_t payloadLen);
void Send(json& jsonMessage); void Send(json& jsonMessage);
private: private:
void SendImpl(const void* payload, uint32_t payloadLen); void SendImpl(const uint8_t* message, uint32_t messageLen);
void SendImpl(
const uint8_t* message, uint32_t messageLen, const uint8_t* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */ /* Pure virtual methods inherited from ConsumerSocket::Listener. */
public: public:
...@@ -92,11 +100,16 @@ namespace PayloadChannel ...@@ -92,11 +100,16 @@ namespace PayloadChannel
Listener* listener{ nullptr }; Listener* listener{ nullptr };
// Others. // Others.
bool closed{ false }; bool closed{ false };
ConsumerSocket consumerSocket; ConsumerSocket* consumerSocket{ nullptr };
ProducerSocket producerSocket; ProducerSocket* producerSocket{ nullptr };
PayloadChannelReadFn payloadChannelReadFn{ nullptr };
PayloadChannelReadCtx payloadChannelReadCtx{ nullptr };
PayloadChannelWriteFn payloadChannelWriteFn{ nullptr };
PayloadChannelWriteCtx payloadChannelWriteCtx{ nullptr };
PayloadChannel::Notification* ongoingNotification{ nullptr }; PayloadChannel::Notification* ongoingNotification{ nullptr };
PayloadChannel::PayloadChannelRequest* ongoingRequest{ nullptr }; PayloadChannel::PayloadChannelRequest* ongoingRequest{ nullptr };
uint8_t* writeBuffer; uv_async_t* uvReadHandle{ nullptr };
uint8_t* writeBuffer{ nullptr };
}; };
} // namespace PayloadChannel } // namespace PayloadChannel
......
...@@ -23,4 +23,43 @@ typedef SSIZE_T ssize_t; ...@@ -23,4 +23,43 @@ typedef SSIZE_T ssize_t;
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6 #include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#endif #endif
using ChannelReadCtx = void*;
using ChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t);
// Returns `ChannelReadFree` on successful read that must be used to free `message`.
using ChannelReadFn = ChannelReadFreeFn (*)(
uint8_t** /* message */,
uint32_t* /* messageLen */,
size_t* /* messageCtx */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read.
const void* /* handle */,
ChannelReadCtx /* ctx */);
using ChannelWriteCtx = void*;
using ChannelWriteFn =
void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */);
using PayloadChannelReadCtx = void*;
using PayloadChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t);
// Returns `PayloadChannelReadFree` on successful read that must be used to free `message` and `payload`.
using PayloadChannelReadFn = PayloadChannelReadFreeFn (*)(
uint8_t** /* message */,
uint32_t* /* messageLen */,
size_t* /* messageCtx */,
uint8_t** /* payload */,
uint32_t* /* payloadLen */,
size_t* /* payloadCapacity */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read.
const void* /* handle */,
PayloadChannelReadCtx /* ctx */);
using PayloadChannelWriteCtx = void*;
using PayloadChannelWriteFn = void (*)(
const uint8_t* /* message */,
uint32_t /* messageLen */,
const uint8_t* /* payload */,
uint32_t /* payloadLen */,
ChannelWriteCtx /* ctx */);
#endif #endif
extern "C" int run_worker( #include "common.hpp"
extern "C" int mediasoup_worker_run(
int argc, int argc,
char* argv[], char* argv[],
const char* version, const char* version,
int consumerChannelFd, int consumerChannelFd,
int producerChannelFd, int producerChannelFd,
int payloadConsumeChannelFd, int payloadConsumeChannelFd,
int payloadProduceChannelFd); int payloadProduceChannelFd,
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx,
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx);
...@@ -19,6 +19,20 @@ namespace Channel ...@@ -19,6 +19,20 @@ namespace Channel
ChannelNotifier::channel = channel; ChannelNotifier::channel = channel;
} }
void ChannelNotifier::Emit(uint64_t targetId, const char* event)
{
MS_TRACE();
MS_ASSERT(ChannelNotifier::channel, "channel unset");
json jsonNotification = json::object();
jsonNotification["targetId"] = targetId;
jsonNotification["event"] = event;
ChannelNotifier::channel->Send(jsonNotification);
}
void ChannelNotifier::Emit(const std::string& targetId, const char* event) void ChannelNotifier::Emit(const std::string& targetId, const char* event)
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
/* Class variables. */ /* Class variables. */
const int64_t Logger::pid{ static_cast<int64_t>(uv_os_getpid()) }; const uint64_t Logger::pid{ static_cast<uint64_t>(uv_os_getpid()) };
thread_local Channel::ChannelSocket* Logger::channel{ nullptr }; thread_local Channel::ChannelSocket* Logger::channel{ nullptr };
thread_local char Logger::buffer[Logger::bufferSize]; thread_local char Logger::buffer[Logger::bufferSize];
......
...@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel ...@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel
DepUsrSCTP::CreateChecker(); DepUsrSCTP::CreateChecker();
// Tell the Node process that we are running. // Tell the Node process that we are running.
Channel::ChannelNotifier::Emit(std::to_string(Logger::pid), "running"); Channel::ChannelNotifier::Emit(Logger::pid, "running");
MS_DEBUG_DEV("starting libuv loop"); MS_DEBUG_DEV("starting libuv loop");
DepLibUV::RunLoop(); DepLibUV::RunLoop();
......
...@@ -28,14 +28,22 @@ ...@@ -28,14 +28,22 @@
void IgnoreSignals(); void IgnoreSignals();
extern "C" int run_worker( extern "C" int mediasoup_worker_run(
int argc, int argc,
char* argv[], char* argv[],
const char* version, const char* version,
int consumerChannelFd, int consumerChannelFd,
int producerChannelFd, int producerChannelFd,
int payloadConsumeChannelFd, int payloadConsumeChannelFd,
int payloadProduceChannelFd) int payloadProduceChannelFd,
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx,
PayloadChannelReadFn payloadChannelReadFn,
PayloadChannelReadCtx payloadChannelReadCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
PayloadChannelWriteCtx payloadChannelWriteCtx)
{ {
// Initialize libuv stuff (we need it for the Channel). // Initialize libuv stuff (we need it for the Channel).
DepLibUV::ClassInit(); DepLibUV::ClassInit();
...@@ -51,9 +59,17 @@ extern "C" int run_worker( ...@@ -51,9 +59,17 @@ extern "C" int run_worker(
std::unique_ptr<PayloadChannel::PayloadChannelSocket> payloadChannel{ nullptr }; std::unique_ptr<PayloadChannel::PayloadChannelSocket> payloadChannel{ nullptr };
try try
{
if (channelReadFn)
{
channel.reset(
new Channel::ChannelSocket(channelReadFn, channelReadCtx, channelWriteFn, channelWriteCtx));
}
else
{ {
channel.reset(new Channel::ChannelSocket(consumerChannelFd, producerChannelFd)); channel.reset(new Channel::ChannelSocket(consumerChannelFd, producerChannelFd));
} }
}
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
{ {
MS_ERROR_STD("error creating the Channel: %s", error.what()); MS_ERROR_STD("error creating the Channel: %s", error.what());
...@@ -65,10 +81,18 @@ extern "C" int run_worker( ...@@ -65,10 +81,18 @@ extern "C" int run_worker(
} }
try try
{
if (payloadChannelReadFn)
{
payloadChannel.reset(new PayloadChannel::PayloadChannelSocket(
payloadChannelReadFn, payloadChannelReadCtx, payloadChannelWriteFn, payloadChannelWriteCtx));
}
else
{ {
payloadChannel.reset( payloadChannel.reset(
new PayloadChannel::PayloadChannelSocket(payloadConsumeChannelFd, payloadProduceChannelFd)); new PayloadChannel::PayloadChannelSocket(payloadConsumeChannelFd, payloadProduceChannelFd));
} }
}
catch (const MediaSoupError& error) catch (const MediaSoupError& error)
{ {
MS_ERROR_STD("error creating the RTC Channel: %s", error.what()); MS_ERROR_STD("error creating the RTC Channel: %s", error.what());
......
差异被折叠。
...@@ -23,14 +23,22 @@ int main(int argc, char* argv[]) ...@@ -23,14 +23,22 @@ int main(int argc, char* argv[])
std::string version = std::getenv("MEDIASOUP_VERSION"); std::string version = std::getenv("MEDIASOUP_VERSION");
auto statusCode = run_worker( auto statusCode = mediasoup_worker_run(
argc, argc,
argv, argv,
version.c_str(), version.c_str(),
ConsumerChannelFd, ConsumerChannelFd,
ProducerChannelFd, ProducerChannelFd,
PayloadConsumerChannelFd, PayloadConsumerChannelFd,
PayloadProducerChannelFd); PayloadProducerChannelFd,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr);
switch (statusCode) switch (statusCode)
{ {
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论