Skip to content
项目
群组
代码片段
帮助
正在加载...
登录
切换导航
M
mediasoup
项目
项目
详情
活动
周期分析
仓库
仓库
文件
提交
分支
标签
贡献者
分枝图
比较
统计图
议题
0
议题
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
CI / CD
CI / CD
流水线
作业
日程
统计图
Wiki
Wiki
代码片段
代码片段
成员
成员
折叠边栏
关闭边栏
活动
分枝图
统计图
创建新议题
作业
提交
议题看板
打开侧边栏
聂卓夫
mediasoup
Commits
f0ebd809
Unverified
提交
f0ebd809
authored
11月 26, 2021
作者:
Nazar Mokrynskyi
提交者:
GitHub
11月 26, 2021
浏览文件
操作
浏览文件
下载
差异文件
Merge pull request #666 from nazar-pc/rust-next
Rust updates and optimizations around communication performance
上级
b6d41de5
ee34ee84
全部展开
隐藏空白字符变更
内嵌
并排
正在显示
57 个修改的文件
包含
994 行增加
和
578 行删除
+994
-578
mediasoup-rust.yaml
.github/workflows/mediasoup-rust.yaml
+3
-8
Channel.js
node/lib/Channel.js
+1
-1
PayloadChannel.js
node/lib/PayloadChannel.js
+1
-1
Channel.ts
node/src/Channel.ts
+1
-1
PayloadChannel.ts
node/src/PayloadChannel.ts
+1
-1
CHANGELOG.md
rust/CHANGELOG.md
+5
-0
Cargo.toml
rust/Cargo.toml
+15
-15
direct_data.rs
rust/benches/direct_data.rs
+10
-35
webpack.config.js
rust/examples-frontend/echo/webpack.config.js
+4
-2
webpack.config.js
rust/examples-frontend/multiopus/webpack.config.js
+4
-2
webpack.config.js
rust/examples-frontend/videoroom/webpack.config.js
+4
-2
videoroom.rs
rust/examples/videoroom.rs
+14
-10
data_structures.rs
rust/src/data_structures.rs
+8
-9
messages.rs
rust/src/messages.rs
+11
-36
router.rs
rust/src/router.rs
+22
-21
active_speaker_observer.rs
rust/src/router/active_speaker_observer.rs
+17
-20
audio_level_observer.rs
rust/src/router/audio_level_observer.rs
+23
-24
consumer.rs
rust/src/router/consumer.rs
+26
-35
data_consumer.rs
rust/src/router/data_consumer.rs
+15
-17
data_producer.rs
rust/src/router/data_producer.rs
+12
-15
direct_transport.rs
rust/src/router/direct_transport.rs
+52
-54
pipe_transport.rs
rust/src/router/pipe_transport.rs
+44
-40
plain_transport.rs
rust/src/router/plain_transport.rs
+0
-0
producer.rs
rust/src/router/producer.rs
+26
-32
transport.rs
rust/src/router/transport.rs
+15
-16
webrtc_transport.rs
rust/src/router/webrtc_transport.rs
+0
-0
worker.rs
rust/src/worker.rs
+39
-18
channel.rs
rust/src/worker/channel.rs
+0
-0
common.rs
rust/src/worker/common.rs
+53
-38
payload_channel.rs
rust/src/worker/payload_channel.rs
+0
-0
utils.rs
rust/src/worker/utils.rs
+47
-36
channel_read_fn.rs
rust/src/worker/utils/channel_read_fn.rs
+168
-0
channel_write_fn.rs
rust/src/worker/utils/channel_write_fn.rs
+128
-0
worker_manager.rs
rust/src/worker_manager.rs
+3
-5
consumer.rs
rust/tests/integration/consumer.rs
+14
-14
data_consumer.rs
rust/tests/integration/data_consumer.rs
+12
-9
data_producer.rs
rust/tests/integration/data_producer.rs
+23
-11
direct_transport.rs
rust/tests/integration/direct_transport.rs
+5
-6
plain_transport.rs
rust/tests/integration/plain_transport.rs
+2
-2
producer.rs
rust/tests/integration/producer.rs
+30
-11
router.rs
rust/tests/integration/router.rs
+14
-8
webrtc_transport.rs
rust/tests/integration/webrtc_transport.rs
+2
-2
build.rs
worker/build.rs
+8
-5
ChannelNotifier.hpp
worker/include/Channel/ChannelNotifier.hpp
+1
-0
ChannelSocket.hpp
worker/include/Channel/ChannelSocket.hpp
+16
-5
Logger.hpp
worker/include/Logger.hpp
+1
-1
PayloadChannelSocket.hpp
worker/include/PayloadChannel/PayloadChannelSocket.hpp
+17
-4
common.hpp
worker/include/common.hpp
+39
-0
lib.hpp
worker/include/lib.hpp
+12
-2
ChannelNotifier.cpp
worker/src/Channel/ChannelNotifier.cpp
+14
-0
ChannelSocket.cpp
worker/src/Channel/ChannelSocket.cpp
+0
-0
Logger.cpp
worker/src/Logger.cpp
+1
-1
PayloadChannelSocket.cpp
worker/src/PayloadChannel/PayloadChannelSocket.cpp
+0
-0
Worker.cpp
worker/src/Worker.cpp
+1
-1
lib.cpp
worker/src/lib.cpp
+0
-0
lib.rs
worker/src/lib.rs
+0
-0
main.cpp
worker/src/main.cpp
+10
-2
没有找到文件。
.github/workflows/mediasoup-rust.yaml
浏览文件 @
f0ebd809
...
...
@@ -22,17 +22,12 @@ jobs:
-
name
:
Checkout
uses
:
actions/checkout@v2
-
name
:
Node.js
uses
:
actions/setup-node@v2
with
:
node-version
:
'
14'
-
name
:
Rust toolchain
uses
:
actions-rs/toolchain@v1
with
:
toolchain
:
${{ matrix.rust }}
override
:
true
components
:
rustfmt, clippy
toolchain
:
${{ matrix.rust }}
override
:
true
components
:
rustfmt, clippy
-
name
:
Configure cache
uses
:
actions/cache@v2
...
...
node/lib/Channel.js
浏览文件 @
f0ebd809
...
...
@@ -207,7 +207,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// 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.
else
{
...
...
node/lib/PayloadChannel.js
浏览文件 @
f0ebd809
...
...
@@ -213,7 +213,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
else
if
(
msg
.
targetId
&&
msg
.
event
)
{
this
.
#
ongoingNotification
=
{
targetId
:
msg
.
targetId
,
targetId
:
String
(
msg
.
targetId
)
,
event
:
msg
.
event
,
data
:
msg
.
data
};
...
...
node/src/Channel.ts
浏览文件 @
f0ebd809
...
...
@@ -330,7 +330,7 @@ export class Channel extends EnhancedEventEmitter
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// 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.
else
...
...
node/src/PayloadChannel.ts
浏览文件 @
f0ebd809
...
...
@@ -354,7 +354,7 @@ export class PayloadChannel extends EnhancedEventEmitter
{
this
.
#
ongoingNotification
=
{
targetId
:
msg
.
targetId
,
targetId
:
String
(
msg
.
targetId
)
,
event
:
msg
.
event
,
data
:
msg
.
data
};
...
...
rust/CHANGELOG.md
浏览文件 @
f0ebd809
...
...
@@ -3,6 +3,11 @@
# Unreleased
*
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
...
...
rust/Cargo.toml
浏览文件 @
f0ebd809
...
...
@@ -22,33 +22,32 @@ targets = []
[dependencies]
async-channel
=
"1.6.1"
async-executor
=
"1.4.1"
async-fs
=
"1.5.0"
async-io
=
"1.6.0"
async-lock
=
"2.4.0"
async-oneshot
=
"0.5.0"
async-trait
=
"0.1.5
0
"
bytes
=
"1.0.1
"
event-listener-primitives
=
"
1.0.0
"
async-trait
=
"0.1.5
1
"
atomic-take
=
"1.0.0
"
event-listener-primitives
=
"
2.0.1
"
fastrand
=
"1.5.0"
futures-lite
=
"1.12.0"
h264-profile-level-id
=
"0.1.1"
hash_hasher
=
"2.0.3"
log
=
"0.4.14"
libc
=
"0.2.98
"
nohash-hasher
=
"0.2.0
"
once_cell
=
"1.8.0"
serde_json
=
"1.0.6
4
"
serde_json
=
"1.0.6
7
"
serde_repr
=
"0.1.7"
thiserror
=
"1.0.2
6
"
thiserror
=
"1.0.2
8
"
[dependencies.lru]
default-features
=
false
version
=
"0.6.
5
"
version
=
"0.6.
6
"
[dependencies.mediasoup-sys]
path
=
"../worker"
version
=
"0.2.5"
[dependencies.parking_lot]
version
=
"0.11.
1
"
version
=
"0.11.
2
"
features
=
["serde"]
[dependencies.regex]
...
...
@@ -58,7 +57,7 @@ version = "1.5.4"
[dependencies.serde]
features
=
["derive"]
version
=
"1.0.1
26
"
version
=
"1.0.1
30
"
[dependencies.uuid]
features
=
[
"serde"
,
"v4"
]
...
...
@@ -66,13 +65,14 @@ version = "0.8.2"
[dev-dependencies]
actix
=
"0.12.0"
actix-web
=
"4.0.0-beta.8"
actix-web-actors
=
"4.0.0-beta.6"
async-io
=
"1.6.0"
criterion
=
"0.3.5"
env_logger
=
"0.9.0"
[dev-dependencies.
criterion
]
version
=
"0.3.5"
features
=
["async_futures"]
[dev-dependencies.
actix-web
]
default-features
=
false
version
=
"4.0.0-beta.8"
[[bench]]
name
=
"direct_data"
...
...
rust/benches/direct_data.rs
浏览文件 @
f0ebd809
use
bytes
::
Bytes
;
use
criterion
::
async_executor
::
FuturesExecutor
;
use
criterion
::{
criterion_group
,
criterion_main
,
Criterion
};
use
futures_lite
::
StreamExt
;
use
mediasoup
::
prelude
::
*
;
use
std
::
borrow
::
Cow
;
use
std
::
sync
::
mpsc
;
async
fn
create_data_producer_consumer_pair
(
)
->
Result
<
(
DataProducer
,
DataConsumer
),
Box
<
dyn
std
::
error
::
Error
>>
{
...
...
@@ -29,32 +28,10 @@ async fn create_data_producer_consumer_pair(
pub
fn
criterion_benchmark
(
c
:
&
mut
Criterion
)
{
let
mut
group
=
c
.benchmark_group
(
"direct_data"
);
let
data
=
Bytes
::
from
(
std
::
iter
::
repeat_with
(||
fastrand
::
u8
(
..
))
.take
(
512
)
.collect
::
<
Vec
<
u8
>>
(),
);
let
data
=
std
::
iter
::
repeat_with
(||
fastrand
::
u8
(
..
))
.take
(
512
)
.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
{
create_data_producer_consumer_pair
()
.await
.unwrap
()
...
...
@@ -68,17 +45,15 @@ pub fn criterion_benchmark(c: &mut Criterion) {
};
group
.bench_with_input
(
"recv"
,
&
data
,
|
b
,
data
|
{
b
.
to_async
(
FuturesExecutor
)
.iter
(||
async
{
let
(
sender
,
mut
receiver
)
=
async_channel
::
unbounded
::
<
()
>
(
);
b
.
iter
(||
{
let
(
sender
,
receiver
)
=
mpsc
::
sync_channel
(
1
);
let
_handler_id
=
data_consumer
.on_message
(
move
|
_message
|
{
let
_
=
sender
.
try_
send
(());
let
_
=
sender
.send
(());
});
let
_
=
direct_data_producer
.send
(
WebRtcMessage
::
Binary
(
data
.clone
()))
.await
;
let
_
=
direct_data_producer
.send
(
WebRtcMessage
::
Binary
(
Cow
::
from
(
data
)));
let
_
=
receiver
.
next
()
.await
;
let
_
=
receiver
.
recv
()
;
})
});
}
...
...
rust/examples-frontend/echo/webpack.config.js
浏览文件 @
f0ebd809
// eslint-disable-next-line @typescript-eslint/no-var-requires
const
path
=
require
(
'path'
);
module
.
exports
=
{
...
...
@@ -22,6 +21,9 @@ module.exports = {
},
devServer
:
{
liveReload
:
false
,
port
:
3001
port
:
3001
,
static
:
{
directory
:
__dirname
}
}
};
rust/examples-frontend/multiopus/webpack.config.js
浏览文件 @
f0ebd809
// eslint-disable-next-line @typescript-eslint/no-var-requires
const
path
=
require
(
'path'
);
module
.
exports
=
{
...
...
@@ -22,6 +21,9 @@ module.exports = {
},
devServer
:
{
liveReload
:
false
,
port
:
3001
port
:
3001
,
static
:
{
directory
:
__dirname
}
}
};
rust/examples-frontend/videoroom/webpack.config.js
浏览文件 @
f0ebd809
// eslint-disable-next-line @typescript-eslint/no-var-requires
const
path
=
require
(
'path'
);
module
.
exports
=
{
...
...
@@ -22,6 +21,9 @@ module.exports = {
},
devServer
:
{
liveReload
:
false
,
port
:
3001
port
:
3001
,
static
:
{
directory
:
__dirname
}
}
};
rust/examples/videoroom.rs
浏览文件 @
f0ebd809
...
...
@@ -37,8 +37,10 @@ mod room {
#[derive(Default)]
struct
Handlers
{
producer_add
:
Bag
<
Box
<
dyn
Fn
(
&
ParticipantId
,
&
Producer
)
+
Send
+
Sync
>>
,
producer_remove
:
Bag
<
Box
<
dyn
Fn
(
&
ParticipantId
,
&
ProducerId
)
+
Send
+
Sync
>>
,
producer_add
:
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
>>
,
}
...
...
@@ -146,9 +148,10 @@ mod room {
.or_default
()
.push
(
producer
.clone
());
self
.inner.handlers.producer_add
.call
(|
callback
|
{
callback
(
&
participant_id
,
&
producer
);
});
self
.inner
.handlers
.producer_add
.call_simple
(
&
participant_id
,
&
producer
);
}
/// Remove participant and all of its associated producers
...
...
@@ -157,9 +160,10 @@ mod room {
for
producer
in
producers
.unwrap_or_default
()
{
let
producer_id
=
&
producer
.id
();
self
.inner.handlers.producer_remove
.call
(|
callback
|
{
callback
(
participant_id
,
producer_id
);
});
self
.inner
.handlers
.producer_remove
.call_simple
(
participant_id
,
producer_id
);
}
}
...
...
@@ -185,7 +189,7 @@ mod room {
&
self
,
callback
:
F
,
)
->
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
...
...
@@ -193,7 +197,7 @@ mod room {
&
self
,
callback
:
F
,
)
->
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
...
...
rust/src/data_structures.rs
浏览文件 @
f0ebd809
...
...
@@ -3,7 +3,6 @@
#[cfg(test)]
mod
tests
;
use
bytes
::
Bytes
;
use
serde
::
de
::{
MapAccess
,
Visitor
};
use
serde
::
ser
::
SerializeStruct
;
use
serde
::{
de
,
Deserialize
,
Deserializer
,
Serialize
,
Serializer
};
...
...
@@ -770,18 +769,18 @@ pub enum TraceEventDirection {
/// Container used for sending/receiving messages using `DirectTransport` data producers and data
/// consumers.
#[derive(Debug,
Clone)]
pub
enum
WebRtcMessage
{
pub
enum
WebRtcMessage
<
'a
>
{
/// String
String
(
String
),
/// Binary
Binary
(
Bytes
),
Binary
(
Cow
<
'a
,
[
u8
]
>
),
/// EmptyString
EmptyString
,
/// EmptyBinary
EmptyBinary
,
}
impl
WebRtcMessage
{
impl
<
'a
>
WebRtcMessage
<
'a
>
{
// +------------------------------------+-----------+
// | Value | SCTP PPID |
// +------------------------------------+-----------+
...
...
@@ -793,7 +792,7 @@ impl WebRtcMessage {
// | 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
{
51
=>
Ok
(
WebRtcMessage
::
String
(
String
::
from_utf8
(
payload
.to_vec
())
.unwrap
(),
...
...
@@ -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
{
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
::
EmptyString
=>
(
56
_u32
,
Bytes
::
from_static
(
b
" "
)),
WebRtcMessage
::
EmptyBinary
=>
(
57
_u32
,
Bytes
::
from
(
vec!
[
0
_u8
])),
WebRtcMessage
::
EmptyString
=>
(
56
_u32
,
Cow
::
from
(
b
" "
.as_ref
()
)),
WebRtcMessage
::
EmptyBinary
=>
(
57
_u32
,
Cow
::
from
(
vec!
[
0
_u8
])),
}
}
}
...
...
rust/src/messages.rs
浏览文件 @
f0ebd809
...
...
@@ -28,8 +28,8 @@ use crate::worker::{WorkerDump, WorkerUpdateSettings};
use
parking_lot
::
Mutex
;
use
serde
::
de
::
DeserializeOwned
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde_json
::
Value
;
use
std
::
fmt
::
Debug
;
use
std
::
marker
::
PhantomData
;
use
std
::
net
::
IpAddr
;
use
std
::
num
::
NonZeroU16
;
...
...
@@ -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.dump"
,
WorkerDumpRequest
{},
WorkerDump
);
...
...
@@ -333,8 +307,9 @@ request_response!(
data
:
RouterCreatePlainTransportData
,
},
PlainTransportData
{
rtcp_mux
:
bool
,
comedia
:
bool
,
// The following fields are present, but unused
// rtcp_mux: bool,
// comedia: bool,
tuple
:
Mutex
<
TransportTuple
>
,
rtcp_tuple
:
Mutex
<
Option
<
TransportTuple
>>
,
sctp_parameters
:
Option
<
SctpParameters
>
,
...
...
@@ -446,20 +421,20 @@ request_response!(
},
);
request_response
_generic
!
(
request_response!
(
"transport.dump"
,
TransportDumpRequest
{
internal
:
TransportInternal
,
},
Dump
,
Value
,
);
request_response
_generic
!
(
request_response!
(
"transport.getStats"
,
TransportGetStatsRequest
{
internal
:
TransportInternal
,
},
Stats
,
Value
,
);
#[derive(Debug,
Serialize)]
...
...
@@ -470,7 +445,7 @@ pub(crate) struct TransportConnectRequestWebRtcData {
request_response!
(
"transport.connect"
,
TransportConnect
RequestWebRtc
{
TransportConnect
WebRtcRequest
{
internal
:
TransportInternal
,
data
:
TransportConnectRequestWebRtcData
,
},
...
...
@@ -490,7 +465,7 @@ pub(crate) struct TransportConnectRequestPipeData {
request_response!
(
"transport.connect"
,
TransportConnect
RequestPipe
{
TransportConnect
PipeRequest
{
internal
:
TransportInternal
,
data
:
TransportConnectRequestPipeData
,
},
...
...
@@ -514,7 +489,7 @@ pub(crate) struct TransportConnectRequestPlainData {
request_response!
(
"transport.connect"
,
TransportConnect
RequestPlain
{
TransportConnect
PlainRequest
{
internal
:
TransportInternal
,
data
:
TransportConnectRequestPlainData
,
},
...
...
rust/src/router.rs
浏览文件 @
f0ebd809
...
...
@@ -59,10 +59,10 @@ use async_executor::Executor;
use
async_lock
::
Mutex
as
AsyncMutex
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
log
::{
debug
,
error
};
use
parking_lot
::{
Mutex
,
RwLock
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
fmt
;
use
std
::
ops
::
Deref
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
...
...
@@ -270,13 +270,14 @@ impl From<ProduceDataError> for PipeDataProducerToRouterError {
#[non_exhaustive]
pub
struct
RouterDump
{
pub
id
:
RouterId
,
pub
map_consumer_id_producer_id
:
HashMap
<
ConsumerId
,
ProducerId
>
,
pub
map_data_consumer_id_data_producer_id
:
HashMap
<
DataConsumerId
,
DataProducerId
>
,
pub
map_data_producer_id_data_consumer_ids
:
HashMap
<
DataProducerId
,
HashSet
<
DataConsumerId
>>
,
pub
map_producer_id_consumer_ids
:
HashMap
<
ProducerId
,
HashSet
<
ConsumerId
>>
,
pub
map_producer_id_observer_ids
:
HashMap
<
ProducerId
,
HashSet
<
RtpObserverId
>>
,
pub
rtp_observer_ids
:
HashSet
<
RtpObserverId
>
,
pub
transport_ids
:
HashSet
<
TransportId
>
,
pub
map_consumer_id_producer_id
:
HashedMap
<
ConsumerId
,
ProducerId
>
,
pub
map_data_consumer_id_data_producer_id
:
HashedMap
<
DataConsumerId
,
DataProducerId
>
,
pub
map_data_producer_id_data_consumer_ids
:
HashedMap
<
DataProducerId
,
HashedSet
<
DataConsumerId
>>
,
pub
map_producer_id_consumer_ids
:
HashedMap
<
ProducerId
,
HashedSet
<
ConsumerId
>>
,
pub
map_producer_id_observer_ids
:
HashedMap
<
ProducerId
,
HashedSet
<
RtpObserverId
>>
,
pub
rtp_observer_ids
:
HashedSet
<
RtpObserverId
>
,
pub
transport_ids
:
HashedSet
<
TransportId
>
,
}
/// New transport that was just created.
...
...
@@ -355,8 +356,8 @@ impl WeakPipeTransportPair {
#[derive(Default)]
struct
Handlers
{
new_transport
:
Bag
<
Box
<
dyn
Fn
(
NewTransport
<
'_
>
)
+
Send
+
Sync
>>
,
new_rtp_observer
:
Bag
<
Box
<
dyn
Fn
(
NewRtpObserver
<
'_
>
)
+
Send
+
Sync
>>
,
new_transport
:
Bag
<
Arc
<
dyn
Fn
(
NewTransport
<
'_
>
)
+
Send
+
Sync
>>
,
new_rtp_observer
:
Bag
<
Arc
<
dyn
Fn
(
NewRtpObserver
<
'_
>
)
+
Send
+
Sync
>>
,
worker_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
...
...
@@ -369,11 +370,11 @@ struct Inner {
payload_channel
:
PayloadChannel
,
handlers
:
Arc
<
Handlers
>
,
app_data
:
AppData
,
producers
:
Arc
<
RwLock
<
HashMap
<
ProducerId
,
WeakProducer
>>>
,
data_producers
:
Arc
<
RwLock
<
HashMap
<
DataProducerId
,
WeakDataProducer
>>>
,
producers
:
Arc
<
RwLock
<
Hash
ed
Map
<
ProducerId
,
WeakProducer
>>>
,
data_producers
:
Arc
<
RwLock
<
Hash
ed
Map
<
DataProducerId
,
WeakDataProducer
>>>
,
#[allow(clippy
::
type_complexity)]
mapped_pipe_transports
:
Arc
<
Mutex
<
HashMap
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>>
,
Arc
<
Mutex
<
Hash
ed
Map
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>>
,
// Make sure worker is not dropped until this router is not dropped
worker
:
Option
<
Worker
>
,
closed
:
AtomicBool
,
...
...
@@ -449,10 +450,10 @@ impl Router {
)
->
Self
{
debug!
(
"new()"
);
let
producers
=
Arc
::
<
RwLock
<
HashMap
<
ProducerId
,
WeakProducer
>>>
::
default
();
let
data_producers
=
Arc
::
<
RwLock
<
HashMap
<
DataProducerId
,
WeakDataProducer
>>>
::
default
();
let
producers
=
Arc
::
<
RwLock
<
Hash
ed
Map
<
ProducerId
,
WeakProducer
>>>
::
default
();
let
data_producers
=
Arc
::
<
RwLock
<
Hash
ed
Map
<
DataProducerId
,
WeakDataProducer
>>>
::
default
();
let
mapped_pipe_transports
=
Arc
::
<
Mutex
<
HashMap
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>
,
Mutex
<
Hash
ed
Map
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>
,
>
::
default
();
let
handlers
=
Arc
::
<
Handlers
>
::
default
();
let
inner_weak
=
Arc
::
<
Mutex
<
Option
<
Weak
<
Inner
>>>>
::
default
();
...
...
@@ -1314,7 +1315,7 @@ impl Router {
&
self
,
callback
:
F
,
)
->
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.
...
...
@@ -1322,7 +1323,7 @@ impl Router {
&
self
,
callback
:
F
,
)
->
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.
...
...
@@ -1351,7 +1352,7 @@ impl Router {
// 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
// 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 `Hash
ed
Map` with mapping behind `Mutex` and
// another `Mutex` on the pair of `PipeTransport`.
let
mut
mapped_pipe_transports
=
self
.inner.mapped_pipe_transports
.lock
();
...
...
@@ -1465,7 +1466,7 @@ impl Router {
{
let
producers_weak
=
Arc
::
downgrade
(
&
self
.inner.producers
);
transport
.on_new_producer
(
Box
::
new
(
move
|
producer
|
{
.on_new_producer
(
Arc
::
new
(
move
|
producer
|
{
let
producer_id
=
producer
.id
();
if
let
Some
(
producers
)
=
producers_weak
.upgrade
()
{
producers
.write
()
.insert
(
producer_id
,
producer
.downgrade
());
...
...
@@ -1486,7 +1487,7 @@ impl Router {
{
let
data_producers_weak
=
Arc
::
downgrade
(
&
self
.inner.data_producers
);
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
();
if
let
Some
(
data_producers
)
=
data_producers_weak
.upgrade
()
{
data_producers
...
...
rust/src/router/active_speaker_observer.rs
浏览文件 @
f0ebd809
...
...
@@ -50,11 +50,14 @@ pub struct ActiveSpeakerObserverDominantSpeaker {
#[derive(Default)]
struct
Handlers
{
dominant_speaker
:
Bag
<
Box
<
dyn
Fn
(
&
ActiveSpeakerObserverDominantSpeaker
)
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
add_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>>
,
remove_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>>
,
dominant_speaker
:
Bag
<
Arc
<
dyn
Fn
(
&
ActiveSpeakerObserverDominantSpeaker
)
+
Send
+
Sync
>
,
ActiveSpeakerObserverDominantSpeaker
,
>
,
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
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
...
...
@@ -220,9 +223,7 @@ impl RtpObserver for ActiveSpeakerObserver {
})
.await
?
;
self
.inner.handlers.add_producer
.call
(|
callback
|
{
callback
(
&
producer
);
});
self
.inner.handlers.add_producer
.call_simple
(
&
producer
);
Ok
(())
}
...
...
@@ -242,33 +243,31 @@ impl RtpObserver for ActiveSpeakerObserver {
})
.await
?
;
self
.inner.handlers.remove_producer
.call
(|
callback
|
{
callback
(
&
producer
);
});
self
.inner.handlers.remove_producer
.call_simple
(
&
producer
);
Ok
(())
}
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
{
self
.inner.handlers.resume
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.resume
.add
(
Arc
::
new
(
callback
))
}
fn
on_add_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.add_producer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.add_producer
.add
(
Arc
::
new
(
callback
))
}
fn
on_remove_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
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
{
...
...
@@ -302,7 +301,7 @@ impl ActiveSpeakerObserver {
let
handlers
=
Arc
::
clone
(
&
handlers
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
DominantSpeaker
(
dominant_speaker
)
=>
{
let
DominantSpeakerNotification
{
producer_id
}
=
dominant_speaker
;
...
...
@@ -311,9 +310,7 @@ impl ActiveSpeakerObserver {
let
dominant_speaker
=
ActiveSpeakerObserverDominantSpeaker
{
producer
};
handlers
.dominant_speaker
.call
(|
callback
|
{
callback
(
&
dominant_speaker
);
});
handlers
.dominant_speaker
.call_simple
(
&
dominant_speaker
);
}
None
=>
{
error!
(
...
...
@@ -367,7 +364,7 @@ impl ActiveSpeakerObserver {
&
self
,
callback
:
F
,
)
->
HandlerId
{
self
.inner.handlers.dominant_speaker
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.dominant_speaker
.add
(
Arc
::
new
(
callback
))
}
/// Downgrade `ActiveSpeakerObserver` to [`WeakActiveSpeakerObserver`] instance.
...
...
rust/src/router/audio_level_observer.rs
浏览文件 @
f0ebd809
...
...
@@ -61,12 +61,12 @@ pub struct AudioLevelObserverVolume {
#[derive(Default)]
struct
Handlers
{
volumes
:
Bag
<
Box
<
dyn
Fn
(
&
Vec
<
AudioLevelObserverVolume
>
)
+
Send
+
Sync
>>
,
silence
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
add_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
remove_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
volumes
:
Bag
<
Arc
<
dyn
Fn
(
&
[
AudioLevelObserverVolume
]
)
+
Send
+
Sync
>>
,
silence
:
Bag
<
Arc
<
dyn
Fn
()
+
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
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
...
...
@@ -234,9 +234,7 @@ impl RtpObserver for AudioLevelObserver {
})
.await
?
;
self
.inner.handlers.add_producer
.call
(|
callback
|
{
callback
(
&
producer
);
});
self
.inner.handlers.add_producer
.call_simple
(
&
producer
);
Ok
(())
}
...
...
@@ -256,33 +254,31 @@ impl RtpObserver for AudioLevelObserver {
})
.await
?
;
self
.inner.handlers.remove_producer
.call
(|
callback
|
{
callback
(
&
producer
);
});
self
.inner.handlers.remove_producer
.call_simple
(
&
producer
);
Ok
(())
}
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
{
self
.inner.handlers.resume
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.resume
.add
(
Arc
::
new
(
callback
))
}
fn
on_add_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.add_producer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.add_producer
.add
(
Arc
::
new
(
callback
))
}
fn
on_remove_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
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
{
...
...
@@ -316,21 +312,24 @@ impl AudioLevelObserver {
let
handlers
=
Arc
::
clone
(
&
handlers
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Volumes
(
volumes
)
=>
{
let
volumes
=
volumes
.i
nto_i
ter
()
.iter
()
.filter_map
(|
notification
|
{
let
VolumeNotification
{
producer_id
,
volume
,
}
=
notification
;
router
.get_producer
(
&
producer_id
)
.map
(|
producer
|
{
AudioLevelObserverVolume
{
producer
,
volume
}
router
.get_producer
(
producer_id
)
.map
(|
producer
|
{
AudioLevelObserverVolume
{
producer
,
volume
:
*
volume
,
}
})
})
.collect
();
.collect
::
<
Vec
<
_
>>
();
handlers
.volumes
.call
(|
callback
|
{
callback
(
&
volumes
);
...
...
@@ -379,17 +378,17 @@ impl AudioLevelObserver {
/// Callback is called at most every interval (see [`AudioLevelObserverOptions`]).
///
/// 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
,
callback
:
F
,
)
->
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
/// beyond the given threshold.
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.
...
...
rust/src/router/consumer.rs
浏览文件 @
f0ebd809
...
...
@@ -13,11 +13,8 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters}
use
crate
::
scalability_modes
::
ScalabilityMode
;
use
crate
::
transport
::
Transport
;
use
crate
::
uuid_based_wrapper_type
;
use
crate
::
worker
::{
Channel
,
NotificationMessage
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
use
crate
::
worker
::{
Channel
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
};
use
async_executor
::
Executor
;
use
bytes
::
Bytes
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
parking_lot
::
Mutex
;
...
...
@@ -347,14 +344,15 @@ enum PayloadNotification {
#[derive(Default)]
struct
Handlers
{
rtp
:
Bag
<
Box
<
dyn
Fn
(
&
Bytes
)
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
score
:
Bag
<
Box
<
dyn
Fn
(
&
ConsumerScore
)
+
Send
+
Sync
>>
,
layers_change
:
Bag
<
Box
<
dyn
Fn
(
&
Option
<
ConsumerLayers
>
)
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
ConsumerTraceEventData
)
+
Send
+
Sync
>>
,
rtp
:
Bag
<
Arc
<
dyn
Fn
(
&
[
u8
])
+
Send
+
Sync
>>
,
pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
score
:
Bag
<
Arc
<
dyn
Fn
(
&
ConsumerScore
)
+
Send
+
Sync
>
,
ConsumerScore
>
,
#[allow(clippy
::
type_complexity)]
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
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
...
...
@@ -492,7 +490,7 @@ impl Consumer {
let
inner_weak
=
Arc
::
clone
(
&
inner_weak
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
ProducerClose
=>
{
if
!
closed
.load
(
Ordering
::
SeqCst
)
{
...
...
@@ -529,20 +527,14 @@ impl Consumer {
}
Notification
::
Score
(
consumer_score
)
=>
{
*
score
.lock
()
=
consumer_score
.clone
();
handlers
.score
.call
(|
callback
|
{
callback
(
&
consumer_score
);
});
handlers
.score
.call_simple
(
&
consumer_score
);
}
Notification
::
LayersChange
(
consumer_layers
)
=>
{
*
current_layers
.lock
()
=
consumer_layers
;
handlers
.layers_change
.call
(|
callback
|
{
callback
(
&
consumer_layers
);
});
handlers
.layers_change
.call_simple
(
&
consumer_layers
);
}
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
callback
(
&
trace_event_data
);
});
handlers
.trace
.call_simple
(
&
trace_event_data
);
}
},
Err
(
error
)
=>
{
...
...
@@ -555,13 +547,12 @@ impl Consumer {
let
payload_subscription_handler
=
{
let
handlers
=
Arc
::
clone
(
&
handlers
);
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
let
NotificationMessage
{
message
,
payload
}
=
notification
;
match
serde_json
::
from_value
::
<
PayloadNotification
>
(
message
)
{
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
message
,
payload
|
{
match
serde_json
::
from_slice
::
<
PayloadNotification
>
(
message
)
{
Ok
(
notification
)
=>
match
notification
{
PayloadNotification
::
Rtp
=>
{
handlers
.rtp
.call
(|
callback
|
{
callback
(
&
payload
);
callback
(
payload
);
});
}
},
...
...
@@ -864,30 +855,30 @@ impl Consumer {
/// # Notes on usage
/// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub
fn
on_rtp
<
F
:
Fn
(
&
Bytes
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.rtp
.add
(
Box
::
new
(
callback
))
pub
fn
on_rtp
<
F
:
Fn
(
&
[
u8
]
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.rtp
.add
(
Arc
::
new
(
callback
))
}
/// Callback is called when the consumer or its associated producer is paused and, as result,
/// the consumer becomes paused.
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,
/// the consumer is no longer paused.
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.
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.
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.
...
...
@@ -895,7 +886,7 @@ impl Consumer {
&
self
,
callback
:
F
,
)
->
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
...
...
@@ -919,7 +910,7 @@ impl Consumer {
&
self
,
callback
:
F
,
)
->
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.
...
...
@@ -927,7 +918,7 @@ impl Consumer {
&
self
,
callback
:
F
,
)
->
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
...
...
rust/src/router/data_consumer.rs
浏览文件 @
f0ebd809
...
...
@@ -12,14 +12,13 @@ use crate::messages::{
use
crate
::
sctp_parameters
::
SctpStreamParameters
;
use
crate
::
transport
::
Transport
;
use
crate
::
uuid_based_wrapper_type
;
use
crate
::
worker
::{
Channel
,
NotificationMessage
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
use
crate
::
worker
::{
Channel
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
};
use
async_executor
::
Executor
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
borrow
::
Cow
;
use
std
::
fmt
;
use
std
::
fmt
::
Debug
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
...
...
@@ -184,9 +183,9 @@ enum PayloadNotification {
#[derive(Default)]
struct
Handlers
{
message
:
Bag
<
Box
<
dyn
Fn
(
&
WebRtcMessage
)
+
Send
+
Sync
>>
,
sctp_send_buffer_full
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
buffered_amount_low
:
Bag
<
Box
<
dyn
Fn
(
u32
)
+
Send
+
Sync
>>
,
message
:
Bag
<
Arc
<
dyn
Fn
(
&
WebRtcMessage
<
'_
>
)
+
Send
+
Sync
>>
,
sctp_send_buffer_full
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
buffered_amount_low
:
Bag
<
Arc
<
dyn
Fn
(
u32
)
+
Send
+
Sync
>>
,
data_producer_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
...
...
@@ -366,7 +365,7 @@ impl DataConsumer {
let
inner_weak
=
Arc
::
clone
(
&
inner_weak
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
DataProducerClose
=>
{
if
!
closed
.load
(
Ordering
::
SeqCst
)
{
...
...
@@ -397,12 +396,11 @@ impl DataConsumer {
let
payload_subscription_handler
=
{
let
handlers
=
Arc
::
clone
(
&
handlers
);
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
let
NotificationMessage
{
message
,
payload
}
=
notification
;
match
serde_json
::
from_value
::
<
PayloadNotification
>
(
message
)
{
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
message
,
payload
|
{
match
serde_json
::
from_slice
::
<
PayloadNotification
>
(
message
)
{
Ok
(
notification
)
=>
match
notification
{
PayloadNotification
::
Message
{
ppid
}
=>
{
match
WebRtcMessage
::
new
(
ppid
,
payload
)
{
match
WebRtcMessage
::
new
(
ppid
,
Cow
::
from
(
payload
)
)
{
Ok
(
message
)
=>
{
handlers
.message
.call
(|
callback
|
{
callback
(
&
message
);
...
...
@@ -582,11 +580,11 @@ impl DataConsumer {
/// # Notes on usage
/// Just available in direct transports, this is, those created via
/// [`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
,
callback
:
F
,
)
->
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.
...
...
@@ -597,7 +595,7 @@ impl DataConsumer {
self
.inner
()
.handlers
.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
...
...
@@ -612,7 +610,7 @@ impl DataConsumer {
self
.inner
()
.handlers
.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
...
...
@@ -671,7 +669,7 @@ impl DataConsumer {
impl
DirectDataConsumer
{
/// 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
();
self
.inner
...
...
@@ -686,7 +684,7 @@ impl DirectDataConsumer {
},
data
:
DataConsumerSendRequestData
{
ppid
},
},
payload
,
payload
.into_owned
()
,
)
.await
}
...
...
rust/src/router/data_producer.rs
浏览文件 @
f0ebd809
...
...
@@ -437,24 +437,21 @@ impl DataProducer {
}
impl
DirectDataProducer
{
/// Sends direct messages from the Rust
process
.
pub
async
fn
send
(
&
self
,
message
:
WebRtcMessage
)
->
Result
<
(),
NotificationError
>
{
/// Sends direct messages from the Rust
to the worker
.
pub
fn
send
(
&
self
,
message
:
WebRtcMessage
<
'_
>
)
->
Result
<
(),
NotificationError
>
{
let
(
ppid
,
payload
)
=
message
.into_ppid_and_payload
();
self
.inner
.payload_channel
.notify
(
DataProducerSendNotification
{
internal
:
DataProducerInternal
{
router_id
:
self
.inner.transport
.router_id
(),
transport_id
:
self
.inner.transport
.id
(),
data_producer_id
:
self
.inner.id
,
},
data
:
DataProducerSendData
{
ppid
},
self
.inner.payload_channel
.notify
(
DataProducerSendNotification
{
internal
:
DataProducerInternal
{
router_id
:
self
.inner.transport
.router_id
(),
transport_id
:
self
.inner.transport
.id
(),
data_producer_id
:
self
.inner.id
,
},
payload
,
)
.await
data
:
DataProducerSendData
{
ppid
},
},
payload
.into_owned
(),
)
}
}
...
...
rust/src/router/direct_transport.rs
浏览文件 @
f0ebd809
...
...
@@ -16,17 +16,15 @@ use crate::transport::{
TransportTraceEventType
,
};
use
crate
::
worker
::{
Channel
,
NotificationError
,
NotificationMessage
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
Channel
,
NotificationError
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
use
async_executor
::
Executor
;
use
async_trait
::
async_trait
;
use
bytes
::
Bytes
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
use
std
::
sync
::{
Arc
,
Weak
};
...
...
@@ -61,8 +59,8 @@ pub struct DirectTransportDump {
pub
direct
:
bool
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
...
...
@@ -113,12 +111,12 @@ pub struct DirectTransportStat {
#[derive(Default)]
struct
Handlers
{
rtcp
:
Bag
<
Box
<
dyn
Fn
(
&
Bytes
)
+
Send
+
Sync
>>
,
new_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
new_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
>
,
new_data_producer
:
Bag
<
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
>
,
new_data_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
>
,
rtcp
:
Bag
<
Arc
<
dyn
Fn
(
&
[
u8
]
)
+
Send
+
Sync
>>
,
new_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
new_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
,
Consumer
>
,
new_data_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
,
DataProducer
>
,
new_data_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
,
DataConsumer
>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
,
TransportTraceEventData
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
...
...
@@ -138,7 +136,7 @@ enum PayloadNotification {
struct
Inner
{
id
:
TransportId
,
next_mid_for_consumers
:
AtomicUsize
,
used_sctp_stream_ids
:
Mutex
<
Hash
Map
<
u16
,
bool
>>
,
used_sctp_stream_ids
:
Mutex
<
Int
Map
<
u16
,
bool
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
channel
:
Channel
,
...
...
@@ -253,9 +251,7 @@ impl Transport for DirectTransport {
.produce_impl
(
producer_options
,
TransportType
::
Direct
)
.await
?
;
self
.inner.handlers.new_producer
.call
(|
callback
|
{
callback
(
&
producer
);
});
self
.inner.handlers.new_producer
.call_simple
(
&
producer
);
Ok
(
producer
)
}
...
...
@@ -270,9 +266,7 @@ impl Transport for DirectTransport {
.consume_impl
(
consumer_options
,
TransportType
::
Direct
,
false
)
.await
?
;
self
.inner.handlers.new_consumer
.call
(|
callback
|
{
callback
(
&
consumer
);
});
self
.inner.handlers.new_consumer
.call_simple
(
&
consumer
);
Ok
(
consumer
)
}
...
...
@@ -294,9 +288,10 @@ impl Transport for DirectTransport {
)
.await
?
;
self
.inner.handlers.new_data_producer
.call
(|
callback
|
{
callback
(
&
data_producer
);
});
self
.inner
.handlers
.new_data_producer
.call_simple
(
&
data_producer
);
Ok
(
data_producer
)
}
...
...
@@ -318,9 +313,10 @@ impl Transport for DirectTransport {
)
.await
?
;
self
.inner.handlers.new_data_consumer
.call
(|
callback
|
{
callback
(
&
data_consumer
);
});
self
.inner
.handlers
.new_data_consumer
.call_simple
(
&
data_consumer
);
Ok
(
data_consumer
)
}
...
...
@@ -336,35 +332,35 @@ impl Transport for DirectTransport {
fn
on_new_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_producer
.add
(
callback
)
}
fn
on_new_consumer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_consumer
.add
(
callback
)
}
fn
on_new_data_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_data_producer
.add
(
callback
)
}
fn
on_new_data_consumer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_data_consumer
.add
(
callback
)
}
fn
on_trace
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
callback
)
}
...
...
@@ -392,7 +388,11 @@ impl TransportGeneric for DirectTransport {
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
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.
...
...
@@ -402,7 +402,11 @@ impl TransportGeneric for DirectTransport {
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
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 {
&
self
.inner.next_mid_for_consumers
}
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Hash
Map
<
u16
,
bool
>>
{
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Int
Map
<
u16
,
bool
>>
{
&
self
.inner.used_sctp_stream_ids
}
...
...
@@ -453,12 +457,10 @@ impl DirectTransport {
let
handlers
=
Arc
::
clone
(
&
handlers
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
callback
(
&
trace_event_data
);
});
handlers
.trace
.call_simple
(
&
trace_event_data
);
}
},
Err
(
error
)
=>
{
...
...
@@ -471,13 +473,12 @@ impl DirectTransport {
let
payload_subscription_handler
=
{
let
handlers
=
Arc
::
clone
(
&
handlers
);
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
let
NotificationMessage
{
message
,
payload
}
=
notification
;
match
serde_json
::
from_value
::
<
PayloadNotification
>
(
message
)
{
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
message
,
payload
|
{
match
serde_json
::
from_slice
::
<
PayloadNotification
>
(
message
)
{
Ok
(
notification
)
=>
match
notification
{
PayloadNotification
::
Rtcp
=>
{
handlers
.rtcp
.call
(|
callback
|
{
callback
(
&
payload
);
callback
(
payload
);
});
}
},
...
...
@@ -489,7 +490,7 @@ impl DirectTransport {
};
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
inner_weak
=
Arc
::
<
Mutex
<
Option
<
Weak
<
Inner
>>>>
::
default
();
let
on_router_close_handler
=
router
.on_close
({
...
...
@@ -526,21 +527,18 @@ impl DirectTransport {
/// Send a RTCP packet from the Rust process.
///
/// * `rtcp_packet` - Bytes containing a valid RTCP packet (can be a compound packet).
pub
async
fn
send_rtcp
(
&
self
,
rtcp_packet
:
Bytes
)
->
Result
<
(),
NotificationError
>
{
self
.inner
.payload_channel
.notify
(
TransportSendRtcpNotification
{
internal
:
self
.get_internal
(),
},
rtcp_packet
,
)
.await
pub
fn
send_rtcp
(
&
self
,
rtcp_packet
:
Vec
<
u8
>
)
->
Result
<
(),
NotificationError
>
{
self
.inner.payload_channel
.notify
(
TransportSendRtcpNotification
{
internal
:
self
.get_internal
(),
},
rtcp_packet
,
)
}
/// 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
{
self
.inner.handlers.rtcp
.add
(
Box
::
new
(
callback
))
pub
fn
on_rtcp
<
F
:
Fn
(
&
[
u8
]
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.rtcp
.add
(
Arc
::
new
(
callback
))
}
/// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance.
...
...
rust/src/router/pipe_transport.rs
浏览文件 @
f0ebd809
...
...
@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da
use
crate
::
data_producer
::{
DataProducer
,
DataProducerId
,
DataProducerOptions
,
DataProducerType
};
use
crate
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportTuple
};
use
crate
::
messages
::{
PipeTransportData
,
TransportCloseRequest
,
TransportConnect
RequestPipe
,
PipeTransportData
,
TransportCloseRequest
,
TransportConnect
PipeRequest
,
TransportConnectRequestPipeData
,
TransportInternal
,
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
...
...
@@ -24,9 +24,9 @@ use async_executor::Executor;
use
async_trait
::
async_trait
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
net
::
IpAddr
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
...
...
@@ -92,8 +92,8 @@ pub struct PipeTransportDump {
pub
direct
:
bool
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
...
...
@@ -162,13 +162,13 @@ pub struct PipeTransportRemoteParameters {
#[derive(Default)]
struct
Handlers
{
new_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
new_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
>
,
new_data_producer
:
Bag
<
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
>
,
new_data_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
>
,
tuple
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
>
,
sctp_state_change
:
Bag
<
Box
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
>
,
new_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
new_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
,
Consumer
>
,
new_data_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
,
DataProducer
>
,
new_data_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
,
DataConsumer
>
,
tuple
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
,
TransportTuple
>
,
sctp_state_change
:
Bag
<
Arc
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
,
TransportTraceEventData
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
...
...
@@ -186,7 +186,7 @@ enum Notification {
struct
Inner
{
id
:
TransportId
,
next_mid_for_consumers
:
AtomicUsize
,
used_sctp_stream_ids
:
Mutex
<
Hash
Map
<
u16
,
bool
>>
,
used_sctp_stream_ids
:
Mutex
<
Int
Map
<
u16
,
bool
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
channel
:
Channel
,
...
...
@@ -290,9 +290,7 @@ impl Transport for PipeTransport {
.produce_impl
(
producer_options
,
TransportType
::
Pipe
)
.await
?
;
self
.inner.handlers.new_producer
.call
(|
callback
|
{
callback
(
&
producer
);
});
self
.inner.handlers.new_producer
.call_simple
(
&
producer
);
Ok
(
producer
)
}
...
...
@@ -304,9 +302,7 @@ impl Transport for PipeTransport {
.consume_impl
(
consumer_options
,
TransportType
::
Pipe
,
self
.inner.data.rtx
)
.await
?
;
self
.inner.handlers.new_consumer
.call
(|
callback
|
{
callback
(
&
consumer
);
});
self
.inner.handlers.new_consumer
.call_simple
(
&
consumer
);
Ok
(
consumer
)
}
...
...
@@ -325,9 +321,10 @@ impl Transport for PipeTransport {
)
.await
?
;
self
.inner.handlers.new_data_producer
.call
(|
callback
|
{
callback
(
&
data_producer
);
});
self
.inner
.handlers
.new_data_producer
.call_simple
(
&
data_producer
);
Ok
(
data_producer
)
}
...
...
@@ -346,9 +343,10 @@ impl Transport for PipeTransport {
)
.await
?
;
self
.inner.handlers.new_data_consumer
.call
(|
callback
|
{
callback
(
&
data_consumer
);
});
self
.inner
.handlers
.new_data_consumer
.call_simple
(
&
data_consumer
);
Ok
(
data_consumer
)
}
...
...
@@ -364,35 +362,35 @@ impl Transport for PipeTransport {
fn
on_new_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_producer
.add
(
callback
)
}
fn
on_new_consumer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_consumer
.add
(
callback
)
}
fn
on_new_data_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_data_producer
.add
(
callback
)
}
fn
on_new_data_consumer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.new_data_consumer
.add
(
callback
)
}
fn
on_trace
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
callback
)
}
...
...
@@ -419,13 +417,21 @@ impl TransportGeneric for PipeTransport {
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
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
>
{
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 {
&
self
.inner.next_mid_for_consumers
}
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Hash
Map
<
u16
,
bool
>>
{
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Int
Map
<
u16
,
bool
>>
{
&
self
.inner.used_sctp_stream_ids
}
...
...
@@ -479,7 +485,7 @@ impl PipeTransport {
let
data
=
Arc
::
clone
(
&
data
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
SctpStateChange
{
sctp_state
}
=>
{
data
.sctp_state
.lock
()
.replace
(
sctp_state
);
...
...
@@ -489,9 +495,7 @@ impl PipeTransport {
});
}
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
callback
(
&
trace_event_data
);
});
handlers
.trace
.call_simple
(
&
trace_event_data
);
}
},
Err
(
error
)
=>
{
...
...
@@ -503,7 +507,7 @@ impl PipeTransport {
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
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
{
for
i
in
0
..
sctp_parameters
.mis
{
used_used_sctp_stream_ids
.insert
(
i
,
false
);
...
...
@@ -555,7 +559,7 @@ impl PipeTransport {
let
response
=
self
.inner
.channel
.request
(
TransportConnect
RequestPipe
{
.request
(
TransportConnect
PipeRequest
{
internal
:
self
.get_internal
(),
data
:
TransportConnectRequestPipeData
{
ip
:
remote_parameters
.ip
,
...
...
@@ -617,7 +621,7 @@ impl PipeTransport {
&
self
,
callback
:
F
,
)
->
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.
...
...
@@ -628,7 +632,7 @@ impl PipeTransport {
self
.inner
.handlers
.sctp_state_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
/// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance.
...
...
rust/src/router/plain_transport.rs
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
rust/src/router/producer.rs
浏览文件 @
f0ebd809
...
...
@@ -16,13 +16,12 @@ use crate::worker::{
Channel
,
NotificationError
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
use
async_executor
::
Executor
;
use
bytes
::
Bytes
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
hash_hasher
::
HashedMap
;
use
log
::{
debug
,
error
};
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde_repr
::{
Deserialize_repr
,
Serialize_repr
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
fmt
::
Debug
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
...
...
@@ -101,7 +100,7 @@ pub struct RtpStreamRecv {
pub
packet_count
:
usize
,
pub
byte_count
:
usize
,
pub
bitrate
:
u32
,
pub
bitrate_by_layer
:
Option
<
HashMap
<
String
,
u32
>>
,
pub
bitrate_by_layer
:
Option
<
Hash
ed
Map
<
String
,
u32
>>
,
}
#[derive(Debug,
Clone,
PartialEq,
Deserialize,
Serialize)]
...
...
@@ -202,7 +201,7 @@ pub struct ProducerStat {
pub
rtx_packets_discarded
:
Option
<
u32
>
,
// RtpStreamRecv specific.
pub
jitter
:
u32
,
pub
bitrate_by_layer
:
Option
<
HashMap
<
String
,
u32
>>
,
pub
bitrate_by_layer
:
Option
<
Hash
ed
Map
<
String
,
u32
>>
,
}
/// 'trace' event data.
...
...
@@ -280,11 +279,11 @@ enum Notification {
#[derive(Default)]
struct
Handlers
{
score
:
Bag
<
Box
<
dyn
Fn
(
&
Vec
<
ProducerScore
>
)
+
Send
+
Sync
>>
,
video_orientation_change
:
Bag
<
Box
<
dyn
Fn
(
ProducerVideoOrientation
)
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
ProducerTraceEventData
)
+
Send
+
Sync
>
>
,
score
:
Bag
<
Arc
<
dyn
Fn
(
&
[
ProducerScore
]
)
+
Send
+
Sync
>>
,
video_orientation_change
:
Bag
<
Arc
<
dyn
Fn
(
ProducerVideoOrientation
)
+
Send
+
Sync
>>
,
pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
ProducerTraceEventData
)
+
Send
+
Sync
>
,
ProducerTraceEventData
>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
...
...
@@ -459,7 +458,7 @@ impl Producer {
let
score
=
Arc
::
clone
(
&
score
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Score
(
scores
)
=>
{
*
score
.lock
()
=
scores
.clone
();
...
...
@@ -473,9 +472,7 @@ impl Producer {
});
}
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
callback
(
&
trace_event_data
);
});
handlers
.trace
.call_simple
(
&
trace_event_data
);
}
},
Err
(
error
)
=>
{
...
...
@@ -666,11 +663,11 @@ impl Producer {
}
/// 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
,
callback
:
F
,
)
->
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
...
...
@@ -683,17 +680,17 @@ impl Producer {
self
.inner
()
.handlers
.video_orientation_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
/// Callback is called when the producer is paused.
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.
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.
...
...
@@ -701,7 +698,7 @@ impl Producer {
&
self
,
callback
:
F
,
)
->
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
...
...
@@ -763,20 +760,17 @@ impl Producer {
impl
DirectProducer
{
/// Sends a RTP packet from the Rust process.
pub
async
fn
send
(
&
self
,
rtp_packet
:
Bytes
)
->
Result
<
(),
NotificationError
>
{
self
.inner
.payload_channel
.notify
(
ProducerSendNotification
{
internal
:
ProducerInternal
{
router_id
:
self
.inner.transport
.router_id
(),
transport_id
:
self
.inner.transport
.id
(),
producer_id
:
self
.inner.id
,
},
pub
fn
send
(
&
self
,
rtp_packet
:
Vec
<
u8
>
)
->
Result
<
(),
NotificationError
>
{
self
.inner.payload_channel
.notify
(
ProducerSendNotification
{
internal
:
ProducerInternal
{
router_id
:
self
.inner.transport
.router_id
(),
transport_id
:
self
.inner.transport
.id
(),
producer_id
:
self
.inner.id
,
},
rtp_packet
,
)
.await
}
,
rtp_packet
,
)
}
}
...
...
rust/src/router/transport.rs
浏览文件 @
f0ebd809
...
...
@@ -23,13 +23,14 @@ use crate::{ortc, uuid_based_wrapper_type};
use
async_executor
::
Executor
;
use
async_trait
::
async_trait
;
use
event_listener_primitives
::
HandlerId
;
use
hash_hasher
::
HashedMap
;
use
log
::{
error
,
warn
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
serde
::
de
::
DeserializeOwned
;
use
serde
::{
Deserialize
,
Serialize
};
use
s
td
::
collections
::
HashMap
;
use
s
erde_json
::
Value
;
use
std
::
fmt
::
Debug
;
use
std
::
marker
::
PhantomData
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
use
thiserror
::
Error
;
...
...
@@ -103,11 +104,11 @@ pub enum TransportTraceEventType {
#[doc(hidden)]
pub
struct
RtpListener
{
/// Map from Ssrc (as string) to producer ID
pub
mid_table
:
HashMap
<
String
,
ProducerId
>
,
pub
mid_table
:
Hash
ed
Map
<
String
,
ProducerId
>
,
/// Map from Ssrc (as string) to producer ID
pub
rid_table
:
HashMap
<
String
,
ProducerId
>
,
pub
rid_table
:
Hash
ed
Map
<
String
,
ProducerId
>
,
/// Map from Ssrc (as string) to producer ID
pub
ssrc_table
:
HashMap
<
String
,
ProducerId
>
,
pub
ssrc_table
:
Hash
ed
Map
<
String
,
ProducerId
>
,
}
#[derive(Debug,
Copy,
Clone,
Ord,
PartialOrd,
Eq,
PartialEq,
Hash,
Deserialize,
Serialize)]
...
...
@@ -126,7 +127,7 @@ pub struct RecvRtpHeaderExtensions {
#[doc(hidden)]
pub
struct
SctpListener
{
/// Map from stream ID (as string) to data producer ID
stream_id_table
:
HashMap
<
String
,
DataProducerId
>
,
stream_id_table
:
Hash
ed
Map
<
String
,
DataProducerId
>
,
}
#[derive(Debug,
Copy,
Clone,
PartialEq)]
...
...
@@ -236,31 +237,31 @@ pub trait Transport: Debug + Send + Sync + private::CloneTransport {
/// Callback is called when a new producer is created.
fn
on_new_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
/// Callback is called when a new consumer is created.
fn
on_new_consumer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
/// Callback is called when a new data producer is created.
fn
on_new_data_producer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
/// Callback is called when a new data consumer is created.
fn
on_new_data_consumer
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
/// See [`Transport::enable_trace_event()`]
fn
on_trace
(
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
/// Callback is called when the router this transport belongs to is closed for whatever reason.
...
...
@@ -371,7 +372,7 @@ pub(super) trait TransportImpl: TransportGeneric {
fn
next_mid_for_consumers
(
&
self
)
->
&
AtomicUsize
;
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Hash
Map
<
u16
,
bool
>>
;
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Int
Map
<
u16
,
bool
>>
;
fn
cname_for_producers
(
&
self
)
->
&
Mutex
<
Option
<
String
>>
;
...
...
@@ -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
()
.request
(
TransportDumpRequest
{
internal
:
TransportInternal
{
router_id
:
self
.router
()
.id
(),
transport_id
:
self
.id
(),
},
phantom_data
:
PhantomData
{},
})
.await
}
async
fn
get_stats_impl
(
&
self
)
->
Result
<
V
ec
<
Self
::
Stat
>
,
RequestError
>
{
async
fn
get_stats_impl
(
&
self
)
->
Result
<
V
alue
,
RequestError
>
{
self
.channel
()
.request
(
TransportGetStatsRequest
{
internal
:
TransportInternal
{
router_id
:
self
.router
()
.id
(),
transport_id
:
self
.id
(),
},
phantom_data
:
PhantomData
{},
})
.await
}
...
...
rust/src/router/webrtc_transport.rs
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
rust/src/worker.rs
浏览文件 @
f0ebd809
//! A worker represents a mediasoup C++ thread that runs on a single CPU core and handles
//! [`Router`] instances.
// TODO: This is Unix-specific and doesn't support Windows in any way
mod
channel
;
mod
common
;
mod
payload_channel
;
...
...
@@ -25,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId};
use
futures_lite
::
FutureExt
;
use
log
::{
debug
,
error
,
warn
};
use
parking_lot
::
Mutex
;
pub
(
crate
)
use
payload_channel
::{
NotificationError
,
NotificationMessage
,
PayloadChannel
};
pub
(
crate
)
use
payload_channel
::{
NotificationError
,
PayloadChannel
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
ops
::
RangeInclusive
;
use
std
::
path
::
PathBuf
;
...
...
@@ -40,18 +39,12 @@ uuid_based_wrapper_type!(
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)]
pub
enum
RequestError
{
/// Channel already closed.
#[error(
"Channel already closed"
)]
ChannelClosed
,
/// Message is too long.
#[error(
"Message is too long"
)]
MessageTooLong
,
/// Payload is too long.
#[error(
"Payload is too long"
)]
PayloadTooLong
,
/// Request timed out.
#[error(
"Request timed out"
)]
TimedOut
,
...
...
@@ -171,7 +164,7 @@ pub struct WorkerDtlsFiles {
}
/// Settings for worker to be created with.
#[derive(
Debug,
Clone)]
#[derive(Clone)]
#[non_exhaustive]
pub
struct
WorkerSettings
{
/// Logging level for logs generated by the media worker thread.
...
...
@@ -187,6 +180,9 @@ pub struct WorkerSettings {
///
/// If `None`, a certificate is dynamically created.
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.
pub
app_data
:
AppData
,
}
...
...
@@ -198,11 +194,37 @@ impl Default for WorkerSettings {
log_tags
:
Vec
::
new
(),
rtc_ports_range
:
10000
..=
59999
,
dtls_files
:
None
,
thread_initializer
:
None
,
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.
#[derive(Default,
Debug,
Clone,
Serialize)]
#[serde(rename_all
=
"camelCase"
)]
...
...
@@ -241,7 +263,7 @@ pub enum CreateRouterError {
#[derive(Default)]
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)]
dead
:
BagOnce
<
Box
<
dyn
FnOnce
(
Result
<
(),
ExitError
>
)
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
...
...
@@ -271,11 +293,12 @@ impl Inner {
async
fn
new
<
OE
:
FnOnce
()
+
Send
+
'static
>
(
executor
:
Arc
<
Executor
<
'static
>>
,
WorkerSettings
{
app_data
,
log_level
,
log_tags
,
rtc_ports_range
,
dtls_files
,
thread_initializer
,
app_data
,
}:
WorkerSettings
,
worker_manager
:
WorkerManager
,
on_exit
:
OE
,
...
...
@@ -327,7 +350,7 @@ impl Inner {
channel
,
payload_channel
,
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
);
on_exit
();
});
...
...
@@ -405,7 +428,7 @@ impl Inner {
let
_handler
=
self
.channel
.subscribe_to_notifications
(
std
::
process
::
id
()
.into
(),
move
|
notification
|
{
let
result
=
match
serde_json
::
from_
value
(
notification
.clone
()
)
{
let
result
=
match
serde_json
::
from_
slice
(
notification
)
{
Ok
(
Notification
::
Running
)
=>
{
debug!
(
"worker thread running [id:{}]"
,
id
);
Ok
(())
...
...
@@ -601,16 +624,14 @@ impl Worker {
self
.clone
(),
);
self
.inner.handlers.new_router
.call
(|
callback
|
{
callback
(
&
router
);
});
self
.inner.handlers.new_router
.call_simple
(
&
router
);
Ok
(
router
)
}
/// Callback is called when a new router is created.
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.
...
...
rust/src/worker/channel.rs
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
rust/src/worker/common.rs
浏览文件 @
f0ebd809
use
hash_hasher
::
HashedMap
;
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
s
td
::
collections
::
HashMap
;
use
s
erde
::
Deserialize
;
use
std
::
sync
::{
Arc
,
Weak
};
use
uuid
::
Uuid
;
struct
EventHandlersList
<
V
:
Clone
+
'static
>
{
struct
EventHandlersList
<
F
>
{
index
:
usize
,
#[allow(clippy
::
type_complexity)]
callbacks
:
HashMap
<
usize
,
Arc
<
Box
<
dyn
Fn
(
V
)
+
Send
+
Sync
>>>
,
callbacks
:
IntMap
<
usize
,
F
>
,
}
impl
<
V
:
Clone
+
'static
>
Default
for
EventHandlersList
<
V
>
{
impl
<
F
>
Default
for
EventHandlersList
<
F
>
{
fn
default
()
->
Self
{
Self
{
index
:
0
,
callbacks
:
HashMap
::
new
(),
callbacks
:
IntMap
::
default
(),
}
}
}
#[derive(Clone)]
pub
(
super
)
struct
EventHandlers
<
V
:
Clone
+
'static
>
{
handlers
:
Arc
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
EventHandlersList
<
V
>>>>
,
pub
(
super
)
struct
EventHandlers
<
F
>
{
handlers
:
Arc
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
EventHandlersList
<
F
>>>>
,
}
impl
<
V
:
Clone
+
'static
>
EventHandlers
<
V
>
{
impl
<
F
:
Sized
+
Send
+
Sync
+
'static
>
EventHandlers
<
F
>
{
pub
(
super
)
fn
new
()
->
Self
{
let
handlers
=
Arc
::
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
EventHandlersList
<
V
>>>>
::
default
();
let
handlers
=
Arc
::
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
EventHandlersList
<
F
>>>>
::
default
();
Self
{
handlers
}
}
pub
(
super
)
fn
add
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
Box
<
dyn
Fn
(
V
)
+
Send
+
Sync
+
'static
>
,
)
->
SubscriptionHandler
{
pub
(
super
)
fn
add
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
F
)
->
SubscriptionHandler
{
let
index
;
{
let
mut
event_handlers
=
self
.handlers
.lock
();
...
...
@@ -42,7 +39,7 @@ impl<V: Clone + 'static> EventHandlers<V> {
.or_insert_with
(
EventHandlersList
::
default
);
index
=
list
.index
;
list
.index
+=
1
;
list
.callbacks
.insert
(
index
,
Arc
::
new
(
Box
::
new
(
callback
))
);
list
.callbacks
.insert
(
index
,
callback
);
drop
(
event_handlers
);
}
...
...
@@ -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
();
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
);
for
callback
in
list
.callbacks
.values
()
{
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
>
{
WeakEventHandlers
{
handlers
:
Arc
::
downgrade
(
&
self
.handlers
),
impl
<
V1
:
?
Sized
,
V2
:
?
Sized
>
EventHandlers
<
Arc
<
dyn
Fn
(
&
V1
,
&
V2
)
+
Send
+
Sync
+
'static
>>
{
pub
(
super
)
fn
call_callbacks_with_two_values
(
&
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)]
pub
(
super
)
struct
WeakEventHandlers
<
V
:
Clone
+
'static
>
{
handlers
:
Weak
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
EventHandlersList
<
V
>>>>
,
pub
(
super
)
struct
WeakEventHandlers
<
F
>
{
handlers
:
Weak
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
EventHandlersList
<
F
>>>>
,
}
impl
<
V
:
Clone
+
'static
>
WeakEventHandlers
<
V
>
{
pub
(
super
)
fn
upgrade
(
&
self
)
->
Option
<
EventHandlers
<
V
>>
{
impl
<
F
>
WeakEventHandlers
<
F
>
{
pub
(
super
)
fn
upgrade
(
&
self
)
->
Option
<
EventHandlers
<
F
>>
{
self
.handlers
.upgrade
()
.map
(|
handlers
|
EventHandlers
{
handlers
})
}
}
#[derive(Copy,
Clone,
Eq,
PartialEq,
Hash)]
#[derive(Debug,
Copy,
Clone,
Eq,
PartialEq,
Hash,
Deserialize)]
#[serde(untagged)]
pub
(
crate
)
enum
SubscriptionTarget
{
Uuid
(
Uuid
),
Number
(
u
32
),
Number
(
u
64
),
}
impl
From
<
u32
>
for
SubscriptionTarget
{
fn
from
(
number
:
u32
)
->
Self
{
Self
::
Number
(
u64
::
from
(
number
))
}
}
impl
From
<
u64
>
for
SubscriptionTarget
{
fn
from
(
number
:
u64
)
->
Self
{
Self
::
Number
(
number
)
}
}
...
...
rust/src/worker/payload_channel.rs
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
rust/src/worker/utils.rs
浏览文件 @
f0ebd809
// 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
,
PayloadChannel
,
WorkerId
};
use
async_executor
::
Executor
;
use
async_fs
::
File
;
pub
(
super
)
use
channel_read_fn
::{
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
::
mem
;
use
std
::
os
::
raw
::{
c_char
,
c_int
};
use
std
::
os
::
unix
::
io
::
FromRawFd
;
use
std
::
sync
::
Arc
;
use
thiserror
::
Error
;
...
...
@@ -30,18 +36,6 @@ pub enum ExitError {
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
)
channel
:
Channel
,
pub
(
super
)
payload_channel
:
PayloadChannel
,
...
...
@@ -50,31 +44,24 @@ pub(super) struct WorkerRunResult {
pub
(
super
)
fn
run_worker_with_channels
<
OE
>
(
id
:
WorkerId
,
executor
:
Arc
<
Executor
<
'stati
c
>>
,
thread_initializer
:
Option
<
Arc
<
dyn
Fn
()
+
Send
+
Syn
c
>>
,
args
:
Vec
<
String
>
,
on_exit
:
OE
,
)
->
WorkerRunResult
where
OE
:
FnOnce
(
Result
<
(),
ExitError
>
)
+
Send
+
'static
,
{
let
[
producer_fd_read
,
producer_fd_write
]
=
pipe
();
let
[
consumer_fd_read
,
consumer_fd_write
]
=
pipe
();
let
[
producer_payload_fd_read
,
producer_payload_fd_write
]
=
pipe
();
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
(
channel
,
prepared_channel_read
,
prepared_channel_write
)
=
Channel
::
new
();
let
(
payload_channel
,
prepared_payload_channel_read
,
prepared_payload_channel_write
)
=
PayloadChannel
::
new
();
let
buffer_worker_messages_guard
=
channel
.buffer_messages_for
(
std
::
process
::
id
()
.into
());
std
::
thread
::
Builder
::
new
()
.name
(
format!
(
"mediasoup-worker-{}"
,
id
))
.spawn
(
move
||
{
if
let
Some
(
thread_initializer
)
=
thread_initializer
{
thread_initializer
();
}
let
argc
=
args
.len
()
as
c_int
;
let
args_cstring
=
args
.into_iter
()
...
...
@@ -85,15 +72,39 @@ where
.map
(|
arg
|
arg
.as_ptr
()
.cast
::
<
c_char
>
())
.collect
::
<
Vec
<
_
>>
();
let
version
=
CString
::
new
(
env!
(
"CARGO_PKG_VERSION"
))
.unwrap
();
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
,
argv
.as_ptr
(),
version
.as_ptr
(),
producer_fd_read
,
consumer_fd_write
,
producer_payload_fd_read
,
consumer_payload_fd_write
,
0
,
0
,
0
,
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
,
)
};
...
...
rust/src/worker/utils/channel_read_fn.rs
0 → 100644
浏览文件 @
f0ebd809
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
),
}
}
rust/src/worker/utils/channel_write_fn.rs
0 → 100644
浏览文件 @
f0ebd809
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
),
}
}
rust/src/worker_manager.rs
浏览文件 @
f0ebd809
...
...
@@ -18,7 +18,7 @@ use std::{fmt, io, mem};
#[derive(Default)]
struct
Handlers
{
new_worker
:
Bag
<
Box
<
dyn
Fn
(
&
Worker
)
+
Send
+
Sync
>
>
,
new_worker
:
Bag
<
Arc
<
dyn
Fn
(
&
Worker
)
+
Send
+
Sync
>
,
Worker
>
,
}
struct
Inner
{
...
...
@@ -145,9 +145,7 @@ impl WorkerManager {
)
.await
?
;
self
.inner.handlers.new_worker
.call
(|
callback
|
{
callback
(
&
worker
);
});
self
.inner.handlers.new_worker
.call_simple
(
&
worker
);
id
.lock
()
.replace
(
worker
.id
());
...
...
@@ -158,6 +156,6 @@ impl WorkerManager {
/// Callback is called when a new worker is created.
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
))
}
}
rust/tests/integration/consumer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
consumer
::{
ConsumableRtpEncoding
,
ConsumerLayers
,
ConsumerOptions
,
ConsumerScore
,
ConsumerType
,
};
...
...
@@ -20,7 +21,6 @@ use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTra
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
parking_lot
::
Mutex
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
...
...
@@ -350,7 +350,7 @@ fn consume_succeeds() {
.on_new_consumer
({
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
);
})
})
...
...
@@ -421,13 +421,13 @@ fn consume_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
audio_consumer
.id
());
set
});
map
.insert
(
video_producer
.id
(),
Hash
Set
::
new
());
map
.insert
(
video_producer
.id
(),
Hash
edSet
::
default
());
map
});
...
...
@@ -525,14 +525,14 @@ fn consume_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
audio_consumer
.id
());
set
});
map
.insert
(
video_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
video_consumer
.id
());
set
});
...
...
@@ -620,14 +620,14 @@ fn consume_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
audio_consumer
.id
());
set
});
map
.insert
(
video_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
video_consumer
.id
());
set
.insert
(
video_pipe_consumer
.id
());
set
...
...
@@ -1387,11 +1387,11 @@ fn close_event() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
map
.insert
(
audio_producer
.id
(),
Hash
Set
::
new
());
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
Hash
edSet
::
default
());
map
});
assert_eq!
(
dump
.map_consumer_id_producer_id
,
Hash
Map
::
new
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
Hash
edMap
::
default
());
}
{
...
...
rust/tests/integration/data_consumer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_consumer
::{
DataConsumerOptions
,
DataConsumerType
};
use
mediasoup
::
data_producer
::{
DataProducer
,
DataProducerOptions
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
...
...
@@ -11,7 +12,6 @@ use mediasoup::sctp_parameters::SctpStreamParameters;
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
...
...
@@ -105,7 +105,7 @@ fn consume_data_succeeds() {
.on_new_data_consumer
({
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
);
})
})
...
...
@@ -154,16 +154,16 @@ fn consume_data_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
data_consumer
.id
());
set
});
map
});
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_consumer
.id
(),
data_producer
.id
());
map
});
...
...
@@ -316,7 +316,7 @@ fn consume_data_on_direct_transport_succeeds() {
.on_new_data_consumer
({
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
);
})
})
...
...
@@ -478,11 +478,14 @@ fn close_event() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
map
.insert
(
data_producer
.id
(),
Hash
Set
::
new
());
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer
.id
(),
Hash
edSet
::
default
());
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
()
);
}
{
...
...
rust/tests/integration/data_producer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_producer
::{
DataProducerOptions
,
DataProducerType
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
plain_transport
::{
PlainTransport
,
PlainTransportOptions
};
...
...
@@ -10,7 +11,6 @@ use mediasoup::transport::ProduceDataError;
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
...
...
@@ -86,7 +86,7 @@ fn transport_1_produce_data_succeeds() {
.on_new_data_producer
({
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
);
})
})
...
...
@@ -131,11 +131,14 @@ fn transport_1_produce_data_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
map
.insert
(
data_producer1
.id
(),
Hash
Set
::
new
());
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer1
.id
(),
Hash
edSet
::
default
());
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() {
.on_new_data_producer
({
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
);
})
})
...
...
@@ -205,11 +208,14 @@ fn transport_2_produce_data_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
map
.insert
(
data_producer2
.id
(),
Hash
Set
::
new
());
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer2
.id
(),
Hash
edSet
::
default
());
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() {
{
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
HashedMap
::
default
()
);
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
}
{
...
...
rust/tests/integration/direct_transport.rs
浏览文件 @
f0ebd809
use
bytes
::
Bytes
;
use
futures_lite
::
future
;
use
hash_hasher
::
HashedSet
;
use
mediasoup
::
data_consumer
::
DataConsumerOptions
;
use
mediasoup
::
data_producer
::{
DataProducer
,
DataProducerOptions
};
use
mediasoup
::
data_structures
::{
AppData
,
WebRtcMessage
};
...
...
@@ -9,7 +9,7 @@ use mediasoup::router::{Router, RouterOptions};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
parking_lot
::
Mutex
;
use
std
::
collections
::
HashSet
;
use
std
::
borrow
::
Cow
;
use
std
::
env
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
...
...
@@ -56,7 +56,7 @@ fn create_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.transport_ids
,
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
transport
.id
());
set
});
...
...
@@ -240,14 +240,13 @@ fn send_succeeds() {
sent_message_bytes
+=
content
.len
();
WebRtcMessage
::
String
(
content
)
}
else
{
let
content
=
Bytes
::
from
(
id
.to_string
()
.into_bytes
()
);
let
content
=
id
.to_string
()
.into_bytes
(
);
sent_message_bytes
+=
content
.len
();
WebRtcMessage
::
Binary
(
content
)
WebRtcMessage
::
Binary
(
Cow
::
from
(
content
)
)
};
direct_data_producer
.send
(
message
)
.await
.expect
(
"Failed to send message"
);
if
id
==
num_messages
{
...
...
rust/tests/integration/plain_transport.rs
浏览文件 @
f0ebd809
use
futures_lite
::
future
;
use
hash_hasher
::
HashedSet
;
use
mediasoup
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportProtocol
,
TransportTuple
,
};
...
...
@@ -12,7 +13,6 @@ use mediasoup::sctp_parameters::SctpParameters;
use
mediasoup
::
srtp_parameters
::{
SrtpCryptoSuite
,
SrtpParameters
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::
HashSet
;
use
std
::
env
;
use
std
::
net
::
IpAddr
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
...
...
@@ -104,7 +104,7 @@ fn create_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
router_dump
.transport_ids
,
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
transport
.id
());
set
});
...
...
rust/tests/integration/producer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
prelude
::
*
;
use
mediasoup
::
producer
::{
ProducerOptions
,
ProducerTraceEventType
,
ProducerType
};
...
...
@@ -14,7 +15,6 @@ use mediasoup::transport::ProduceError;
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
...
...
@@ -229,7 +229,7 @@ fn produce_succeeds() {
.on_new_producer
({
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
);
})
})
...
...
@@ -266,11 +266,14 @@ fn produce_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
map
.insert
(
audio_producer
.id
(),
Hash
Set
::
new
());
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
Hash
edSet
::
default
());
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
.dump
()
...
...
@@ -279,6 +282,19 @@ fn produce_succeeds() {
assert_eq!
(
transport_1_dump
.producer_ids
,
vec!
[
audio_producer
.id
()]);
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() {
.on_new_producer
({
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
);
})
})
...
...
@@ -325,11 +341,14 @@ fn produce_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
map
.insert
(
video_producer
.id
(),
Hash
Set
::
new
());
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
video_producer
.id
(),
Hash
edSet
::
default
());
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
.dump
()
...
...
@@ -903,8 +922,8 @@ fn close_event() {
{
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
Hash
Map
::
new
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
Hash
Map
::
new
());
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
Hash
edMap
::
default
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
Hash
edMap
::
default
());
}
{
...
...
rust/tests/integration/router.rs
浏览文件 @
f0ebd809
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_structures
::
AppData
;
use
mediasoup
::
router
::
RouterOptions
;
use
mediasoup
::
rtp_parameters
::{
...
...
@@ -6,7 +7,6 @@ use mediasoup::rtp_parameters::{
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
...
...
@@ -106,13 +106,19 @@ fn create_router_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.id
,
router
.id
());
assert_eq!
(
dump
.transport_ids
,
HashSet
::
new
());
assert_eq!
(
dump
.rtp_observer_ids
,
HashSet
::
new
());
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
HashMap
::
new
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.map_producer_id_observer_ids
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.transport_ids
,
HashedSet
::
default
());
assert_eq!
(
dump
.rtp_observer_ids
,
HashedSet
::
default
());
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
HashedMap
::
default
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
HashedMap
::
default
());
assert_eq!
(
dump
.map_producer_id_observer_ids
,
HashedMap
::
default
());
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
HashedMap
::
default
()
);
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
});
}
...
...
rust/tests/integration/webrtc_transport.rs
浏览文件 @
f0ebd809
use
futures_lite
::
future
;
use
hash_hasher
::
HashedSet
;
use
mediasoup
::
data_structures
::{
AppData
,
DtlsFingerprint
,
DtlsParameters
,
DtlsRole
,
DtlsState
,
IceCandidateTcpType
,
IceCandidateType
,
IceRole
,
IceState
,
SctpState
,
TransportListenIp
,
TransportProtocol
,
...
...
@@ -15,7 +16,6 @@ use mediasoup::webrtc_transport::{
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::
HashSet
;
use
std
::
convert
::
TryInto
;
use
std
::
env
;
use
std
::
net
::
IpAddr
;
...
...
@@ -104,7 +104,7 @@ fn create_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
router_dump
.transport_ids
,
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
transport
.id
());
set
});
...
...
worker/build.rs
浏览文件 @
f0ebd809
...
...
@@ -7,6 +7,12 @@ fn main() {
return
;
}
let
build_type
=
if
cfg!
(
debug_assertions
)
{
"Debug"
}
else
{
"Release"
};
let
out_dir
=
env
::
var
(
"OUT_DIR"
)
.unwrap
();
// Add C++ std lib
...
...
@@ -79,9 +85,8 @@ fn main() {
// Build
if
!
Command
::
new
(
"make"
)
.arg
(
"libmediasoup-worker"
)
.env
(
"PYTHONDONTWRITEBYTECODE"
,
"1"
)
.env
(
"MEDIASOUP_OUT_DIR"
,
&
out_dir
)
.env
(
"MEDIASOUP_BUILDTYPE"
,
"Release"
)
.env
(
"MEDIASOUP_BUILDTYPE"
,
&
build_type
)
.spawn
()
.expect
(
"Failed to start"
)
.wait
()
...
...
@@ -95,7 +100,6 @@ fn main() {
// Clean
if
!
Command
::
new
(
"make"
)
.arg
(
"clean-all"
)
.env
(
"PYTHONDONTWRITEBYTECODE"
,
"1"
)
.spawn
()
.expect
(
"Failed to start"
)
.wait
()
...
...
@@ -108,6 +112,5 @@ fn main() {
}
println!
(
"cargo:rustc-link-lib=static=mediasoup-worker"
);
println!
(
"cargo:rustc-link-search=native={}"
,
out_dir
);
println!
(
"cargo:rustc-link-search=native={}/Release"
,
out_dir
);
println!
(
"cargo:rustc-link-search=native={}/{}"
,
out_dir
,
build_type
);
}
worker/include/Channel/ChannelNotifier.hpp
浏览文件 @
f0ebd809
...
...
@@ -12,6 +12,7 @@ namespace Channel
{
public
:
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
,
json
&
data
);
...
...
worker/include/Channel/ChannelSocket.hpp
浏览文件 @
f0ebd809
...
...
@@ -64,16 +64,22 @@ namespace Channel
public
:
explicit
ChannelSocket
(
int
consumerFd
,
int
producerFd
);
explicit
ChannelSocket
(
ChannelReadFn
channelReadFn
,
ChannelReadCtx
channelReadCtx
,
ChannelWriteFn
channelWriteFn
,
ChannelWriteCtx
channelWriteCtx
);
virtual
~
ChannelSocket
();
public
:
void
Close
();
void
SetListener
(
Listener
*
listener
);
bool
CallbackRead
();
void
Send
(
json
&
jsonMessage
);
void
SendLog
(
char
*
message
,
uint32_t
messageLen
);
void
SendLog
(
c
onst
c
har
*
message
,
uint32_t
messageLen
);
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. */
public
:
...
...
@@ -85,9 +91,14 @@ namespace Channel
Listener
*
listener
{
nullptr
};
// Others.
bool
closed
{
false
};
ConsumerSocket
consumerSocket
;
ProducerSocket
producerSocket
;
uint8_t
*
writeBuffer
;
ConsumerSocket
*
consumerSocket
{
nullptr
};
ProducerSocket
*
producerSocket
{
nullptr
};
ChannelReadFn
channelReadFn
{
nullptr
};
ChannelReadCtx
channelReadCtx
{
nullptr
};
ChannelWriteFn
channelWriteFn
{
nullptr
};
ChannelWriteCtx
channelWriteCtx
{
nullptr
};
uv_async_t
*
uvReadHandle
{
nullptr
};
uint8_t
*
writeBuffer
{
nullptr
};
};
}
// namespace Channel
...
...
worker/include/Logger.hpp
浏览文件 @
f0ebd809
...
...
@@ -132,7 +132,7 @@ public:
static
void
ClassInit
(
Channel
::
ChannelSocket
*
channel
);
public
:
static
const
int64_t
pid
;
static
const
u
int64_t
pid
;
thread_local
static
Channel
::
ChannelSocket
*
channel
;
static
const
size_t
bufferSize
{
50000
};
thread_local
static
char
buffer
[];
...
...
worker/include/PayloadChannel/PayloadChannelSocket.hpp
浏览文件 @
f0ebd809
...
...
@@ -71,16 +71,24 @@ namespace PayloadChannel
public
:
explicit
PayloadChannelSocket
(
int
consumerFd
,
int
producerFd
);
explicit
PayloadChannelSocket
(
PayloadChannelReadFn
payloadChannelReadFn
,
PayloadChannelReadCtx
payloadChannelReadCtx
,
PayloadChannelWriteFn
payloadChannelWriteFn
,
PayloadChannelWriteCtx
payloadChannelWriteCtx
);
virtual
~
PayloadChannelSocket
();
public
:
void
Close
();
void
SetListener
(
Listener
*
listener
);
bool
CallbackRead
();
void
Send
(
json
&
jsonMessage
,
const
uint8_t
*
payload
,
size_t
payloadLen
);
void
Send
(
json
&
jsonMessage
);
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. */
public
:
...
...
@@ -92,11 +100,16 @@ namespace PayloadChannel
Listener
*
listener
{
nullptr
};
// Others.
bool
closed
{
false
};
ConsumerSocket
consumerSocket
;
ProducerSocket
producerSocket
;
ConsumerSocket
*
consumerSocket
{
nullptr
};
ProducerSocket
*
producerSocket
{
nullptr
};
PayloadChannelReadFn
payloadChannelReadFn
{
nullptr
};
PayloadChannelReadCtx
payloadChannelReadCtx
{
nullptr
};
PayloadChannelWriteFn
payloadChannelWriteFn
{
nullptr
};
PayloadChannelWriteCtx
payloadChannelWriteCtx
{
nullptr
};
PayloadChannel
::
Notification
*
ongoingNotification
{
nullptr
};
PayloadChannel
::
PayloadChannelRequest
*
ongoingRequest
{
nullptr
};
uint8_t
*
writeBuffer
;
uv_async_t
*
uvReadHandle
{
nullptr
};
uint8_t
*
writeBuffer
{
nullptr
};
};
}
// namespace PayloadChannel
...
...
worker/include/common.hpp
浏览文件 @
f0ebd809
...
...
@@ -23,4 +23,43 @@ typedef SSIZE_T ssize_t;
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#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
worker/include/lib.hpp
浏览文件 @
f0ebd809
extern
"C"
int
run_worker
(
#include "common.hpp"
extern
"C"
int
mediasoup_worker_run
(
int
argc
,
char
*
argv
[],
const
char
*
version
,
int
consumerChannelFd
,
int
producerChannelFd
,
int
payloadConsumeChannelFd
,
int
payloadProduceChannelFd
);
int
payloadProduceChannelFd
,
ChannelReadFn
channelReadFn
,
ChannelReadCtx
channelReadCtx
,
ChannelWriteFn
channelWriteFn
,
ChannelWriteCtx
channelWriteCtx
,
PayloadChannelReadFn
payloadChannelReadFn
,
PayloadChannelReadCtx
payloadChannelReadCtx
,
PayloadChannelWriteFn
payloadChannelWriteFn
,
PayloadChannelWriteCtx
payloadChannelWriteCtx
);
worker/src/Channel/ChannelNotifier.cpp
浏览文件 @
f0ebd809
...
...
@@ -19,6 +19,20 @@ namespace 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
)
{
MS_TRACE
();
...
...
worker/src/Channel/ChannelSocket.cpp
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
worker/src/Logger.cpp
浏览文件 @
f0ebd809
...
...
@@ -6,7 +6,7 @@
/* Class variables. */
const
int64_t
Logger
::
pid
{
static_cast
<
int64_t
>
(
uv_os_getpid
())
};
const
uint64_t
Logger
::
pid
{
static_cast
<
u
int64_t
>
(
uv_os_getpid
())
};
thread_local
Channel
::
ChannelSocket
*
Logger
::
channel
{
nullptr
};
thread_local
char
Logger
::
buffer
[
Logger
::
bufferSize
];
...
...
worker/src/PayloadChannel/PayloadChannelSocket.cpp
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
worker/src/Worker.cpp
浏览文件 @
f0ebd809
...
...
@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel
DepUsrSCTP
::
CreateChecker
();
// 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"
);
DepLibUV
::
RunLoop
();
...
...
worker/src/lib.cpp
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
worker/src/lib.rs
浏览文件 @
f0ebd809
差异被折叠。
点击展开。
worker/src/main.cpp
浏览文件 @
f0ebd809
...
...
@@ -23,14 +23,22 @@ int main(int argc, char* argv[])
std
::
string
version
=
std
::
getenv
(
"MEDIASOUP_VERSION"
);
auto
statusCode
=
run_worker
(
auto
statusCode
=
mediasoup_worker_run
(
argc
,
argv
,
version
.
c_str
(),
ConsumerChannelFd
,
ProducerChannelFd
,
PayloadConsumerChannelFd
,
PayloadProducerChannelFd
);
PayloadProducerChannelFd
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
);
switch
(
statusCode
)
{
...
...
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论