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

Optimize notifications handling

上级 336c398e
...@@ -2,6 +2,7 @@ use criterion::async_executor::FuturesExecutor; ...@@ -2,6 +2,7 @@ use criterion::async_executor::FuturesExecutor;
use criterion::{criterion_group, criterion_main, Criterion}; use criterion::{criterion_group, criterion_main, Criterion};
use futures_lite::StreamExt; use futures_lite::StreamExt;
use mediasoup::prelude::*; use mediasoup::prelude::*;
use std::borrow::Cow;
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>> {
...@@ -47,7 +48,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { ...@@ -47,7 +48,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
group.bench_with_input("send", &data, |b, data| { group.bench_with_input("send", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async { b.to_async(FuturesExecutor).iter(|| async {
let _ = direct_data_producer let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone())) .send(WebRtcMessage::Binary(Cow::from(data)))
.await; .await;
}) })
}); });
...@@ -72,7 +73,7 @@ pub fn criterion_benchmark(c: &mut Criterion) { ...@@ -72,7 +73,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
}); });
let _ = direct_data_producer let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone())) .send(WebRtcMessage::Binary(Cow::from(data)))
.await; .await;
let _ = receiver.next().await; let _ = receiver.next().await;
......
...@@ -769,18 +769,18 @@ pub enum TraceEventDirection { ...@@ -769,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(Vec<u8>), Binary(Cow<'a, [u8]>),
/// EmptyString /// EmptyString
EmptyString, EmptyString,
/// EmptyBinary /// EmptyBinary
EmptyBinary, EmptyBinary,
} }
impl WebRtcMessage { impl<'a> WebRtcMessage<'a> {
// +------------------------------------+-----------+ // +------------------------------------+-----------+
// | Value | SCTP PPID | // | Value | SCTP PPID |
// +------------------------------------+-----------+ // +------------------------------------+-----------+
...@@ -792,7 +792,7 @@ impl WebRtcMessage { ...@@ -792,7 +792,7 @@ impl WebRtcMessage {
// | WebRTC Binary Empty | 57 | // | WebRTC Binary Empty | 57 |
// +------------------------------------+-----------+ // +------------------------------------+-----------+
pub(crate) fn new(ppid: u32, payload: Vec<u8>) -> 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(),
...@@ -804,12 +804,12 @@ impl WebRtcMessage { ...@@ -804,12 +804,12 @@ impl WebRtcMessage {
} }
} }
pub(crate) fn into_ppid_and_payload(self) -> (u32, Vec<u8>) { pub(crate) fn into_ppid_and_payload(self) -> (u32, Cow<'a, [u8]>) {
match self { match self {
WebRtcMessage::String(string) => (51_u32, string.into_bytes()), 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, Vec::from(b" ".as_ref())), WebRtcMessage::EmptyString => (56_u32, Cow::from(b" ".as_ref())),
WebRtcMessage::EmptyBinary => (57_u32, vec![0_u8]), WebRtcMessage::EmptyBinary => (57_u32, Cow::from(vec![0_u8])),
} }
} }
} }
......
...@@ -13,9 +13,7 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters} ...@@ -13,9 +13,7 @@ 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 event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use log::{debug, error}; use log::{debug, error};
...@@ -346,7 +344,7 @@ enum PayloadNotification { ...@@ -346,7 +344,7 @@ enum PayloadNotification {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
rtp: Bag<Box<dyn Fn(&Vec<u8>) + Send + Sync>>, rtp: Bag<Box<dyn Fn(&[u8]) + Send + Sync>>,
pause: Bag<Box<dyn Fn() + Send + Sync>>, pause: Bag<Box<dyn Fn() + Send + Sync>>,
resume: Bag<Box<dyn Fn() + Send + Sync>>, resume: Bag<Box<dyn Fn() + Send + Sync>>,
producer_pause: Bag<Box<dyn Fn() + Send + Sync>>, producer_pause: Bag<Box<dyn Fn() + Send + Sync>>,
...@@ -558,13 +556,12 @@ impl Consumer { ...@@ -558,13 +556,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_value::<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);
}); });
} }
}, },
...@@ -867,7 +864,7 @@ impl Consumer { ...@@ -867,7 +864,7 @@ 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(&Vec<u8>) + 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(Box::new(callback))
} }
......
...@@ -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,7 +183,7 @@ enum PayloadNotification { ...@@ -184,7 +183,7 @@ enum PayloadNotification {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
message: Bag<Box<dyn Fn(&WebRtcMessage) + Send + Sync>>, message: Bag<Box<dyn Fn(&WebRtcMessage<'_>) + Send + Sync>>,
sctp_send_buffer_full: Bag<Box<dyn Fn() + Send + Sync>>, sctp_send_buffer_full: Bag<Box<dyn Fn() + Send + Sync>>,
buffered_amount_low: Bag<Box<dyn Fn(u32) + Send + Sync>>, buffered_amount_low: Bag<Box<dyn Fn(u32) + Send + Sync>>,
data_producer_close: BagOnce<Box<dyn FnOnce() + Send>>, data_producer_close: BagOnce<Box<dyn FnOnce() + Send>>,
...@@ -401,12 +400,11 @@ impl DataConsumer { ...@@ -401,12 +400,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_value::<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);
...@@ -586,7 +584,7 @@ impl DataConsumer { ...@@ -586,7 +584,7 @@ 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 {
...@@ -675,7 +673,7 @@ impl DataConsumer { ...@@ -675,7 +673,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<'a>(&self, message: WebRtcMessage<'a>) -> Result<(), RequestError> {
let (ppid, payload) = message.into_ppid_and_payload(); let (ppid, payload) = message.into_ppid_and_payload();
self.inner self.inner
...@@ -690,7 +688,7 @@ impl DirectDataConsumer { ...@@ -690,7 +688,7 @@ impl DirectDataConsumer {
}, },
data: DataConsumerSendRequestData { ppid }, data: DataConsumerSendRequestData { ppid },
}, },
payload, payload.into_owned(),
) )
.await .await
} }
......
...@@ -441,7 +441,7 @@ impl DataProducer { ...@@ -441,7 +441,7 @@ impl DataProducer {
impl DirectDataProducer { impl DirectDataProducer {
/// Sends direct messages from the Rust process. /// Sends direct messages from the Rust process.
pub async fn send(&self, message: WebRtcMessage) -> Result<(), NotificationError> { pub async fn send<'a>(&self, message: WebRtcMessage<'a>) -> Result<(), NotificationError> {
let (ppid, payload) = message.into_ppid_and_payload(); let (ppid, payload) = message.into_ppid_and_payload();
self.inner self.inner
...@@ -455,7 +455,7 @@ impl DirectDataProducer { ...@@ -455,7 +455,7 @@ impl DirectDataProducer {
}, },
data: DataProducerSendData { ppid }, data: DataProducerSendData { ppid },
}, },
payload, payload.into_owned(),
) )
.await .await
} }
......
...@@ -16,8 +16,7 @@ use crate::transport::{ ...@@ -16,8 +16,7 @@ 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;
...@@ -112,7 +111,7 @@ pub struct DirectTransportStat { ...@@ -112,7 +111,7 @@ pub struct DirectTransportStat {
#[derive(Default)] #[derive(Default)]
struct Handlers { struct Handlers {
rtcp: Bag<Box<dyn Fn(&Vec<u8>) + Send + Sync>>, rtcp: Bag<Box<dyn Fn(&[u8]) + Send + Sync>>,
new_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>, new_producer: Bag<Box<dyn Fn(&Producer) + Send + Sync>>,
new_consumer: Bag<Box<dyn Fn(&Consumer) + Send + Sync>>, new_consumer: Bag<Box<dyn Fn(&Consumer) + Send + Sync>>,
new_data_producer: Bag<Box<dyn Fn(&DataProducer) + Send + Sync>>, new_data_producer: Bag<Box<dyn Fn(&DataProducer) + Send + Sync>>,
...@@ -481,13 +480,12 @@ impl DirectTransport { ...@@ -481,13 +480,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_value::<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);
}); });
} }
}, },
...@@ -549,7 +547,7 @@ impl DirectTransport { ...@@ -549,7 +547,7 @@ impl DirectTransport {
} }
/// 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(&Vec<u8>) + 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(Box::new(callback))
} }
......
...@@ -24,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId}; ...@@ -24,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,7 +40,7 @@ pub(super) enum InternalMessage { ...@@ -40,7 +40,7 @@ pub(super) enum InternalMessage {
pub(crate) struct BufferMessagesGuard { pub(crate) struct BufferMessagesGuard {
target_id: SubscriptionTarget, target_id: SubscriptionTarget,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>, buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>,
event_handlers_weak: WeakEventHandlers<Value>, event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>,
} }
impl Drop for BufferMessagesGuard { impl Drop for BufferMessagesGuard {
...@@ -49,7 +49,7 @@ impl Drop for BufferMessagesGuard { ...@@ -49,7 +49,7 @@ impl Drop for BufferMessagesGuard {
if let Some(notifications) = buffered_notifications_for.remove(&self.target_id) { if let Some(notifications) = buffered_notifications_for.remove(&self.target_id) {
if let Some(event_handlers) = self.event_handlers_weak.upgrade() { if let Some(event_handlers) = self.event_handlers_weak.upgrade() {
for notification in notifications { for notification in notifications {
event_handlers.call_callbacks_with_value(&self.target_id, notification); event_handlers.call_callbacks_with_single_value(&self.target_id, notification);
} }
} }
} }
...@@ -120,7 +120,7 @@ struct Inner { ...@@ -120,7 +120,7 @@ struct Inner {
internal_message_receiver: async_channel::Receiver<InternalMessage>, internal_message_receiver: async_channel::Receiver<InternalMessage>,
requests_container_weak: Weak<Mutex<RequestsContainer>>, requests_container_weak: Weak<Mutex<RequestsContainer>>,
buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>, buffered_notifications_for: Arc<Mutex<HashMap<SubscriptionTarget, Vec<Value>>>>,
event_handlers_weak: WeakEventHandlers<Value>, event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value) + Send + Sync + 'static>>,
} }
impl Drop for Inner { impl Drop for Inner {
...@@ -225,7 +225,8 @@ impl Channel { ...@@ -225,7 +225,8 @@ impl Channel {
// Remember we don't need to buffer these // Remember we don't need to buffer these
non_buffered_notifications.put(target_id, ()); non_buffered_notifications.put(target_id, ());
} }
event_handlers.call_callbacks_with_value(&target_id, notification); event_handlers
.call_callbacks_with_single_value(&target_id, notification);
} else { } else {
let unexpected_message = let unexpected_message =
InternalMessage::Unexpected(Vec::from(message)); InternalMessage::Unexpected(Vec::from(message));
...@@ -401,6 +402,6 @@ impl Channel { ...@@ -401,6 +402,6 @@ impl Channel {
self.inner self.inner
.event_handlers_weak .event_handlers_weak
.upgrade() .upgrade()
.map(|event_handlers| event_handlers.add(target_id, Box::new(callback))) .map(|event_handlers| event_handlers.add(target_id, Arc::new(callback)))
} }
} }
...@@ -3,13 +3,13 @@ use std::collections::HashMap; ...@@ -3,13 +3,13 @@ use std::collections::HashMap;
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)] #[allow(clippy::type_complexity)]
callbacks: HashMap<usize, Arc<dyn Fn(V) + Send + Sync>>, callbacks: HashMap<usize, F>,
} }
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,
...@@ -19,21 +19,17 @@ impl<V: Clone + 'static> Default for EventHandlersList<V> { ...@@ -19,21 +19,17 @@ impl<V: Clone + 'static> Default for EventHandlersList<V> {
} }
#[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<HashMap<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<HashMap<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 +38,7 @@ impl<V: Clone + 'static> EventHandlers<V> { ...@@ -42,7 +38,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,7 +71,19 @@ impl<V: Clone + 'static> EventHandlers<V> { ...@@ -75,7 +71,19 @@ 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: Clone> 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 // Tiny optimization that avoids cloning `value` unless necessary
...@@ -94,21 +102,42 @@ impl<V: Clone + 'static> EventHandlers<V> { ...@@ -94,21 +102,42 @@ impl<V: Clone + 'static> EventHandlers<V> {
} }
} }
} }
}
pub(super) fn downgrade(&self) -> WeakEventHandlers<V> { impl<V1: Clone, 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) {
// Tiny optimization that avoids cloning `value` unless necessary
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(value1, value2);
} 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(value1.clone(), 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<HashMap<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 })
......
...@@ -22,12 +22,6 @@ pub(super) enum InternalMessage { ...@@ -22,12 +22,6 @@ pub(super) enum InternalMessage {
UnexpectedData(Vec<u8>), UnexpectedData(Vec<u8>),
} }
#[derive(Clone)]
pub(crate) struct NotificationMessage {
pub(crate) message: Value,
pub(crate) payload: Vec<u8>,
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
#[serde(untagged)] #[serde(untagged)]
enum PayloadChannelReceiveMessage { enum PayloadChannelReceiveMessage {
...@@ -89,7 +83,7 @@ struct Inner { ...@@ -89,7 +83,7 @@ struct Inner {
outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>, outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>,
internal_message_receiver: async_channel::Receiver<InternalMessage>, internal_message_receiver: async_channel::Receiver<InternalMessage>,
requests_container_weak: Weak<Mutex<RequestsContainer>>, requests_container_weak: Weak<Mutex<RequestsContainer>>,
event_handlers_weak: WeakEventHandlers<NotificationMessage>, event_handlers_weak: WeakEventHandlers<Arc<dyn Fn(Value, &[u8]) + Send + Sync + 'static>>,
} }
impl Drop for Inner { impl Drop for Inner {
...@@ -179,15 +173,11 @@ impl PayloadChannel { ...@@ -179,15 +173,11 @@ impl PayloadChannel {
trace!("received notification payload of {} bytes", payload.len()); trace!("received notification payload of {} bytes", payload.len());
let payload = Vec::from(payload);
if let Some(target_id) = target_id { if let Some(target_id) = target_id {
event_handlers.call_callbacks_with_value( event_handlers.call_callbacks_with_two_values(
&target_id, &target_id,
NotificationMessage { notification,
message: notification,
payload, payload,
},
); );
} else { } else {
let unexpected_message = let unexpected_message =
...@@ -394,11 +384,11 @@ impl PayloadChannel { ...@@ -394,11 +384,11 @@ impl PayloadChannel {
callback: F, callback: F,
) -> Option<SubscriptionHandler> ) -> Option<SubscriptionHandler>
where where
F: Fn(NotificationMessage) + Send + Sync + 'static, F: Fn(Value, &[u8]) + Send + Sync + 'static,
{ {
self.inner self.inner
.event_handlers_weak .event_handlers_weak
.upgrade() .upgrade()
.map(|event_handlers| event_handlers.add(target_id, Box::new(callback))) .map(|event_handlers| event_handlers.add(target_id, Arc::new(callback)))
} }
} }
...@@ -8,6 +8,7 @@ use mediasoup::router::{Router, RouterOptions}; ...@@ -8,6 +8,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::borrow::Cow;
use std::collections::HashSet; use std::collections::HashSet;
use std::env; use std::env;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
...@@ -241,7 +242,7 @@ fn send_succeeds() { ...@@ -241,7 +242,7 @@ fn send_succeeds() {
} else { } else {
let content = 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
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论