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 个修改的文件
包含
1938 行增加
和
1218 行删除
+1938
-1218
mediasoup-rust.yaml
.github/workflows/mediasoup-rust.yaml
+0
-5
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
+9
-34
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
+4
-7
direct_transport.rs
rust/src/router/direct_transport.rs
+47
-49
pipe_transport.rs
rust/src/router/pipe_transport.rs
+44
-40
plain_transport.rs
rust/src/router/plain_transport.rs
+57
-52
producer.rs
rust/src/router/producer.rs
+18
-24
transport.rs
rust/src/router/transport.rs
+15
-16
webrtc_transport.rs
rust/src/router/webrtc_transport.rs
+51
-47
worker.rs
rust/src/worker.rs
+39
-18
channel.rs
rust/src/worker/channel.rs
+176
-218
common.rs
rust/src/worker/common.rs
+53
-38
payload_channel.rs
rust/src/worker/payload_channel.rs
+216
-317
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
+137
-10
Logger.cpp
worker/src/Logger.cpp
+1
-1
PayloadChannelSocket.cpp
worker/src/PayloadChannel/PayloadChannelSocket.cpp
+226
-17
Worker.cpp
worker/src/Worker.cpp
+1
-1
lib.cpp
worker/src/lib.cpp
+26
-2
lib.rs
worker/src/lib.rs
+80
-2
main.cpp
worker/src/main.cpp
+10
-2
没有找到文件。
.github/workflows/mediasoup-rust.yaml
浏览文件 @
f0ebd809
...
@@ -22,11 +22,6 @@ jobs:
...
@@ -22,11 +22,6 @@ jobs:
-
name
:
Checkout
-
name
:
Checkout
uses
:
actions/checkout@v2
uses
:
actions/checkout@v2
-
name
:
Node.js
uses
:
actions/setup-node@v2
with
:
node-version
:
'
14'
-
name
:
Rust toolchain
-
name
:
Rust toolchain
uses
:
actions-rs/toolchain@v1
uses
:
actions-rs/toolchain@v1
with
:
with
:
...
...
node/lib/Channel.js
浏览文件 @
f0ebd809
...
@@ -207,7 +207,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
...
@@ -207,7 +207,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// the response, destroying the ordered delivery. So we must wait a bit
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// here.
// See https://github.com/versatica/mediasoup/issues/510
// See https://github.com/versatica/mediasoup/issues/510
setImmediate
(()
=>
this
.
emit
(
msg
.
targetId
,
msg
.
event
,
msg
.
data
));
setImmediate
(()
=>
this
.
emit
(
String
(
msg
.
targetId
)
,
msg
.
event
,
msg
.
data
));
}
}
// Otherwise unexpected message.
// Otherwise unexpected message.
else
{
else
{
...
...
node/lib/PayloadChannel.js
浏览文件 @
f0ebd809
...
@@ -213,7 +213,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
...
@@ -213,7 +213,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
else
if
(
msg
.
targetId
&&
msg
.
event
)
{
else
if
(
msg
.
targetId
&&
msg
.
event
)
{
this
.
#
ongoingNotification
=
this
.
#
ongoingNotification
=
{
{
targetId
:
msg
.
targetId
,
targetId
:
String
(
msg
.
targetId
)
,
event
:
msg
.
event
,
event
:
msg
.
event
,
data
:
msg
.
data
data
:
msg
.
data
};
};
...
...
node/src/Channel.ts
浏览文件 @
f0ebd809
...
@@ -330,7 +330,7 @@ export class Channel extends EnhancedEventEmitter
...
@@ -330,7 +330,7 @@ export class Channel extends EnhancedEventEmitter
// the response, destroying the ordered delivery. So we must wait a bit
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// here.
// See https://github.com/versatica/mediasoup/issues/510
// See https://github.com/versatica/mediasoup/issues/510
setImmediate
(()
=>
this
.
emit
(
msg
.
targetId
,
msg
.
event
,
msg
.
data
));
setImmediate
(()
=>
this
.
emit
(
String
(
msg
.
targetId
)
,
msg
.
event
,
msg
.
data
));
}
}
// Otherwise unexpected message.
// Otherwise unexpected message.
else
else
...
...
node/src/PayloadChannel.ts
浏览文件 @
f0ebd809
...
@@ -354,7 +354,7 @@ export class PayloadChannel extends EnhancedEventEmitter
...
@@ -354,7 +354,7 @@ export class PayloadChannel extends EnhancedEventEmitter
{
{
this
.
#
ongoingNotification
=
this
.
#
ongoingNotification
=
{
{
targetId
:
msg
.
targetId
,
targetId
:
String
(
msg
.
targetId
)
,
event
:
msg
.
event
,
event
:
msg
.
event
,
data
:
msg
.
data
data
:
msg
.
data
};
};
...
...
rust/CHANGELOG.md
浏览文件 @
f0ebd809
...
@@ -3,6 +3,11 @@
...
@@ -3,6 +3,11 @@
# Unreleased
# Unreleased
*
Fix for receiving data over payload channel
*
Fix for receiving data over payload channel
*
Support thread initializer function for worker threads, can be used for pinning worker threads to CPU cores
*
Significant worker communication optimizations (especially latency)
*
Switch from file descriptors to function calls when communicating with worker
*
Various optimizations that caused minor breaking changes to public API
*
Requests no longer have internal timeout, but they can now be cancelled, add your own timeouts on top if needed
# 0.8.5
# 0.8.5
...
...
rust/Cargo.toml
浏览文件 @
f0ebd809
...
@@ -22,33 +22,32 @@ targets = []
...
@@ -22,33 +22,32 @@ targets = []
[dependencies]
[dependencies]
async-channel
=
"1.6.1"
async-channel
=
"1.6.1"
async-executor
=
"1.4.1"
async-executor
=
"1.4.1"
async-fs
=
"1.5.0"
async-io
=
"1.6.0"
async-lock
=
"2.4.0"
async-lock
=
"2.4.0"
async-oneshot
=
"0.5.0"
async-oneshot
=
"0.5.0"
async-trait
=
"0.1.5
0
"
async-trait
=
"0.1.5
1
"
bytes
=
"1.0.1
"
atomic-take
=
"1.0.0
"
event-listener-primitives
=
"
1.0.0
"
event-listener-primitives
=
"
2.0.1
"
fastrand
=
"1.5.0"
fastrand
=
"1.5.0"
futures-lite
=
"1.12.0"
futures-lite
=
"1.12.0"
h264-profile-level-id
=
"0.1.1"
h264-profile-level-id
=
"0.1.1"
hash_hasher
=
"2.0.3"
log
=
"0.4.14"
log
=
"0.4.14"
libc
=
"0.2.98
"
nohash-hasher
=
"0.2.0
"
once_cell
=
"1.8.0"
once_cell
=
"1.8.0"
serde_json
=
"1.0.6
4
"
serde_json
=
"1.0.6
7
"
serde_repr
=
"0.1.7"
serde_repr
=
"0.1.7"
thiserror
=
"1.0.2
6
"
thiserror
=
"1.0.2
8
"
[dependencies.lru]
[dependencies.lru]
default-features
=
false
default-features
=
false
version
=
"0.6.
5
"
version
=
"0.6.
6
"
[dependencies.mediasoup-sys]
[dependencies.mediasoup-sys]
path
=
"../worker"
path
=
"../worker"
version
=
"0.2.5"
version
=
"0.2.5"
[dependencies.parking_lot]
[dependencies.parking_lot]
version
=
"0.11.
1
"
version
=
"0.11.
2
"
features
=
["serde"]
features
=
["serde"]
[dependencies.regex]
[dependencies.regex]
...
@@ -58,7 +57,7 @@ version = "1.5.4"
...
@@ -58,7 +57,7 @@ version = "1.5.4"
[dependencies.serde]
[dependencies.serde]
features
=
["derive"]
features
=
["derive"]
version
=
"1.0.1
26
"
version
=
"1.0.1
30
"
[dependencies.uuid]
[dependencies.uuid]
features
=
[
"serde"
,
"v4"
]
features
=
[
"serde"
,
"v4"
]
...
@@ -66,13 +65,14 @@ version = "0.8.2"
...
@@ -66,13 +65,14 @@ version = "0.8.2"
[dev-dependencies]
[dev-dependencies]
actix
=
"0.12.0"
actix
=
"0.12.0"
actix-web
=
"4.0.0-beta.8"
actix-web-actors
=
"4.0.0-beta.6"
actix-web-actors
=
"4.0.0-beta.6"
async-io
=
"1.6.0"
criterion
=
"0.3.5"
env_logger
=
"0.9.0"
env_logger
=
"0.9.0"
[dev-dependencies.
criterion
]
[dev-dependencies.
actix-web
]
version
=
"0.3.5"
default-features
=
false
features
=
["async_futures"]
version
=
"4.0.0-beta.8"
[[bench]]
[[bench]]
name
=
"direct_data"
name
=
"direct_data"
...
...
rust/benches/direct_data.rs
浏览文件 @
f0ebd809
use
bytes
::
Bytes
;
use
criterion
::
async_executor
::
FuturesExecutor
;
use
criterion
::{
criterion_group
,
criterion_main
,
Criterion
};
use
criterion
::{
criterion_group
,
criterion_main
,
Criterion
};
use
futures_lite
::
StreamExt
;
use
mediasoup
::
prelude
::
*
;
use
mediasoup
::
prelude
::
*
;
use
std
::
borrow
::
Cow
;
use
std
::
sync
::
mpsc
;
async
fn
create_data_producer_consumer_pair
(
async
fn
create_data_producer_consumer_pair
(
)
->
Result
<
(
DataProducer
,
DataConsumer
),
Box
<
dyn
std
::
error
::
Error
>>
{
)
->
Result
<
(
DataProducer
,
DataConsumer
),
Box
<
dyn
std
::
error
::
Error
>>
{
...
@@ -29,32 +28,10 @@ async fn create_data_producer_consumer_pair(
...
@@ -29,32 +28,10 @@ async fn create_data_producer_consumer_pair(
pub
fn
criterion_benchmark
(
c
:
&
mut
Criterion
)
{
pub
fn
criterion_benchmark
(
c
:
&
mut
Criterion
)
{
let
mut
group
=
c
.benchmark_group
(
"direct_data"
);
let
mut
group
=
c
.benchmark_group
(
"direct_data"
);
let
data
=
Bytes
::
from
(
let
data
=
std
::
iter
::
repeat_with
(||
fastrand
::
u8
(
..
))
std
::
iter
::
repeat_with
(||
fastrand
::
u8
(
..
))
.take
(
512
)
.take
(
512
)
.collect
::
<
Vec
<
u8
>>
(),
.collect
::
<
Vec
<
u8
>>
();
);
{
let
(
data_producer
,
_data_consumer
)
=
futures_lite
::
future
::
block_on
(
async
{
create_data_producer_consumer_pair
()
.await
.unwrap
()
});
let
direct_data_producer
=
if
let
DataProducer
::
Direct
(
direct_data_producer
)
=
data_producer
.clone
()
{
direct_data_producer
}
else
{
unreachable!
()
};
group
.bench_with_input
(
"send"
,
&
data
,
|
b
,
data
|
{
b
.to_async
(
FuturesExecutor
)
.iter
(||
async
{
let
_
=
direct_data_producer
.send
(
WebRtcMessage
::
Binary
(
data
.clone
()))
.await
;
})
});
}
{
{
let
(
data_producer
,
data_consumer
)
=
futures_lite
::
future
::
block_on
(
async
{
let
(
data_producer
,
data_consumer
)
=
futures_lite
::
future
::
block_on
(
async
{
create_data_producer_consumer_pair
()
.await
.unwrap
()
create_data_producer_consumer_pair
()
.await
.unwrap
()
...
@@ -68,17 +45,15 @@ pub fn criterion_benchmark(c: &mut Criterion) {
...
@@ -68,17 +45,15 @@ pub fn criterion_benchmark(c: &mut Criterion) {
};
};
group
.bench_with_input
(
"recv"
,
&
data
,
|
b
,
data
|
{
group
.bench_with_input
(
"recv"
,
&
data
,
|
b
,
data
|
{
b
.
to_async
(
FuturesExecutor
)
.iter
(||
async
{
b
.
iter
(||
{
let
(
sender
,
mut
receiver
)
=
async_channel
::
unbounded
::
<
()
>
(
);
let
(
sender
,
receiver
)
=
mpsc
::
sync_channel
(
1
);
let
_handler_id
=
data_consumer
.on_message
(
move
|
_message
|
{
let
_handler_id
=
data_consumer
.on_message
(
move
|
_message
|
{
let
_
=
sender
.
try_
send
(());
let
_
=
sender
.send
(());
});
});
let
_
=
direct_data_producer
let
_
=
direct_data_producer
.send
(
WebRtcMessage
::
Binary
(
Cow
::
from
(
data
)));
.send
(
WebRtcMessage
::
Binary
(
data
.clone
()))
.await
;
let
_
=
receiver
.
next
()
.await
;
let
_
=
receiver
.
recv
()
;
})
})
});
});
}
}
...
...
rust/examples-frontend/echo/webpack.config.js
浏览文件 @
f0ebd809
// eslint-disable-next-line @typescript-eslint/no-var-requires
const
path
=
require
(
'path'
);
const
path
=
require
(
'path'
);
module
.
exports
=
{
module
.
exports
=
{
...
@@ -22,6 +21,9 @@ module.exports = {
...
@@ -22,6 +21,9 @@ module.exports = {
},
},
devServer
:
{
devServer
:
{
liveReload
:
false
,
liveReload
:
false
,
port
:
3001
port
:
3001
,
static
:
{
directory
:
__dirname
}
}
}
};
};
rust/examples-frontend/multiopus/webpack.config.js
浏览文件 @
f0ebd809
// eslint-disable-next-line @typescript-eslint/no-var-requires
const
path
=
require
(
'path'
);
const
path
=
require
(
'path'
);
module
.
exports
=
{
module
.
exports
=
{
...
@@ -22,6 +21,9 @@ module.exports = {
...
@@ -22,6 +21,9 @@ module.exports = {
},
},
devServer
:
{
devServer
:
{
liveReload
:
false
,
liveReload
:
false
,
port
:
3001
port
:
3001
,
static
:
{
directory
:
__dirname
}
}
}
};
};
rust/examples-frontend/videoroom/webpack.config.js
浏览文件 @
f0ebd809
// eslint-disable-next-line @typescript-eslint/no-var-requires
const
path
=
require
(
'path'
);
const
path
=
require
(
'path'
);
module
.
exports
=
{
module
.
exports
=
{
...
@@ -22,6 +21,9 @@ module.exports = {
...
@@ -22,6 +21,9 @@ module.exports = {
},
},
devServer
:
{
devServer
:
{
liveReload
:
false
,
liveReload
:
false
,
port
:
3001
port
:
3001
,
static
:
{
directory
:
__dirname
}
}
}
};
};
rust/examples/videoroom.rs
浏览文件 @
f0ebd809
...
@@ -37,8 +37,10 @@ mod room {
...
@@ -37,8 +37,10 @@ mod room {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
producer_add
:
Bag
<
Box
<
dyn
Fn
(
&
ParticipantId
,
&
Producer
)
+
Send
+
Sync
>>
,
producer_add
:
producer_remove
:
Bag
<
Box
<
dyn
Fn
(
&
ParticipantId
,
&
ProducerId
)
+
Send
+
Sync
>>
,
Bag
<
Arc
<
dyn
Fn
(
&
ParticipantId
,
&
Producer
)
+
Send
+
Sync
>
,
ParticipantId
,
Producer
>
,
producer_remove
:
Bag
<
Arc
<
dyn
Fn
(
&
ParticipantId
,
&
ProducerId
)
+
Send
+
Sync
>
,
ParticipantId
,
ProducerId
>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -146,9 +148,10 @@ mod room {
...
@@ -146,9 +148,10 @@ mod room {
.or_default
()
.or_default
()
.push
(
producer
.clone
());
.push
(
producer
.clone
());
self
.inner.handlers.producer_add
.call
(|
callback
|
{
self
.inner
callback
(
&
participant_id
,
&
producer
);
.handlers
});
.producer_add
.call_simple
(
&
participant_id
,
&
producer
);
}
}
/// Remove participant and all of its associated producers
/// Remove participant and all of its associated producers
...
@@ -157,9 +160,10 @@ mod room {
...
@@ -157,9 +160,10 @@ mod room {
for
producer
in
producers
.unwrap_or_default
()
{
for
producer
in
producers
.unwrap_or_default
()
{
let
producer_id
=
&
producer
.id
();
let
producer_id
=
&
producer
.id
();
self
.inner.handlers.producer_remove
.call
(|
callback
|
{
self
.inner
callback
(
participant_id
,
producer_id
);
.handlers
});
.producer_remove
.call_simple
(
participant_id
,
producer_id
);
}
}
}
}
...
@@ -185,7 +189,7 @@ mod room {
...
@@ -185,7 +189,7 @@ mod room {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.producer_add
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.producer_add
.add
(
Arc
::
new
(
callback
))
}
}
/// Subscribe to notifications when producer is removed from the room
/// Subscribe to notifications when producer is removed from the room
...
@@ -193,7 +197,7 @@ mod room {
...
@@ -193,7 +197,7 @@ mod room {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.producer_remove
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.producer_remove
.add
(
Arc
::
new
(
callback
))
}
}
/// Subscribe to notification when room is closed
/// Subscribe to notification when room is closed
...
...
rust/src/data_structures.rs
浏览文件 @
f0ebd809
...
@@ -3,7 +3,6 @@
...
@@ -3,7 +3,6 @@
#[cfg(test)]
#[cfg(test)]
mod
tests
;
mod
tests
;
use
bytes
::
Bytes
;
use
serde
::
de
::{
MapAccess
,
Visitor
};
use
serde
::
de
::{
MapAccess
,
Visitor
};
use
serde
::
ser
::
SerializeStruct
;
use
serde
::
ser
::
SerializeStruct
;
use
serde
::{
de
,
Deserialize
,
Deserializer
,
Serialize
,
Serializer
};
use
serde
::{
de
,
Deserialize
,
Deserializer
,
Serialize
,
Serializer
};
...
@@ -770,18 +769,18 @@ pub enum TraceEventDirection {
...
@@ -770,18 +769,18 @@ pub enum TraceEventDirection {
/// Container used for sending/receiving messages using `DirectTransport` data producers and data
/// Container used for sending/receiving messages using `DirectTransport` data producers and data
/// consumers.
/// consumers.
#[derive(Debug,
Clone)]
#[derive(Debug,
Clone)]
pub
enum
WebRtcMessage
{
pub
enum
WebRtcMessage
<
'a
>
{
/// String
/// String
String
(
String
),
String
(
String
),
/// Binary
/// Binary
Binary
(
Bytes
),
Binary
(
Cow
<
'a
,
[
u8
]
>
),
/// EmptyString
/// EmptyString
EmptyString
,
EmptyString
,
/// EmptyBinary
/// EmptyBinary
EmptyBinary
,
EmptyBinary
,
}
}
impl
WebRtcMessage
{
impl
<
'a
>
WebRtcMessage
<
'a
>
{
// +------------------------------------+-----------+
// +------------------------------------+-----------+
// | Value | SCTP PPID |
// | Value | SCTP PPID |
// +------------------------------------+-----------+
// +------------------------------------+-----------+
...
@@ -793,7 +792,7 @@ impl WebRtcMessage {
...
@@ -793,7 +792,7 @@ impl WebRtcMessage {
// | WebRTC Binary Empty | 57 |
// | WebRTC Binary Empty | 57 |
// +------------------------------------+-----------+
// +------------------------------------+-----------+
pub
(
crate
)
fn
new
(
ppid
:
u32
,
payload
:
Bytes
)
->
Result
<
Self
,
u32
>
{
pub
(
crate
)
fn
new
(
ppid
:
u32
,
payload
:
Cow
<
'a
,
[
u8
]
>
)
->
Result
<
Self
,
u32
>
{
match
ppid
{
match
ppid
{
51
=>
Ok
(
WebRtcMessage
::
String
(
51
=>
Ok
(
WebRtcMessage
::
String
(
String
::
from_utf8
(
payload
.to_vec
())
.unwrap
(),
String
::
from_utf8
(
payload
.to_vec
())
.unwrap
(),
...
@@ -805,12 +804,12 @@ impl WebRtcMessage {
...
@@ -805,12 +804,12 @@ impl WebRtcMessage {
}
}
}
}
pub
(
crate
)
fn
into_ppid_and_payload
(
self
)
->
(
u32
,
Bytes
)
{
pub
(
crate
)
fn
into_ppid_and_payload
(
self
)
->
(
u32
,
Cow
<
'a
,
[
u8
]
>
)
{
match
self
{
match
self
{
WebRtcMessage
::
String
(
string
)
=>
(
51
_u32
,
Bytes
::
from
(
string
)),
WebRtcMessage
::
String
(
string
)
=>
(
51
_u32
,
Cow
::
from
(
string
.into_bytes
()
)),
WebRtcMessage
::
Binary
(
binary
)
=>
(
53
_u32
,
binary
),
WebRtcMessage
::
Binary
(
binary
)
=>
(
53
_u32
,
binary
),
WebRtcMessage
::
EmptyString
=>
(
56
_u32
,
Bytes
::
from_static
(
b
" "
)),
WebRtcMessage
::
EmptyString
=>
(
56
_u32
,
Cow
::
from
(
b
" "
.as_ref
()
)),
WebRtcMessage
::
EmptyBinary
=>
(
57
_u32
,
Bytes
::
from
(
vec!
[
0
_u8
])),
WebRtcMessage
::
EmptyBinary
=>
(
57
_u32
,
Cow
::
from
(
vec!
[
0
_u8
])),
}
}
}
}
}
}
...
...
rust/src/messages.rs
浏览文件 @
f0ebd809
...
@@ -28,8 +28,8 @@ use crate::worker::{WorkerDump, WorkerUpdateSettings};
...
@@ -28,8 +28,8 @@ use crate::worker::{WorkerDump, WorkerUpdateSettings};
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::
de
::
DeserializeOwned
;
use
serde
::
de
::
DeserializeOwned
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
serde_json
::
Value
;
use
std
::
fmt
::
Debug
;
use
std
::
fmt
::
Debug
;
use
std
::
marker
::
PhantomData
;
use
std
::
net
::
IpAddr
;
use
std
::
net
::
IpAddr
;
use
std
::
num
::
NonZeroU16
;
use
std
::
num
::
NonZeroU16
;
...
@@ -149,32 +149,6 @@ macro_rules! request_response {
...
@@ -149,32 +149,6 @@ macro_rules! request_response {
};
};
}
}
macro_rules!
request_response_generic
{
(
$method
:
literal
,
$request_struct_name
:
ident
{
$
(
$request_field_name
:
ident
:
$request_field_type
:
ty
$
(,)
?
)
*
},
$generic_response
:
ident
,
)
=>
{
#[derive(Debug,
Serialize)]
pub
(
crate
)
struct
$request_struct_name
<
$generic_response
>
where
$generic_response
:
Debug
+
DeserializeOwned
,
{
$
(
pub
(
crate
)
$request_field_name
:
$request_field_type
,
)
*
#[serde(skip)]
pub
(
crate
)
phantom_data
:
PhantomData
<
$generic_response
>
,
}
impl
<
$generic_response
:
Debug
+
DeserializeOwned
>
Request
for
$request_struct_name
<
$generic_response
>
{
type
Response
=
$generic_response
;
fn
as_method
(
&
self
)
->
&
'static
str
{
$method
}
}
};
}
request_response!
(
"worker.close"
,
WorkerCloseRequest
{});
request_response!
(
"worker.close"
,
WorkerCloseRequest
{});
request_response!
(
"worker.dump"
,
WorkerDumpRequest
{},
WorkerDump
);
request_response!
(
"worker.dump"
,
WorkerDumpRequest
{},
WorkerDump
);
...
@@ -333,8 +307,9 @@ request_response!(
...
@@ -333,8 +307,9 @@ request_response!(
data
:
RouterCreatePlainTransportData
,
data
:
RouterCreatePlainTransportData
,
},
},
PlainTransportData
{
PlainTransportData
{
rtcp_mux
:
bool
,
// The following fields are present, but unused
comedia
:
bool
,
// rtcp_mux: bool,
// comedia: bool,
tuple
:
Mutex
<
TransportTuple
>
,
tuple
:
Mutex
<
TransportTuple
>
,
rtcp_tuple
:
Mutex
<
Option
<
TransportTuple
>>
,
rtcp_tuple
:
Mutex
<
Option
<
TransportTuple
>>
,
sctp_parameters
:
Option
<
SctpParameters
>
,
sctp_parameters
:
Option
<
SctpParameters
>
,
...
@@ -446,20 +421,20 @@ request_response!(
...
@@ -446,20 +421,20 @@ request_response!(
},
},
);
);
request_response
_generic
!
(
request_response!
(
"transport.dump"
,
"transport.dump"
,
TransportDumpRequest
{
TransportDumpRequest
{
internal
:
TransportInternal
,
internal
:
TransportInternal
,
},
},
Dump
,
Value
,
);
);
request_response
_generic
!
(
request_response!
(
"transport.getStats"
,
"transport.getStats"
,
TransportGetStatsRequest
{
TransportGetStatsRequest
{
internal
:
TransportInternal
,
internal
:
TransportInternal
,
},
},
Stats
,
Value
,
);
);
#[derive(Debug,
Serialize)]
#[derive(Debug,
Serialize)]
...
@@ -470,7 +445,7 @@ pub(crate) struct TransportConnectRequestWebRtcData {
...
@@ -470,7 +445,7 @@ pub(crate) struct TransportConnectRequestWebRtcData {
request_response!
(
request_response!
(
"transport.connect"
,
"transport.connect"
,
TransportConnect
RequestWebRtc
{
TransportConnect
WebRtcRequest
{
internal
:
TransportInternal
,
internal
:
TransportInternal
,
data
:
TransportConnectRequestWebRtcData
,
data
:
TransportConnectRequestWebRtcData
,
},
},
...
@@ -490,7 +465,7 @@ pub(crate) struct TransportConnectRequestPipeData {
...
@@ -490,7 +465,7 @@ pub(crate) struct TransportConnectRequestPipeData {
request_response!
(
request_response!
(
"transport.connect"
,
"transport.connect"
,
TransportConnect
RequestPipe
{
TransportConnect
PipeRequest
{
internal
:
TransportInternal
,
internal
:
TransportInternal
,
data
:
TransportConnectRequestPipeData
,
data
:
TransportConnectRequestPipeData
,
},
},
...
@@ -514,7 +489,7 @@ pub(crate) struct TransportConnectRequestPlainData {
...
@@ -514,7 +489,7 @@ pub(crate) struct TransportConnectRequestPlainData {
request_response!
(
request_response!
(
"transport.connect"
,
"transport.connect"
,
TransportConnect
RequestPlain
{
TransportConnect
PlainRequest
{
internal
:
TransportInternal
,
internal
:
TransportInternal
,
data
:
TransportConnectRequestPlainData
,
data
:
TransportConnectRequestPlainData
,
},
},
...
...
rust/src/router.rs
浏览文件 @
f0ebd809
...
@@ -59,10 +59,10 @@ use async_executor::Executor;
...
@@ -59,10 +59,10 @@ use async_executor::Executor;
use
async_lock
::
Mutex
as
AsyncMutex
;
use
async_lock
::
Mutex
as
AsyncMutex
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
parking_lot
::{
Mutex
,
RwLock
};
use
parking_lot
::{
Mutex
,
RwLock
};
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
ops
::
Deref
;
use
std
::
ops
::
Deref
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
...
@@ -270,13 +270,14 @@ impl From<ProduceDataError> for PipeDataProducerToRouterError {
...
@@ -270,13 +270,14 @@ impl From<ProduceDataError> for PipeDataProducerToRouterError {
#[non_exhaustive]
#[non_exhaustive]
pub
struct
RouterDump
{
pub
struct
RouterDump
{
pub
id
:
RouterId
,
pub
id
:
RouterId
,
pub
map_consumer_id_producer_id
:
HashMap
<
ConsumerId
,
ProducerId
>
,
pub
map_consumer_id_producer_id
:
HashedMap
<
ConsumerId
,
ProducerId
>
,
pub
map_data_consumer_id_data_producer_id
:
HashMap
<
DataConsumerId
,
DataProducerId
>
,
pub
map_data_consumer_id_data_producer_id
:
HashedMap
<
DataConsumerId
,
DataProducerId
>
,
pub
map_data_producer_id_data_consumer_ids
:
HashMap
<
DataProducerId
,
HashSet
<
DataConsumerId
>>
,
pub
map_data_producer_id_data_consumer_ids
:
pub
map_producer_id_consumer_ids
:
HashMap
<
ProducerId
,
HashSet
<
ConsumerId
>>
,
HashedMap
<
DataProducerId
,
HashedSet
<
DataConsumerId
>>
,
pub
map_producer_id_observer_ids
:
HashMap
<
ProducerId
,
HashSet
<
RtpObserverId
>>
,
pub
map_producer_id_consumer_ids
:
HashedMap
<
ProducerId
,
HashedSet
<
ConsumerId
>>
,
pub
rtp_observer_ids
:
HashSet
<
RtpObserverId
>
,
pub
map_producer_id_observer_ids
:
HashedMap
<
ProducerId
,
HashedSet
<
RtpObserverId
>>
,
pub
transport_ids
:
HashSet
<
TransportId
>
,
pub
rtp_observer_ids
:
HashedSet
<
RtpObserverId
>
,
pub
transport_ids
:
HashedSet
<
TransportId
>
,
}
}
/// New transport that was just created.
/// New transport that was just created.
...
@@ -355,8 +356,8 @@ impl WeakPipeTransportPair {
...
@@ -355,8 +356,8 @@ impl WeakPipeTransportPair {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
new_transport
:
Bag
<
Box
<
dyn
Fn
(
NewTransport
<
'_
>
)
+
Send
+
Sync
>>
,
new_transport
:
Bag
<
Arc
<
dyn
Fn
(
NewTransport
<
'_
>
)
+
Send
+
Sync
>>
,
new_rtp_observer
:
Bag
<
Box
<
dyn
Fn
(
NewRtpObserver
<
'_
>
)
+
Send
+
Sync
>>
,
new_rtp_observer
:
Bag
<
Arc
<
dyn
Fn
(
NewRtpObserver
<
'_
>
)
+
Send
+
Sync
>>
,
worker_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
worker_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -369,11 +370,11 @@ struct Inner {
...
@@ -369,11 +370,11 @@ struct Inner {
payload_channel
:
PayloadChannel
,
payload_channel
:
PayloadChannel
,
handlers
:
Arc
<
Handlers
>
,
handlers
:
Arc
<
Handlers
>
,
app_data
:
AppData
,
app_data
:
AppData
,
producers
:
Arc
<
RwLock
<
HashMap
<
ProducerId
,
WeakProducer
>>>
,
producers
:
Arc
<
RwLock
<
Hash
ed
Map
<
ProducerId
,
WeakProducer
>>>
,
data_producers
:
Arc
<
RwLock
<
HashMap
<
DataProducerId
,
WeakDataProducer
>>>
,
data_producers
:
Arc
<
RwLock
<
Hash
ed
Map
<
DataProducerId
,
WeakDataProducer
>>>
,
#[allow(clippy
::
type_complexity)]
#[allow(clippy
::
type_complexity)]
mapped_pipe_transports
:
mapped_pipe_transports
:
Arc
<
Mutex
<
HashMap
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>>
,
Arc
<
Mutex
<
Hash
ed
Map
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>>
,
// Make sure worker is not dropped until this router is not dropped
// Make sure worker is not dropped until this router is not dropped
worker
:
Option
<
Worker
>
,
worker
:
Option
<
Worker
>
,
closed
:
AtomicBool
,
closed
:
AtomicBool
,
...
@@ -449,10 +450,10 @@ impl Router {
...
@@ -449,10 +450,10 @@ impl Router {
)
->
Self
{
)
->
Self
{
debug!
(
"new()"
);
debug!
(
"new()"
);
let
producers
=
Arc
::
<
RwLock
<
HashMap
<
ProducerId
,
WeakProducer
>>>
::
default
();
let
producers
=
Arc
::
<
RwLock
<
Hash
ed
Map
<
ProducerId
,
WeakProducer
>>>
::
default
();
let
data_producers
=
Arc
::
<
RwLock
<
HashMap
<
DataProducerId
,
WeakDataProducer
>>>
::
default
();
let
data_producers
=
Arc
::
<
RwLock
<
Hash
ed
Map
<
DataProducerId
,
WeakDataProducer
>>>
::
default
();
let
mapped_pipe_transports
=
Arc
::
<
let
mapped_pipe_transports
=
Arc
::
<
Mutex
<
HashMap
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>
,
Mutex
<
Hash
ed
Map
<
RouterId
,
Arc
<
AsyncMutex
<
Option
<
WeakPipeTransportPair
>>>>>
,
>
::
default
();
>
::
default
();
let
handlers
=
Arc
::
<
Handlers
>
::
default
();
let
handlers
=
Arc
::
<
Handlers
>
::
default
();
let
inner_weak
=
Arc
::
<
Mutex
<
Option
<
Weak
<
Inner
>>>>
::
default
();
let
inner_weak
=
Arc
::
<
Mutex
<
Option
<
Weak
<
Inner
>>>>
::
default
();
...
@@ -1314,7 +1315,7 @@ impl Router {
...
@@ -1314,7 +1315,7 @@ impl Router {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_transport
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.new_transport
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when a new RTP observer is created.
/// Callback is called when a new RTP observer is created.
...
@@ -1322,7 +1323,7 @@ impl Router {
...
@@ -1322,7 +1323,7 @@ impl Router {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_rtp_observer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.new_rtp_observer
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the worker this router belongs to is closed for whatever reason.
/// Callback is called when the worker this router belongs to is closed for whatever reason.
...
@@ -1351,7 +1352,7 @@ impl Router {
...
@@ -1351,7 +1352,7 @@ impl Router {
// destination Routers. We just want to keep a PipeTransport pair for each
// destination Routers. We just want to keep a PipeTransport pair for each
// pair of Routers. Since this operation is async, it may happen that two
// pair of Routers. Since this operation is async, it may happen that two
// simultaneous calls piping to the same router would end up generating two pairs of
// simultaneous calls piping to the same router would end up generating two pairs of
// `PipeTransport`. To prevent that, we have `HashMap` with mapping behind `Mutex` and
// `PipeTransport`. To prevent that, we have `Hash
ed
Map` with mapping behind `Mutex` and
// another `Mutex` on the pair of `PipeTransport`.
// another `Mutex` on the pair of `PipeTransport`.
let
mut
mapped_pipe_transports
=
self
.inner.mapped_pipe_transports
.lock
();
let
mut
mapped_pipe_transports
=
self
.inner.mapped_pipe_transports
.lock
();
...
@@ -1465,7 +1466,7 @@ impl Router {
...
@@ -1465,7 +1466,7 @@ impl Router {
{
{
let
producers_weak
=
Arc
::
downgrade
(
&
self
.inner.producers
);
let
producers_weak
=
Arc
::
downgrade
(
&
self
.inner.producers
);
transport
transport
.on_new_producer
(
Box
::
new
(
move
|
producer
|
{
.on_new_producer
(
Arc
::
new
(
move
|
producer
|
{
let
producer_id
=
producer
.id
();
let
producer_id
=
producer
.id
();
if
let
Some
(
producers
)
=
producers_weak
.upgrade
()
{
if
let
Some
(
producers
)
=
producers_weak
.upgrade
()
{
producers
.write
()
.insert
(
producer_id
,
producer
.downgrade
());
producers
.write
()
.insert
(
producer_id
,
producer
.downgrade
());
...
@@ -1486,7 +1487,7 @@ impl Router {
...
@@ -1486,7 +1487,7 @@ impl Router {
{
{
let
data_producers_weak
=
Arc
::
downgrade
(
&
self
.inner.data_producers
);
let
data_producers_weak
=
Arc
::
downgrade
(
&
self
.inner.data_producers
);
transport
transport
.on_new_data_producer
(
Box
::
new
(
move
|
data_producer
|
{
.on_new_data_producer
(
Arc
::
new
(
move
|
data_producer
|
{
let
data_producer_id
=
data_producer
.id
();
let
data_producer_id
=
data_producer
.id
();
if
let
Some
(
data_producers
)
=
data_producers_weak
.upgrade
()
{
if
let
Some
(
data_producers
)
=
data_producers_weak
.upgrade
()
{
data_producers
data_producers
...
...
rust/src/router/active_speaker_observer.rs
浏览文件 @
f0ebd809
...
@@ -50,11 +50,14 @@ pub struct ActiveSpeakerObserverDominantSpeaker {
...
@@ -50,11 +50,14 @@ pub struct ActiveSpeakerObserverDominantSpeaker {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
dominant_speaker
:
Bag
<
Box
<
dyn
Fn
(
&
ActiveSpeakerObserverDominantSpeaker
)
+
Send
+
Sync
>>
,
dominant_speaker
:
Bag
<
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
Arc
<
dyn
Fn
(
&
ActiveSpeakerObserverDominantSpeaker
)
+
Send
+
Sync
>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
ActiveSpeakerObserverDominantSpeaker
,
add_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>>
,
>
,
remove_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>>
,
pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
add_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
remove_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -220,9 +223,7 @@ impl RtpObserver for ActiveSpeakerObserver {
...
@@ -220,9 +223,7 @@ impl RtpObserver for ActiveSpeakerObserver {
})
})
.await
?
;
.await
?
;
self
.inner.handlers.add_producer
.call
(|
callback
|
{
self
.inner.handlers.add_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(())
Ok
(())
}
}
...
@@ -242,33 +243,31 @@ impl RtpObserver for ActiveSpeakerObserver {
...
@@ -242,33 +243,31 @@ impl RtpObserver for ActiveSpeakerObserver {
})
})
.await
?
;
.await
?
;
self
.inner.handlers.remove_producer
.call
(|
callback
|
{
self
.inner.handlers.remove_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(())
Ok
(())
}
}
fn
on_pause
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
fn
on_pause
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
self
.inner.handlers.pause
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.pause
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_resume
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
fn
on_resume
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
self
.inner.handlers.resume
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.resume
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_add_producer
(
fn
on_add_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.add_producer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.add_producer
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_remove_producer
(
fn
on_remove_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.remove_producer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.remove_producer
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_router_close
(
&
self
,
callback
:
Box
<
dyn
FnOnce
()
+
Send
+
'static
>
)
->
HandlerId
{
fn
on_router_close
(
&
self
,
callback
:
Box
<
dyn
FnOnce
()
+
Send
+
'static
>
)
->
HandlerId
{
...
@@ -302,7 +301,7 @@ impl ActiveSpeakerObserver {
...
@@ -302,7 +301,7 @@ impl ActiveSpeakerObserver {
let
handlers
=
Arc
::
clone
(
&
handlers
);
let
handlers
=
Arc
::
clone
(
&
handlers
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
DominantSpeaker
(
dominant_speaker
)
=>
{
Notification
::
DominantSpeaker
(
dominant_speaker
)
=>
{
let
DominantSpeakerNotification
{
producer_id
}
=
dominant_speaker
;
let
DominantSpeakerNotification
{
producer_id
}
=
dominant_speaker
;
...
@@ -311,9 +310,7 @@ impl ActiveSpeakerObserver {
...
@@ -311,9 +310,7 @@ impl ActiveSpeakerObserver {
let
dominant_speaker
=
let
dominant_speaker
=
ActiveSpeakerObserverDominantSpeaker
{
producer
};
ActiveSpeakerObserverDominantSpeaker
{
producer
};
handlers
.dominant_speaker
.call
(|
callback
|
{
handlers
.dominant_speaker
.call_simple
(
&
dominant_speaker
);
callback
(
&
dominant_speaker
);
});
}
}
None
=>
{
None
=>
{
error!
(
error!
(
...
@@ -367,7 +364,7 @@ impl ActiveSpeakerObserver {
...
@@ -367,7 +364,7 @@ impl ActiveSpeakerObserver {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.dominant_speaker
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.dominant_speaker
.add
(
Arc
::
new
(
callback
))
}
}
/// Downgrade `ActiveSpeakerObserver` to [`WeakActiveSpeakerObserver`] instance.
/// Downgrade `ActiveSpeakerObserver` to [`WeakActiveSpeakerObserver`] instance.
...
...
rust/src/router/audio_level_observer.rs
浏览文件 @
f0ebd809
...
@@ -61,12 +61,12 @@ pub struct AudioLevelObserverVolume {
...
@@ -61,12 +61,12 @@ pub struct AudioLevelObserverVolume {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
volumes
:
Bag
<
Box
<
dyn
Fn
(
&
Vec
<
AudioLevelObserverVolume
>
)
+
Send
+
Sync
>>
,
volumes
:
Bag
<
Arc
<
dyn
Fn
(
&
[
AudioLevelObserverVolume
]
)
+
Send
+
Sync
>>
,
silence
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
silence
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
add_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
add_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
remove_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
remove_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -234,9 +234,7 @@ impl RtpObserver for AudioLevelObserver {
...
@@ -234,9 +234,7 @@ impl RtpObserver for AudioLevelObserver {
})
})
.await
?
;
.await
?
;
self
.inner.handlers.add_producer
.call
(|
callback
|
{
self
.inner.handlers.add_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(())
Ok
(())
}
}
...
@@ -256,33 +254,31 @@ impl RtpObserver for AudioLevelObserver {
...
@@ -256,33 +254,31 @@ impl RtpObserver for AudioLevelObserver {
})
})
.await
?
;
.await
?
;
self
.inner.handlers.remove_producer
.call
(|
callback
|
{
self
.inner.handlers.remove_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(())
Ok
(())
}
}
fn
on_pause
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
fn
on_pause
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
self
.inner.handlers.pause
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.pause
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_resume
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
fn
on_resume
(
&
self
,
callback
:
Box
<
dyn
Fn
()
+
Send
+
Sync
+
'static
>
)
->
HandlerId
{
self
.inner.handlers.resume
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.resume
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_add_producer
(
fn
on_add_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.add_producer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.add_producer
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_remove_producer
(
fn
on_remove_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.remove_producer
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.remove_producer
.add
(
Arc
::
new
(
callback
))
}
}
fn
on_router_close
(
&
self
,
callback
:
Box
<
dyn
FnOnce
()
+
Send
+
'static
>
)
->
HandlerId
{
fn
on_router_close
(
&
self
,
callback
:
Box
<
dyn
FnOnce
()
+
Send
+
'static
>
)
->
HandlerId
{
...
@@ -316,21 +312,24 @@ impl AudioLevelObserver {
...
@@ -316,21 +312,24 @@ impl AudioLevelObserver {
let
handlers
=
Arc
::
clone
(
&
handlers
);
let
handlers
=
Arc
::
clone
(
&
handlers
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Volumes
(
volumes
)
=>
{
Notification
::
Volumes
(
volumes
)
=>
{
let
volumes
=
volumes
let
volumes
=
volumes
.i
nto_i
ter
()
.iter
()
.filter_map
(|
notification
|
{
.filter_map
(|
notification
|
{
let
VolumeNotification
{
let
VolumeNotification
{
producer_id
,
producer_id
,
volume
,
volume
,
}
=
notification
;
}
=
notification
;
router
.get_producer
(
&
producer_id
)
.map
(|
producer
|
{
router
.get_producer
(
producer_id
)
.map
(|
producer
|
{
AudioLevelObserverVolume
{
producer
,
volume
}
AudioLevelObserverVolume
{
producer
,
volume
:
*
volume
,
}
})
})
})
})
.collect
();
.collect
::
<
Vec
<
_
>>
();
handlers
.volumes
.call
(|
callback
|
{
handlers
.volumes
.call
(|
callback
|
{
callback
(
&
volumes
);
callback
(
&
volumes
);
...
@@ -379,17 +378,17 @@ impl AudioLevelObserver {
...
@@ -379,17 +378,17 @@ impl AudioLevelObserver {
/// Callback is called at most every interval (see [`AudioLevelObserverOptions`]).
/// Callback is called at most every interval (see [`AudioLevelObserverOptions`]).
///
///
/// Audio volumes entries ordered by volume (louder ones go first).
/// Audio volumes entries ordered by volume (louder ones go first).
pub
fn
on_volumes
<
F
:
Fn
(
&
Vec
<
AudioLevelObserverVolume
>
)
+
Send
+
Sync
+
'static
>
(
pub
fn
on_volumes
<
F
:
Fn
(
&
[
AudioLevelObserverVolume
]
)
+
Send
+
Sync
+
'static
>
(
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.volumes
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.volumes
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when no one of the producers in this RTP observer is generating audio with a volume
/// Callback is called when no one of the producers in this RTP observer is generating audio with a volume
/// beyond the given threshold.
/// beyond the given threshold.
pub
fn
on_silence
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_silence
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.silence
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.silence
.add
(
Arc
::
new
(
callback
))
}
}
/// Downgrade `AudioLevelObserver` to [`WeakAudioLevelObserver`] instance.
/// Downgrade `AudioLevelObserver` to [`WeakAudioLevelObserver`] instance.
...
...
rust/src/router/consumer.rs
浏览文件 @
f0ebd809
...
@@ -13,11 +13,8 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters}
...
@@ -13,11 +13,8 @@ use crate::rtp_parameters::{MediaKind, MimeType, RtpCapabilities, RtpParameters}
use
crate
::
scalability_modes
::
ScalabilityMode
;
use
crate
::
scalability_modes
::
ScalabilityMode
;
use
crate
::
transport
::
Transport
;
use
crate
::
transport
::
Transport
;
use
crate
::
uuid_based_wrapper_type
;
use
crate
::
uuid_based_wrapper_type
;
use
crate
::
worker
::{
use
crate
::
worker
::{
Channel
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
};
Channel
,
NotificationMessage
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
use
async_executor
::
Executor
;
use
async_executor
::
Executor
;
use
bytes
::
Bytes
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
...
@@ -347,14 +344,15 @@ enum PayloadNotification {
...
@@ -347,14 +344,15 @@ enum PayloadNotification {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
rtp
:
Bag
<
Box
<
dyn
Fn
(
&
Bytes
)
+
Send
+
Sync
>>
,
rtp
:
Bag
<
Arc
<
dyn
Fn
(
&
[
u8
])
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
producer_resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
score
:
Bag
<
Box
<
dyn
Fn
(
&
ConsumerScore
)
+
Send
+
Sync
>>
,
score
:
Bag
<
Arc
<
dyn
Fn
(
&
ConsumerScore
)
+
Send
+
Sync
>
,
ConsumerScore
>
,
layers_change
:
Bag
<
Box
<
dyn
Fn
(
&
Option
<
ConsumerLayers
>
)
+
Send
+
Sync
>>
,
#[allow(clippy
::
type_complexity)]
trace
:
Bag
<
Box
<
dyn
Fn
(
&
ConsumerTraceEventData
)
+
Send
+
Sync
>>
,
layers_change
:
Bag
<
Arc
<
dyn
Fn
(
&
Option
<
ConsumerLayers
>
)
+
Send
+
Sync
>
,
Option
<
ConsumerLayers
>>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
ConsumerTraceEventData
)
+
Send
+
Sync
>
,
ConsumerTraceEventData
>
,
producer_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
producer_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
...
@@ -492,7 +490,7 @@ impl Consumer {
...
@@ -492,7 +490,7 @@ impl Consumer {
let
inner_weak
=
Arc
::
clone
(
&
inner_weak
);
let
inner_weak
=
Arc
::
clone
(
&
inner_weak
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
ProducerClose
=>
{
Notification
::
ProducerClose
=>
{
if
!
closed
.load
(
Ordering
::
SeqCst
)
{
if
!
closed
.load
(
Ordering
::
SeqCst
)
{
...
@@ -529,20 +527,14 @@ impl Consumer {
...
@@ -529,20 +527,14 @@ impl Consumer {
}
}
Notification
::
Score
(
consumer_score
)
=>
{
Notification
::
Score
(
consumer_score
)
=>
{
*
score
.lock
()
=
consumer_score
.clone
();
*
score
.lock
()
=
consumer_score
.clone
();
handlers
.score
.call
(|
callback
|
{
handlers
.score
.call_simple
(
&
consumer_score
);
callback
(
&
consumer_score
);
});
}
}
Notification
::
LayersChange
(
consumer_layers
)
=>
{
Notification
::
LayersChange
(
consumer_layers
)
=>
{
*
current_layers
.lock
()
=
consumer_layers
;
*
current_layers
.lock
()
=
consumer_layers
;
handlers
.layers_change
.call
(|
callback
|
{
handlers
.layers_change
.call_simple
(
&
consumer_layers
);
callback
(
&
consumer_layers
);
});
}
}
Notification
::
Trace
(
trace_event_data
)
=>
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
handlers
.trace
.call_simple
(
&
trace_event_data
);
callback
(
&
trace_event_data
);
});
}
}
},
},
Err
(
error
)
=>
{
Err
(
error
)
=>
{
...
@@ -555,13 +547,12 @@ impl Consumer {
...
@@ -555,13 +547,12 @@ impl Consumer {
let
payload_subscription_handler
=
{
let
payload_subscription_handler
=
{
let
handlers
=
Arc
::
clone
(
&
handlers
);
let
handlers
=
Arc
::
clone
(
&
handlers
);
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
message
,
payload
|
{
let
NotificationMessage
{
message
,
payload
}
=
notification
;
match
serde_json
::
from_slice
::
<
PayloadNotification
>
(
message
)
{
match
serde_json
::
from_value
::
<
PayloadNotification
>
(
message
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
PayloadNotification
::
Rtp
=>
{
PayloadNotification
::
Rtp
=>
{
handlers
.rtp
.call
(|
callback
|
{
handlers
.rtp
.call
(|
callback
|
{
callback
(
&
payload
);
callback
(
payload
);
});
});
}
}
},
},
...
@@ -864,30 +855,30 @@ impl Consumer {
...
@@ -864,30 +855,30 @@ impl Consumer {
/// # Notes on usage
/// # Notes on usage
/// Just available in direct transports, this is, those created via
/// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub
fn
on_rtp
<
F
:
Fn
(
&
Bytes
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_rtp
<
F
:
Fn
(
&
[
u8
]
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.rtp
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.rtp
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the consumer or its associated producer is paused and, as result,
/// Callback is called when the consumer or its associated producer is paused and, as result,
/// the consumer becomes paused.
/// the consumer becomes paused.
pub
fn
on_pause
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_pause
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.pause
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.pause
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the consumer or its associated producer is resumed and, as result,
/// Callback is called when the consumer or its associated producer is resumed and, as result,
/// the consumer is no longer paused.
/// the consumer is no longer paused.
pub
fn
on_resume
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_resume
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.resume
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.resume
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the associated producer is paused.
/// Callback is called when the associated producer is paused.
pub
fn
on_producer_pause
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_producer_pause
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.producer_pause
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.producer_pause
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the associated producer is resumed.
/// Callback is called when the associated producer is resumed.
pub
fn
on_producer_resume
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_producer_resume
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.producer_resume
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.producer_resume
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the consumer score changes.
/// Callback is called when the consumer score changes.
...
@@ -895,7 +886,7 @@ impl Consumer {
...
@@ -895,7 +886,7 @@ impl Consumer {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.score
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.score
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the spatial/temporal layers being sent to the endpoint change. Just
/// Callback is called when the spatial/temporal layers being sent to the endpoint change. Just
...
@@ -919,7 +910,7 @@ impl Consumer {
...
@@ -919,7 +910,7 @@ impl Consumer {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.layers_change
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.layers_change
.add
(
Arc
::
new
(
callback
))
}
}
/// See [`Consumer::enable_trace_event`] method.
/// See [`Consumer::enable_trace_event`] method.
...
@@ -927,7 +918,7 @@ impl Consumer {
...
@@ -927,7 +918,7 @@ impl Consumer {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.trace
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the associated producer is closed for whatever reason. The consumer
/// Callback is called when the associated producer is closed for whatever reason. The consumer
...
...
rust/src/router/data_consumer.rs
浏览文件 @
f0ebd809
...
@@ -12,14 +12,13 @@ use crate::messages::{
...
@@ -12,14 +12,13 @@ use crate::messages::{
use
crate
::
sctp_parameters
::
SctpStreamParameters
;
use
crate
::
sctp_parameters
::
SctpStreamParameters
;
use
crate
::
transport
::
Transport
;
use
crate
::
transport
::
Transport
;
use
crate
::
uuid_based_wrapper_type
;
use
crate
::
uuid_based_wrapper_type
;
use
crate
::
worker
::{
use
crate
::
worker
::{
Channel
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
};
Channel
,
NotificationMessage
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
use
async_executor
::
Executor
;
use
async_executor
::
Executor
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
borrow
::
Cow
;
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
fmt
::
Debug
;
use
std
::
fmt
::
Debug
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
...
@@ -184,9 +183,9 @@ enum PayloadNotification {
...
@@ -184,9 +183,9 @@ enum PayloadNotification {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
message
:
Bag
<
Box
<
dyn
Fn
(
&
WebRtcMessage
)
+
Send
+
Sync
>>
,
message
:
Bag
<
Arc
<
dyn
Fn
(
&
WebRtcMessage
<
'_
>
)
+
Send
+
Sync
>>
,
sctp_send_buffer_full
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
sctp_send_buffer_full
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
buffered_amount_low
:
Bag
<
Box
<
dyn
Fn
(
u32
)
+
Send
+
Sync
>>
,
buffered_amount_low
:
Bag
<
Arc
<
dyn
Fn
(
u32
)
+
Send
+
Sync
>>
,
data_producer_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
data_producer_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
...
@@ -366,7 +365,7 @@ impl DataConsumer {
...
@@ -366,7 +365,7 @@ impl DataConsumer {
let
inner_weak
=
Arc
::
clone
(
&
inner_weak
);
let
inner_weak
=
Arc
::
clone
(
&
inner_weak
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
DataProducerClose
=>
{
Notification
::
DataProducerClose
=>
{
if
!
closed
.load
(
Ordering
::
SeqCst
)
{
if
!
closed
.load
(
Ordering
::
SeqCst
)
{
...
@@ -397,12 +396,11 @@ impl DataConsumer {
...
@@ -397,12 +396,11 @@ impl DataConsumer {
let
payload_subscription_handler
=
{
let
payload_subscription_handler
=
{
let
handlers
=
Arc
::
clone
(
&
handlers
);
let
handlers
=
Arc
::
clone
(
&
handlers
);
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
message
,
payload
|
{
let
NotificationMessage
{
message
,
payload
}
=
notification
;
match
serde_json
::
from_slice
::
<
PayloadNotification
>
(
message
)
{
match
serde_json
::
from_value
::
<
PayloadNotification
>
(
message
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
PayloadNotification
::
Message
{
ppid
}
=>
{
PayloadNotification
::
Message
{
ppid
}
=>
{
match
WebRtcMessage
::
new
(
ppid
,
payload
)
{
match
WebRtcMessage
::
new
(
ppid
,
Cow
::
from
(
payload
)
)
{
Ok
(
message
)
=>
{
Ok
(
message
)
=>
{
handlers
.message
.call
(|
callback
|
{
handlers
.message
.call
(|
callback
|
{
callback
(
&
message
);
callback
(
&
message
);
...
@@ -582,11 +580,11 @@ impl DataConsumer {
...
@@ -582,11 +580,11 @@ impl DataConsumer {
/// # Notes on usage
/// # Notes on usage
/// Just available in direct transports, this is, those created via
/// Just available in direct transports, this is, those created via
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
/// [`Router::create_direct_transport`](crate::router::Router::create_direct_transport).
pub
fn
on_message
<
F
:
Fn
(
&
WebRtcMessage
)
+
Send
+
Sync
+
'static
>
(
pub
fn
on_message
<
F
:
Fn
(
&
WebRtcMessage
<
'_
>
)
+
Send
+
Sync
+
'static
>
(
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner
()
.handlers.message
.add
(
Box
::
new
(
callback
))
self
.inner
()
.handlers.message
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when a message could not be sent because the SCTP send buffer was full.
/// Callback is called when a message could not be sent because the SCTP send buffer was full.
...
@@ -597,7 +595,7 @@ impl DataConsumer {
...
@@ -597,7 +595,7 @@ impl DataConsumer {
self
.inner
()
self
.inner
()
.handlers
.handlers
.sctp_send_buffer_full
.sctp_send_buffer_full
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Emitted when the underlying SCTP association buffered bytes drop down to the value set with
/// Emitted when the underlying SCTP association buffered bytes drop down to the value set with
...
@@ -612,7 +610,7 @@ impl DataConsumer {
...
@@ -612,7 +610,7 @@ impl DataConsumer {
self
.inner
()
self
.inner
()
.handlers
.handlers
.buffered_amount_low
.buffered_amount_low
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the associated data producer is closed for whatever reason. The data
/// Callback is called when the associated data producer is closed for whatever reason. The data
...
@@ -671,7 +669,7 @@ impl DataConsumer {
...
@@ -671,7 +669,7 @@ impl DataConsumer {
impl
DirectDataConsumer
{
impl
DirectDataConsumer
{
/// Sends direct messages from the Rust process.
/// Sends direct messages from the Rust process.
pub
async
fn
send
(
&
self
,
message
:
WebRtcMessage
)
->
Result
<
(),
RequestError
>
{
pub
async
fn
send
(
&
self
,
message
:
WebRtcMessage
<
'_
>
)
->
Result
<
(),
RequestError
>
{
let
(
ppid
,
payload
)
=
message
.into_ppid_and_payload
();
let
(
ppid
,
payload
)
=
message
.into_ppid_and_payload
();
self
.inner
self
.inner
...
@@ -686,7 +684,7 @@ impl DirectDataConsumer {
...
@@ -686,7 +684,7 @@ impl DirectDataConsumer {
},
},
data
:
DataConsumerSendRequestData
{
ppid
},
data
:
DataConsumerSendRequestData
{
ppid
},
},
},
payload
,
payload
.into_owned
()
,
)
)
.await
.await
}
}
...
...
rust/src/router/data_producer.rs
浏览文件 @
f0ebd809
...
@@ -437,13 +437,11 @@ impl DataProducer {
...
@@ -437,13 +437,11 @@ impl DataProducer {
}
}
impl
DirectDataProducer
{
impl
DirectDataProducer
{
/// Sends direct messages from the Rust
process
.
/// Sends direct messages from the Rust
to the worker
.
pub
async
fn
send
(
&
self
,
message
:
WebRtcMessage
)
->
Result
<
(),
NotificationError
>
{
pub
fn
send
(
&
self
,
message
:
WebRtcMessage
<
'_
>
)
->
Result
<
(),
NotificationError
>
{
let
(
ppid
,
payload
)
=
message
.into_ppid_and_payload
();
let
(
ppid
,
payload
)
=
message
.into_ppid_and_payload
();
self
.inner
self
.inner.payload_channel
.notify
(
.payload_channel
.notify
(
DataProducerSendNotification
{
DataProducerSendNotification
{
internal
:
DataProducerInternal
{
internal
:
DataProducerInternal
{
router_id
:
self
.inner.transport
.router_id
(),
router_id
:
self
.inner.transport
.router_id
(),
...
@@ -452,9 +450,8 @@ impl DirectDataProducer {
...
@@ -452,9 +450,8 @@ impl DirectDataProducer {
},
},
data
:
DataProducerSendData
{
ppid
},
data
:
DataProducerSendData
{
ppid
},
},
},
payload
,
payload
.into_owned
()
,
)
)
.await
}
}
}
}
...
...
rust/src/router/direct_transport.rs
浏览文件 @
f0ebd809
...
@@ -16,17 +16,15 @@ use crate::transport::{
...
@@ -16,17 +16,15 @@ use crate::transport::{
TransportTraceEventType
,
TransportTraceEventType
,
};
};
use
crate
::
worker
::{
use
crate
::
worker
::{
Channel
,
NotificationError
,
NotificationMessage
,
PayloadChannel
,
RequestError
,
Channel
,
NotificationError
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
SubscriptionHandler
,
};
};
use
async_executor
::
Executor
;
use
async_executor
::
Executor
;
use
async_trait
::
async_trait
;
use
async_trait
::
async_trait
;
use
bytes
::
Bytes
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
use
std
::
sync
::{
Arc
,
Weak
};
use
std
::
sync
::{
Arc
,
Weak
};
...
@@ -61,8 +59,8 @@ pub struct DirectTransportDump {
...
@@ -61,8 +59,8 @@ pub struct DirectTransportDump {
pub
direct
:
bool
,
pub
direct
:
bool
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
...
@@ -113,12 +111,12 @@ pub struct DirectTransportStat {
...
@@ -113,12 +111,12 @@ pub struct DirectTransportStat {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
rtcp
:
Bag
<
Box
<
dyn
Fn
(
&
Bytes
)
+
Send
+
Sync
>>
,
rtcp
:
Bag
<
Arc
<
dyn
Fn
(
&
[
u8
]
)
+
Send
+
Sync
>>
,
new_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
new_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
new_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
>
,
new_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
,
Consumer
>
,
new_data_producer
:
Bag
<
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
>
,
new_data_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
,
DataProducer
>
,
new_data_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
>
,
new_data_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
,
DataConsumer
>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
,
TransportTraceEventData
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -138,7 +136,7 @@ enum PayloadNotification {
...
@@ -138,7 +136,7 @@ enum PayloadNotification {
struct
Inner
{
struct
Inner
{
id
:
TransportId
,
id
:
TransportId
,
next_mid_for_consumers
:
AtomicUsize
,
next_mid_for_consumers
:
AtomicUsize
,
used_sctp_stream_ids
:
Mutex
<
Hash
Map
<
u16
,
bool
>>
,
used_sctp_stream_ids
:
Mutex
<
Int
Map
<
u16
,
bool
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
channel
:
Channel
,
channel
:
Channel
,
...
@@ -253,9 +251,7 @@ impl Transport for DirectTransport {
...
@@ -253,9 +251,7 @@ impl Transport for DirectTransport {
.produce_impl
(
producer_options
,
TransportType
::
Direct
)
.produce_impl
(
producer_options
,
TransportType
::
Direct
)
.await
?
;
.await
?
;
self
.inner.handlers.new_producer
.call
(|
callback
|
{
self
.inner.handlers.new_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(
producer
)
Ok
(
producer
)
}
}
...
@@ -270,9 +266,7 @@ impl Transport for DirectTransport {
...
@@ -270,9 +266,7 @@ impl Transport for DirectTransport {
.consume_impl
(
consumer_options
,
TransportType
::
Direct
,
false
)
.consume_impl
(
consumer_options
,
TransportType
::
Direct
,
false
)
.await
?
;
.await
?
;
self
.inner.handlers.new_consumer
.call
(|
callback
|
{
self
.inner.handlers.new_consumer
.call_simple
(
&
consumer
);
callback
(
&
consumer
);
});
Ok
(
consumer
)
Ok
(
consumer
)
}
}
...
@@ -294,9 +288,10 @@ impl Transport for DirectTransport {
...
@@ -294,9 +288,10 @@ impl Transport for DirectTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_producer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_producer
);
.handlers
});
.new_data_producer
.call_simple
(
&
data_producer
);
Ok
(
data_producer
)
Ok
(
data_producer
)
}
}
...
@@ -318,9 +313,10 @@ impl Transport for DirectTransport {
...
@@ -318,9 +313,10 @@ impl Transport for DirectTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_consumer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_consumer
);
.handlers
});
.new_data_consumer
.call_simple
(
&
data_consumer
);
Ok
(
data_consumer
)
Ok
(
data_consumer
)
}
}
...
@@ -336,35 +332,35 @@ impl Transport for DirectTransport {
...
@@ -336,35 +332,35 @@ impl Transport for DirectTransport {
fn
on_new_producer
(
fn
on_new_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_producer
.add
(
callback
)
self
.inner.handlers.new_producer
.add
(
callback
)
}
}
fn
on_new_consumer
(
fn
on_new_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_consumer
.add
(
callback
)
self
.inner.handlers.new_consumer
.add
(
callback
)
}
}
fn
on_new_data_producer
(
fn
on_new_data_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_producer
.add
(
callback
)
self
.inner.handlers.new_data_producer
.add
(
callback
)
}
}
fn
on_new_data_consumer
(
fn
on_new_data_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_consumer
.add
(
callback
)
self
.inner.handlers.new_data_consumer
.add
(
callback
)
}
}
fn
on_trace
(
fn
on_trace
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
callback
)
self
.inner.handlers.trace
.add
(
callback
)
}
}
...
@@ -392,7 +388,11 @@ impl TransportGeneric for DirectTransport {
...
@@ -392,7 +388,11 @@ impl TransportGeneric for DirectTransport {
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
debug!
(
"dump()"
);
debug!
(
"dump()"
);
self
.dump_impl
()
.await
serde_json
::
from_value
(
self
.dump_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
/// Returns current RTC statistics of the transport.
/// Returns current RTC statistics of the transport.
...
@@ -402,7 +402,11 @@ impl TransportGeneric for DirectTransport {
...
@@ -402,7 +402,11 @@ impl TransportGeneric for DirectTransport {
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
debug!
(
"get_stats()"
);
debug!
(
"get_stats()"
);
self
.get_stats_impl
()
.await
serde_json
::
from_value
(
self
.get_stats_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
}
}
...
@@ -427,7 +431,7 @@ impl TransportImpl for DirectTransport {
...
@@ -427,7 +431,7 @@ impl TransportImpl for DirectTransport {
&
self
.inner.next_mid_for_consumers
&
self
.inner.next_mid_for_consumers
}
}
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Hash
Map
<
u16
,
bool
>>
{
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Int
Map
<
u16
,
bool
>>
{
&
self
.inner.used_sctp_stream_ids
&
self
.inner.used_sctp_stream_ids
}
}
...
@@ -453,12 +457,10 @@ impl DirectTransport {
...
@@ -453,12 +457,10 @@ impl DirectTransport {
let
handlers
=
Arc
::
clone
(
&
handlers
);
let
handlers
=
Arc
::
clone
(
&
handlers
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Trace
(
trace_event_data
)
=>
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
handlers
.trace
.call_simple
(
&
trace_event_data
);
callback
(
&
trace_event_data
);
});
}
}
},
},
Err
(
error
)
=>
{
Err
(
error
)
=>
{
...
@@ -471,13 +473,12 @@ impl DirectTransport {
...
@@ -471,13 +473,12 @@ impl DirectTransport {
let
payload_subscription_handler
=
{
let
payload_subscription_handler
=
{
let
handlers
=
Arc
::
clone
(
&
handlers
);
let
handlers
=
Arc
::
clone
(
&
handlers
);
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
payload_channel
.subscribe_to_notifications
(
id
.into
(),
move
|
message
,
payload
|
{
let
NotificationMessage
{
message
,
payload
}
=
notification
;
match
serde_json
::
from_slice
::
<
PayloadNotification
>
(
message
)
{
match
serde_json
::
from_value
::
<
PayloadNotification
>
(
message
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
PayloadNotification
::
Rtcp
=>
{
PayloadNotification
::
Rtcp
=>
{
handlers
.rtcp
.call
(|
callback
|
{
handlers
.rtcp
.call
(|
callback
|
{
callback
(
&
payload
);
callback
(
payload
);
});
});
}
}
},
},
...
@@ -489,7 +490,7 @@ impl DirectTransport {
...
@@ -489,7 +490,7 @@ impl DirectTransport {
};
};
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
used_sctp_stream_ids
=
Mutex
::
new
(
HashMap
::
new
());
let
used_sctp_stream_ids
=
Mutex
::
new
(
IntMap
::
default
());
let
cname_for_producers
=
Mutex
::
new
(
None
);
let
cname_for_producers
=
Mutex
::
new
(
None
);
let
inner_weak
=
Arc
::
<
Mutex
<
Option
<
Weak
<
Inner
>>>>
::
default
();
let
inner_weak
=
Arc
::
<
Mutex
<
Option
<
Weak
<
Inner
>>>>
::
default
();
let
on_router_close_handler
=
router
.on_close
({
let
on_router_close_handler
=
router
.on_close
({
...
@@ -526,21 +527,18 @@ impl DirectTransport {
...
@@ -526,21 +527,18 @@ impl DirectTransport {
/// Send a RTCP packet from the Rust process.
/// Send a RTCP packet from the Rust process.
///
///
/// * `rtcp_packet` - Bytes containing a valid RTCP packet (can be a compound packet).
/// * `rtcp_packet` - Bytes containing a valid RTCP packet (can be a compound packet).
pub
async
fn
send_rtcp
(
&
self
,
rtcp_packet
:
Bytes
)
->
Result
<
(),
NotificationError
>
{
pub
fn
send_rtcp
(
&
self
,
rtcp_packet
:
Vec
<
u8
>
)
->
Result
<
(),
NotificationError
>
{
self
.inner
self
.inner.payload_channel
.notify
(
.payload_channel
.notify
(
TransportSendRtcpNotification
{
TransportSendRtcpNotification
{
internal
:
self
.get_internal
(),
internal
:
self
.get_internal
(),
},
},
rtcp_packet
,
rtcp_packet
,
)
)
.await
}
}
/// Callback is called when the direct transport receives a RTCP packet from its router.
/// Callback is called when the direct transport receives a RTCP packet from its router.
pub
fn
on_rtcp
<
F
:
Fn
(
&
Bytes
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_rtcp
<
F
:
Fn
(
&
[
u8
]
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.rtcp
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.rtcp
.add
(
Arc
::
new
(
callback
))
}
}
/// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance.
/// Downgrade `DirectTransport` to [`WeakDirectTransport`] instance.
...
...
rust/src/router/pipe_transport.rs
浏览文件 @
f0ebd809
...
@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da
...
@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da
use
crate
::
data_producer
::{
DataProducer
,
DataProducerId
,
DataProducerOptions
,
DataProducerType
};
use
crate
::
data_producer
::{
DataProducer
,
DataProducerId
,
DataProducerOptions
,
DataProducerType
};
use
crate
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportTuple
};
use
crate
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportTuple
};
use
crate
::
messages
::{
use
crate
::
messages
::{
PipeTransportData
,
TransportCloseRequest
,
TransportConnect
RequestPipe
,
PipeTransportData
,
TransportCloseRequest
,
TransportConnect
PipeRequest
,
TransportConnectRequestPipeData
,
TransportInternal
,
TransportConnectRequestPipeData
,
TransportInternal
,
};
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
...
@@ -24,9 +24,9 @@ use async_executor::Executor;
...
@@ -24,9 +24,9 @@ use async_executor::Executor;
use
async_trait
::
async_trait
;
use
async_trait
::
async_trait
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
net
::
IpAddr
;
use
std
::
net
::
IpAddr
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
...
@@ -92,8 +92,8 @@ pub struct PipeTransportDump {
...
@@ -92,8 +92,8 @@ pub struct PipeTransportDump {
pub
direct
:
bool
,
pub
direct
:
bool
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
...
@@ -162,13 +162,13 @@ pub struct PipeTransportRemoteParameters {
...
@@ -162,13 +162,13 @@ pub struct PipeTransportRemoteParameters {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
new_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
new_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
new_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
>
,
new_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
,
Consumer
>
,
new_data_producer
:
Bag
<
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
>
,
new_data_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
,
DataProducer
>
,
new_data_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
>
,
new_data_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
,
DataConsumer
>
,
tuple
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
>
,
tuple
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
,
TransportTuple
>
,
sctp_state_change
:
Bag
<
Box
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
sctp_state_change
:
Bag
<
Arc
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
,
TransportTraceEventData
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -186,7 +186,7 @@ enum Notification {
...
@@ -186,7 +186,7 @@ enum Notification {
struct
Inner
{
struct
Inner
{
id
:
TransportId
,
id
:
TransportId
,
next_mid_for_consumers
:
AtomicUsize
,
next_mid_for_consumers
:
AtomicUsize
,
used_sctp_stream_ids
:
Mutex
<
Hash
Map
<
u16
,
bool
>>
,
used_sctp_stream_ids
:
Mutex
<
Int
Map
<
u16
,
bool
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
channel
:
Channel
,
channel
:
Channel
,
...
@@ -290,9 +290,7 @@ impl Transport for PipeTransport {
...
@@ -290,9 +290,7 @@ impl Transport for PipeTransport {
.produce_impl
(
producer_options
,
TransportType
::
Pipe
)
.produce_impl
(
producer_options
,
TransportType
::
Pipe
)
.await
?
;
.await
?
;
self
.inner.handlers.new_producer
.call
(|
callback
|
{
self
.inner.handlers.new_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(
producer
)
Ok
(
producer
)
}
}
...
@@ -304,9 +302,7 @@ impl Transport for PipeTransport {
...
@@ -304,9 +302,7 @@ impl Transport for PipeTransport {
.consume_impl
(
consumer_options
,
TransportType
::
Pipe
,
self
.inner.data.rtx
)
.consume_impl
(
consumer_options
,
TransportType
::
Pipe
,
self
.inner.data.rtx
)
.await
?
;
.await
?
;
self
.inner.handlers.new_consumer
.call
(|
callback
|
{
self
.inner.handlers.new_consumer
.call_simple
(
&
consumer
);
callback
(
&
consumer
);
});
Ok
(
consumer
)
Ok
(
consumer
)
}
}
...
@@ -325,9 +321,10 @@ impl Transport for PipeTransport {
...
@@ -325,9 +321,10 @@ impl Transport for PipeTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_producer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_producer
);
.handlers
});
.new_data_producer
.call_simple
(
&
data_producer
);
Ok
(
data_producer
)
Ok
(
data_producer
)
}
}
...
@@ -346,9 +343,10 @@ impl Transport for PipeTransport {
...
@@ -346,9 +343,10 @@ impl Transport for PipeTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_consumer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_consumer
);
.handlers
});
.new_data_consumer
.call_simple
(
&
data_consumer
);
Ok
(
data_consumer
)
Ok
(
data_consumer
)
}
}
...
@@ -364,35 +362,35 @@ impl Transport for PipeTransport {
...
@@ -364,35 +362,35 @@ impl Transport for PipeTransport {
fn
on_new_producer
(
fn
on_new_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_producer
.add
(
callback
)
self
.inner.handlers.new_producer
.add
(
callback
)
}
}
fn
on_new_consumer
(
fn
on_new_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_consumer
.add
(
callback
)
self
.inner.handlers.new_consumer
.add
(
callback
)
}
}
fn
on_new_data_producer
(
fn
on_new_data_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_producer
.add
(
callback
)
self
.inner.handlers.new_data_producer
.add
(
callback
)
}
}
fn
on_new_data_consumer
(
fn
on_new_data_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_consumer
.add
(
callback
)
self
.inner.handlers.new_data_consumer
.add
(
callback
)
}
}
fn
on_trace
(
fn
on_trace
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
callback
)
self
.inner.handlers.trace
.add
(
callback
)
}
}
...
@@ -419,13 +417,21 @@ impl TransportGeneric for PipeTransport {
...
@@ -419,13 +417,21 @@ impl TransportGeneric for PipeTransport {
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
debug!
(
"dump()"
);
debug!
(
"dump()"
);
self
.dump_impl
()
.await
serde_json
::
from_value
(
self
.dump_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
debug!
(
"get_stats()"
);
debug!
(
"get_stats()"
);
self
.get_stats_impl
()
.await
serde_json
::
from_value
(
self
.get_stats_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
}
}
...
@@ -450,7 +456,7 @@ impl TransportImpl for PipeTransport {
...
@@ -450,7 +456,7 @@ impl TransportImpl for PipeTransport {
&
self
.inner.next_mid_for_consumers
&
self
.inner.next_mid_for_consumers
}
}
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Hash
Map
<
u16
,
bool
>>
{
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Int
Map
<
u16
,
bool
>>
{
&
self
.inner.used_sctp_stream_ids
&
self
.inner.used_sctp_stream_ids
}
}
...
@@ -479,7 +485,7 @@ impl PipeTransport {
...
@@ -479,7 +485,7 @@ impl PipeTransport {
let
data
=
Arc
::
clone
(
&
data
);
let
data
=
Arc
::
clone
(
&
data
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
SctpStateChange
{
sctp_state
}
=>
{
Notification
::
SctpStateChange
{
sctp_state
}
=>
{
data
.sctp_state
.lock
()
.replace
(
sctp_state
);
data
.sctp_state
.lock
()
.replace
(
sctp_state
);
...
@@ -489,9 +495,7 @@ impl PipeTransport {
...
@@ -489,9 +495,7 @@ impl PipeTransport {
});
});
}
}
Notification
::
Trace
(
trace_event_data
)
=>
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
handlers
.trace
.call_simple
(
&
trace_event_data
);
callback
(
&
trace_event_data
);
});
}
}
},
},
Err
(
error
)
=>
{
Err
(
error
)
=>
{
...
@@ -503,7 +507,7 @@ impl PipeTransport {
...
@@ -503,7 +507,7 @@ impl PipeTransport {
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
used_sctp_stream_ids
=
Mutex
::
new
({
let
used_sctp_stream_ids
=
Mutex
::
new
({
let
mut
used_used_sctp_stream_ids
=
HashMap
::
new
();
let
mut
used_used_sctp_stream_ids
=
IntMap
::
default
();
if
let
Some
(
sctp_parameters
)
=
&
data
.sctp_parameters
{
if
let
Some
(
sctp_parameters
)
=
&
data
.sctp_parameters
{
for
i
in
0
..
sctp_parameters
.mis
{
for
i
in
0
..
sctp_parameters
.mis
{
used_used_sctp_stream_ids
.insert
(
i
,
false
);
used_used_sctp_stream_ids
.insert
(
i
,
false
);
...
@@ -555,7 +559,7 @@ impl PipeTransport {
...
@@ -555,7 +559,7 @@ impl PipeTransport {
let
response
=
self
let
response
=
self
.inner
.inner
.channel
.channel
.request
(
TransportConnect
RequestPipe
{
.request
(
TransportConnect
PipeRequest
{
internal
:
self
.get_internal
(),
internal
:
self
.get_internal
(),
data
:
TransportConnectRequestPipeData
{
data
:
TransportConnectRequestPipeData
{
ip
:
remote_parameters
.ip
,
ip
:
remote_parameters
.ip
,
...
@@ -617,7 +621,7 @@ impl PipeTransport {
...
@@ -617,7 +621,7 @@ impl PipeTransport {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.tuple
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.tuple
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the transport SCTP state changes.
/// Callback is called when the transport SCTP state changes.
...
@@ -628,7 +632,7 @@ impl PipeTransport {
...
@@ -628,7 +632,7 @@ impl PipeTransport {
self
.inner
self
.inner
.handlers
.handlers
.sctp_state_change
.sctp_state_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance.
/// Downgrade `PipeTransport` to [`WeakPipeTransport`] instance.
...
...
rust/src/router/plain_transport.rs
浏览文件 @
f0ebd809
...
@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da
...
@@ -6,7 +6,7 @@ use crate::data_consumer::{DataConsumer, DataConsumerId, DataConsumerOptions, Da
use
crate
::
data_producer
::{
DataProducer
,
DataProducerId
,
DataProducerOptions
,
DataProducerType
};
use
crate
::
data_producer
::{
DataProducer
,
DataProducerId
,
DataProducerOptions
,
DataProducerType
};
use
crate
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportTuple
};
use
crate
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportTuple
};
use
crate
::
messages
::{
use
crate
::
messages
::{
PlainTransportData
,
TransportCloseRequest
,
TransportConnect
RequestPlain
,
PlainTransportData
,
TransportCloseRequest
,
TransportConnect
PlainRequest
,
TransportConnectRequestPlainData
,
TransportInternal
,
TransportConnectRequestPlainData
,
TransportInternal
,
};
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
...
@@ -24,9 +24,9 @@ use async_executor::Executor;
...
@@ -24,9 +24,9 @@ use async_executor::Executor;
use
async_trait
::
async_trait
;
use
async_trait
::
async_trait
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
net
::
IpAddr
;
use
std
::
net
::
IpAddr
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicBool
,
AtomicUsize
,
Ordering
};
...
@@ -108,8 +108,8 @@ pub struct PlainTransportDump {
...
@@ -108,8 +108,8 @@ pub struct PlainTransportDump {
pub
direct
:
bool
,
pub
direct
:
bool
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
...
@@ -191,14 +191,14 @@ pub struct PlainTransportRemoteParameters {
...
@@ -191,14 +191,14 @@ pub struct PlainTransportRemoteParameters {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
new_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
new_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
new_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
>
,
new_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
,
Consumer
>
,
new_data_producer
:
Bag
<
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
>
,
new_data_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
,
DataProducer
>
,
new_data_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
>
,
new_data_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
,
DataConsumer
>
,
tuple
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
>
,
tuple
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
,
TransportTuple
>
,
rtcp_tuple
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
>
,
rtcp_tuple
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
,
TransportTuple
>
,
sctp_state_change
:
Bag
<
Box
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
sctp_state_change
:
Bag
<
Arc
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
,
TransportTraceEventData
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -206,8 +206,13 @@ struct Handlers {
...
@@ -206,8 +206,13 @@ struct Handlers {
#[derive(Debug,
Deserialize)]
#[derive(Debug,
Deserialize)]
#[serde(tag
=
"event"
,
rename_all
=
"lowercase"
,
content
=
"data"
)]
#[serde(tag
=
"event"
,
rename_all
=
"lowercase"
,
content
=
"data"
)]
enum
Notification
{
enum
Notification
{
Tuple
(
TransportTuple
),
Tuple
{
RtcpTuple
(
TransportTuple
),
tuple
:
TransportTuple
,
},
#[serde(rename_all
=
"camelCase"
)]
RtcpTuple
{
rtcp_tuple
:
TransportTuple
,
},
#[serde(rename_all
=
"camelCase"
)]
#[serde(rename_all
=
"camelCase"
)]
SctpStateChange
{
SctpStateChange
{
sctp_state
:
SctpState
,
sctp_state
:
SctpState
,
...
@@ -218,7 +223,7 @@ enum Notification {
...
@@ -218,7 +223,7 @@ enum Notification {
struct
Inner
{
struct
Inner
{
id
:
TransportId
,
id
:
TransportId
,
next_mid_for_consumers
:
AtomicUsize
,
next_mid_for_consumers
:
AtomicUsize
,
used_sctp_stream_ids
:
Mutex
<
Hash
Map
<
u16
,
bool
>>
,
used_sctp_stream_ids
:
Mutex
<
Int
Map
<
u16
,
bool
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
channel
:
Channel
,
channel
:
Channel
,
...
@@ -315,9 +320,7 @@ impl Transport for PlainTransport {
...
@@ -315,9 +320,7 @@ impl Transport for PlainTransport {
.produce_impl
(
producer_options
,
TransportType
::
Plain
)
.produce_impl
(
producer_options
,
TransportType
::
Plain
)
.await
?
;
.await
?
;
self
.inner.handlers.new_producer
.call
(|
callback
|
{
self
.inner.handlers.new_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(
producer
)
Ok
(
producer
)
}
}
...
@@ -329,9 +332,7 @@ impl Transport for PlainTransport {
...
@@ -329,9 +332,7 @@ impl Transport for PlainTransport {
.consume_impl
(
consumer_options
,
TransportType
::
Plain
,
false
)
.consume_impl
(
consumer_options
,
TransportType
::
Plain
,
false
)
.await
?
;
.await
?
;
self
.inner.handlers.new_consumer
.call
(|
callback
|
{
self
.inner.handlers.new_consumer
.call_simple
(
&
consumer
);
callback
(
&
consumer
);
});
Ok
(
consumer
)
Ok
(
consumer
)
}
}
...
@@ -350,9 +351,10 @@ impl Transport for PlainTransport {
...
@@ -350,9 +351,10 @@ impl Transport for PlainTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_producer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_producer
);
.handlers
});
.new_data_producer
.call_simple
(
&
data_producer
);
Ok
(
data_producer
)
Ok
(
data_producer
)
}
}
...
@@ -371,9 +373,10 @@ impl Transport for PlainTransport {
...
@@ -371,9 +373,10 @@ impl Transport for PlainTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_consumer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_consumer
);
.handlers
});
.new_data_consumer
.call_simple
(
&
data_consumer
);
Ok
(
data_consumer
)
Ok
(
data_consumer
)
}
}
...
@@ -389,35 +392,35 @@ impl Transport for PlainTransport {
...
@@ -389,35 +392,35 @@ impl Transport for PlainTransport {
fn
on_new_producer
(
fn
on_new_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_producer
.add
(
callback
)
self
.inner.handlers.new_producer
.add
(
callback
)
}
}
fn
on_new_consumer
(
fn
on_new_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_consumer
.add
(
callback
)
self
.inner.handlers.new_consumer
.add
(
callback
)
}
}
fn
on_new_data_producer
(
fn
on_new_data_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_producer
.add
(
callback
)
self
.inner.handlers.new_data_producer
.add
(
callback
)
}
}
fn
on_new_data_consumer
(
fn
on_new_data_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_consumer
.add
(
callback
)
self
.inner.handlers.new_data_consumer
.add
(
callback
)
}
}
fn
on_trace
(
fn
on_trace
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
callback
)
self
.inner.handlers.trace
.add
(
callback
)
}
}
...
@@ -444,13 +447,21 @@ impl TransportGeneric for PlainTransport {
...
@@ -444,13 +447,21 @@ impl TransportGeneric for PlainTransport {
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
debug!
(
"dump()"
);
debug!
(
"dump()"
);
self
.dump_impl
()
.await
serde_json
::
from_value
(
self
.dump_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
debug!
(
"get_stats()"
);
debug!
(
"get_stats()"
);
self
.get_stats_impl
()
.await
serde_json
::
from_value
(
self
.get_stats_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
}
}
...
@@ -475,7 +486,7 @@ impl TransportImpl for PlainTransport {
...
@@ -475,7 +486,7 @@ impl TransportImpl for PlainTransport {
&
self
.inner.next_mid_for_consumers
&
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
&
self
.inner.used_sctp_stream_ids
}
}
...
@@ -504,21 +515,17 @@ impl PlainTransport {
...
@@ -504,21 +515,17 @@ impl PlainTransport {
let
data
=
Arc
::
clone
(
&
data
);
let
data
=
Arc
::
clone
(
&
data
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Tuple
(
tuple
)
=>
{
Notification
::
Tuple
{
tuple
}
=>
{
*
data
.tuple
.lock
()
=
tuple
;
*
data
.tuple
.lock
()
=
tuple
;
handlers
.tuple
.call
(|
callback
|
{
handlers
.tuple
.call_simple
(
&
tuple
);
callback
(
&
tuple
);
});
}
}
Notification
::
RtcpTuple
(
rtcp_tuple
)
=>
{
Notification
::
RtcpTuple
{
rtcp_tuple
}
=>
{
data
.rtcp_tuple
.lock
()
.replace
(
rtcp_tuple
);
data
.rtcp_tuple
.lock
()
.replace
(
rtcp_tuple
);
handlers
.rtcp_tuple
.call
(|
callback
|
{
handlers
.rtcp_tuple
.call_simple
(
&
rtcp_tuple
);
callback
(
&
rtcp_tuple
);
});
}
}
Notification
::
SctpStateChange
{
sctp_state
}
=>
{
Notification
::
SctpStateChange
{
sctp_state
}
=>
{
data
.sctp_state
.lock
()
.replace
(
sctp_state
);
data
.sctp_state
.lock
()
.replace
(
sctp_state
);
...
@@ -528,9 +535,7 @@ impl PlainTransport {
...
@@ -528,9 +535,7 @@ impl PlainTransport {
});
});
}
}
Notification
::
Trace
(
trace_event_data
)
=>
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
handlers
.trace
.call_simple
(
&
trace_event_data
);
callback
(
&
trace_event_data
);
});
}
}
},
},
Err
(
error
)
=>
{
Err
(
error
)
=>
{
...
@@ -542,7 +547,7 @@ impl PlainTransport {
...
@@ -542,7 +547,7 @@ impl PlainTransport {
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
used_sctp_stream_ids
=
Mutex
::
new
({
let
used_sctp_stream_ids
=
Mutex
::
new
({
let
mut
used_used_sctp_stream_ids
=
HashMap
::
new
();
let
mut
used_used_sctp_stream_ids
=
IntMap
::
default
();
if
let
Some
(
sctp_parameters
)
=
&
data
.sctp_parameters
{
if
let
Some
(
sctp_parameters
)
=
&
data
.sctp_parameters
{
for
i
in
0
..
sctp_parameters
.mis
{
for
i
in
0
..
sctp_parameters
.mis
{
used_used_sctp_stream_ids
.insert
(
i
,
false
);
used_used_sctp_stream_ids
.insert
(
i
,
false
);
...
@@ -689,7 +694,7 @@ impl PlainTransport {
...
@@ -689,7 +694,7 @@ impl PlainTransport {
let
response
=
self
let
response
=
self
.inner
.inner
.channel
.channel
.request
(
TransportConnect
RequestPlain
{
.request
(
TransportConnect
PlainRequest
{
internal
:
self
.get_internal
(),
internal
:
self
.get_internal
(),
data
:
TransportConnectRequestPlainData
{
data
:
TransportConnectRequestPlainData
{
ip
:
remote_parameters
.ip
,
ip
:
remote_parameters
.ip
,
...
@@ -782,7 +787,7 @@ impl PlainTransport {
...
@@ -782,7 +787,7 @@ impl PlainTransport {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.tuple
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.tuple
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called after the remote RTCP origin has been discovered. Only if `comedia` mode
/// Callback is called after the remote RTCP origin has been discovered. Only if `comedia` mode
...
@@ -791,7 +796,7 @@ impl PlainTransport {
...
@@ -791,7 +796,7 @@ impl PlainTransport {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.rtcp_tuple
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.rtcp_tuple
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the transport SCTP state changes.
/// Callback is called when the transport SCTP state changes.
...
@@ -802,7 +807,7 @@ impl PlainTransport {
...
@@ -802,7 +807,7 @@ impl PlainTransport {
self
.inner
self
.inner
.handlers
.handlers
.sctp_state_change
.sctp_state_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Downgrade `PlainTransport` to [`WeakPlainTransport`] instance.
/// Downgrade `PlainTransport` to [`WeakPlainTransport`] instance.
...
...
rust/src/router/producer.rs
浏览文件 @
f0ebd809
...
@@ -16,13 +16,12 @@ use crate::worker::{
...
@@ -16,13 +16,12 @@ use crate::worker::{
Channel
,
NotificationError
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
Channel
,
NotificationError
,
PayloadChannel
,
RequestError
,
SubscriptionHandler
,
};
};
use
async_executor
::
Executor
;
use
async_executor
::
Executor
;
use
bytes
::
Bytes
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
hash_hasher
::
HashedMap
;
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
serde_repr
::{
Deserialize_repr
,
Serialize_repr
};
use
serde_repr
::{
Deserialize_repr
,
Serialize_repr
};
use
std
::
collections
::
HashMap
;
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
fmt
::
Debug
;
use
std
::
fmt
::
Debug
;
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicBool
,
Ordering
};
...
@@ -101,7 +100,7 @@ pub struct RtpStreamRecv {
...
@@ -101,7 +100,7 @@ pub struct RtpStreamRecv {
pub
packet_count
:
usize
,
pub
packet_count
:
usize
,
pub
byte_count
:
usize
,
pub
byte_count
:
usize
,
pub
bitrate
:
u32
,
pub
bitrate
:
u32
,
pub
bitrate_by_layer
:
Option
<
HashMap
<
String
,
u32
>>
,
pub
bitrate_by_layer
:
Option
<
Hash
ed
Map
<
String
,
u32
>>
,
}
}
#[derive(Debug,
Clone,
PartialEq,
Deserialize,
Serialize)]
#[derive(Debug,
Clone,
PartialEq,
Deserialize,
Serialize)]
...
@@ -202,7 +201,7 @@ pub struct ProducerStat {
...
@@ -202,7 +201,7 @@ pub struct ProducerStat {
pub
rtx_packets_discarded
:
Option
<
u32
>
,
pub
rtx_packets_discarded
:
Option
<
u32
>
,
// RtpStreamRecv specific.
// RtpStreamRecv specific.
pub
jitter
:
u32
,
pub
jitter
:
u32
,
pub
bitrate_by_layer
:
Option
<
HashMap
<
String
,
u32
>>
,
pub
bitrate_by_layer
:
Option
<
Hash
ed
Map
<
String
,
u32
>>
,
}
}
/// 'trace' event data.
/// 'trace' event data.
...
@@ -280,11 +279,11 @@ enum Notification {
...
@@ -280,11 +279,11 @@ enum Notification {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
score
:
Bag
<
Box
<
dyn
Fn
(
&
Vec
<
ProducerScore
>
)
+
Send
+
Sync
>>
,
score
:
Bag
<
Arc
<
dyn
Fn
(
&
[
ProducerScore
]
)
+
Send
+
Sync
>>
,
video_orientation_change
:
Bag
<
Box
<
dyn
Fn
(
ProducerVideoOrientation
)
+
Send
+
Sync
>>
,
video_orientation_change
:
Bag
<
Arc
<
dyn
Fn
(
ProducerVideoOrientation
)
+
Send
+
Sync
>>
,
pause
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
pause
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Box
<
dyn
Fn
()
+
Send
+
Sync
>>
,
resume
:
Bag
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
ProducerTraceEventData
)
+
Send
+
Sync
>
>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
ProducerTraceEventData
)
+
Send
+
Sync
>
,
ProducerTraceEventData
>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
transport_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -459,7 +458,7 @@ impl Producer {
...
@@ -459,7 +458,7 @@ impl Producer {
let
score
=
Arc
::
clone
(
&
score
);
let
score
=
Arc
::
clone
(
&
score
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
Score
(
scores
)
=>
{
Notification
::
Score
(
scores
)
=>
{
*
score
.lock
()
=
scores
.clone
();
*
score
.lock
()
=
scores
.clone
();
...
@@ -473,9 +472,7 @@ impl Producer {
...
@@ -473,9 +472,7 @@ impl Producer {
});
});
}
}
Notification
::
Trace
(
trace_event_data
)
=>
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
handlers
.trace
.call_simple
(
&
trace_event_data
);
callback
(
&
trace_event_data
);
});
}
}
},
},
Err
(
error
)
=>
{
Err
(
error
)
=>
{
...
@@ -666,11 +663,11 @@ impl Producer {
...
@@ -666,11 +663,11 @@ impl Producer {
}
}
/// Callback is called when the producer score changes.
/// Callback is called when the producer score changes.
pub
fn
on_score
<
F
:
Fn
(
&
Vec
<
ProducerScore
>
)
+
Send
+
Sync
+
'static
>
(
pub
fn
on_score
<
F
:
Fn
(
&
[
ProducerScore
]
)
+
Send
+
Sync
+
'static
>
(
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner
()
.handlers.score
.add
(
Box
::
new
(
callback
))
self
.inner
()
.handlers.score
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the video orientation changes. This is just possible if the
/// Callback is called when the video orientation changes. This is just possible if the
...
@@ -683,17 +680,17 @@ impl Producer {
...
@@ -683,17 +680,17 @@ impl Producer {
self
.inner
()
self
.inner
()
.handlers
.handlers
.video_orientation_change
.video_orientation_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the producer is paused.
/// Callback is called when the producer is paused.
pub
fn
on_pause
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_pause
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner
()
.handlers.pause
.add
(
Box
::
new
(
callback
))
self
.inner
()
.handlers.pause
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the producer is resumed.
/// Callback is called when the producer is resumed.
pub
fn
on_resume
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_resume
<
F
:
Fn
()
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner
()
.handlers.resume
.add
(
Box
::
new
(
callback
))
self
.inner
()
.handlers.resume
.add
(
Arc
::
new
(
callback
))
}
}
/// See [`Producer::enable_trace_event`] method.
/// See [`Producer::enable_trace_event`] method.
...
@@ -701,7 +698,7 @@ impl Producer {
...
@@ -701,7 +698,7 @@ impl Producer {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner
()
.handlers.trace
.add
(
Box
::
new
(
callback
))
self
.inner
()
.handlers.trace
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the transport this producer belongs to is closed for whatever
/// Callback is called when the transport this producer belongs to is closed for whatever
...
@@ -763,10 +760,8 @@ impl Producer {
...
@@ -763,10 +760,8 @@ impl Producer {
impl
DirectProducer
{
impl
DirectProducer
{
/// Sends a RTP packet from the Rust process.
/// Sends a RTP packet from the Rust process.
pub
async
fn
send
(
&
self
,
rtp_packet
:
Bytes
)
->
Result
<
(),
NotificationError
>
{
pub
fn
send
(
&
self
,
rtp_packet
:
Vec
<
u8
>
)
->
Result
<
(),
NotificationError
>
{
self
.inner
self
.inner.payload_channel
.notify
(
.payload_channel
.notify
(
ProducerSendNotification
{
ProducerSendNotification
{
internal
:
ProducerInternal
{
internal
:
ProducerInternal
{
router_id
:
self
.inner.transport
.router_id
(),
router_id
:
self
.inner.transport
.router_id
(),
...
@@ -776,7 +771,6 @@ impl DirectProducer {
...
@@ -776,7 +771,6 @@ impl DirectProducer {
},
},
rtp_packet
,
rtp_packet
,
)
)
.await
}
}
}
}
...
...
rust/src/router/transport.rs
浏览文件 @
f0ebd809
...
@@ -23,13 +23,14 @@ use crate::{ortc, uuid_based_wrapper_type};
...
@@ -23,13 +23,14 @@ use crate::{ortc, uuid_based_wrapper_type};
use
async_executor
::
Executor
;
use
async_executor
::
Executor
;
use
async_trait
::
async_trait
;
use
async_trait
::
async_trait
;
use
event_listener_primitives
::
HandlerId
;
use
event_listener_primitives
::
HandlerId
;
use
hash_hasher
::
HashedMap
;
use
log
::{
error
,
warn
};
use
log
::{
error
,
warn
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::
de
::
DeserializeOwned
;
use
serde
::
de
::
DeserializeOwned
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
s
td
::
collections
::
HashMap
;
use
s
erde_json
::
Value
;
use
std
::
fmt
::
Debug
;
use
std
::
fmt
::
Debug
;
use
std
::
marker
::
PhantomData
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
use
std
::
sync
::
Arc
;
use
thiserror
::
Error
;
use
thiserror
::
Error
;
...
@@ -103,11 +104,11 @@ pub enum TransportTraceEventType {
...
@@ -103,11 +104,11 @@ pub enum TransportTraceEventType {
#[doc(hidden)]
#[doc(hidden)]
pub
struct
RtpListener
{
pub
struct
RtpListener
{
/// Map from Ssrc (as string) to producer ID
/// Map from Ssrc (as string) to producer ID
pub
mid_table
:
HashMap
<
String
,
ProducerId
>
,
pub
mid_table
:
Hash
ed
Map
<
String
,
ProducerId
>
,
/// Map from Ssrc (as string) to producer ID
/// Map from Ssrc (as string) to producer ID
pub
rid_table
:
HashMap
<
String
,
ProducerId
>
,
pub
rid_table
:
Hash
ed
Map
<
String
,
ProducerId
>
,
/// Map from Ssrc (as string) to producer ID
/// Map from Ssrc (as string) to producer ID
pub
ssrc_table
:
HashMap
<
String
,
ProducerId
>
,
pub
ssrc_table
:
Hash
ed
Map
<
String
,
ProducerId
>
,
}
}
#[derive(Debug,
Copy,
Clone,
Ord,
PartialOrd,
Eq,
PartialEq,
Hash,
Deserialize,
Serialize)]
#[derive(Debug,
Copy,
Clone,
Ord,
PartialOrd,
Eq,
PartialEq,
Hash,
Deserialize,
Serialize)]
...
@@ -126,7 +127,7 @@ pub struct RecvRtpHeaderExtensions {
...
@@ -126,7 +127,7 @@ pub struct RecvRtpHeaderExtensions {
#[doc(hidden)]
#[doc(hidden)]
pub
struct
SctpListener
{
pub
struct
SctpListener
{
/// Map from stream ID (as string) to data producer ID
/// Map from stream ID (as string) to data producer ID
stream_id_table
:
HashMap
<
String
,
DataProducerId
>
,
stream_id_table
:
Hash
ed
Map
<
String
,
DataProducerId
>
,
}
}
#[derive(Debug,
Copy,
Clone,
PartialEq)]
#[derive(Debug,
Copy,
Clone,
PartialEq)]
...
@@ -236,31 +237,31 @@ pub trait Transport: Debug + Send + Sync + private::CloneTransport {
...
@@ -236,31 +237,31 @@ pub trait Transport: Debug + Send + Sync + private::CloneTransport {
/// Callback is called when a new producer is created.
/// Callback is called when a new producer is created.
fn
on_new_producer
(
fn
on_new_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
)
->
HandlerId
;
/// Callback is called when a new consumer is created.
/// Callback is called when a new consumer is created.
fn
on_new_consumer
(
fn
on_new_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
)
->
HandlerId
;
/// Callback is called when a new data producer is created.
/// Callback is called when a new data producer is created.
fn
on_new_data_producer
(
fn
on_new_data_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
)
->
HandlerId
;
/// Callback is called when a new data consumer is created.
/// Callback is called when a new data consumer is created.
fn
on_new_data_consumer
(
fn
on_new_data_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
)
->
HandlerId
;
/// See [`Transport::enable_trace_event()`]
/// See [`Transport::enable_trace_event()`]
fn
on_trace
(
fn
on_trace
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
;
)
->
HandlerId
;
/// Callback is called when the router this transport belongs to is closed for whatever reason.
/// Callback is called when the router this transport belongs to is closed for whatever reason.
...
@@ -371,7 +372,7 @@ pub(super) trait TransportImpl: TransportGeneric {
...
@@ -371,7 +372,7 @@ pub(super) trait TransportImpl: TransportGeneric {
fn
next_mid_for_consumers
(
&
self
)
->
&
AtomicUsize
;
fn
next_mid_for_consumers
(
&
self
)
->
&
AtomicUsize
;
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Hash
Map
<
u16
,
bool
>>
;
fn
used_sctp_stream_ids
(
&
self
)
->
&
Mutex
<
Int
Map
<
u16
,
bool
>>
;
fn
cname_for_producers
(
&
self
)
->
&
Mutex
<
Option
<
String
>>
;
fn
cname_for_producers
(
&
self
)
->
&
Mutex
<
Option
<
String
>>
;
...
@@ -395,26 +396,24 @@ pub(super) trait TransportImpl: TransportGeneric {
...
@@ -395,26 +396,24 @@ pub(super) trait TransportImpl: TransportGeneric {
}
}
}
}
async
fn
dump_impl
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
async
fn
dump_impl
(
&
self
)
->
Result
<
Value
,
RequestError
>
{
self
.channel
()
self
.channel
()
.request
(
TransportDumpRequest
{
.request
(
TransportDumpRequest
{
internal
:
TransportInternal
{
internal
:
TransportInternal
{
router_id
:
self
.router
()
.id
(),
router_id
:
self
.router
()
.id
(),
transport_id
:
self
.id
(),
transport_id
:
self
.id
(),
},
},
phantom_data
:
PhantomData
{},
})
})
.await
.await
}
}
async
fn
get_stats_impl
(
&
self
)
->
Result
<
V
ec
<
Self
::
Stat
>
,
RequestError
>
{
async
fn
get_stats_impl
(
&
self
)
->
Result
<
V
alue
,
RequestError
>
{
self
.channel
()
self
.channel
()
.request
(
TransportGetStatsRequest
{
.request
(
TransportGetStatsRequest
{
internal
:
TransportInternal
{
internal
:
TransportInternal
{
router_id
:
self
.router
()
.id
(),
router_id
:
self
.router
()
.id
(),
transport_id
:
self
.id
(),
transport_id
:
self
.id
(),
},
},
phantom_data
:
PhantomData
{},
})
})
.await
.await
}
}
...
...
rust/src/router/webrtc_transport.rs
浏览文件 @
f0ebd809
...
@@ -9,7 +9,7 @@ use crate::data_structures::{
...
@@ -9,7 +9,7 @@ use crate::data_structures::{
TransportListenIp
,
TransportTuple
,
TransportListenIp
,
TransportTuple
,
};
};
use
crate
::
messages
::{
use
crate
::
messages
::{
TransportCloseRequest
,
TransportConnectRequestWebRtc
,
TransportConnectRequestWebRtcData
,
TransportCloseRequest
,
TransportConnectRequestWebRtc
Data
,
TransportConnectWebRtcRequest
,
TransportInternal
,
TransportRestartIceRequest
,
WebRtcTransportData
,
TransportInternal
,
TransportRestartIceRequest
,
WebRtcTransportData
,
};
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
use
crate
::
producer
::{
Producer
,
ProducerId
,
ProducerOptions
};
...
@@ -27,9 +27,9 @@ use async_executor::Executor;
...
@@ -27,9 +27,9 @@ use async_executor::Executor;
use
async_trait
::
async_trait
;
use
async_trait
::
async_trait
;
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
event_listener_primitives
::{
Bag
,
BagOnce
,
HandlerId
};
use
log
::{
debug
,
error
};
use
log
::{
debug
,
error
};
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
collections
::
HashMap
;
use
std
::
convert
::
TryFrom
;
use
std
::
convert
::
TryFrom
;
use
std
::
fmt
;
use
std
::
fmt
;
use
std
::
ops
::
Deref
;
use
std
::
ops
::
Deref
;
...
@@ -157,8 +157,8 @@ pub struct WebRtcTransportDump {
...
@@ -157,8 +157,8 @@ pub struct WebRtcTransportDump {
pub
direct
:
bool
,
pub
direct
:
bool
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
producer_ids
:
Vec
<
ProducerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
consumer_ids
:
Vec
<
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Hash
Map
<
u32
,
ConsumerId
>
,
pub
map_rtx_ssrc_consumer_id
:
Int
Map
<
u32
,
ConsumerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_producer_ids
:
Vec
<
DataProducerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
data_consumer_ids
:
Vec
<
DataConsumerId
>
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
pub
recv_rtp_header_extensions
:
RecvRtpHeaderExtensions
,
...
@@ -231,15 +231,15 @@ pub struct WebRtcTransportRemoteParameters {
...
@@ -231,15 +231,15 @@ pub struct WebRtcTransportRemoteParameters {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
new_producer
:
Bag
<
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
>
,
new_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
>
,
Producer
>
,
new_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
>
,
new_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
>
,
Consumer
>
,
new_data_producer
:
Bag
<
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
>
,
new_data_producer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
>
,
DataProducer
>
,
new_data_consumer
:
Bag
<
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
>
,
new_data_consumer
:
Bag
<
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
>
,
DataConsumer
>
,
ice_state_change
:
Bag
<
Box
<
dyn
Fn
(
IceState
)
+
Send
+
Sync
>>
,
ice_state_change
:
Bag
<
Arc
<
dyn
Fn
(
IceState
)
+
Send
+
Sync
>>
,
ice_selected_tuple_change
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
>
,
ice_selected_tuple_change
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTuple
)
+
Send
+
Sync
>
,
TransportTuple
>
,
dtls_state_change
:
Bag
<
Box
<
dyn
Fn
(
DtlsState
)
+
Send
+
Sync
>>
,
dtls_state_change
:
Bag
<
Arc
<
dyn
Fn
(
DtlsState
)
+
Send
+
Sync
>>
,
sctp_state_change
:
Bag
<
Box
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
sctp_state_change
:
Bag
<
Arc
<
dyn
Fn
(
SctpState
)
+
Send
+
Sync
>>
,
trace
:
Bag
<
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
>
,
trace
:
Bag
<
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
>
,
TransportTraceEventData
>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
router_close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
}
}
...
@@ -270,7 +270,7 @@ enum Notification {
...
@@ -270,7 +270,7 @@ enum Notification {
struct
Inner
{
struct
Inner
{
id
:
TransportId
,
id
:
TransportId
,
next_mid_for_consumers
:
AtomicUsize
,
next_mid_for_consumers
:
AtomicUsize
,
used_sctp_stream_ids
:
Mutex
<
Hash
Map
<
u16
,
bool
>>
,
used_sctp_stream_ids
:
Mutex
<
Int
Map
<
u16
,
bool
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
cname_for_producers
:
Mutex
<
Option
<
String
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
channel
:
Channel
,
channel
:
Channel
,
...
@@ -375,9 +375,7 @@ impl Transport for WebRtcTransport {
...
@@ -375,9 +375,7 @@ impl Transport for WebRtcTransport {
.produce_impl
(
producer_options
,
TransportType
::
WebRtc
)
.produce_impl
(
producer_options
,
TransportType
::
WebRtc
)
.await
?
;
.await
?
;
self
.inner.handlers.new_producer
.call
(|
callback
|
{
self
.inner.handlers.new_producer
.call_simple
(
&
producer
);
callback
(
&
producer
);
});
Ok
(
producer
)
Ok
(
producer
)
}
}
...
@@ -389,9 +387,7 @@ impl Transport for WebRtcTransport {
...
@@ -389,9 +387,7 @@ impl Transport for WebRtcTransport {
.consume_impl
(
consumer_options
,
TransportType
::
WebRtc
,
false
)
.consume_impl
(
consumer_options
,
TransportType
::
WebRtc
,
false
)
.await
?
;
.await
?
;
self
.inner.handlers.new_consumer
.call
(|
callback
|
{
self
.inner.handlers.new_consumer
.call_simple
(
&
consumer
);
callback
(
&
consumer
);
});
Ok
(
consumer
)
Ok
(
consumer
)
}
}
...
@@ -410,9 +406,10 @@ impl Transport for WebRtcTransport {
...
@@ -410,9 +406,10 @@ impl Transport for WebRtcTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_producer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_producer
);
.handlers
});
.new_data_producer
.call_simple
(
&
data_producer
);
Ok
(
data_producer
)
Ok
(
data_producer
)
}
}
...
@@ -431,9 +428,10 @@ impl Transport for WebRtcTransport {
...
@@ -431,9 +428,10 @@ impl Transport for WebRtcTransport {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_data_consumer
.call
(|
callback
|
{
self
.inner
callback
(
&
data_consumer
);
.handlers
});
.new_data_consumer
.call_simple
(
&
data_consumer
);
Ok
(
data_consumer
)
Ok
(
data_consumer
)
}
}
...
@@ -449,35 +447,35 @@ impl Transport for WebRtcTransport {
...
@@ -449,35 +447,35 @@ impl Transport for WebRtcTransport {
fn
on_new_producer
(
fn
on_new_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Producer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_producer
.add
(
callback
)
self
.inner.handlers.new_producer
.add
(
callback
)
}
}
fn
on_new_consumer
(
fn
on_new_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
Consumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_consumer
.add
(
callback
)
self
.inner.handlers.new_consumer
.add
(
callback
)
}
}
fn
on_new_data_producer
(
fn
on_new_data_producer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataProducer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_producer
.add
(
callback
)
self
.inner.handlers.new_data_producer
.add
(
callback
)
}
}
fn
on_new_data_consumer
(
fn
on_new_data_consumer
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
DataConsumer
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.new_data_consumer
.add
(
callback
)
self
.inner.handlers.new_data_consumer
.add
(
callback
)
}
}
fn
on_trace
(
fn
on_trace
(
&
self
,
&
self
,
callback
:
Box
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
callback
:
Arc
<
dyn
Fn
(
&
TransportTraceEventData
)
+
Send
+
Sync
+
'static
>
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.trace
.add
(
callback
)
self
.inner.handlers.trace
.add
(
callback
)
}
}
...
@@ -504,13 +502,21 @@ impl TransportGeneric for WebRtcTransport {
...
@@ -504,13 +502,21 @@ impl TransportGeneric for WebRtcTransport {
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
async
fn
dump
(
&
self
)
->
Result
<
Self
::
Dump
,
RequestError
>
{
debug!
(
"dump()"
);
debug!
(
"dump()"
);
self
.dump_impl
()
.await
serde_json
::
from_value
(
self
.dump_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
async
fn
get_stats
(
&
self
)
->
Result
<
Vec
<
Self
::
Stat
>
,
RequestError
>
{
debug!
(
"get_stats()"
);
debug!
(
"get_stats()"
);
self
.get_stats_impl
()
.await
serde_json
::
from_value
(
self
.get_stats_impl
()
.await
?
)
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
}
}
...
@@ -535,7 +541,7 @@ impl TransportImpl for WebRtcTransport {
...
@@ -535,7 +541,7 @@ impl TransportImpl for WebRtcTransport {
&
self
.inner.next_mid_for_consumers
&
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
&
self
.inner.used_sctp_stream_ids
}
}
...
@@ -564,7 +570,7 @@ impl WebRtcTransport {
...
@@ -564,7 +570,7 @@ impl WebRtcTransport {
let
data
=
Arc
::
clone
(
&
data
);
let
data
=
Arc
::
clone
(
&
data
);
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
channel
.subscribe_to_notifications
(
id
.into
(),
move
|
notification
|
{
match
serde_json
::
from_
valu
e
::
<
Notification
>
(
notification
)
{
match
serde_json
::
from_
slic
e
::
<
Notification
>
(
notification
)
{
Ok
(
notification
)
=>
match
notification
{
Ok
(
notification
)
=>
match
notification
{
Notification
::
IceStateChange
{
ice_state
}
=>
{
Notification
::
IceStateChange
{
ice_state
}
=>
{
*
data
.ice_state
.lock
()
=
ice_state
;
*
data
.ice_state
.lock
()
=
ice_state
;
...
@@ -574,9 +580,9 @@ impl WebRtcTransport {
...
@@ -574,9 +580,9 @@ impl WebRtcTransport {
}
}
Notification
::
IceSelectedTupleChange
{
ice_selected_tuple
}
=>
{
Notification
::
IceSelectedTupleChange
{
ice_selected_tuple
}
=>
{
data
.ice_selected_tuple
.lock
()
.replace
(
ice_selected_tuple
);
data
.ice_selected_tuple
.lock
()
.replace
(
ice_selected_tuple
);
handlers
.ice_selected_tuple_change
.call
(|
callback
|
{
handlers
callback
(
&
ice_selected_tuple
);
.ice_selected_tuple_change
}
);
.call_simple
(
&
ice_selected_tuple
);
}
}
Notification
::
DtlsStateChange
{
Notification
::
DtlsStateChange
{
dtls_state
,
dtls_state
,
...
@@ -600,9 +606,7 @@ impl WebRtcTransport {
...
@@ -600,9 +606,7 @@ impl WebRtcTransport {
});
});
}
}
Notification
::
Trace
(
trace_event_data
)
=>
{
Notification
::
Trace
(
trace_event_data
)
=>
{
handlers
.trace
.call
(|
callback
|
{
handlers
.trace
.call_simple
(
&
trace_event_data
);
callback
(
&
trace_event_data
);
});
}
}
},
},
Err
(
error
)
=>
{
Err
(
error
)
=>
{
...
@@ -614,7 +618,7 @@ impl WebRtcTransport {
...
@@ -614,7 +618,7 @@ impl WebRtcTransport {
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
next_mid_for_consumers
=
AtomicUsize
::
default
();
let
used_sctp_stream_ids
=
Mutex
::
new
({
let
used_sctp_stream_ids
=
Mutex
::
new
({
let
mut
used_used_sctp_stream_ids
=
HashMap
::
new
();
let
mut
used_used_sctp_stream_ids
=
IntMap
::
default
();
if
let
Some
(
sctp_parameters
)
=
&
data
.sctp_parameters
{
if
let
Some
(
sctp_parameters
)
=
&
data
.sctp_parameters
{
for
i
in
0
..
sctp_parameters
.mis
{
for
i
in
0
..
sctp_parameters
.mis
{
used_used_sctp_stream_ids
.insert
(
i
,
false
);
used_used_sctp_stream_ids
.insert
(
i
,
false
);
...
@@ -695,7 +699,7 @@ impl WebRtcTransport {
...
@@ -695,7 +699,7 @@ impl WebRtcTransport {
let
response
=
self
let
response
=
self
.inner
.inner
.channel
.channel
.request
(
TransportConnect
RequestWebRtc
{
.request
(
TransportConnect
WebRtcRequest
{
internal
:
self
.get_internal
(),
internal
:
self
.get_internal
(),
data
:
TransportConnectRequestWebRtcData
{
data
:
TransportConnectRequestWebRtcData
{
dtls_parameters
:
remote_parameters
.dtls_parameters
,
dtls_parameters
:
remote_parameters
.dtls_parameters
,
...
@@ -810,7 +814,7 @@ impl WebRtcTransport {
...
@@ -810,7 +814,7 @@ impl WebRtcTransport {
&
self
,
&
self
,
callback
:
F
,
callback
:
F
,
)
->
HandlerId
{
)
->
HandlerId
{
self
.inner.handlers.ice_state_change
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.ice_state_change
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called after ICE state becomes `Completed` and when the ICE selected tuple
/// Callback is called after ICE state becomes `Completed` and when the ICE selected tuple
...
@@ -822,7 +826,7 @@ impl WebRtcTransport {
...
@@ -822,7 +826,7 @@ impl WebRtcTransport {
self
.inner
self
.inner
.handlers
.handlers
.ice_selected_tuple_change
.ice_selected_tuple_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the transport DTLS state changes.
/// Callback is called when the transport DTLS state changes.
...
@@ -833,7 +837,7 @@ impl WebRtcTransport {
...
@@ -833,7 +837,7 @@ impl WebRtcTransport {
self
.inner
self
.inner
.handlers
.handlers
.dtls_state_change
.dtls_state_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the transport SCTP state changes.
/// Callback is called when the transport SCTP state changes.
...
@@ -844,7 +848,7 @@ impl WebRtcTransport {
...
@@ -844,7 +848,7 @@ impl WebRtcTransport {
self
.inner
self
.inner
.handlers
.handlers
.sctp_state_change
.sctp_state_change
.add
(
Box
::
new
(
callback
))
.add
(
Arc
::
new
(
callback
))
}
}
/// Downgrade `WebRtcTransport` to [`WeakWebRtcTransport`] instance.
/// Downgrade `WebRtcTransport` to [`WeakWebRtcTransport`] instance.
...
...
rust/src/worker.rs
浏览文件 @
f0ebd809
//! A worker represents a mediasoup C++ thread that runs on a single CPU core and handles
//! A worker represents a mediasoup C++ thread that runs on a single CPU core and handles
//! [`Router`] instances.
//! [`Router`] instances.
// TODO: This is Unix-specific and doesn't support Windows in any way
mod
channel
;
mod
channel
;
mod
common
;
mod
common
;
mod
payload_channel
;
mod
payload_channel
;
...
@@ -25,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId};
...
@@ -25,7 +24,7 @@ use event_listener_primitives::{Bag, BagOnce, HandlerId};
use
futures_lite
::
FutureExt
;
use
futures_lite
::
FutureExt
;
use
log
::{
debug
,
error
,
warn
};
use
log
::{
debug
,
error
,
warn
};
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
pub
(
crate
)
use
payload_channel
::{
NotificationError
,
NotificationMessage
,
PayloadChannel
};
pub
(
crate
)
use
payload_channel
::{
NotificationError
,
PayloadChannel
};
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
std
::
ops
::
RangeInclusive
;
use
std
::
ops
::
RangeInclusive
;
use
std
::
path
::
PathBuf
;
use
std
::
path
::
PathBuf
;
...
@@ -40,18 +39,12 @@ uuid_based_wrapper_type!(
...
@@ -40,18 +39,12 @@ uuid_based_wrapper_type!(
WorkerId
WorkerId
);
);
/// Error that caused request to mediasoup-worker
thread
to fail.
/// Error that caused request to mediasoup-worker
request
to fail.
#[derive(Debug,
Error,
Eq,
PartialEq)]
#[derive(Debug,
Error,
Eq,
PartialEq)]
pub
enum
RequestError
{
pub
enum
RequestError
{
/// Channel already closed.
/// Channel already closed.
#[error(
"Channel already closed"
)]
#[error(
"Channel already closed"
)]
ChannelClosed
,
ChannelClosed
,
/// Message is too long.
#[error(
"Message is too long"
)]
MessageTooLong
,
/// Payload is too long.
#[error(
"Payload is too long"
)]
PayloadTooLong
,
/// Request timed out.
/// Request timed out.
#[error(
"Request timed out"
)]
#[error(
"Request timed out"
)]
TimedOut
,
TimedOut
,
...
@@ -171,7 +164,7 @@ pub struct WorkerDtlsFiles {
...
@@ -171,7 +164,7 @@ pub struct WorkerDtlsFiles {
}
}
/// Settings for worker to be created with.
/// Settings for worker to be created with.
#[derive(
Debug,
Clone)]
#[derive(Clone)]
#[non_exhaustive]
#[non_exhaustive]
pub
struct
WorkerSettings
{
pub
struct
WorkerSettings
{
/// Logging level for logs generated by the media worker thread.
/// Logging level for logs generated by the media worker thread.
...
@@ -187,6 +180,9 @@ pub struct WorkerSettings {
...
@@ -187,6 +180,9 @@ pub struct WorkerSettings {
///
///
/// If `None`, a certificate is dynamically created.
/// If `None`, a certificate is dynamically created.
pub
dtls_files
:
Option
<
WorkerDtlsFiles
>
,
pub
dtls_files
:
Option
<
WorkerDtlsFiles
>
,
/// Function that will be called under worker thread before worker starts, can be used for
/// pinning worker threads to CPU cores.
pub
thread_initializer
:
Option
<
Arc
<
dyn
Fn
()
+
Send
+
Sync
>>
,
/// Custom application data.
/// Custom application data.
pub
app_data
:
AppData
,
pub
app_data
:
AppData
,
}
}
...
@@ -198,11 +194,37 @@ impl Default for WorkerSettings {
...
@@ -198,11 +194,37 @@ impl Default for WorkerSettings {
log_tags
:
Vec
::
new
(),
log_tags
:
Vec
::
new
(),
rtc_ports_range
:
10000
..=
59999
,
rtc_ports_range
:
10000
..=
59999
,
dtls_files
:
None
,
dtls_files
:
None
,
thread_initializer
:
None
,
app_data
:
AppData
::
default
(),
app_data
:
AppData
::
default
(),
}
}
}
}
}
}
impl
fmt
::
Debug
for
WorkerSettings
{
fn
fmt
(
&
self
,
f
:
&
mut
fmt
::
Formatter
<
'_
>
)
->
fmt
::
Result
{
let
WorkerSettings
{
log_level
,
log_tags
,
rtc_ports_range
,
dtls_files
,
thread_initializer
,
app_data
,
}
=
self
;
f
.debug_struct
(
"WorkerSettings"
)
.field
(
"log_level"
,
&
log_level
)
.field
(
"log_tags"
,
&
log_tags
)
.field
(
"rtc_ports_range"
,
&
rtc_ports_range
)
.field
(
"dtls_files"
,
&
dtls_files
)
.field
(
"thread_initializer"
,
&
thread_initializer
.as_ref
()
.map
(|
_
|
"ThreadInitializer"
),
)
.field
(
"app_data"
,
&
app_data
)
.finish
()
}
}
/// Worker settings that can be updated in runtime.
/// Worker settings that can be updated in runtime.
#[derive(Default,
Debug,
Clone,
Serialize)]
#[derive(Default,
Debug,
Clone,
Serialize)]
#[serde(rename_all
=
"camelCase"
)]
#[serde(rename_all
=
"camelCase"
)]
...
@@ -241,7 +263,7 @@ pub enum CreateRouterError {
...
@@ -241,7 +263,7 @@ pub enum CreateRouterError {
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
new_router
:
Bag
<
Box
<
dyn
Fn
(
&
Router
)
+
Send
+
Sync
>
>
,
new_router
:
Bag
<
Arc
<
dyn
Fn
(
&
Router
)
+
Send
+
Sync
>
,
Router
>
,
#[allow(clippy
::
type_complexity)]
#[allow(clippy
::
type_complexity)]
dead
:
BagOnce
<
Box
<
dyn
FnOnce
(
Result
<
(),
ExitError
>
)
+
Send
>>
,
dead
:
BagOnce
<
Box
<
dyn
FnOnce
(
Result
<
(),
ExitError
>
)
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
close
:
BagOnce
<
Box
<
dyn
FnOnce
()
+
Send
>>
,
...
@@ -271,11 +293,12 @@ impl Inner {
...
@@ -271,11 +293,12 @@ impl Inner {
async
fn
new
<
OE
:
FnOnce
()
+
Send
+
'static
>
(
async
fn
new
<
OE
:
FnOnce
()
+
Send
+
'static
>
(
executor
:
Arc
<
Executor
<
'static
>>
,
executor
:
Arc
<
Executor
<
'static
>>
,
WorkerSettings
{
WorkerSettings
{
app_data
,
log_level
,
log_level
,
log_tags
,
log_tags
,
rtc_ports_range
,
rtc_ports_range
,
dtls_files
,
dtls_files
,
thread_initializer
,
app_data
,
}:
WorkerSettings
,
}:
WorkerSettings
,
worker_manager
:
WorkerManager
,
worker_manager
:
WorkerManager
,
on_exit
:
OE
,
on_exit
:
OE
,
...
@@ -327,7 +350,7 @@ impl Inner {
...
@@ -327,7 +350,7 @@ impl Inner {
channel
,
channel
,
payload_channel
,
payload_channel
,
buffer_worker_messages_guard
,
buffer_worker_messages_guard
,
}
=
utils
::
run_worker_with_channels
(
id
,
Arc
::
clone
(
&
executor
)
,
spawn_args
,
move
|
result
|
{
}
=
utils
::
run_worker_with_channels
(
id
,
thread_initializer
,
spawn_args
,
move
|
result
|
{
let
_
=
status_sender
.send
(
result
);
let
_
=
status_sender
.send
(
result
);
on_exit
();
on_exit
();
});
});
...
@@ -405,7 +428,7 @@ impl Inner {
...
@@ -405,7 +428,7 @@ impl Inner {
let
_handler
=
self
.channel
.subscribe_to_notifications
(
let
_handler
=
self
.channel
.subscribe_to_notifications
(
std
::
process
::
id
()
.into
(),
std
::
process
::
id
()
.into
(),
move
|
notification
|
{
move
|
notification
|
{
let
result
=
match
serde_json
::
from_
value
(
notification
.clone
()
)
{
let
result
=
match
serde_json
::
from_
slice
(
notification
)
{
Ok
(
Notification
::
Running
)
=>
{
Ok
(
Notification
::
Running
)
=>
{
debug!
(
"worker thread running [id:{}]"
,
id
);
debug!
(
"worker thread running [id:{}]"
,
id
);
Ok
(())
Ok
(())
...
@@ -601,16 +624,14 @@ impl Worker {
...
@@ -601,16 +624,14 @@ impl Worker {
self
.clone
(),
self
.clone
(),
);
);
self
.inner.handlers.new_router
.call
(|
callback
|
{
self
.inner.handlers.new_router
.call_simple
(
&
router
);
callback
(
&
router
);
});
Ok
(
router
)
Ok
(
router
)
}
}
/// Callback is called when a new router is created.
/// Callback is called when a new router is created.
pub
fn
on_new_router
<
F
:
Fn
(
&
Router
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_new_router
<
F
:
Fn
(
&
Router
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.new_router
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.new_router
.add
(
Arc
::
new
(
callback
))
}
}
/// Callback is called when the worker thread unexpectedly dies.
/// Callback is called when the worker thread unexpectedly dies.
...
...
rust/src/worker/channel.rs
浏览文件 @
f0ebd809
use
crate
::
messages
::
Request
;
use
crate
::
messages
::
Request
;
use
crate
::
worker
::
common
::{
EventHandlers
,
SubscriptionTarget
,
WeakEventHandlers
};
use
crate
::
worker
::
common
::{
EventHandlers
,
SubscriptionTarget
,
WeakEventHandlers
};
use
crate
::
worker
::
utils
;
use
crate
::
worker
::
utils
::{
PreparedChannelRead
,
PreparedChannelWrite
};
use
crate
::
worker
::{
RequestError
,
SubscriptionHandler
};
use
crate
::
worker
::{
RequestError
,
SubscriptionHandler
};
use
async_executor
::
Executor
;
use
atomic_take
::
AtomicTake
;
use
async_fs
::
File
;
use
hash_hasher
::
HashedMap
;
use
bytes
::{
BufMut
,
Bytes
,
BytesMut
};
use
log
::{
debug
,
error
,
trace
,
warn
};
use
futures_lite
::
io
::
BufReader
;
use
futures_lite
::{
future
,
AsyncReadExt
,
AsyncWriteExt
};
use
log
::{
debug
,
trace
,
warn
};
use
lru
::
LruCache
;
use
lru
::
LruCache
;
use
mediasoup_sys
::
UvAsyncT
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
serde_json
::
Value
;
use
serde_json
::
Value
;
use
std
::
collections
::
HashMap
;
use
std
::
collections
::
VecDeque
;
use
std
::
fmt
::
Debug
;
use
std
::
fmt
::
Debug
;
use
std
::
io
;
use
std
::
sync
::{
Arc
,
Weak
};
use
std
::
sync
::{
Arc
,
Weak
};
use
std
::
time
::
Duration
;
const
NS_PAYLOAD_MAX_LEN
:
usize
=
4
_194_304
;
#[derive(Debug,
Deserialize)]
#[derive(Debug,
Deserialize)]
#[serde(untagged)]
#[serde(untagged)]
...
@@ -41,8 +37,8 @@ pub(super) enum InternalMessage {
...
@@ -41,8 +37,8 @@ pub(super) enum InternalMessage {
pub
(
crate
)
struct
BufferMessagesGuard
{
pub
(
crate
)
struct
BufferMessagesGuard
{
target_id
:
SubscriptionTarget
,
target_id
:
SubscriptionTarget
,
buffered_notifications_for
:
Arc
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
Vec
<
Value
>>>>
,
buffered_notifications_for
:
Arc
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
Vec
<
Vec
<
u8
>
>>>>
,
event_handlers_weak
:
WeakEventHandlers
<
Value
>
,
event_handlers_weak
:
WeakEventHandlers
<
Arc
<
dyn
Fn
(
&
[
u8
])
+
Send
+
Sync
+
'static
>
>
,
}
}
impl
Drop
for
BufferMessagesGuard
{
impl
Drop
for
BufferMessagesGuard
{
...
@@ -51,7 +47,7 @@ impl Drop for BufferMessagesGuard {
...
@@ -51,7 +47,7 @@ impl Drop for BufferMessagesGuard {
if
let
Some
(
notifications
)
=
buffered_notifications_for
.remove
(
&
self
.target_id
)
{
if
let
Some
(
notifications
)
=
buffered_notifications_for
.remove
(
&
self
.target_id
)
{
if
let
Some
(
event_handlers
)
=
self
.event_handlers_weak
.upgrade
()
{
if
let
Some
(
event_handlers
)
=
self
.event_handlers_weak
.upgrade
()
{
for
notification
in
notifications
{
for
notification
in
notifications
{
event_handlers
.call_callbacks_with_
value
(
&
self
.target_id
,
notification
);
event_handlers
.call_callbacks_with_
single_value
(
&
self
.target_id
,
&
notification
);
}
}
}
}
}
}
...
@@ -61,17 +57,24 @@ impl Drop for BufferMessagesGuard {
...
@@ -61,17 +57,24 @@ impl Drop for BufferMessagesGuard {
#[derive(Debug,
Deserialize)]
#[derive(Debug,
Deserialize)]
#[serde(untagged)]
#[serde(untagged)]
enum
ChannelReceiveMessage
{
enum
ChannelReceiveMessage
{
#[serde(rename_all
=
"camelCase"
)]
Notification
{
target_id
:
SubscriptionTarget
,
},
ResponseSuccess
{
ResponseSuccess
{
id
:
u32
,
id
:
u32
,
// The following field is present, unused, but needed for differentiating successful
// response from error case
#[allow(dead_code)]
accepted
:
bool
,
accepted
:
bool
,
data
:
Option
<
Value
>
,
data
:
Option
<
Value
>
,
},
},
ResponseError
{
ResponseError
{
id
:
u32
,
id
:
u32
,
error
:
Value
,
// The following field is present, but unused
// error: Value,
reason
:
String
,
reason
:
String
,
},
},
Notification
(
Value
),
Event
(
InternalMessage
),
Event
(
InternalMessage
),
}
}
...
@@ -100,29 +103,69 @@ fn deserialize_message(bytes: &[u8]) -> ChannelReceiveMessage {
...
@@ -100,29 +103,69 @@ fn deserialize_message(bytes: &[u8]) -> ChannelReceiveMessage {
}
}
}
}
#[derive(Debug,
Serialize)]
struct
RequestMessage
<
'a
,
R
:
Serialize
>
{
id
:
u32
,
method
:
&
'static
str
,
#[serde(flatten)]
request
:
&
'a
R
,
}
struct
ResponseError
{
struct
ResponseError
{
reason
:
String
,
reason
:
String
,
}
}
type
Response
<
T
>
=
Result
<
Option
<
T
>
,
ResponseError
>
;
type
ResponseResult
<
T
>
=
Result
<
Option
<
T
>
,
ResponseError
>
;
struct
RequestDropGuard
<
'a
>
{
id
:
u32
,
message
:
Arc
<
AtomicTake
<
Vec
<
u8
>>>
,
channel
:
&
'a
Channel
,
removed
:
bool
,
}
impl
<
'a
>
Drop
for
RequestDropGuard
<
'a
>
{
fn
drop
(
&
mut
self
)
{
if
self
.removed
{
return
;
}
// Drop pending message from memory
self
.message
.take
();
// Remove request handler from the container
if
let
Some
(
requests_container
)
=
self
.channel.inner.requests_container_weak
.upgrade
()
{
requests_container
.lock
()
.handlers
.remove
(
&
self
.id
);
}
}
}
impl
<
'a
>
RequestDropGuard
<
'a
>
{
fn
remove
(
mut
self
)
{
self
.removed
=
true
;
}
}
#[derive(Default)]
#[derive(Default)]
struct
RequestsContainer
{
struct
RequestsContainer
{
next_id
:
u32
,
next_id
:
u32
,
handlers
:
HashMap
<
u32
,
async_oneshot
::
Sender
<
Response
<
Value
>>>
,
handlers
:
HashedMap
<
u32
,
async_oneshot
::
Sender
<
ResponseResult
<
Value
>>>
,
}
struct
OutgoingMessageBuffer
{
handle
:
Option
<
UvAsyncT
>
,
messages
:
VecDeque
<
Arc
<
AtomicTake
<
Vec
<
u8
>>>>
,
}
}
struct
Inner
{
struct
Inner
{
sender
:
async_channel
::
Sender
<
Bytes
>
,
outgoing_message_buffer
:
Arc
<
Mutex
<
OutgoingMessageBuffer
>
>
,
internal_message_receiver
:
async_channel
::
Receiver
<
InternalMessage
>
,
internal_message_receiver
:
async_channel
::
Receiver
<
InternalMessage
>
,
requests_container_weak
:
Weak
<
Mutex
<
RequestsContainer
>>
,
requests_container_weak
:
Weak
<
Mutex
<
RequestsContainer
>>
,
buffered_notifications_for
:
Arc
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
Vec
<
Value
>>>>
,
buffered_notifications_for
:
Arc
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
Vec
<
Vec
<
u8
>
>>>>
,
event_handlers_weak
:
WeakEventHandlers
<
Value
>
,
event_handlers_weak
:
WeakEventHandlers
<
Arc
<
dyn
Fn
(
&
[
u8
])
+
Send
+
Sync
+
'static
>
>
,
}
}
impl
Drop
for
Inner
{
impl
Drop
for
Inner
{
fn
drop
(
&
mut
self
)
{
fn
drop
(
&
mut
self
)
{
self
.sender
.close
();
self
.internal_message_receiver
.close
();
self
.internal_message_receiver
.close
();
}
}
}
}
...
@@ -133,160 +176,107 @@ pub(crate) struct Channel {
...
@@ -133,160 +176,107 @@ pub(crate) struct Channel {
}
}
impl
Channel
{
impl
Channel
{
pub
(
super
)
fn
new
(
executor
:
&
Executor
<
'static
>
,
reader
:
File
,
mut
writer
:
File
)
->
Self
{
pub
(
super
)
fn
new
()
->
(
Self
,
PreparedChannelRead
,
PreparedChannelWrite
)
{
let
outgoing_message_buffer
=
Arc
::
new
(
Mutex
::
new
(
OutgoingMessageBuffer
{
handle
:
None
,
messages
:
VecDeque
::
with_capacity
(
10
),
}));
let
requests_container
=
Arc
::
<
Mutex
<
RequestsContainer
>>
::
default
();
let
requests_container
=
Arc
::
<
Mutex
<
RequestsContainer
>>
::
default
();
let
requests_container_weak
=
Arc
::
downgrade
(
&
requests_container
);
let
requests_container_weak
=
Arc
::
downgrade
(
&
requests_container
);
let
buffered_notifications_for
=
let
buffered_notifications_for
=
Arc
::
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
Vec
<
Value
>>>>
::
default
();
Arc
::
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
Vec
<
Vec
<
u8
>
>>>>
::
default
();
let
event_handlers
=
EventHandlers
::
new
();
let
event_handlers
=
EventHandlers
::
new
();
let
event_handlers_weak
=
event_handlers
.downgrade
();
let
event_handlers_weak
=
event_handlers
.downgrade
();
let
internal_message_receiver
=
{
let
prepared_channel_read
=
utils
::
prepare_channel_read_fn
({
let
buffered_notifications_for
=
buffered_notifications_for
.clone
();
let
outgoing_message_buffer
=
Arc
::
clone
(
&
outgoing_message_buffer
);
let
(
sender
,
receiver
)
=
async_channel
::
bounded
(
1
);
move
|
handle
|
{
let
mut
outgoing_message_buffer
=
outgoing_message_buffer
.lock
();
if
outgoing_message_buffer
.handle
.is_none
()
{
outgoing_message_buffer
.handle
.replace
(
handle
);
}
executor
while
let
Some
(
maybe_message
)
=
outgoing_message_buffer
.messages
.pop_front
()
{
.spawn
(
async
move
{
// Request might have already been cancelled
let
mut
len_bytes
=
[
0u8
;
4
];
if
let
Some
(
message
)
=
maybe_message
.take
()
{
let
mut
bytes
=
Vec
::
new
();
return
Some
(
message
);
let
mut
reader
=
BufReader
::
new
(
reader
);
}
}
None
}
});
let
(
internal_message_sender
,
internal_message_receiver
)
=
async_channel
::
unbounded
();
let
prepared_channel_write
=
utils
::
prepare_channel_write_fn
({
let
buffered_notifications_for
=
Arc
::
clone
(
&
buffered_notifications_for
);
// This this contain cache of targets that are known to not have buffering, so
// This this contain cache of targets that are known to not have buffering, so
// that we can avoid Mutex locking overhead for them
// that we can avoid Mutex locking overhead for them
let
mut
non_buffered_notifications
=
let
mut
non_buffered_notifications
=
LruCache
::
<
SubscriptionTarget
,
()
>
::
new
(
1000
);
LruCache
::
<
SubscriptionTarget
,
()
>
::
new
(
1000
);
loop
{
move
|
message
|
{
reader
.read_exact
(
&
mut
len_bytes
)
.await
?
;
trace!
(
"received raw message: {}"
,
String
::
from_utf8_lossy
(
message
));
let
length
=
u32
::
from_ne_bytes
(
len_bytes
)
as
usize
;
if
length
>
NS_PAYLOAD_MAX_LEN
{
match
deserialize_message
(
message
)
{
warn!
(
ChannelReceiveMessage
::
Notification
{
target_id
}
=>
{
"received message {} is too long, max supported is {}"
,
if
!
non_buffered_notifications
.contains
(
&
target_id
)
{
length
,
NS_PAYLOAD_MAX_LEN
,
let
mut
buffer_notifications_for
=
buffered_notifications_for
.lock
();
);
// Check if we need to buffer notifications for this
// target_id
if
let
Some
(
list
)
=
buffer_notifications_for
.get_mut
(
&
target_id
)
{
list
.push
(
Vec
::
from
(
message
));
return
;
}
}
if
bytes
.len
()
<
length
{
// Remember we don't need to buffer these
// Increase bytes size if/when needed
non_buffered_notifications
.put
(
target_id
,
());
bytes
.resize
(
length
,
0
);
}
}
reader
.read_exact
(
&
mut
bytes
[
..
length
])
.await
?
;
event_handlers
.call_callbacks_with_single_value
(
&
target_id
,
message
);
}
trace!
(
ChannelReceiveMessage
::
ResponseSuccess
{
id
,
data
,
..
}
=>
{
"received raw message: {}"
,
String
::
from_utf8_lossy
(
&
bytes
[
..
length
]),
);
match
deserialize_message
(
&
bytes
[
..
length
])
{
ChannelReceiveMessage
::
ResponseSuccess
{
id
,
accepted
:
_
,
data
,
}
=>
{
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
if
let
Some
(
mut
sender
)
=
sender
{
if
let
Some
(
mut
sender
)
=
sender
{
let
_
=
sender
.send
(
Ok
(
data
));
let
_
=
sender
.send
(
Ok
(
data
));
}
else
{
}
else
{
warn!
(
warn!
(
"received success response does not match any sent request
\
"received success response does not match any sent request [id:{}]"
,
[id:{}]"
,
id
,
id
,
);
);
}
}
}
}
ChannelReceiveMessage
::
ResponseError
{
ChannelReceiveMessage
::
ResponseError
{
id
,
reason
}
=>
{
id
,
error
:
_
,
reason
,
}
=>
{
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
if
let
Some
(
mut
sender
)
=
sender
{
if
let
Some
(
mut
sender
)
=
sender
{
let
_
=
sender
.send
(
Err
(
ResponseError
{
reason
}));
let
_
=
sender
.send
(
Err
(
ResponseError
{
reason
}));
}
else
{
}
else
{
warn!
(
warn!
(
"received error response does not match any sent request
\
"received error response does not match any sent request [id:{}]"
,
[id:{}]"
,
id
,
id
,
);
);
}
}
}
}
ChannelReceiveMessage
::
Notification
(
notification
)
=>
{
let
target_id
=
notification
.get
(
"targetId"
)
.and_then
(|
value
|
{
let
str
=
value
.as_str
()
?
;
str
.parse
()
.ok
()
.map
(
SubscriptionTarget
::
Uuid
)
.or_else
(||
{
str
.parse
()
.ok
()
.map
(
SubscriptionTarget
::
Number
)
})
});
if
let
Some
(
target_id
)
=
target_id
{
if
!
non_buffered_notifications
.contains
(
&
target_id
)
{
let
mut
buffer_notifications_for
=
buffered_notifications_for
.lock
();
// Check if we need to buffer notifications for this
// target_id
if
let
Some
(
list
)
=
buffer_notifications_for
.get_mut
(
&
target_id
)
{
list
.push
(
notification
);
continue
;
}
// Remember we don't need to buffer these
non_buffered_notifications
.put
(
target_id
,
());
}
event_handlers
.call_callbacks_with_value
(
&
target_id
,
notification
);
}
else
{
let
unexpected_message
=
InternalMessage
::
Unexpected
(
Vec
::
from
(
&
bytes
[
..
length
]));
if
sender
.send
(
unexpected_message
)
.await
.is_err
()
{
break
;
}
}
}
ChannelReceiveMessage
::
Event
(
event_message
)
=>
{
ChannelReceiveMessage
::
Event
(
event_message
)
=>
{
if
sender
.send
(
event_message
)
.await
.is_err
()
{
let
_
=
internal_message_sender
.try_send
(
event_message
);
break
;
}
}
}
}
}
}
}
});
io
::
Result
::
Ok
(())
})
.detach
();
receiver
};
let
sender
=
{
let
(
sender
,
receiver
)
=
async_channel
::
bounded
::
<
Bytes
>
(
1
);
executor
.spawn
(
async
move
{
while
let
Ok
(
message
)
=
receiver
.recv
()
.await
{
writer
.write_all
(
&
(
message
.len
()
as
u32
)
.to_ne_bytes
())
.await
?
;
writer
.write_all
(
&
message
)
.await
?
;
}
io
::
Result
::
Ok
(())
})
.detach
();
sender
};
let
inner
=
Arc
::
new
(
Inner
{
let
inner
=
Arc
::
new
(
Inner
{
send
er
,
outgoing_message_buff
er
,
internal_message_receiver
,
internal_message_receiver
,
requests_container_weak
,
requests_container_weak
,
buffered_notifications_for
,
buffered_notifications_for
,
event_handlers_weak
,
event_handlers_weak
,
});
});
Self
{
inner
}
(
Self
{
inner
},
prepared_channel_read
,
prepared_channel_write
,
)
}
}
pub
(
super
)
fn
get_internal_message_receiver
(
&
self
)
->
async_channel
::
Receiver
<
InternalMessage
>
{
pub
(
super
)
fn
get_internal_message_receiver
(
&
self
)
->
async_channel
::
Receiver
<
InternalMessage
>
{
...
@@ -313,46 +303,9 @@ impl Channel {
...
@@ -313,46 +303,9 @@ impl Channel {
where
where
R
:
Request
,
R
:
Request
,
{
{
// Default will work for `()` response
let
method
=
request
.as_method
();
let
data
=
self
.request_internal
(
request
.as_method
(),
serde_json
::
to_value
(
request
)
.unwrap
())
.await
?
.unwrap_or_default
();
serde_json
::
from_value
(
data
)
.map_err
(|
error
|
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
})
}
pub
(
crate
)
fn
subscribe_to_notifications
<
F
>
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
F
,
)
->
Option
<
SubscriptionHandler
>
where
F
:
Fn
(
Value
)
+
Send
+
Sync
+
'static
,
{
self
.inner
.event_handlers_weak
.upgrade
()
.map
(|
event_handlers
|
event_handlers
.add
(
target_id
,
Box
::
new
(
callback
)))
}
/// Non-generic method to avoid significant duplication in final binary
async
fn
request_internal
(
&
self
,
method
:
&
'static
str
,
message
:
Value
,
)
->
Result
<
Option
<
Value
>
,
RequestError
>
{
#[derive(Debug,
Serialize)]
struct
RequestMessagePrivate
{
id
:
u32
,
method
:
&
'static
str
,
#[serde(flatten)]
message
:
Value
,
}
let
id
;
let
id
;
let
queue_len
;
let
(
result_sender
,
result_receiver
)
=
async_oneshot
::
oneshot
();
let
(
result_sender
,
result_receiver
)
=
async_oneshot
::
oneshot
();
{
{
...
@@ -364,70 +317,61 @@ impl Channel {
...
@@ -364,70 +317,61 @@ impl Channel {
let
mut
requests_container
=
requests_container_lock
.lock
();
let
mut
requests_container
=
requests_container_lock
.lock
();
id
=
requests_container
.next_id
;
id
=
requests_container
.next_id
;
queue_len
=
requests_container
.handlers
.len
();
requests_container
.next_id
=
requests_container
.next_id
.wrapping_add
(
1
);
requests_container
.next_id
=
requests_container
.next_id
.wrapping_add
(
1
);
requests_container
.handlers
.insert
(
id
,
result_sender
);
requests_container
.handlers
.insert
(
id
,
result_sender
);
}
}
debug!
(
"request() [method:{}, id:{}]: {
}"
,
method
,
id
,
message
);
debug!
(
"request() [method:{}, id:{}]: {
:?}"
,
method
,
id
,
request
);
let
bytes
=
{
let
message
=
Arc
::
new
(
AtomicTake
::
new
(
let
mut
bytes
=
BytesMut
::
new
()
.writer
();
serde_json
::
to_vec
(
&
RequestMessage
{
serde_json
::
to_writer
(
&
mut
bytes
,
&
RequestMessagePrivate
{
id
,
id
,
method
,
method
,
message
,
request
:
&
request
,
},
})
)
.unwrap
(),
.unwrap
();
));
bytes
.into_inner
()
};
if
bytes
.len
()
>
NS_PAYLOAD_MAX_LEN
{
{
self
.inner
let
mut
outgoing_message_buffer
=
self
.inner.outgoing_message_buffer
.lock
();
.requests_container_weak
outgoing_message_buffer
.upgrade
()
.messages
.ok_or
(
RequestError
::
ChannelClosed
)
?
.push_back
(
Arc
::
clone
(
&
message
));
.lock
()
if
let
Some
(
handle
)
=
&
outgoing_message_buffer
.handle
{
.handlers
unsafe
{
.remove
(
&
id
);
// Notify worker that there is something to read
return
Err
(
RequestError
::
MessageTooLong
);
let
ret
=
mediasoup_sys
::
uv_async_send
(
*
handle
);
if
ret
!=
0
{
error!
(
"uv_async_send call failed with code {}"
,
ret
);
return
Err
(
RequestError
::
ChannelClosed
);
}
}
}
}
}
self
.inner
// Drop guard to make sure to drop pending request when future is cancelled
.sender
let
request_drop_guard
=
RequestDropGuard
{
.send
(
bytes
.freeze
())
id
,
.await
message
,
.map_err
(|
_
|
RequestError
::
ChannelClosed
{})
?
;
channel
:
self
,
removed
:
false
,
let
result
=
future
::
or
(
};
async
{
result_receiver
.await
.map_err
(|
_
|
RequestError
::
ChannelClosed
{})
},
async
{
async_io
::
Timer
::
after
(
Duration
::
from_millis
(
(
1000.0
*
(
15.0
+
(
0.1
*
queue_len
as
f64
)))
.round
()
as
u64
,
))
.await
;
if
let
Some
(
requests_container
)
=
self
.inner.requests_container_weak
.upgrade
()
{
let
response_result_fut
=
result_receiver
.await
;
requests_container
.lock
()
.handlers
.remove
(
&
id
);
}
Err
(
RequestError
::
TimedOut
)
request_drop_guard
.remove
();
},
)
.await
?
;
match
res
ult
{
match
res
ponse_result_fut
.map_err
(|
_
|
RequestError
::
ChannelClosed
{})
?
{
Ok
(
data
)
=>
{
Ok
(
data
)
=>
{
debug!
(
"request succeeded [method:{}, id:{}]"
,
method
,
id
);
debug!
(
"request succeeded [method:{}, id:{}]"
,
method
,
id
);
Ok
(
data
)
// Default will work for `()` response
serde_json
::
from_value
(
data
.unwrap_or_default
())
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
Err
(
ResponseError
{
reason
})
=>
{
Err
(
ResponseError
{
reason
})
=>
{
debug!
(
"request failed [method:{}, id:{}]: {}"
,
method
,
id
,
reason
);
debug!
(
"request failed [method:{}, id:{}]: {}"
,
method
,
id
,
reason
);
...
@@ -436,4 +380,18 @@ impl Channel {
...
@@ -436,4 +380,18 @@ impl Channel {
}
}
}
}
}
}
pub
(
crate
)
fn
subscribe_to_notifications
<
F
>
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
F
,
)
->
Option
<
SubscriptionHandler
>
where
F
:
Fn
(
&
[
u8
])
+
Send
+
Sync
+
'static
,
{
self
.inner
.event_handlers_weak
.upgrade
()
.map
(|
event_handlers
|
event_handlers
.add
(
target_id
,
Arc
::
new
(
callback
)))
}
}
}
rust/src/worker/common.rs
浏览文件 @
f0ebd809
use
hash_hasher
::
HashedMap
;
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
s
td
::
collections
::
HashMap
;
use
s
erde
::
Deserialize
;
use
std
::
sync
::{
Arc
,
Weak
};
use
std
::
sync
::{
Arc
,
Weak
};
use
uuid
::
Uuid
;
use
uuid
::
Uuid
;
struct
EventHandlersList
<
V
:
Clone
+
'static
>
{
struct
EventHandlersList
<
F
>
{
index
:
usize
,
index
:
usize
,
#[allow(clippy
::
type_complexity)]
callbacks
:
IntMap
<
usize
,
F
>
,
callbacks
:
HashMap
<
usize
,
Arc
<
Box
<
dyn
Fn
(
V
)
+
Send
+
Sync
>>>
,
}
}
impl
<
V
:
Clone
+
'static
>
Default
for
EventHandlersList
<
V
>
{
impl
<
F
>
Default
for
EventHandlersList
<
F
>
{
fn
default
()
->
Self
{
fn
default
()
->
Self
{
Self
{
Self
{
index
:
0
,
index
:
0
,
callbacks
:
HashMap
::
new
(),
callbacks
:
IntMap
::
default
(),
}
}
}
}
}
}
#[derive(Clone)]
#[derive(Clone)]
pub
(
super
)
struct
EventHandlers
<
V
:
Clone
+
'static
>
{
pub
(
super
)
struct
EventHandlers
<
F
>
{
handlers
:
Arc
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
EventHandlersList
<
V
>>>>
,
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
{
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
}
Self
{
handlers
}
}
}
pub
(
super
)
fn
add
(
pub
(
super
)
fn
add
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
F
)
->
SubscriptionHandler
{
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
Box
<
dyn
Fn
(
V
)
+
Send
+
Sync
+
'static
>
,
)
->
SubscriptionHandler
{
let
index
;
let
index
;
{
{
let
mut
event_handlers
=
self
.handlers
.lock
();
let
mut
event_handlers
=
self
.handlers
.lock
();
...
@@ -42,7 +39,7 @@ impl<V: Clone + 'static> EventHandlers<V> {
...
@@ -42,7 +39,7 @@ impl<V: Clone + 'static> EventHandlers<V> {
.or_insert_with
(
EventHandlersList
::
default
);
.or_insert_with
(
EventHandlersList
::
default
);
index
=
list
.index
;
index
=
list
.index
;
list
.index
+=
1
;
list
.index
+=
1
;
list
.callbacks
.insert
(
index
,
Arc
::
new
(
Box
::
new
(
callback
))
);
list
.callbacks
.insert
(
index
,
callback
);
drop
(
event_handlers
);
drop
(
event_handlers
);
}
}
...
@@ -75,54 +72,72 @@ impl<V: Clone + 'static> EventHandlers<V> {
...
@@ -75,54 +72,72 @@ impl<V: Clone + 'static> EventHandlers<V> {
})
})
}
}
pub
(
super
)
fn
call_callbacks_with_value
(
&
self
,
target_id
:
&
SubscriptionTarget
,
value
:
V
)
{
pub
(
super
)
fn
downgrade
(
&
self
)
->
WeakEventHandlers
<
F
>
{
WeakEventHandlers
{
handlers
:
Arc
::
downgrade
(
&
self
.handlers
),
}
}
}
impl
<
V
:
?
Sized
>
EventHandlers
<
Arc
<
dyn
Fn
(
&
V
)
+
Send
+
Sync
+
'static
>>
{
pub
(
super
)
fn
call_callbacks_with_single_value
(
&
self
,
target_id
:
&
SubscriptionTarget
,
value
:
&
V
,
)
{
let
handlers
=
self
.handlers
.lock
();
let
handlers
=
self
.handlers
.lock
();
if
let
Some
(
list
)
=
handlers
.get
(
target_id
)
{
if
let
Some
(
list
)
=
handlers
.get
(
target_id
)
{
// Tiny optimization that avoids cloning `value` unless necessary
for
callback
in
list
.callbacks
.values
()
{
if
list
.callbacks
.len
()
==
1
{
let
callback
=
list
.callbacks
.values
()
.next
()
.cloned
()
.unwrap
();
// Drop mutex guard before running callbacks to avoid deadlocks
drop
(
handlers
);
callback
(
value
);
callback
(
value
);
}
else
{
let
callbacks
=
list
.callbacks
.values
()
.cloned
()
.collect
::
<
Vec
<
_
>>
();
// Drop mutex guard before running callbacks to avoid deadlocks
drop
(
handlers
);
for
callback
in
callbacks
{
callback
(
value
.clone
());
}
}
}
}
}
}
}
}
pub
(
super
)
fn
downgrade
(
&
self
)
->
WeakEventHandlers
<
V
>
{
impl
<
V1
:
?
Sized
,
V2
:
?
Sized
>
EventHandlers
<
Arc
<
dyn
Fn
(
&
V1
,
&
V2
)
+
Send
+
Sync
+
'static
>>
{
WeakEventHandlers
{
pub
(
super
)
fn
call_callbacks_with_two_values
(
handlers
:
Arc
::
downgrade
(
&
self
.handlers
),
&
self
,
target_id
:
&
SubscriptionTarget
,
value1
:
&
V1
,
value2
:
&
V2
,
)
{
let
handlers
=
self
.handlers
.lock
();
if
let
Some
(
list
)
=
handlers
.get
(
target_id
)
{
for
callback
in
list
.callbacks
.values
()
{
callback
(
value1
,
value2
);
}
}
}
}
}
}
}
#[derive(Clone)]
#[derive(Clone)]
pub
(
super
)
struct
WeakEventHandlers
<
V
:
Clone
+
'static
>
{
pub
(
super
)
struct
WeakEventHandlers
<
F
>
{
handlers
:
Weak
<
Mutex
<
Hash
Map
<
SubscriptionTarget
,
EventHandlersList
<
V
>>>>
,
handlers
:
Weak
<
Mutex
<
Hash
edMap
<
SubscriptionTarget
,
EventHandlersList
<
F
>>>>
,
}
}
impl
<
V
:
Clone
+
'static
>
WeakEventHandlers
<
V
>
{
impl
<
F
>
WeakEventHandlers
<
F
>
{
pub
(
super
)
fn
upgrade
(
&
self
)
->
Option
<
EventHandlers
<
V
>>
{
pub
(
super
)
fn
upgrade
(
&
self
)
->
Option
<
EventHandlers
<
F
>>
{
self
.handlers
self
.handlers
.upgrade
()
.upgrade
()
.map
(|
handlers
|
EventHandlers
{
handlers
})
.map
(|
handlers
|
EventHandlers
{
handlers
})
}
}
}
}
#[derive(Copy,
Clone,
Eq,
PartialEq,
Hash)]
#[derive(Debug,
Copy,
Clone,
Eq,
PartialEq,
Hash,
Deserialize)]
#[serde(untagged)]
pub
(
crate
)
enum
SubscriptionTarget
{
pub
(
crate
)
enum
SubscriptionTarget
{
Uuid
(
Uuid
),
Uuid
(
Uuid
),
Number
(
u
32
),
Number
(
u
64
),
}
}
impl
From
<
u32
>
for
SubscriptionTarget
{
impl
From
<
u32
>
for
SubscriptionTarget
{
fn
from
(
number
:
u32
)
->
Self
{
fn
from
(
number
:
u32
)
->
Self
{
Self
::
Number
(
u64
::
from
(
number
))
}
}
impl
From
<
u64
>
for
SubscriptionTarget
{
fn
from
(
number
:
u64
)
->
Self
{
Self
::
Number
(
number
)
Self
::
Number
(
number
)
}
}
}
}
...
...
rust/src/worker/payload_channel.rs
浏览文件 @
f0ebd809
use
crate
::
messages
::{
Notification
,
Request
};
use
crate
::
messages
::{
Notification
,
Request
};
use
crate
::
worker
::
common
::{
EventHandlers
,
SubscriptionTarget
,
WeakEventHandlers
};
use
crate
::
worker
::
common
::{
EventHandlers
,
SubscriptionTarget
,
WeakEventHandlers
};
use
crate
::
worker
::{
RequestError
,
SubscriptionHandler
};
use
crate
::
worker
::
utils
::{
PreparedPayloadChannelRead
,
PreparedPayloadChannelWrite
};
use
async_executor
::
Executor
;
use
crate
::
worker
::{
utils
,
RequestError
,
SubscriptionHandler
};
use
async_fs
::
File
;
use
atomic_take
::
AtomicTake
;
use
bytes
::{
BufMut
,
Bytes
,
BytesMut
};
use
futures_lite
::
io
::
BufReader
;
use
futures_lite
::{
future
,
AsyncReadExt
,
AsyncWriteExt
};
use
log
::{
debug
,
error
,
trace
,
warn
};
use
log
::{
debug
,
error
,
trace
,
warn
};
use
mediasoup_sys
::
UvAsyncT
;
use
nohash_hasher
::
IntMap
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
serde
::{
Deserialize
,
Serialize
};
use
serde
::{
Deserialize
,
Serialize
};
use
serde_json
::
Value
;
use
serde_json
::
Value
;
use
std
::
collections
::
HashMap
;
use
std
::
collections
::
VecDeque
;
use
std
::
fmt
::
Debug
;
use
std
::
fmt
::
Debug
;
use
std
::
io
;
use
std
::
sync
::{
Arc
,
Weak
};
use
std
::
sync
::{
Arc
,
Weak
};
use
std
::
time
::
Duration
;
use
thiserror
::
Error
;
use
thiserror
::
Error
;
const
NS_PAYLOAD_MAX_LEN
:
usize
=
4
_194_304
;
#[derive(Debug)]
#[derive(Debug)]
pub
(
super
)
enum
InternalMessage
{
pub
(
super
)
enum
InternalMessage
{
/// Unknown data
/// Unknown data
UnexpectedData
(
Vec
<
u8
>
),
UnexpectedData
(
Vec
<
u8
>
),
}
}
struct
MessageWithPayload
{
message
:
Bytes
,
payload
:
Bytes
,
}
#[derive(Clone)]
pub
(
crate
)
struct
NotificationMessage
{
pub
(
crate
)
message
:
Value
,
pub
(
crate
)
payload
:
Bytes
,
}
#[derive(Debug,
Deserialize)]
#[derive(Debug,
Deserialize)]
#[serde(untagged)]
#[serde(untagged)]
enum
PayloadChannelReceiveMessage
{
enum
PayloadChannelReceiveMessage
{
#[serde(rename_all
=
"camelCase"
)]
Notification
{
target_id
:
SubscriptionTarget
},
ResponseSuccess
{
ResponseSuccess
{
id
:
u32
,
id
:
u32
,
// The following field is present, unused, but needed for differentiating successful
// response from error case
#[allow(dead_code)]
accepted
:
bool
,
accepted
:
bool
,
data
:
Option
<
Value
>
,
data
:
Option
<
Value
>
,
},
},
ResponseError
{
ResponseError
{
id
:
u32
,
id
:
u32
,
error
:
Value
,
// The following field is present, but unused
// error: Value,
reason
:
String
,
reason
:
String
,
},
},
Notification
(
Value
),
/// Unknown data
/// Unknown data
#[serde(skip)]
#[serde(skip)]
Internal
(
InternalMessage
),
Internal
(
InternalMessage
),
...
@@ -68,38 +57,92 @@ fn deserialize_message(bytes: &[u8]) -> PayloadChannelReceiveMessage {
...
@@ -68,38 +57,92 @@ fn deserialize_message(bytes: &[u8]) -> PayloadChannelReceiveMessage {
}
}
}
}
#[derive(Debug,
Error,
Eq,
PartialEq)]
#[derive(Debug,
Serialize)]
pub
enum
NotificationError
{
struct
RequestMessage
<
'a
,
R
>
{
#[error(
"Channel already closed"
)]
id
:
u32
,
ChannelClosed
,
method
:
&
'static
str
,
#[error(
"Message is too long"
)]
#[serde(flatten)]
MessageTooLong
,
request
:
&
'a
R
,
#[error(
"Payload is too long"
)]
PayloadTooLong
,
}
}
struct
ResponseError
{
struct
ResponseError
{
reason
:
String
,
reason
:
String
,
}
}
type
Response
<
T
>
=
Result
<
Option
<
T
>
,
ResponseError
>
;
type
ResponseResult
<
T
>
=
Result
<
Option
<
T
>
,
ResponseError
>
;
struct
RequestDropGuard
<
'a
>
{
id
:
u32
,
message_with_payload
:
Arc
<
AtomicTake
<
OutgoingMessageRequest
>>
,
channel
:
&
'a
PayloadChannel
,
removed
:
bool
,
}
impl
<
'a
>
Drop
for
RequestDropGuard
<
'a
>
{
fn
drop
(
&
mut
self
)
{
if
self
.removed
{
return
;
}
// Drop pending message from memory
self
.message_with_payload
.take
();
// Remove request handler from the container
if
let
Some
(
requests_container
)
=
self
.channel.inner.requests_container_weak
.upgrade
()
{
requests_container
.lock
()
.handlers
.remove
(
&
self
.id
);
}
}
}
impl
<
'a
>
RequestDropGuard
<
'a
>
{
fn
remove
(
mut
self
)
{
self
.removed
=
true
;
}
}
#[derive(Default)]
#[derive(Default)]
struct
RequestsContainer
{
struct
RequestsContainer
{
next_id
:
u32
,
next_id
:
u32
,
handlers
:
HashMap
<
u32
,
async_oneshot
::
Sender
<
Response
<
Value
>>>
,
handlers
:
IntMap
<
u32
,
async_oneshot
::
Sender
<
ResponseResult
<
Value
>>>
,
}
struct
OutgoingMessageRequest
{
message
:
Vec
<
u8
>
,
payload
:
Vec
<
u8
>
,
}
enum
OutgoingMessage
{
Request
(
Arc
<
AtomicTake
<
OutgoingMessageRequest
>>
),
Notification
{
message
:
Vec
<
u8
>
,
payload
:
Vec
<
u8
>
},
}
struct
OutgoingMessageBuffer
{
handle
:
Option
<
UvAsyncT
>
,
messages
:
VecDeque
<
OutgoingMessage
>
,
}
#[derive(Debug,
Serialize)]
struct
NotificationMessage
<
'a
,
N
:
Serialize
>
{
event
:
&
'static
str
,
#[serde(flatten)]
notification
:
&
'a
N
,
}
#[derive(Debug,
Error,
Eq,
PartialEq)]
pub
enum
NotificationError
{
#[error(
"Channel already closed"
)]
ChannelClosed
,
}
}
struct
Inner
{
struct
Inner
{
sender
:
async_channel
::
Sender
<
MessageWithPayload
>
,
outgoing_message_buffer
:
Arc
<
Mutex
<
OutgoingMessageBuffer
>
>
,
internal_message_receiver
:
async_channel
::
Receiver
<
InternalMessage
>
,
internal_message_receiver
:
async_channel
::
Receiver
<
InternalMessage
>
,
requests_container_weak
:
Weak
<
Mutex
<
RequestsContainer
>>
,
requests_container_weak
:
Weak
<
Mutex
<
RequestsContainer
>>
,
event_handlers_weak
:
WeakEventHandlers
<
NotificationMessage
>
,
#[allow(clippy
::
type_complexity)]
event_handlers_weak
:
WeakEventHandlers
<
Arc
<
dyn
Fn
(
&
[
u8
],
&
[
u8
])
+
Send
+
Sync
+
'static
>>
,
}
}
impl
Drop
for
Inner
{
impl
Drop
for
Inner
{
fn
drop
(
&
mut
self
)
{
fn
drop
(
&
mut
self
)
{
self
.sender
.close
();
self
.internal_message_receiver
.close
();
self
.internal_message_receiver
.close
();
}
}
}
}
...
@@ -110,168 +153,101 @@ pub(crate) struct PayloadChannel {
...
@@ -110,168 +153,101 @@ pub(crate) struct PayloadChannel {
}
}
impl
PayloadChannel
{
impl
PayloadChannel
{
pub
(
super
)
fn
new
(
executor
:
&
Executor
<
'static
>
,
reader
:
File
,
mut
writer
:
File
)
->
Self
{
pub
(
super
)
fn
new
()
->
(
Self
,
PreparedPayloadChannelRead
,
PreparedPayloadChannelWrite
,
)
{
let
outgoing_message_buffer
=
Arc
::
new
(
Mutex
::
new
(
OutgoingMessageBuffer
{
handle
:
None
,
messages
:
VecDeque
::
with_capacity
(
10
),
}));
let
requests_container
=
Arc
::
<
Mutex
<
RequestsContainer
>>
::
default
();
let
requests_container
=
Arc
::
<
Mutex
<
RequestsContainer
>>
::
default
();
let
requests_container_weak
=
Arc
::
downgrade
(
&
requests_container
);
let
requests_container_weak
=
Arc
::
downgrade
(
&
requests_container
);
let
event_handlers
=
EventHandlers
::
new
();
let
event_handlers
=
EventHandlers
::
new
();
let
event_handlers_weak
=
event_handlers
.downgrade
();
let
event_handlers_weak
=
event_handlers
.downgrade
();
let
internal_message_receiver
=
{
let
prepared_payload_channel_read
=
utils
::
prepare_payload_channel_read_fn
({
let
(
sender
,
receiver
)
=
async_channel
::
bounded
(
1
);
let
outgoing_message_buffer
=
Arc
::
clone
(
&
outgoing_message_buffer
);
executor
.spawn
(
async
move
{
let
mut
len_bytes
=
[
0u8
;
4
];
let
mut
bytes
=
Vec
::
new
();
let
mut
reader
=
BufReader
::
new
(
reader
);
loop
{
move
|
handle
|
{
reader
.read_exact
(
&
mut
len_bytes
)
.await
?
;
let
mut
outgoing_message_buffer
=
outgoing_message_buffer
.lock
();
let
length
=
u32
::
from_ne_bytes
(
len_bytes
)
as
usize
;
if
outgoing_message_buffer
.handle
.is_none
()
{
outgoing_message_buffer
.handle
.replace
(
handle
);
}
if
length
>
NS_PAYLOAD_MAX_LEN
{
while
let
Some
(
outgoing_message
)
=
outgoing_message_buffer
.messages
.pop_front
()
{
warn!
(
match
outgoing_message
{
"received message {} is too long, max supported is {}"
,
OutgoingMessage
::
Request
(
maybe_message
)
=>
{
length
,
NS_PAYLOAD_MAX_LEN
,
// Request might have already been cancelled
);
if
let
Some
(
OutgoingMessageRequest
{
message
,
payload
})
=
maybe_message
.take
()
{
return
Some
((
message
,
payload
));
}
}
OutgoingMessage
::
Notification
{
message
,
payload
}
=>
{
return
Some
((
message
,
payload
));
}
}
}
}
if
bytes
.len
()
<
length
{
None
// Increase bytes size if/when needed
bytes
.resize
(
length
,
0
);
}
}
reader
.read_exact
(
&
mut
bytes
[
..
length
])
.await
?
;
})
;
trace!
(
let
(
internal_message_sender
,
internal_message_receiver
)
=
async_channel
::
bounded
(
1
);
"received raw message: {}"
,
String
::
from_utf8_lossy
(
&
bytes
[
..
length
]),
);
match
deserialize_message
(
&
bytes
[
..
length
])
{
let
prepared_payload_channel_write
=
PayloadChannelReceiveMessage
::
ResponseSuccess
{
utils
::
prepare_payload_channel_write_fn
(
move
|
message
,
payload
|
{
id
,
trace!
(
"received raw message: {}"
,
String
::
from_utf8_lossy
(
message
));
accepted
:
_
,
data
,
match
deserialize_message
(
message
)
{
}
=>
{
PayloadChannelReceiveMessage
::
Notification
{
target_id
}
=>
{
trace!
(
"received notification payload of {} bytes"
,
payload
.len
());
event_handlers
.call_callbacks_with_two_values
(
&
target_id
,
message
,
payload
);
}
PayloadChannelReceiveMessage
::
ResponseSuccess
{
id
,
data
,
..
}
=>
{
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
if
let
Some
(
mut
sender
)
=
sender
{
if
let
Some
(
mut
sender
)
=
sender
{
let
_
=
sender
.send
(
Ok
(
data
));
let
_
=
sender
.send
(
Ok
(
data
));
}
else
{
}
else
{
warn!
(
warn!
(
"received success response does not match any sent request
\
"received success response does not match any sent request [id:{}]"
,
[id:{}]"
,
id
,
id
,
);
);
}
}
}
}
PayloadChannelReceiveMessage
::
ResponseError
{
PayloadChannelReceiveMessage
::
ResponseError
{
id
,
reason
}
=>
{
id
,
error
:
_
,
reason
,
}
=>
{
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
let
sender
=
requests_container
.lock
()
.handlers
.remove
(
&
id
);
if
let
Some
(
mut
sender
)
=
sender
{
if
let
Some
(
mut
sender
)
=
sender
{
let
_
=
sender
.send
(
Err
(
ResponseError
{
reason
}));
let
_
=
sender
.send
(
Err
(
ResponseError
{
reason
}));
}
else
{
}
else
{
warn!
(
warn!
(
"received error response does not match any sent request
\
"received error response does not match any sent request [id:{}]"
,
[id:{}]"
,
id
,
id
,
);
);
}
}
}
}
PayloadChannelReceiveMessage
::
Notification
(
notification
)
=>
{
let
target_id
=
notification
.get
(
"targetId"
)
.and_then
(|
value
|
{
let
str
=
value
.as_str
()
?
;
str
.parse
()
.ok
()
.map
(
SubscriptionTarget
::
Uuid
)
.or_else
(||
{
str
.parse
()
.ok
()
.map
(
SubscriptionTarget
::
Number
)
})
});
reader
.read_exact
(
&
mut
len_bytes
)
.await
?
;
let
length
=
u32
::
from_ne_bytes
(
len_bytes
)
as
usize
;
if
length
>
NS_PAYLOAD_MAX_LEN
{
warn!
(
"received payload {} is too long, max supported is {}"
,
length
,
NS_PAYLOAD_MAX_LEN
,
);
}
if
bytes
.len
()
<
length
{
// Increase bytes size if/when needed
bytes
.resize
(
length
,
0
);
}
reader
.read_exact
(
&
mut
bytes
[
..
length
])
.await
?
;
trace!
(
"received notification payload of {} bytes"
,
length
);
let
payload
=
Bytes
::
copy_from_slice
(
&
bytes
[
..
length
]);
if
let
Some
(
target_id
)
=
target_id
{
event_handlers
.call_callbacks_with_value
(
&
target_id
,
NotificationMessage
{
message
:
notification
,
payload
,
},
);
}
else
{
let
unexpected_message
=
InternalMessage
::
UnexpectedData
(
Vec
::
from
(
&
bytes
[
..
length
]),
);
if
sender
.send
(
unexpected_message
)
.await
.is_err
()
{
break
;
}
}
}
PayloadChannelReceiveMessage
::
Internal
(
internal_message
)
=>
{
PayloadChannelReceiveMessage
::
Internal
(
internal_message
)
=>
{
if
sender
.send
(
internal_message
)
.await
.is_err
()
{
let
_
=
internal_message_sender
.try_send
(
internal_message
);
break
;
}
}
}
}
}
}
});
io
::
Result
::
Ok
(())
})
.detach
();
receiver
};
let
sender
=
{
let
(
sender
,
receiver
)
=
async_channel
::
bounded
::
<
MessageWithPayload
>
(
1
);
executor
.spawn
(
async
move
{
while
let
Ok
(
message
)
=
receiver
.recv
()
.await
{
writer
.write_all
(
&
(
message
.message
.len
()
as
u32
)
.to_ne_bytes
())
.await
?
;
writer
.write_all
(
&
message
.message
)
.await
?
;
writer
.write_all
(
&
(
message
.payload
.len
()
as
u32
)
.to_ne_bytes
())
.await
?
;
writer
.write_all
(
&
message
.payload
)
.await
?
;
}
io
::
Result
::
Ok
(())
})
.detach
();
sender
};
let
inner
=
Arc
::
new
(
Inner
{
let
inner
=
Arc
::
new
(
Inner
{
send
er
,
outgoing_message_buff
er
,
internal_message_receiver
,
internal_message_receiver
,
requests_container_weak
,
requests_container_weak
,
event_handlers_weak
,
event_handlers_weak
,
});
});
Self
{
inner
}
(
Self
{
inner
},
prepared_payload_channel_read
,
prepared_payload_channel_write
,
)
}
}
pub
(
super
)
fn
get_internal_message_receiver
(
&
self
)
->
async_channel
::
Receiver
<
InternalMessage
>
{
pub
(
super
)
fn
get_internal_message_receiver
(
&
self
)
->
async_channel
::
Receiver
<
InternalMessage
>
{
...
@@ -281,72 +257,14 @@ impl PayloadChannel {
...
@@ -281,72 +257,14 @@ impl PayloadChannel {
pub
(
crate
)
async
fn
request
<
R
>
(
pub
(
crate
)
async
fn
request
<
R
>
(
&
self
,
&
self
,
request
:
R
,
request
:
R
,
payload
:
Bytes
,
payload
:
Vec
<
u8
>
,
)
->
Result
<
R
::
Response
,
RequestError
>
)
->
Result
<
R
::
Response
,
RequestError
>
where
where
R
:
Request
,
R
:
Request
,
{
{
// Default will work for `()` response
let
method
=
request
.as_method
();
let
data
=
self
.request_internal
(
request
.as_method
(),
serde_json
::
to_value
(
request
)
.unwrap
(),
payload
,
)
.await
?
.unwrap_or_default
();
serde_json
::
from_value
(
data
)
.map_err
(|
error
|
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
})
}
pub
(
crate
)
async
fn
notify
<
N
>
(
&
self
,
notification
:
N
,
payload
:
Bytes
,
)
->
Result
<
(),
NotificationError
>
where
N
:
Notification
,
{
self
.notify_internal
(
notification
.as_event
(),
serde_json
::
to_value
(
notification
)
.unwrap
(),
payload
,
)
.await
}
pub
(
crate
)
fn
subscribe_to_notifications
<
F
>
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
F
,
)
->
Option
<
SubscriptionHandler
>
where
F
:
Fn
(
NotificationMessage
)
+
Send
+
Sync
+
'static
,
{
self
.inner
.event_handlers_weak
.upgrade
()
.map
(|
event_handlers
|
event_handlers
.add
(
target_id
,
Box
::
new
(
callback
)))
}
/// Non-generic method to avoid significant duplication in final binary
async
fn
request_internal
(
&
self
,
method
:
&
'static
str
,
message
:
Value
,
payload
:
Bytes
,
)
->
Result
<
Option
<
Value
>
,
RequestError
>
{
#[derive(Debug,
Serialize)]
struct
RequestMessagePrivate
{
id
:
u32
,
method
:
&
'static
str
,
#[serde(flatten)]
message
:
Value
,
}
let
id
;
let
id
;
let
queue_len
;
let
(
result_sender
,
result_receiver
)
=
async_oneshot
::
oneshot
();
let
(
result_sender
,
result_receiver
)
=
async_oneshot
::
oneshot
();
{
{
...
@@ -358,84 +276,62 @@ impl PayloadChannel {
...
@@ -358,84 +276,62 @@ impl PayloadChannel {
let
mut
requests_container
=
requests_container_lock
.lock
();
let
mut
requests_container
=
requests_container_lock
.lock
();
id
=
requests_container
.next_id
;
id
=
requests_container
.next_id
;
queue_len
=
requests_container
.handlers
.len
();
requests_container
.next_id
=
requests_container
.next_id
.wrapping_add
(
1
);
requests_container
.next_id
=
requests_container
.next_id
.wrapping_add
(
1
);
requests_container
.handlers
.insert
(
id
,
result_sender
);
requests_container
.handlers
.insert
(
id
,
result_sender
);
}
}
debug!
(
"request() [method:{}, id:{}]: {
}"
,
method
,
id
,
message
);
debug!
(
"request() [method:{}, id:{}]: {
:?}"
,
method
,
id
,
request
);
let
bytes
=
{
let
message
=
serde_json
::
to_vec
(
&
RequestMessage
{
let
mut
bytes
=
BytesMut
::
new
()
.writer
();
serde_json
::
to_writer
(
&
mut
bytes
,
&
RequestMessagePrivate
{
id
,
id
,
method
,
method
:
request
.as_method
(),
message
,
request
:
&
request
,
},
})
)
.unwrap
();
.unwrap
();
bytes
.into_inner
()
};
if
bytes
.len
()
>
NS_PAYLOAD_MAX_LEN
{
let
message_with_payload
=
self
.inner
Arc
::
new
(
AtomicTake
::
new
(
OutgoingMessageRequest
{
message
,
payload
}));
.requests_container_weak
.upgrade
()
.ok_or
(
RequestError
::
ChannelClosed
)
?
.lock
()
.handlers
.remove
(
&
id
);
return
Err
(
RequestError
::
MessageTooLong
);
}
if
payload
.len
()
>
NS_PAYLOAD_MAX_LEN
{
{
self
.inner
let
mut
outgoing_message_buffer
=
self
.inner.outgoing_message_buffer
.lock
();
.requests_container_weak
outgoing_message_buffer
.upgrade
()
.messages
.ok_or
(
RequestError
::
ChannelClosed
)
?
.push_back
(
OutgoingMessage
::
Request
(
Arc
::
clone
(
&
message_with_payload
)));
.lock
()
if
let
Some
(
handle
)
=
&
outgoing_message_buffer
.handle
{
.handlers
unsafe
{
.remove
(
&
id
);
// Notify worker that there is something to read
return
Err
(
RequestError
::
PayloadTooLong
);
let
ret
=
mediasoup_sys
::
uv_async_send
(
*
handle
);
if
ret
!=
0
{
error!
(
"uv_async_send call failed with code {}"
,
ret
);
return
Err
(
RequestError
::
ChannelClosed
);
}
}
}
}
}
self
.inner
// Drop guard to make sure to drop pending request when future is cancelled
.sender
let
request_drop_guard
=
RequestDropGuard
{
.send
(
MessageWithPayload
{
id
,
message
:
bytes
.freeze
(),
message_with_payload
,
payload
,
channel
:
self
,
})
removed
:
false
,
.await
};
.map_err
(|
_
|
RequestError
::
ChannelClosed
{})
?
;
let
result
=
future
::
or
(
async
move
{
result_receiver
.await
.map_err
(|
_
|
RequestError
::
ChannelClosed
{})
},
async
move
{
async_io
::
Timer
::
after
(
Duration
::
from_millis
(
(
1000.0
*
(
15.0
+
(
0.1
*
queue_len
as
f64
)))
.round
()
as
u64
,
))
.await
;
if
let
Some
(
requests_container
)
=
self
.inner.requests_container_weak
.upgrade
()
{
let
response_result_fut
=
result_receiver
.await
;
requests_container
.lock
()
.handlers
.remove
(
&
id
);
}
Err
(
RequestError
::
TimedOut
)
request_drop_guard
.remove
();
},
)
.await
?
;
match
res
ult
{
match
res
ponse_result_fut
.map_err
(|
_
|
RequestError
::
ChannelClosed
{})
?
{
Ok
(
data
)
=>
{
Ok
(
data
)
=>
{
debug!
(
"request succeeded [method:{}, id:{}]"
,
method
,
id
);
debug!
(
"request succeeded [method:{}, id:{}]"
,
method
,
id
);
Ok
(
data
)
// Default will work for `()` response
serde_json
::
from_value
(
data
.unwrap_or_default
())
.map_err
(|
error
|
{
RequestError
::
FailedToParse
{
error
:
error
.to_string
(),
}
})
}
}
Err
(
ResponseError
{
reason
})
=>
{
Err
(
ResponseError
{
reason
})
=>
{
debug!
(
"request failed [method:{}, id:{}]: {}"
,
method
,
id
,
reason
);
debug!
(
"request failed [method:{}, id:{}]: {}"
,
method
,
id
,
reason
);
...
@@ -445,50 +341,53 @@ impl PayloadChannel {
...
@@ -445,50 +341,53 @@ impl PayloadChannel {
}
}
}
}
/// Non-generic method to avoid significant duplication in final binary
pub
(
crate
)
fn
notify
<
N
>
(
async
fn
notify_internal
(
&
self
,
&
self
,
event
:
&
'static
str
,
notification
:
N
,
notification
:
Value
,
payload
:
Vec
<
u8
>
,
payload
:
Bytes
,
)
->
Result
<
(),
NotificationError
>
)
->
Result
<
(),
NotificationError
>
{
where
#[derive(Debug,
Serialize)]
N
:
Notification
,
struct
NotificationMessagePrivate
{
{
event
:
&
'static
str
,
debug!
(
"notify() [event:{}]"
,
notification
.as_event
());
#[serde(flatten)]
notification
:
Value
,
}
debug!
(
"notify() [event:{}]"
,
event
);
let
message
=
serde_json
::
to_vec
(
&
NotificationMessage
{
event
:
notification
.as_event
(),
notification
:
&
notification
,
})
.unwrap
();
if
payload
.len
()
>
NS_PAYLOAD_MAX_LEN
{
{
return
Err
(
NotificationError
::
PayloadTooLong
);
let
mut
outgoing_message_buffer
=
self
.inner.outgoing_message_buffer
.lock
();
outgoing_message_buffer
.messages
.push_back
(
OutgoingMessage
::
Notification
{
message
,
payload
});
if
let
Some
(
handle
)
=
&
outgoing_message_buffer
.handle
{
unsafe
{
// Notify worker that there is something to read
let
ret
=
mediasoup_sys
::
uv_async_send
(
*
handle
);
if
ret
!=
0
{
error!
(
"uv_async_send call failed with code {}"
,
ret
);
return
Err
(
NotificationError
::
ChannelClosed
);
}
}
}
}
}
let
bytes
=
{
Ok
(())
let
mut
bytes
=
BytesMut
::
new
()
.writer
();
serde_json
::
to_writer
(
&
mut
bytes
,
&
NotificationMessagePrivate
{
event
,
notification
,
},
)
.unwrap
();
bytes
.into_inner
()
};
if
bytes
.len
()
>
NS_PAYLOAD_MAX_LEN
{
return
Err
(
NotificationError
::
MessageTooLong
);
}
}
pub
(
crate
)
fn
subscribe_to_notifications
<
F
>
(
&
self
,
target_id
:
SubscriptionTarget
,
callback
:
F
,
)
->
Option
<
SubscriptionHandler
>
where
F
:
Fn
(
&
[
u8
],
&
[
u8
])
+
Send
+
Sync
+
'static
,
{
self
.inner
self
.inner
.sender
.event_handlers_weak
.send
(
MessageWithPayload
{
.upgrade
()
message
:
bytes
.freeze
(),
.map
(|
event_handlers
|
event_handlers
.add
(
target_id
,
Arc
::
new
(
callback
)))
payload
,
})
.await
.map_err
(|
_
|
NotificationError
::
ChannelClosed
{})
}
}
}
}
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
::
BufferMessagesGuard
;
use
crate
::
worker
::{
Channel
,
PayloadChannel
,
WorkerId
};
use
crate
::
worker
::{
Channel
,
PayloadChannel
,
WorkerId
};
use
async_executor
::
Executor
;
pub
(
super
)
use
channel_read_fn
::{
use
async_fs
::
File
;
prepare_channel_read_fn
,
prepare_payload_channel_read_fn
,
PreparedChannelRead
,
PreparedPayloadChannelRead
,
};
pub
(
super
)
use
channel_write_fn
::{
prepare_channel_write_fn
,
prepare_payload_channel_write_fn
,
PreparedChannelWrite
,
PreparedPayloadChannelWrite
,
};
use
std
::
ffi
::
CString
;
use
std
::
ffi
::
CString
;
use
std
::
mem
;
use
std
::
os
::
raw
::{
c_char
,
c_int
};
use
std
::
os
::
raw
::{
c_char
,
c_int
};
use
std
::
os
::
unix
::
io
::
FromRawFd
;
use
std
::
sync
::
Arc
;
use
std
::
sync
::
Arc
;
use
thiserror
::
Error
;
use
thiserror
::
Error
;
...
@@ -30,18 +36,6 @@ pub enum ExitError {
...
@@ -30,18 +36,6 @@ pub enum ExitError {
Unexpected
,
Unexpected
,
}
}
fn
pipe
()
->
[
c_int
;
2
]
{
unsafe
{
let
mut
fds
=
mem
::
MaybeUninit
::
<
[
c_int
;
2
]
>
::
uninit
();
if
libc
::
pipe
(
fds
.as_mut_ptr
()
.cast
::
<
c_int
>
())
!=
0
{
panic!
(
"libc::pipe() failed: {:?}"
,
std
::
io
::
Error
::
last_os_error
());
}
fds
.assume_init
()
}
}
pub
(
super
)
struct
WorkerRunResult
{
pub
(
super
)
struct
WorkerRunResult
{
pub
(
super
)
channel
:
Channel
,
pub
(
super
)
channel
:
Channel
,
pub
(
super
)
payload_channel
:
PayloadChannel
,
pub
(
super
)
payload_channel
:
PayloadChannel
,
...
@@ -50,31 +44,24 @@ pub(super) struct WorkerRunResult {
...
@@ -50,31 +44,24 @@ pub(super) struct WorkerRunResult {
pub
(
super
)
fn
run_worker_with_channels
<
OE
>
(
pub
(
super
)
fn
run_worker_with_channels
<
OE
>
(
id
:
WorkerId
,
id
:
WorkerId
,
executor
:
Arc
<
Executor
<
'stati
c
>>
,
thread_initializer
:
Option
<
Arc
<
dyn
Fn
()
+
Send
+
Syn
c
>>
,
args
:
Vec
<
String
>
,
args
:
Vec
<
String
>
,
on_exit
:
OE
,
on_exit
:
OE
,
)
->
WorkerRunResult
)
->
WorkerRunResult
where
where
OE
:
FnOnce
(
Result
<
(),
ExitError
>
)
+
Send
+
'static
,
OE
:
FnOnce
(
Result
<
(),
ExitError
>
)
+
Send
+
'static
,
{
{
let
[
producer_fd_read
,
producer_fd_write
]
=
pipe
();
let
(
channel
,
prepared_channel_read
,
prepared_channel_write
)
=
Channel
::
new
();
let
[
consumer_fd_read
,
consumer_fd_write
]
=
pipe
();
let
(
payload_channel
,
prepared_payload_channel_read
,
prepared_payload_channel_write
)
=
let
[
producer_payload_fd_read
,
producer_payload_fd_write
]
=
pipe
();
PayloadChannel
::
new
();
let
[
consumer_payload_fd_read
,
consumer_payload_fd_write
]
=
pipe
();
let
producer_file
=
unsafe
{
File
::
from_raw_fd
(
producer_fd_write
)
};
let
consumer_file
=
unsafe
{
File
::
from_raw_fd
(
consumer_fd_read
)
};
let
producer_payload_file
=
unsafe
{
File
::
from_raw_fd
(
producer_payload_fd_write
)
};
let
consumer_payload_file
=
unsafe
{
File
::
from_raw_fd
(
consumer_payload_fd_read
)
};
let
channel
=
Channel
::
new
(
&
executor
,
consumer_file
,
producer_file
);
let
payload_channel
=
PayloadChannel
::
new
(
&
executor
,
consumer_payload_file
,
producer_payload_file
);
let
buffer_worker_messages_guard
=
channel
.buffer_messages_for
(
std
::
process
::
id
()
.into
());
let
buffer_worker_messages_guard
=
channel
.buffer_messages_for
(
std
::
process
::
id
()
.into
());
std
::
thread
::
Builder
::
new
()
std
::
thread
::
Builder
::
new
()
.name
(
format!
(
"mediasoup-worker-{}"
,
id
))
.name
(
format!
(
"mediasoup-worker-{}"
,
id
))
.spawn
(
move
||
{
.spawn
(
move
||
{
if
let
Some
(
thread_initializer
)
=
thread_initializer
{
thread_initializer
();
}
let
argc
=
args
.len
()
as
c_int
;
let
argc
=
args
.len
()
as
c_int
;
let
args_cstring
=
args
let
args_cstring
=
args
.into_iter
()
.into_iter
()
...
@@ -85,15 +72,39 @@ where
...
@@ -85,15 +72,39 @@ where
.map
(|
arg
|
arg
.as_ptr
()
.cast
::
<
c_char
>
())
.map
(|
arg
|
arg
.as_ptr
()
.cast
::
<
c_char
>
())
.collect
::
<
Vec
<
_
>>
();
.collect
::
<
Vec
<
_
>>
();
let
version
=
CString
::
new
(
env!
(
"CARGO_PKG_VERSION"
))
.unwrap
();
let
version
=
CString
::
new
(
env!
(
"CARGO_PKG_VERSION"
))
.unwrap
();
let
status_code
=
unsafe
{
let
status_code
=
unsafe
{
mediasoup_sys
::
run_worker
(
let
(
channel_read_fn
,
channel_read_ctx
,
_channel_write_callback
)
=
prepared_channel_read
.deconstruct
();
let
(
channel_write_fn
,
channel_write_ctx
,
_channel_read_callback
)
=
prepared_channel_write
.deconstruct
();
let
(
payload_channel_read_fn
,
payload_channel_read_ctx
,
_payload_channel_write_callback
,
)
=
prepared_payload_channel_read
.deconstruct
();
let
(
payload_channel_write_fn
,
payload_channel_write_ctx
,
_payload_channel_read_callback
,
)
=
prepared_payload_channel_write
.deconstruct
();
mediasoup_sys
::
mediasoup_worker_run
(
argc
,
argc
,
argv
.as_ptr
(),
argv
.as_ptr
(),
version
.as_ptr
(),
version
.as_ptr
(),
producer_fd_read
,
0
,
consumer_fd_write
,
0
,
producer_payload_fd_read
,
0
,
consumer_payload_fd_write
,
0
,
channel_read_fn
,
channel_read_ctx
,
channel_write_fn
,
channel_write_ctx
,
payload_channel_read_fn
,
payload_channel_read_ctx
,
payload_channel_write_fn
,
payload_channel_write_ctx
,
)
)
};
};
...
...
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};
...
@@ -18,7 +18,7 @@ use std::{fmt, io, mem};
#[derive(Default)]
#[derive(Default)]
struct
Handlers
{
struct
Handlers
{
new_worker
:
Bag
<
Box
<
dyn
Fn
(
&
Worker
)
+
Send
+
Sync
>
>
,
new_worker
:
Bag
<
Arc
<
dyn
Fn
(
&
Worker
)
+
Send
+
Sync
>
,
Worker
>
,
}
}
struct
Inner
{
struct
Inner
{
...
@@ -145,9 +145,7 @@ impl WorkerManager {
...
@@ -145,9 +145,7 @@ impl WorkerManager {
)
)
.await
?
;
.await
?
;
self
.inner.handlers.new_worker
.call
(|
callback
|
{
self
.inner.handlers.new_worker
.call_simple
(
&
worker
);
callback
(
&
worker
);
});
id
.lock
()
.replace
(
worker
.id
());
id
.lock
()
.replace
(
worker
.id
());
...
@@ -158,6 +156,6 @@ impl WorkerManager {
...
@@ -158,6 +156,6 @@ impl WorkerManager {
/// Callback is called when a new worker is created.
/// Callback is called when a new worker is created.
pub
fn
on_new_worker
<
F
:
Fn
(
&
Worker
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
pub
fn
on_new_worker
<
F
:
Fn
(
&
Worker
)
+
Send
+
Sync
+
'static
>
(
&
self
,
callback
:
F
)
->
HandlerId
{
self
.inner.handlers.new_worker
.add
(
Box
::
new
(
callback
))
self
.inner.handlers.new_worker
.add
(
Arc
::
new
(
callback
))
}
}
}
}
rust/tests/integration/consumer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
consumer
::{
use
mediasoup
::
consumer
::{
ConsumableRtpEncoding
,
ConsumerLayers
,
ConsumerOptions
,
ConsumerScore
,
ConsumerType
,
ConsumableRtpEncoding
,
ConsumerLayers
,
ConsumerOptions
,
ConsumerScore
,
ConsumerType
,
};
};
...
@@ -20,7 +21,6 @@ use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTra
...
@@ -20,7 +21,6 @@ use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTra
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
env
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
...
@@ -350,7 +350,7 @@ fn consume_succeeds() {
...
@@ -350,7 +350,7 @@ fn consume_succeeds() {
.on_new_consumer
({
.on_new_consumer
({
let
new_consumer_count
=
Arc
::
clone
(
&
new_consumer_count
);
let
new_consumer_count
=
Arc
::
clone
(
&
new_consumer_count
);
Box
::
new
(
move
|
_consumer
|
{
Arc
::
new
(
move
|
_consumer
|
{
new_consumer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_consumer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -421,13 +421,13 @@ fn consume_succeeds() {
...
@@ -421,13 +421,13 @@ fn consume_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
{
map
.insert
(
audio_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
audio_consumer
.id
());
set
.insert
(
audio_consumer
.id
());
set
set
});
});
map
.insert
(
video_producer
.id
(),
Hash
Set
::
new
());
map
.insert
(
video_producer
.id
(),
Hash
edSet
::
default
());
map
map
});
});
...
@@ -525,14 +525,14 @@ fn consume_succeeds() {
...
@@ -525,14 +525,14 @@ fn consume_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
{
map
.insert
(
audio_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
audio_consumer
.id
());
set
.insert
(
audio_consumer
.id
());
set
set
});
});
map
.insert
(
video_producer
.id
(),
{
map
.insert
(
video_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
video_consumer
.id
());
set
.insert
(
video_consumer
.id
());
set
set
});
});
...
@@ -620,14 +620,14 @@ fn consume_succeeds() {
...
@@ -620,14 +620,14 @@ fn consume_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
{
map
.insert
(
audio_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
audio_consumer
.id
());
set
.insert
(
audio_consumer
.id
());
set
set
});
});
map
.insert
(
video_producer
.id
(),
{
map
.insert
(
video_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
video_consumer
.id
());
set
.insert
(
video_consumer
.id
());
set
.insert
(
video_pipe_consumer
.id
());
set
.insert
(
video_pipe_consumer
.id
());
set
set
...
@@ -1387,11 +1387,11 @@ fn close_event() {
...
@@ -1387,11 +1387,11 @@ fn close_event() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
{
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
Hash
Set
::
new
());
map
.insert
(
audio_producer
.id
(),
Hash
edSet
::
default
());
map
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
async_io
::
Timer
;
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_consumer
::{
DataConsumerOptions
,
DataConsumerType
};
use
mediasoup
::
data_consumer
::{
DataConsumerOptions
,
DataConsumerType
};
use
mediasoup
::
data_producer
::{
DataProducer
,
DataProducerOptions
};
use
mediasoup
::
data_producer
::{
DataProducer
,
DataProducerOptions
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
...
@@ -11,7 +12,6 @@ use mediasoup::sctp_parameters::SctpStreamParameters;
...
@@ -11,7 +12,6 @@ use mediasoup::sctp_parameters::SctpStreamParameters;
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
env
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
use
std
::
sync
::
Arc
;
...
@@ -105,7 +105,7 @@ fn consume_data_succeeds() {
...
@@ -105,7 +105,7 @@ fn consume_data_succeeds() {
.on_new_data_consumer
({
.on_new_data_consumer
({
let
new_data_consumer_count
=
Arc
::
clone
(
&
new_data_consumer_count
);
let
new_data_consumer_count
=
Arc
::
clone
(
&
new_data_consumer_count
);
Box
::
new
(
move
|
_data_consumer
|
{
Arc
::
new
(
move
|
_data_consumer
|
{
new_data_consumer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_data_consumer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -154,16 +154,16 @@ fn consume_data_succeeds() {
...
@@ -154,16 +154,16 @@ fn consume_data_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer
.id
(),
{
map
.insert
(
data_producer
.id
(),
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
data_consumer
.id
());
set
.insert
(
data_consumer
.id
());
set
set
});
});
map
map
});
});
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
{
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_consumer
.id
(),
data_producer
.id
());
map
.insert
(
data_consumer
.id
(),
data_producer
.id
());
map
map
});
});
...
@@ -316,7 +316,7 @@ fn consume_data_on_direct_transport_succeeds() {
...
@@ -316,7 +316,7 @@ fn consume_data_on_direct_transport_succeeds() {
.on_new_data_consumer
({
.on_new_data_consumer
({
let
new_data_consumer_count
=
Arc
::
clone
(
&
new_data_consumer_count
);
let
new_data_consumer_count
=
Arc
::
clone
(
&
new_data_consumer_count
);
Box
::
new
(
move
|
_data_consumer
|
{
Arc
::
new
(
move
|
_data_consumer
|
{
new_data_consumer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_data_consumer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -478,11 +478,14 @@ fn close_event() {
...
@@ -478,11 +478,14 @@ fn close_event() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer
.id
(),
Hash
Set
::
new
());
map
.insert
(
data_producer
.id
(),
Hash
edSet
::
default
());
map
map
});
});
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
}
}
{
{
...
...
rust/tests/integration/data_producer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_producer
::{
DataProducerOptions
,
DataProducerType
};
use
mediasoup
::
data_producer
::{
DataProducerOptions
,
DataProducerType
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
plain_transport
::{
PlainTransport
,
PlainTransportOptions
};
use
mediasoup
::
plain_transport
::{
PlainTransport
,
PlainTransportOptions
};
...
@@ -10,7 +11,6 @@ use mediasoup::transport::ProduceDataError;
...
@@ -10,7 +11,6 @@ use mediasoup::transport::ProduceDataError;
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
env
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
use
std
::
sync
::
Arc
;
...
@@ -86,7 +86,7 @@ fn transport_1_produce_data_succeeds() {
...
@@ -86,7 +86,7 @@ fn transport_1_produce_data_succeeds() {
.on_new_data_producer
({
.on_new_data_producer
({
let
new_data_producer_count
=
Arc
::
clone
(
&
new_data_producer_count
);
let
new_data_producer_count
=
Arc
::
clone
(
&
new_data_producer_count
);
Box
::
new
(
move
|
_data_producer
|
{
Arc
::
new
(
move
|
_data_producer
|
{
new_data_producer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_data_producer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -131,11 +131,14 @@ fn transport_1_produce_data_succeeds() {
...
@@ -131,11 +131,14 @@ fn transport_1_produce_data_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer1
.id
(),
Hash
Set
::
new
());
map
.insert
(
data_producer1
.id
(),
Hash
edSet
::
default
());
map
map
});
});
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
}
}
{
{
...
@@ -159,7 +162,7 @@ fn transport_2_produce_data_succeeds() {
...
@@ -159,7 +162,7 @@ fn transport_2_produce_data_succeeds() {
.on_new_data_producer
({
.on_new_data_producer
({
let
new_data_producer_count
=
Arc
::
clone
(
&
new_data_producer_count
);
let
new_data_producer_count
=
Arc
::
clone
(
&
new_data_producer_count
);
Box
::
new
(
move
|
_data_producer
|
{
Arc
::
new
(
move
|
_data_producer
|
{
new_data_producer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_data_producer_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -205,11 +208,14 @@ fn transport_2_produce_data_succeeds() {
...
@@ -205,11 +208,14 @@ fn transport_2_produce_data_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
data_producer2
.id
(),
Hash
Set
::
new
());
map
.insert
(
data_producer2
.id
(),
Hash
edSet
::
default
());
map
map
});
});
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
}
}
{
{
...
@@ -447,8 +453,14 @@ fn close_event() {
...
@@ -447,8 +453,14 @@ fn close_event() {
{
{
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
HashMap
::
new
());
assert_eq!
(
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
dump
.map_data_producer_id_data_consumer_ids
,
HashedMap
::
default
()
);
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
}
}
{
{
...
...
rust/tests/integration/direct_transport.rs
浏览文件 @
f0ebd809
use
bytes
::
Bytes
;
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::
HashedSet
;
use
mediasoup
::
data_consumer
::
DataConsumerOptions
;
use
mediasoup
::
data_consumer
::
DataConsumerOptions
;
use
mediasoup
::
data_producer
::{
DataProducer
,
DataProducerOptions
};
use
mediasoup
::
data_producer
::{
DataProducer
,
DataProducerOptions
};
use
mediasoup
::
data_structures
::{
AppData
,
WebRtcMessage
};
use
mediasoup
::
data_structures
::{
AppData
,
WebRtcMessage
};
...
@@ -9,7 +9,7 @@ use mediasoup::router::{Router, RouterOptions};
...
@@ -9,7 +9,7 @@ use mediasoup::router::{Router, RouterOptions};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
parking_lot
::
Mutex
;
use
parking_lot
::
Mutex
;
use
std
::
collections
::
HashSet
;
use
std
::
borrow
::
Cow
;
use
std
::
env
;
use
std
::
env
;
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
Arc
;
use
std
::
sync
::
Arc
;
...
@@ -56,7 +56,7 @@ fn create_succeeds() {
...
@@ -56,7 +56,7 @@ fn create_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.transport_ids
,
{
assert_eq!
(
dump
.transport_ids
,
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
transport
.id
());
set
.insert
(
transport
.id
());
set
set
});
});
...
@@ -240,14 +240,13 @@ fn send_succeeds() {
...
@@ -240,14 +240,13 @@ fn send_succeeds() {
sent_message_bytes
+=
content
.len
();
sent_message_bytes
+=
content
.len
();
WebRtcMessage
::
String
(
content
)
WebRtcMessage
::
String
(
content
)
}
else
{
}
else
{
let
content
=
Bytes
::
from
(
id
.to_string
()
.into_bytes
()
);
let
content
=
id
.to_string
()
.into_bytes
(
);
sent_message_bytes
+=
content
.len
();
sent_message_bytes
+=
content
.len
();
WebRtcMessage
::
Binary
(
content
)
WebRtcMessage
::
Binary
(
Cow
::
from
(
content
)
)
};
};
direct_data_producer
direct_data_producer
.send
(
message
)
.send
(
message
)
.await
.expect
(
"Failed to send message"
);
.expect
(
"Failed to send message"
);
if
id
==
num_messages
{
if
id
==
num_messages
{
...
...
rust/tests/integration/plain_transport.rs
浏览文件 @
f0ebd809
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::
HashedSet
;
use
mediasoup
::
data_structures
::{
use
mediasoup
::
data_structures
::{
AppData
,
SctpState
,
TransportListenIp
,
TransportProtocol
,
TransportTuple
,
AppData
,
SctpState
,
TransportListenIp
,
TransportProtocol
,
TransportTuple
,
};
};
...
@@ -12,7 +13,6 @@ use mediasoup::sctp_parameters::SctpParameters;
...
@@ -12,7 +13,6 @@ use mediasoup::sctp_parameters::SctpParameters;
use
mediasoup
::
srtp_parameters
::{
SrtpCryptoSuite
,
SrtpParameters
};
use
mediasoup
::
srtp_parameters
::{
SrtpCryptoSuite
,
SrtpParameters
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::
HashSet
;
use
std
::
env
;
use
std
::
env
;
use
std
::
net
::
IpAddr
;
use
std
::
net
::
IpAddr
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
...
@@ -104,7 +104,7 @@ fn create_succeeds() {
...
@@ -104,7 +104,7 @@ fn create_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
router_dump
.transport_ids
,
{
assert_eq!
(
router_dump
.transport_ids
,
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
transport
.id
());
set
.insert
(
transport
.id
());
set
set
});
});
...
...
rust/tests/integration/producer.rs
浏览文件 @
f0ebd809
use
async_io
::
Timer
;
use
async_io
::
Timer
;
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
data_structures
::{
AppData
,
TransportListenIp
};
use
mediasoup
::
prelude
::
*
;
use
mediasoup
::
prelude
::
*
;
use
mediasoup
::
producer
::{
ProducerOptions
,
ProducerTraceEventType
,
ProducerType
};
use
mediasoup
::
producer
::{
ProducerOptions
,
ProducerTraceEventType
,
ProducerType
};
...
@@ -14,7 +15,6 @@ use mediasoup::transport::ProduceError;
...
@@ -14,7 +15,6 @@ use mediasoup::transport::ProduceError;
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
webrtc_transport
::{
TransportListenIps
,
WebRtcTransport
,
WebRtcTransportOptions
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
env
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
...
@@ -229,7 +229,7 @@ fn produce_succeeds() {
...
@@ -229,7 +229,7 @@ fn produce_succeeds() {
.on_new_producer
({
.on_new_producer
({
let
new_producers_count
=
Arc
::
clone
(
&
new_producers_count
);
let
new_producers_count
=
Arc
::
clone
(
&
new_producers_count
);
Box
::
new
(
move
|
_producer
|
{
Arc
::
new
(
move
|
_producer
|
{
new_producers_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_producers_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -266,11 +266,14 @@ fn produce_succeeds() {
...
@@ -266,11 +266,14 @@ fn produce_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
audio_producer
.id
(),
Hash
Set
::
new
());
map
.insert
(
audio_producer
.id
(),
Hash
edSet
::
default
());
map
map
});
});
assert_eq!
(
router_dump
.map_consumer_id_producer_id
,
HashMap
::
new
());
assert_eq!
(
router_dump
.map_consumer_id_producer_id
,
HashedMap
::
default
()
);
let
transport_1_dump
=
transport_1
let
transport_1_dump
=
transport_1
.dump
()
.dump
()
...
@@ -279,6 +282,19 @@ fn produce_succeeds() {
...
@@ -279,6 +282,19 @@ fn produce_succeeds() {
assert_eq!
(
transport_1_dump
.producer_ids
,
vec!
[
audio_producer
.id
()]);
assert_eq!
(
transport_1_dump
.producer_ids
,
vec!
[
audio_producer
.id
()]);
assert_eq!
(
transport_1_dump
.consumer_ids
,
vec!
[]);
assert_eq!
(
transport_1_dump
.consumer_ids
,
vec!
[]);
let
(
mut
tx
,
rx
)
=
async_oneshot
::
oneshot
::
<
()
>
();
transport_1
.on_close
(
Box
::
new
(
move
||
{
let
_
=
tx
.send
(());
}))
.detach
();
drop
(
audio_producer
);
drop
(
transport_1
);
// This means producer was definitely dropped
rx
.await
.expect
(
"Failed to receive transport close event"
);
}
}
{
{
...
@@ -288,7 +304,7 @@ fn produce_succeeds() {
...
@@ -288,7 +304,7 @@ fn produce_succeeds() {
.on_new_producer
({
.on_new_producer
({
let
new_producers_count
=
Arc
::
clone
(
&
new_producers_count
);
let
new_producers_count
=
Arc
::
clone
(
&
new_producers_count
);
Box
::
new
(
move
|
_producer
|
{
Arc
::
new
(
move
|
_producer
|
{
new_producers_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
new_producers_count
.fetch_add
(
1
,
Ordering
::
SeqCst
);
})
})
})
})
...
@@ -325,11 +341,14 @@ fn produce_succeeds() {
...
@@ -325,11 +341,14 @@ fn produce_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to get router dump"
);
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
assert_eq!
(
router_dump
.map_producer_id_consumer_ids
,
{
let
mut
map
=
Hash
Map
::
new
();
let
mut
map
=
Hash
edMap
::
default
();
map
.insert
(
video_producer
.id
(),
Hash
Set
::
new
());
map
.insert
(
video_producer
.id
(),
Hash
edSet
::
default
());
map
map
});
});
assert_eq!
(
router_dump
.map_consumer_id_producer_id
,
HashMap
::
new
());
assert_eq!
(
router_dump
.map_consumer_id_producer_id
,
HashedMap
::
default
()
);
let
transport_2_dump
=
transport_2
let
transport_2_dump
=
transport_2
.dump
()
.dump
()
...
@@ -903,8 +922,8 @@ fn close_event() {
...
@@ -903,8 +922,8 @@ fn close_event() {
{
{
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
Hash
Map
::
new
());
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
Hash
edMap
::
default
());
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/router.rs
浏览文件 @
f0ebd809
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::{
HashedMap
,
HashedSet
};
use
mediasoup
::
data_structures
::
AppData
;
use
mediasoup
::
data_structures
::
AppData
;
use
mediasoup
::
router
::
RouterOptions
;
use
mediasoup
::
router
::
RouterOptions
;
use
mediasoup
::
rtp_parameters
::{
use
mediasoup
::
rtp_parameters
::{
...
@@ -6,7 +7,6 @@ use mediasoup::rtp_parameters::{
...
@@ -6,7 +7,6 @@ use mediasoup::rtp_parameters::{
};
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::{
HashMap
,
HashSet
};
use
std
::
env
;
use
std
::
env
;
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
num
::{
NonZeroU32
,
NonZeroU8
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
use
std
::
sync
::
atomic
::{
AtomicUsize
,
Ordering
};
...
@@ -106,13 +106,19 @@ fn create_router_succeeds() {
...
@@ -106,13 +106,19 @@ fn create_router_succeeds() {
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
dump
.id
,
router
.id
());
assert_eq!
(
dump
.id
,
router
.id
());
assert_eq!
(
dump
.transport_ids
,
HashSet
::
new
());
assert_eq!
(
dump
.transport_ids
,
HashedSet
::
default
());
assert_eq!
(
dump
.rtp_observer_ids
,
HashSet
::
new
());
assert_eq!
(
dump
.rtp_observer_ids
,
HashedSet
::
default
());
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
HashMap
::
new
());
assert_eq!
(
dump
.map_producer_id_consumer_ids
,
HashedMap
::
default
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
HashMap
::
new
());
assert_eq!
(
dump
.map_consumer_id_producer_id
,
HashedMap
::
default
());
assert_eq!
(
dump
.map_producer_id_observer_ids
,
HashMap
::
new
());
assert_eq!
(
dump
.map_producer_id_observer_ids
,
HashedMap
::
default
());
assert_eq!
(
dump
.map_data_producer_id_data_consumer_ids
,
HashMap
::
new
());
assert_eq!
(
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashMap
::
new
());
dump
.map_data_producer_id_data_consumer_ids
,
HashedMap
::
default
()
);
assert_eq!
(
dump
.map_data_consumer_id_data_producer_id
,
HashedMap
::
default
()
);
});
});
}
}
...
...
rust/tests/integration/webrtc_transport.rs
浏览文件 @
f0ebd809
use
futures_lite
::
future
;
use
futures_lite
::
future
;
use
hash_hasher
::
HashedSet
;
use
mediasoup
::
data_structures
::{
use
mediasoup
::
data_structures
::{
AppData
,
DtlsFingerprint
,
DtlsParameters
,
DtlsRole
,
DtlsState
,
IceCandidateTcpType
,
AppData
,
DtlsFingerprint
,
DtlsParameters
,
DtlsRole
,
DtlsState
,
IceCandidateTcpType
,
IceCandidateType
,
IceRole
,
IceState
,
SctpState
,
TransportListenIp
,
TransportProtocol
,
IceCandidateType
,
IceRole
,
IceState
,
SctpState
,
TransportListenIp
,
TransportProtocol
,
...
@@ -15,7 +16,6 @@ use mediasoup::webrtc_transport::{
...
@@ -15,7 +16,6 @@ use mediasoup::webrtc_transport::{
};
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker
::{
RequestError
,
Worker
,
WorkerSettings
};
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
mediasoup
::
worker_manager
::
WorkerManager
;
use
std
::
collections
::
HashSet
;
use
std
::
convert
::
TryInto
;
use
std
::
convert
::
TryInto
;
use
std
::
env
;
use
std
::
env
;
use
std
::
net
::
IpAddr
;
use
std
::
net
::
IpAddr
;
...
@@ -104,7 +104,7 @@ fn create_succeeds() {
...
@@ -104,7 +104,7 @@ fn create_succeeds() {
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
let
router_dump
=
router
.dump
()
.await
.expect
(
"Failed to dump router"
);
assert_eq!
(
router_dump
.transport_ids
,
{
assert_eq!
(
router_dump
.transport_ids
,
{
let
mut
set
=
Hash
Set
::
new
();
let
mut
set
=
Hash
edSet
::
default
();
set
.insert
(
transport
.id
());
set
.insert
(
transport
.id
());
set
set
});
});
...
...
worker/build.rs
浏览文件 @
f0ebd809
...
@@ -7,6 +7,12 @@ fn main() {
...
@@ -7,6 +7,12 @@ fn main() {
return
;
return
;
}
}
let
build_type
=
if
cfg!
(
debug_assertions
)
{
"Debug"
}
else
{
"Release"
};
let
out_dir
=
env
::
var
(
"OUT_DIR"
)
.unwrap
();
let
out_dir
=
env
::
var
(
"OUT_DIR"
)
.unwrap
();
// Add C++ std lib
// Add C++ std lib
...
@@ -79,9 +85,8 @@ fn main() {
...
@@ -79,9 +85,8 @@ fn main() {
// Build
// Build
if
!
Command
::
new
(
"make"
)
if
!
Command
::
new
(
"make"
)
.arg
(
"libmediasoup-worker"
)
.arg
(
"libmediasoup-worker"
)
.env
(
"PYTHONDONTWRITEBYTECODE"
,
"1"
)
.env
(
"MEDIASOUP_OUT_DIR"
,
&
out_dir
)
.env
(
"MEDIASOUP_OUT_DIR"
,
&
out_dir
)
.env
(
"MEDIASOUP_BUILDTYPE"
,
"Release"
)
.env
(
"MEDIASOUP_BUILDTYPE"
,
&
build_type
)
.spawn
()
.spawn
()
.expect
(
"Failed to start"
)
.expect
(
"Failed to start"
)
.wait
()
.wait
()
...
@@ -95,7 +100,6 @@ fn main() {
...
@@ -95,7 +100,6 @@ fn main() {
// Clean
// Clean
if
!
Command
::
new
(
"make"
)
if
!
Command
::
new
(
"make"
)
.arg
(
"clean-all"
)
.arg
(
"clean-all"
)
.env
(
"PYTHONDONTWRITEBYTECODE"
,
"1"
)
.spawn
()
.spawn
()
.expect
(
"Failed to start"
)
.expect
(
"Failed to start"
)
.wait
()
.wait
()
...
@@ -108,6 +112,5 @@ fn main() {
...
@@ -108,6 +112,5 @@ fn main() {
}
}
println!
(
"cargo:rustc-link-lib=static=mediasoup-worker"
);
println!
(
"cargo:rustc-link-lib=static=mediasoup-worker"
);
println!
(
"cargo:rustc-link-search=native={}"
,
out_dir
);
println!
(
"cargo:rustc-link-search=native={}/{}"
,
out_dir
,
build_type
);
println!
(
"cargo:rustc-link-search=native={}/Release"
,
out_dir
);
}
}
worker/include/Channel/ChannelNotifier.hpp
浏览文件 @
f0ebd809
...
@@ -12,6 +12,7 @@ namespace Channel
...
@@ -12,6 +12,7 @@ namespace Channel
{
{
public
:
public
:
static
void
ClassInit
(
Channel
::
ChannelSocket
*
channel
);
static
void
ClassInit
(
Channel
::
ChannelSocket
*
channel
);
static
void
Emit
(
uint64_t
targetId
,
const
char
*
event
);
static
void
Emit
(
const
std
::
string
&
targetId
,
const
char
*
event
);
static
void
Emit
(
const
std
::
string
&
targetId
,
const
char
*
event
);
static
void
Emit
(
const
std
::
string
&
targetId
,
const
char
*
event
,
json
&
data
);
static
void
Emit
(
const
std
::
string
&
targetId
,
const
char
*
event
,
json
&
data
);
...
...
worker/include/Channel/ChannelSocket.hpp
浏览文件 @
f0ebd809
...
@@ -64,16 +64,22 @@ namespace Channel
...
@@ -64,16 +64,22 @@ namespace Channel
public
:
public
:
explicit
ChannelSocket
(
int
consumerFd
,
int
producerFd
);
explicit
ChannelSocket
(
int
consumerFd
,
int
producerFd
);
explicit
ChannelSocket
(
ChannelReadFn
channelReadFn
,
ChannelReadCtx
channelReadCtx
,
ChannelWriteFn
channelWriteFn
,
ChannelWriteCtx
channelWriteCtx
);
virtual
~
ChannelSocket
();
virtual
~
ChannelSocket
();
public
:
public
:
void
Close
();
void
Close
();
void
SetListener
(
Listener
*
listener
);
void
SetListener
(
Listener
*
listener
);
bool
CallbackRead
();
void
Send
(
json
&
jsonMessage
);
void
Send
(
json
&
jsonMessage
);
void
SendLog
(
char
*
message
,
uint32_t
messageLen
);
void
SendLog
(
c
onst
c
har
*
message
,
uint32_t
messageLen
);
private
:
private
:
void
SendImpl
(
const
void
*
payload
,
uint32_t
payloadLen
);
void
SendImpl
(
const
uint8_t
*
payload
,
uint32_t
payloadLen
);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */
/* Pure virtual methods inherited from ConsumerSocket::Listener. */
public
:
public
:
...
@@ -85,9 +91,14 @@ namespace Channel
...
@@ -85,9 +91,14 @@ namespace Channel
Listener
*
listener
{
nullptr
};
Listener
*
listener
{
nullptr
};
// Others.
// Others.
bool
closed
{
false
};
bool
closed
{
false
};
ConsumerSocket
consumerSocket
;
ConsumerSocket
*
consumerSocket
{
nullptr
};
ProducerSocket
producerSocket
;
ProducerSocket
*
producerSocket
{
nullptr
};
uint8_t
*
writeBuffer
;
ChannelReadFn
channelReadFn
{
nullptr
};
ChannelReadCtx
channelReadCtx
{
nullptr
};
ChannelWriteFn
channelWriteFn
{
nullptr
};
ChannelWriteCtx
channelWriteCtx
{
nullptr
};
uv_async_t
*
uvReadHandle
{
nullptr
};
uint8_t
*
writeBuffer
{
nullptr
};
};
};
}
// namespace Channel
}
// namespace Channel
...
...
worker/include/Logger.hpp
浏览文件 @
f0ebd809
...
@@ -132,7 +132,7 @@ public:
...
@@ -132,7 +132,7 @@ public:
static
void
ClassInit
(
Channel
::
ChannelSocket
*
channel
);
static
void
ClassInit
(
Channel
::
ChannelSocket
*
channel
);
public
:
public
:
static
const
int64_t
pid
;
static
const
u
int64_t
pid
;
thread_local
static
Channel
::
ChannelSocket
*
channel
;
thread_local
static
Channel
::
ChannelSocket
*
channel
;
static
const
size_t
bufferSize
{
50000
};
static
const
size_t
bufferSize
{
50000
};
thread_local
static
char
buffer
[];
thread_local
static
char
buffer
[];
...
...
worker/include/PayloadChannel/PayloadChannelSocket.hpp
浏览文件 @
f0ebd809
...
@@ -71,16 +71,24 @@ namespace PayloadChannel
...
@@ -71,16 +71,24 @@ namespace PayloadChannel
public
:
public
:
explicit
PayloadChannelSocket
(
int
consumerFd
,
int
producerFd
);
explicit
PayloadChannelSocket
(
int
consumerFd
,
int
producerFd
);
explicit
PayloadChannelSocket
(
PayloadChannelReadFn
payloadChannelReadFn
,
PayloadChannelReadCtx
payloadChannelReadCtx
,
PayloadChannelWriteFn
payloadChannelWriteFn
,
PayloadChannelWriteCtx
payloadChannelWriteCtx
);
virtual
~
PayloadChannelSocket
();
virtual
~
PayloadChannelSocket
();
public
:
public
:
void
Close
();
void
Close
();
void
SetListener
(
Listener
*
listener
);
void
SetListener
(
Listener
*
listener
);
bool
CallbackRead
();
void
Send
(
json
&
jsonMessage
,
const
uint8_t
*
payload
,
size_t
payloadLen
);
void
Send
(
json
&
jsonMessage
,
const
uint8_t
*
payload
,
size_t
payloadLen
);
void
Send
(
json
&
jsonMessage
);
void
Send
(
json
&
jsonMessage
);
private
:
private
:
void
SendImpl
(
const
void
*
payload
,
uint32_t
payloadLen
);
void
SendImpl
(
const
uint8_t
*
message
,
uint32_t
messageLen
);
void
SendImpl
(
const
uint8_t
*
message
,
uint32_t
messageLen
,
const
uint8_t
*
payload
,
uint32_t
payloadLen
);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */
/* Pure virtual methods inherited from ConsumerSocket::Listener. */
public
:
public
:
...
@@ -92,11 +100,16 @@ namespace PayloadChannel
...
@@ -92,11 +100,16 @@ namespace PayloadChannel
Listener
*
listener
{
nullptr
};
Listener
*
listener
{
nullptr
};
// Others.
// Others.
bool
closed
{
false
};
bool
closed
{
false
};
ConsumerSocket
consumerSocket
;
ConsumerSocket
*
consumerSocket
{
nullptr
};
ProducerSocket
producerSocket
;
ProducerSocket
*
producerSocket
{
nullptr
};
PayloadChannelReadFn
payloadChannelReadFn
{
nullptr
};
PayloadChannelReadCtx
payloadChannelReadCtx
{
nullptr
};
PayloadChannelWriteFn
payloadChannelWriteFn
{
nullptr
};
PayloadChannelWriteCtx
payloadChannelWriteCtx
{
nullptr
};
PayloadChannel
::
Notification
*
ongoingNotification
{
nullptr
};
PayloadChannel
::
Notification
*
ongoingNotification
{
nullptr
};
PayloadChannel
::
PayloadChannelRequest
*
ongoingRequest
{
nullptr
};
PayloadChannel
::
PayloadChannelRequest
*
ongoingRequest
{
nullptr
};
uint8_t
*
writeBuffer
;
uv_async_t
*
uvReadHandle
{
nullptr
};
uint8_t
*
writeBuffer
{
nullptr
};
};
};
}
// namespace PayloadChannel
}
// namespace PayloadChannel
...
...
worker/include/common.hpp
浏览文件 @
f0ebd809
...
@@ -23,4 +23,43 @@ typedef SSIZE_T ssize_t;
...
@@ -23,4 +23,43 @@ typedef SSIZE_T ssize_t;
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#endif
#endif
using
ChannelReadCtx
=
void
*
;
using
ChannelReadFreeFn
=
void
(
*
)(
uint8_t
*
,
uint32_t
,
size_t
);
// Returns `ChannelReadFree` on successful read that must be used to free `message`.
using
ChannelReadFn
=
ChannelReadFreeFn
(
*
)(
uint8_t
**
/* message */
,
uint32_t
*
/* messageLen */
,
size_t
*
/* messageCtx */
,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read.
const
void
*
/* handle */
,
ChannelReadCtx
/* ctx */
);
using
ChannelWriteCtx
=
void
*
;
using
ChannelWriteFn
=
void
(
*
)(
const
uint8_t
*
/* message */
,
uint32_t
/* messageLen */
,
ChannelWriteCtx
/* ctx */
);
using
PayloadChannelReadCtx
=
void
*
;
using
PayloadChannelReadFreeFn
=
void
(
*
)(
uint8_t
*
,
uint32_t
,
size_t
);
// Returns `PayloadChannelReadFree` on successful read that must be used to free `message` and `payload`.
using
PayloadChannelReadFn
=
PayloadChannelReadFreeFn
(
*
)(
uint8_t
**
/* message */
,
uint32_t
*
/* messageLen */
,
size_t
*
/* messageCtx */
,
uint8_t
**
/* payload */
,
uint32_t
*
/* payloadLen */
,
size_t
*
/* payloadCapacity */
,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read.
const
void
*
/* handle */
,
PayloadChannelReadCtx
/* ctx */
);
using
PayloadChannelWriteCtx
=
void
*
;
using
PayloadChannelWriteFn
=
void
(
*
)(
const
uint8_t
*
/* message */
,
uint32_t
/* messageLen */
,
const
uint8_t
*
/* payload */
,
uint32_t
/* payloadLen */
,
ChannelWriteCtx
/* ctx */
);
#endif
#endif
worker/include/lib.hpp
浏览文件 @
f0ebd809
extern
"C"
int
run_worker
(
#include "common.hpp"
extern
"C"
int
mediasoup_worker_run
(
int
argc
,
int
argc
,
char
*
argv
[],
char
*
argv
[],
const
char
*
version
,
const
char
*
version
,
int
consumerChannelFd
,
int
consumerChannelFd
,
int
producerChannelFd
,
int
producerChannelFd
,
int
payloadConsumeChannelFd
,
int
payloadConsumeChannelFd
,
int
payloadProduceChannelFd
);
int
payloadProduceChannelFd
,
ChannelReadFn
channelReadFn
,
ChannelReadCtx
channelReadCtx
,
ChannelWriteFn
channelWriteFn
,
ChannelWriteCtx
channelWriteCtx
,
PayloadChannelReadFn
payloadChannelReadFn
,
PayloadChannelReadCtx
payloadChannelReadCtx
,
PayloadChannelWriteFn
payloadChannelWriteFn
,
PayloadChannelWriteCtx
payloadChannelWriteCtx
);
worker/src/Channel/ChannelNotifier.cpp
浏览文件 @
f0ebd809
...
@@ -19,6 +19,20 @@ namespace Channel
...
@@ -19,6 +19,20 @@ namespace Channel
ChannelNotifier
::
channel
=
channel
;
ChannelNotifier
::
channel
=
channel
;
}
}
void
ChannelNotifier
::
Emit
(
uint64_t
targetId
,
const
char
*
event
)
{
MS_TRACE
();
MS_ASSERT
(
ChannelNotifier
::
channel
,
"channel unset"
);
json
jsonNotification
=
json
::
object
();
jsonNotification
[
"targetId"
]
=
targetId
;
jsonNotification
[
"event"
]
=
event
;
ChannelNotifier
::
channel
->
Send
(
jsonNotification
);
}
void
ChannelNotifier
::
Emit
(
const
std
::
string
&
targetId
,
const
char
*
event
)
void
ChannelNotifier
::
Emit
(
const
std
::
string
&
targetId
,
const
char
*
event
)
{
{
MS_TRACE
();
MS_TRACE
();
...
...
worker/src/Channel/ChannelSocket.cpp
浏览文件 @
f0ebd809
...
@@ -2,6 +2,7 @@
...
@@ -2,6 +2,7 @@
// #define MS_LOG_DEV_LEVEL 3
// #define MS_LOG_DEV_LEVEL 3
#include "Channel/ChannelSocket.hpp"
#include "Channel/ChannelSocket.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "MediaSoupErrors.hpp"
#include <cmath> // std::ceil()
#include <cmath> // std::ceil()
...
@@ -10,7 +11,19 @@
...
@@ -10,7 +11,19 @@
namespace
Channel
namespace
Channel
{
{
/* Static. */
/* Static methods for UV callbacks. */
inline
static
void
onAsync
(
uv_handle_t
*
handle
)
{
while
(
static_cast
<
ChannelSocket
*>
(
handle
->
data
)
->
CallbackRead
())
{
// Read while there are new messages.
}
}
inline
static
void
onClose
(
uv_handle_t
*
handle
)
{
delete
handle
;
}
// Binary length for a 4194304 bytes payload.
// Binary length for a 4194304 bytes payload.
static
constexpr
size_t
MessageMaxLen
{
4194308
};
static
constexpr
size_t
MessageMaxLen
{
4194308
};
...
@@ -18,11 +31,48 @@ namespace Channel
...
@@ -18,11 +31,48 @@ namespace Channel
/* Instance methods. */
/* Instance methods. */
ChannelSocket
::
ChannelSocket
(
int
consumerFd
,
int
producerFd
)
ChannelSocket
::
ChannelSocket
(
int
consumerFd
,
int
producerFd
)
:
consumerSocket
(
consumerFd
,
MessageMaxLen
,
this
),
producerSocket
(
producerFd
,
MessageMaxLen
)
:
consumerSocket
(
new
ConsumerSocket
(
consumerFd
,
MessageMaxLen
,
this
)),
producerSocket
(
new
ProducerSocket
(
producerFd
,
MessageMaxLen
)),
writeBuffer
(
static_cast
<
uint8_t
*>
(
std
::
malloc
(
MessageMaxLen
)))
{
MS_TRACE_STD
();
}
ChannelSocket
::
ChannelSocket
(
ChannelReadFn
channelReadFn
,
ChannelReadCtx
channelReadCtx
,
ChannelWriteFn
channelWriteFn
,
ChannelWriteCtx
channelWriteCtx
)
:
channelReadFn
(
channelReadFn
),
channelReadCtx
(
channelReadCtx
),
channelWriteFn
(
channelWriteFn
),
channelWriteCtx
(
channelWriteCtx
)
{
{
MS_TRACE_STD
();
MS_TRACE_STD
();
this
->
writeBuffer
=
static_cast
<
uint8_t
*>
(
std
::
malloc
(
MessageMaxLen
));
int
err
;
this
->
uvReadHandle
=
new
uv_async_t
;
this
->
uvReadHandle
->
data
=
static_cast
<
void
*>
(
this
);
err
=
uv_async_init
(
DepLibUV
::
GetLoop
(),
this
->
uvReadHandle
,
reinterpret_cast
<
uv_async_cb
>
(
onAsync
));
if
(
err
!=
0
)
{
delete
this
->
uvReadHandle
;
this
->
uvReadHandle
=
nullptr
;
MS_THROW_ERROR_STD
(
"uv_async_init() failed: %s"
,
uv_strerror
(
err
));
}
err
=
uv_async_send
(
this
->
uvReadHandle
);
if
(
err
!=
0
)
{
delete
this
->
uvReadHandle
;
this
->
uvReadHandle
=
nullptr
;
MS_THROW_ERROR_STD
(
"uv_async_send() failed: %s"
,
uv_strerror
(
err
));
}
}
}
ChannelSocket
::~
ChannelSocket
()
ChannelSocket
::~
ChannelSocket
()
...
@@ -33,6 +83,9 @@ namespace Channel
...
@@ -33,6 +83,9 @@ namespace Channel
if
(
!
this
->
closed
)
if
(
!
this
->
closed
)
Close
();
Close
();
delete
this
->
consumerSocket
;
delete
this
->
producerSocket
;
}
}
void
ChannelSocket
::
Close
()
void
ChannelSocket
::
Close
()
...
@@ -44,8 +97,20 @@ namespace Channel
...
@@ -44,8 +97,20 @@ namespace Channel
this
->
closed
=
true
;
this
->
closed
=
true
;
this
->
consumerSocket
.
Close
();
if
(
this
->
uvReadHandle
)
this
->
producerSocket
.
Close
();
{
uv_close
(
reinterpret_cast
<
uv_handle_t
*>
(
this
->
uvReadHandle
),
static_cast
<
uv_close_cb
>
(
onClose
));
}
if
(
this
->
consumerSocket
)
{
this
->
consumerSocket
->
Close
();
}
if
(
this
->
producerSocket
)
{
this
->
producerSocket
->
Close
();
}
}
}
void
ChannelSocket
::
SetListener
(
Listener
*
listener
)
void
ChannelSocket
::
SetListener
(
Listener
*
listener
)
...
@@ -71,10 +136,11 @@ namespace Channel
...
@@ -71,10 +136,11 @@ namespace Channel
return
;
return
;
}
}
SendImpl
(
message
.
c_str
(),
static_cast
<
uint32_t
>
(
message
.
length
()));
SendImpl
(
reinterpret_cast
<
const
uint8_t
*>
(
message
.
c_str
()),
static_cast
<
uint32_t
>
(
message
.
length
()));
}
}
void
ChannelSocket
::
SendLog
(
char
*
message
,
uint32_t
messageLen
)
void
ChannelSocket
::
SendLog
(
c
onst
c
har
*
message
,
uint32_t
messageLen
)
{
{
MS_TRACE_STD
();
MS_TRACE_STD
();
...
@@ -88,13 +154,73 @@ namespace Channel
...
@@ -88,13 +154,73 @@ namespace Channel
return
;
return
;
}
}
SendImpl
(
message
,
messageLen
);
SendImpl
(
reinterpret_cast
<
const
uint8_t
*>
(
message
)
,
messageLen
);
}
}
inline
void
ChannelSocket
::
SendImpl
(
const
void
*
payload
,
uint32_t
payloadLen
)
bool
ChannelSocket
::
CallbackRead
(
)
{
{
MS_TRACE_STD
();
MS_TRACE_STD
();
if
(
this
->
closed
)
return
false
;
uint8_t
*
message
{
nullptr
};
uint32_t
messageLen
;
size_t
messageCtx
;
auto
free
=
this
->
channelReadFn
(
&
message
,
&
messageLen
,
&
messageCtx
,
this
->
uvReadHandle
,
this
->
channelReadCtx
);
if
(
free
)
{
try
{
json
jsonMessage
=
json
::
parse
(
message
,
message
+
static_cast
<
size_t
>
(
messageLen
));
auto
*
request
=
new
Channel
::
ChannelRequest
(
this
,
jsonMessage
);
// Notify the listener.
try
{
this
->
listener
->
OnChannelRequest
(
this
,
request
);
}
catch
(
const
MediaSoupTypeError
&
error
)
{
request
->
TypeError
(
error
.
what
());
}
catch
(
const
MediaSoupError
&
error
)
{
request
->
Error
(
error
.
what
());
}
// Delete the Request.
delete
request
;
}
catch
(
const
json
::
parse_error
&
error
)
{
MS_ERROR_STD
(
"JSON parsing error: %s"
,
error
.
what
());
}
catch
(
const
MediaSoupError
&
error
)
{
MS_ERROR_STD
(
"discarding wrong Channel request"
);
}
free
(
message
,
messageLen
,
messageCtx
);
}
return
free
!=
nullptr
;
}
inline
void
ChannelSocket
::
SendImpl
(
const
uint8_t
*
payload
,
uint32_t
payloadLen
)
{
MS_TRACE_STD
();
// Write using function call if provided.
if
(
this
->
channelWriteFn
)
{
this
->
channelWriteFn
(
payload
,
payloadLen
,
this
->
channelWriteCtx
);
}
else
{
std
::
memcpy
(
this
->
writeBuffer
,
&
payloadLen
,
sizeof
(
uint32_t
));
std
::
memcpy
(
this
->
writeBuffer
,
&
payloadLen
,
sizeof
(
uint32_t
));
if
(
payloadLen
!=
0
)
if
(
payloadLen
!=
0
)
...
@@ -104,7 +230,8 @@ namespace Channel
...
@@ -104,7 +230,8 @@ namespace Channel
size_t
len
=
sizeof
(
uint32_t
)
+
payloadLen
;
size_t
len
=
sizeof
(
uint32_t
)
+
payloadLen
;
this
->
producerSocket
.
Write
(
this
->
writeBuffer
,
len
);
this
->
producerSocket
->
Write
(
this
->
writeBuffer
,
len
);
}
}
}
void
ChannelSocket
::
OnConsumerSocketMessage
(
ConsumerSocket
*
/*consumerSocket*/
,
char
*
msg
,
size_t
msgLen
)
void
ChannelSocket
::
OnConsumerSocketMessage
(
ConsumerSocket
*
/*consumerSocket*/
,
char
*
msg
,
size_t
msgLen
)
...
...
worker/src/Logger.cpp
浏览文件 @
f0ebd809
...
@@ -6,7 +6,7 @@
...
@@ -6,7 +6,7 @@
/* Class variables. */
/* Class variables. */
const
int64_t
Logger
::
pid
{
static_cast
<
int64_t
>
(
uv_os_getpid
())
};
const
uint64_t
Logger
::
pid
{
static_cast
<
u
int64_t
>
(
uv_os_getpid
())
};
thread_local
Channel
::
ChannelSocket
*
Logger
::
channel
{
nullptr
};
thread_local
Channel
::
ChannelSocket
*
Logger
::
channel
{
nullptr
};
thread_local
char
Logger
::
buffer
[
Logger
::
bufferSize
];
thread_local
char
Logger
::
buffer
[
Logger
::
bufferSize
];
...
...
worker/src/PayloadChannel/PayloadChannelSocket.cpp
浏览文件 @
f0ebd809
...
@@ -2,6 +2,7 @@
...
@@ -2,6 +2,7 @@
// #define MS_LOG_DEV_LEVEL 3
// #define MS_LOG_DEV_LEVEL 3
#include "PayloadChannel/PayloadChannelSocket.hpp"
#include "PayloadChannel/PayloadChannelSocket.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "MediaSoupErrors.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
...
@@ -12,6 +13,18 @@
...
@@ -12,6 +13,18 @@
namespace
PayloadChannel
namespace
PayloadChannel
{
{
/* Static. */
/* Static. */
inline
static
void
onAsync
(
uv_handle_t
*
handle
)
{
while
(
static_cast
<
PayloadChannelSocket
*>
(
handle
->
data
)
->
CallbackRead
())
{
// Read while there are new messages.
}
}
inline
static
void
onClose
(
uv_handle_t
*
handle
)
{
delete
handle
;
}
// Binary length for a 4194304 bytes payload.
// Binary length for a 4194304 bytes payload.
static
constexpr
size_t
MessageMaxLen
{
4194308
};
static
constexpr
size_t
MessageMaxLen
{
4194308
};
...
@@ -19,11 +32,48 @@ namespace PayloadChannel
...
@@ -19,11 +32,48 @@ namespace PayloadChannel
/* Instance methods. */
/* Instance methods. */
PayloadChannelSocket
::
PayloadChannelSocket
(
int
consumerFd
,
int
producerFd
)
PayloadChannelSocket
::
PayloadChannelSocket
(
int
consumerFd
,
int
producerFd
)
:
consumerSocket
(
consumerFd
,
MessageMaxLen
,
this
),
producerSocket
(
producerFd
,
MessageMaxLen
)
:
consumerSocket
(
new
ConsumerSocket
(
consumerFd
,
MessageMaxLen
,
this
)),
producerSocket
(
new
ProducerSocket
(
producerFd
,
MessageMaxLen
)),
writeBuffer
(
static_cast
<
uint8_t
*>
(
std
::
malloc
(
MessageMaxLen
)))
{
MS_TRACE
();
}
PayloadChannelSocket
::
PayloadChannelSocket
(
PayloadChannelReadFn
payloadChannelReadFn
,
PayloadChannelReadCtx
payloadChannelReadCtx
,
PayloadChannelWriteFn
payloadChannelWriteFn
,
PayloadChannelWriteCtx
payloadChannelWriteCtx
)
:
payloadChannelReadFn
(
payloadChannelReadFn
),
payloadChannelReadCtx
(
payloadChannelReadCtx
),
payloadChannelWriteFn
(
payloadChannelWriteFn
),
payloadChannelWriteCtx
(
payloadChannelWriteCtx
)
{
{
MS_TRACE
();
MS_TRACE
();
this
->
writeBuffer
=
(
uint8_t
*
)
std
::
malloc
(
MessageMaxLen
);
int
err
;
this
->
uvReadHandle
=
new
uv_async_t
;
this
->
uvReadHandle
->
data
=
static_cast
<
void
*>
(
this
);
err
=
uv_async_init
(
DepLibUV
::
GetLoop
(),
this
->
uvReadHandle
,
reinterpret_cast
<
uv_async_cb
>
(
onAsync
));
if
(
err
!=
0
)
{
delete
this
->
uvReadHandle
;
this
->
uvReadHandle
=
nullptr
;
MS_THROW_ERROR
(
"uv_async_init() failed: %s"
,
uv_strerror
(
err
));
}
err
=
uv_async_send
(
this
->
uvReadHandle
);
if
(
err
!=
0
)
{
delete
this
->
uvReadHandle
;
this
->
uvReadHandle
=
nullptr
;
MS_THROW_ERROR
(
"uv_async_send() failed: %s"
,
uv_strerror
(
err
));
}
}
}
PayloadChannelSocket
::~
PayloadChannelSocket
()
PayloadChannelSocket
::~
PayloadChannelSocket
()
...
@@ -35,6 +85,9 @@ namespace PayloadChannel
...
@@ -35,6 +85,9 @@ namespace PayloadChannel
if
(
!
this
->
closed
)
if
(
!
this
->
closed
)
Close
();
Close
();
delete
this
->
consumerSocket
;
delete
this
->
producerSocket
;
}
}
void
PayloadChannelSocket
::
Close
()
void
PayloadChannelSocket
::
Close
()
...
@@ -46,8 +99,20 @@ namespace PayloadChannel
...
@@ -46,8 +99,20 @@ namespace PayloadChannel
this
->
closed
=
true
;
this
->
closed
=
true
;
this
->
consumerSocket
.
Close
();
if
(
this
->
uvReadHandle
)
this
->
producerSocket
.
Close
();
{
uv_close
(
reinterpret_cast
<
uv_handle_t
*>
(
this
->
uvReadHandle
),
static_cast
<
uv_close_cb
>
(
onClose
));
}
if
(
this
->
consumerSocket
)
{
this
->
consumerSocket
->
Close
();
}
if
(
this
->
producerSocket
)
{
this
->
producerSocket
->
Close
();
}
}
}
void
PayloadChannelSocket
::
SetListener
(
Listener
*
listener
)
void
PayloadChannelSocket
::
SetListener
(
Listener
*
listener
)
...
@@ -79,8 +144,11 @@ namespace PayloadChannel
...
@@ -79,8 +144,11 @@ namespace PayloadChannel
return
;
return
;
}
}
SendImpl
(
message
.
c_str
(),
static_cast
<
uint32_t
>
(
message
.
length
()));
SendImpl
(
SendImpl
(
payload
,
static_cast
<
uint32_t
>
(
payloadLen
));
reinterpret_cast
<
const
uint8_t
*>
(
message
.
c_str
()),
static_cast
<
uint32_t
>
(
message
.
length
()),
payload
,
static_cast
<
uint32_t
>
(
payloadLen
));
}
}
void
PayloadChannelSocket
::
Send
(
json
&
jsonMessage
)
void
PayloadChannelSocket
::
Send
(
json
&
jsonMessage
)
...
@@ -99,23 +167,166 @@ namespace PayloadChannel
...
@@ -99,23 +167,166 @@ namespace PayloadChannel
return
;
return
;
}
}
SendImpl
(
message
.
c_str
(),
static_cast
<
uint32_t
>
(
message
.
length
()));
SendImpl
(
reinterpret_cast
<
const
uint8_t
*>
(
message
.
c_str
()),
static_cast
<
uint32_t
>
(
message
.
length
()));
}
bool
PayloadChannelSocket
::
CallbackRead
()
{
MS_TRACE
();
if
(
this
->
closed
)
return
false
;
uint8_t
*
message
{
nullptr
};
uint32_t
messageLen
;
size_t
messageCtx
;
uint8_t
*
payload
{
nullptr
};
uint32_t
payloadLen
;
size_t
payloadCapacity
;
auto
free
=
this
->
payloadChannelReadFn
(
&
message
,
&
messageLen
,
&
messageCtx
,
&
payload
,
&
payloadLen
,
&
payloadCapacity
,
this
->
uvReadHandle
,
this
->
payloadChannelReadCtx
);
if
(
free
)
{
try
{
json
jsonData
=
json
::
parse
(
message
,
message
+
static_cast
<
size_t
>
(
messageLen
));
if
(
PayloadChannelRequest
::
IsRequest
(
jsonData
))
{
try
{
auto
*
request
=
new
PayloadChannel
::
PayloadChannelRequest
(
this
,
jsonData
);
request
->
SetPayload
(
payload
,
payloadLen
);
// Notify the listener.
try
{
this
->
listener
->
OnPayloadChannelRequest
(
this
,
request
);
}
catch
(
const
MediaSoupTypeError
&
error
)
{
request
->
TypeError
(
error
.
what
());
}
catch
(
const
MediaSoupError
&
error
)
{
request
->
Error
(
error
.
what
());
}
// Delete the Request.
delete
request
;
}
catch
(
const
json
::
parse_error
&
error
)
{
MS_ERROR_STD
(
"JSON parsing error: %s"
,
error
.
what
());
}
catch
(
const
MediaSoupError
&
error
)
{
MS_ERROR
(
"discarding wrong Payload Channel notification"
);
}
}
else
if
(
Notification
::
IsNotification
(
jsonData
))
{
try
{
auto
*
notification
=
new
PayloadChannel
::
Notification
(
jsonData
);
notification
->
SetPayload
(
payload
,
payloadLen
);
// Notify the listener.
try
{
this
->
listener
->
OnPayloadChannelNotification
(
this
,
notification
);
}
catch
(
const
MediaSoupError
&
error
)
{
MS_ERROR
(
"notification failed: %s"
,
error
.
what
());
}
// Delete the Notification.
delete
notification
;
}
catch
(
const
json
::
parse_error
&
error
)
{
MS_ERROR_STD
(
"JSON parsing error: %s"
,
error
.
what
());
}
catch
(
const
MediaSoupError
&
error
)
{
MS_ERROR
(
"discarding wrong Payload Channel notification"
);
}
}
else
{
MS_ERROR
(
"discarding wrong Payload Channel data"
);
}
}
catch
(
const
json
::
parse_error
&
error
)
{
MS_ERROR
(
"JSON parsing error: %s"
,
error
.
what
());
}
catch
(
const
MediaSoupError
&
error
)
{
MS_ERROR
(
"discarding wrong Channel request"
);
}
free
(
message
,
messageLen
,
messageCtx
);
free
(
payload
,
payloadLen
,
payloadCapacity
);
}
return
free
!=
nullptr
;
}
}
inline
void
PayloadChannelSocket
::
SendImpl
(
const
void
*
payload
,
uint32_t
payload
Len
)
inline
void
PayloadChannelSocket
::
SendImpl
(
const
uint8_t
*
message
,
uint32_t
message
Len
)
{
{
MS_TRACE
();
MS_TRACE
();
std
::
memcpy
(
this
->
writeBuffer
,
&
payloadLen
,
sizeof
(
uint32_t
));
// Write using function call if provided.
if
(
this
->
payloadChannelWriteFn
)
{
this
->
payloadChannelWriteFn
(
message
,
messageLen
,
nullptr
,
0
,
this
->
payloadChannelWriteCtx
);
}
else
{
std
::
memcpy
(
this
->
writeBuffer
,
&
messageLen
,
sizeof
(
uint32_t
));
if
(
payload
Len
!=
0
)
if
(
message
Len
!=
0
)
{
{
std
::
memcpy
(
this
->
writeBuffer
+
sizeof
(
uint32_t
),
payload
,
payloadLen
);
std
::
memcpy
(
this
->
writeBuffer
+
sizeof
(
uint32_t
),
message
,
messageLen
);
}
size_t
len
=
sizeof
(
uint32_t
)
+
messageLen
;
this
->
producerSocket
->
Write
(
this
->
writeBuffer
,
len
);
}
}
}
size_t
len
=
sizeof
(
uint32_t
)
+
payloadLen
;
inline
void
PayloadChannelSocket
::
SendImpl
(
const
uint8_t
*
message
,
uint32_t
messageLen
,
const
uint8_t
*
payload
,
uint32_t
payloadLen
)
{
MS_TRACE
();
this
->
producerSocket
.
Write
(
this
->
writeBuffer
,
len
);
// Write using function call if provided.
if
(
this
->
payloadChannelWriteFn
)
{
this
->
payloadChannelWriteFn
(
message
,
messageLen
,
payload
,
payloadLen
,
this
->
payloadChannelWriteCtx
);
}
else
{
SendImpl
(
message
,
messageLen
);
SendImpl
(
payload
,
payloadLen
);
}
}
}
void
PayloadChannelSocket
::
OnConsumerSocketMessage
(
void
PayloadChannelSocket
::
OnConsumerSocketMessage
(
...
@@ -130,8 +341,7 @@ namespace PayloadChannel
...
@@ -130,8 +341,7 @@ namespace PayloadChannel
{
{
try
try
{
{
json
jsonMessage
=
json
::
parse
(
msg
,
msg
+
msgLen
);
this
->
ongoingRequest
=
new
PayloadChannel
::
PayloadChannelRequest
(
this
,
jsonData
);
this
->
ongoingRequest
=
new
PayloadChannel
::
PayloadChannelRequest
(
this
,
jsonMessage
);
}
}
catch
(
const
json
::
parse_error
&
error
)
catch
(
const
json
::
parse_error
&
error
)
{
{
...
@@ -147,8 +357,7 @@ namespace PayloadChannel
...
@@ -147,8 +357,7 @@ namespace PayloadChannel
{
{
try
try
{
{
json
jsonMessage
=
json
::
parse
(
msg
,
msg
+
msgLen
);
this
->
ongoingNotification
=
new
PayloadChannel
::
Notification
(
jsonData
);
this
->
ongoingNotification
=
new
PayloadChannel
::
Notification
(
jsonMessage
);
}
}
catch
(
const
json
::
parse_error
&
error
)
catch
(
const
json
::
parse_error
&
error
)
{
{
...
...
worker/src/Worker.cpp
浏览文件 @
f0ebd809
...
@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel
...
@@ -37,7 +37,7 @@ Worker::Worker(::Channel::ChannelSocket* channel, PayloadChannel::PayloadChannel
DepUsrSCTP
::
CreateChecker
();
DepUsrSCTP
::
CreateChecker
();
// Tell the Node process that we are running.
// Tell the Node process that we are running.
Channel
::
ChannelNotifier
::
Emit
(
std
::
to_string
(
Logger
::
pid
)
,
"running"
);
Channel
::
ChannelNotifier
::
Emit
(
Logger
::
pid
,
"running"
);
MS_DEBUG_DEV
(
"starting libuv loop"
);
MS_DEBUG_DEV
(
"starting libuv loop"
);
DepLibUV
::
RunLoop
();
DepLibUV
::
RunLoop
();
...
...
worker/src/lib.cpp
浏览文件 @
f0ebd809
...
@@ -28,14 +28,22 @@
...
@@ -28,14 +28,22 @@
void
IgnoreSignals
();
void
IgnoreSignals
();
extern
"C"
int
run_worker
(
extern
"C"
int
mediasoup_worker_run
(
int
argc
,
int
argc
,
char
*
argv
[],
char
*
argv
[],
const
char
*
version
,
const
char
*
version
,
int
consumerChannelFd
,
int
consumerChannelFd
,
int
producerChannelFd
,
int
producerChannelFd
,
int
payloadConsumeChannelFd
,
int
payloadConsumeChannelFd
,
int
payloadProduceChannelFd
)
int
payloadProduceChannelFd
,
ChannelReadFn
channelReadFn
,
ChannelReadCtx
channelReadCtx
,
ChannelWriteFn
channelWriteFn
,
ChannelWriteCtx
channelWriteCtx
,
PayloadChannelReadFn
payloadChannelReadFn
,
PayloadChannelReadCtx
payloadChannelReadCtx
,
PayloadChannelWriteFn
payloadChannelWriteFn
,
PayloadChannelWriteCtx
payloadChannelWriteCtx
)
{
{
// Initialize libuv stuff (we need it for the Channel).
// Initialize libuv stuff (we need it for the Channel).
DepLibUV
::
ClassInit
();
DepLibUV
::
ClassInit
();
...
@@ -51,9 +59,17 @@ extern "C" int run_worker(
...
@@ -51,9 +59,17 @@ extern "C" int run_worker(
std
::
unique_ptr
<
PayloadChannel
::
PayloadChannelSocket
>
payloadChannel
{
nullptr
};
std
::
unique_ptr
<
PayloadChannel
::
PayloadChannelSocket
>
payloadChannel
{
nullptr
};
try
try
{
if
(
channelReadFn
)
{
channel
.
reset
(
new
Channel
::
ChannelSocket
(
channelReadFn
,
channelReadCtx
,
channelWriteFn
,
channelWriteCtx
));
}
else
{
{
channel
.
reset
(
new
Channel
::
ChannelSocket
(
consumerChannelFd
,
producerChannelFd
));
channel
.
reset
(
new
Channel
::
ChannelSocket
(
consumerChannelFd
,
producerChannelFd
));
}
}
}
catch
(
const
MediaSoupError
&
error
)
catch
(
const
MediaSoupError
&
error
)
{
{
MS_ERROR_STD
(
"error creating the Channel: %s"
,
error
.
what
());
MS_ERROR_STD
(
"error creating the Channel: %s"
,
error
.
what
());
...
@@ -65,10 +81,18 @@ extern "C" int run_worker(
...
@@ -65,10 +81,18 @@ extern "C" int run_worker(
}
}
try
try
{
if
(
payloadChannelReadFn
)
{
payloadChannel
.
reset
(
new
PayloadChannel
::
PayloadChannelSocket
(
payloadChannelReadFn
,
payloadChannelReadCtx
,
payloadChannelWriteFn
,
payloadChannelWriteCtx
));
}
else
{
{
payloadChannel
.
reset
(
payloadChannel
.
reset
(
new
PayloadChannel
::
PayloadChannelSocket
(
payloadConsumeChannelFd
,
payloadProduceChannelFd
));
new
PayloadChannel
::
PayloadChannelSocket
(
payloadConsumeChannelFd
,
payloadProduceChannelFd
));
}
}
}
catch
(
const
MediaSoupError
&
error
)
catch
(
const
MediaSoupError
&
error
)
{
{
MS_ERROR_STD
(
"error creating the RTC Channel: %s"
,
error
.
what
());
MS_ERROR_STD
(
"error creating the RTC Channel: %s"
,
error
.
what
());
...
...
worker/src/lib.rs
浏览文件 @
f0ebd809
use
std
::
os
::
raw
::{
c_char
,
c_int
};
use
std
::
os
::
raw
::{
c_char
,
c_int
,
c_void
};
#[repr(transparent)]
#[derive(Copy,
Clone)]
pub
struct
UvAsyncT
(
pub
*
const
c_void
);
unsafe
impl
Send
for
UvAsyncT
{}
#[repr(transparent)]
pub
struct
ChannelReadCtx
(
pub
*
const
c_void
);
pub
type
ChannelReadFreeFn
=
Option
<
unsafe
extern
"C"
fn
(
/* message: */
*
mut
u8
,
/* message_len: */
u32
,
/* message_ctx: */
usize
,
),
>
;
pub
type
ChannelReadFn
=
unsafe
extern
"C"
fn
(
/* message: */
*
mut
*
mut
u8
,
/* message_len: */
*
mut
u32
,
/* message_ctx: */
*
mut
usize
,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is
// more data to read
/* handle */
UvAsyncT
,
/* ctx: */
ChannelReadCtx
,
)
->
ChannelReadFreeFn
;
#[repr(transparent)]
pub
struct
ChannelWriteCtx
(
pub
*
const
c_void
);
pub
type
ChannelWriteFn
=
unsafe
extern
"C"
fn
(
/* message: */
*
const
u8
,
/* message_len: */
u32
,
/* ctx: */
ChannelWriteCtx
,
);
#[repr(transparent)]
pub
struct
PayloadChannelReadCtx
(
pub
*
const
c_void
);
pub
type
PayloadChannelReadFreeFn
=
Option
<
unsafe
extern
"C"
fn
(
/* message: */
*
mut
u8
,
/* message_len: */
u32
,
/* message_ctx: */
usize
,
),
>
;
pub
type
PayloadChannelReadFn
=
unsafe
extern
"C"
fn
(
/* message: */
*
mut
*
mut
u8
,
/* message_len: */
*
mut
u32
,
/* message_ctx: */
*
mut
usize
,
/* payload: */
*
mut
*
mut
u8
,
/* payload_len: */
*
mut
u32
,
/* payload_capacity: */
*
mut
usize
,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is
// more data to read
/* handle */
UvAsyncT
,
/* ctx: */
PayloadChannelReadCtx
,
)
->
PayloadChannelReadFreeFn
;
#[repr(transparent)]
pub
struct
PayloadChannelWriteCtx
(
pub
*
const
c_void
);
pub
type
PayloadChannelWriteFn
=
unsafe
extern
"C"
fn
(
/* message: */
*
const
u8
,
/* message_len: */
u32
,
/* payload: */
*
const
u8
,
/* payload_len: */
u32
,
/* ctx: */
PayloadChannelWriteCtx
,
);
#[link(name
=
"mediasoup-worker"
,
kind
=
"static"
)]
#[link(name
=
"mediasoup-worker"
,
kind
=
"static"
)]
extern
"C"
{
extern
"C"
{
pub
fn
run_worker
(
/// Returns `0` on success, or an error code `< 0` on failure
pub
fn
uv_async_send
(
handle
:
UvAsyncT
)
->
c_int
;
pub
fn
mediasoup_worker_run
(
argc
:
c_int
,
argc
:
c_int
,
argv
:
*
const
*
const
c_char
,
argv
:
*
const
*
const
c_char
,
version
:
*
const
c_char
,
version
:
*
const
c_char
,
...
@@ -10,5 +80,13 @@ extern "C" {
...
@@ -10,5 +80,13 @@ extern "C" {
producer_channel_fd
:
c_int
,
producer_channel_fd
:
c_int
,
payload_consumer_channel_fd
:
c_int
,
payload_consumer_channel_fd
:
c_int
,
payload_producer_channel_fd
:
c_int
,
payload_producer_channel_fd
:
c_int
,
channel_read_fn
:
ChannelReadFn
,
channel_read_ctx
:
ChannelReadCtx
,
channel_write_fn
:
ChannelWriteFn
,
channel_write_ctx
:
ChannelWriteCtx
,
payload_channel_read_fn
:
PayloadChannelReadFn
,
payload_channel_read_ctx
:
PayloadChannelReadCtx
,
payload_channel_write_fn
:
PayloadChannelWriteFn
,
payload_channel_write_ctx
:
PayloadChannelWriteCtx
,
)
->
c_int
;
)
->
c_int
;
}
}
worker/src/main.cpp
浏览文件 @
f0ebd809
...
@@ -23,14 +23,22 @@ int main(int argc, char* argv[])
...
@@ -23,14 +23,22 @@ int main(int argc, char* argv[])
std
::
string
version
=
std
::
getenv
(
"MEDIASOUP_VERSION"
);
std
::
string
version
=
std
::
getenv
(
"MEDIASOUP_VERSION"
);
auto
statusCode
=
run_worker
(
auto
statusCode
=
mediasoup_worker_run
(
argc
,
argc
,
argv
,
argv
,
version
.
c_str
(),
version
.
c_str
(),
ConsumerChannelFd
,
ConsumerChannelFd
,
ProducerChannelFd
,
ProducerChannelFd
,
PayloadConsumerChannelFd
,
PayloadConsumerChannelFd
,
PayloadProducerChannelFd
);
PayloadProducerChannelFd
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
,
nullptr
);
switch
(
statusCode
)
switch
(
statusCode
)
{
{
...
...
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论