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

Rust port of mediasoup! (#518)

上级 1a805366
name: mediasoup-rust
on: [push, pull_request]
env:
CARGO_TERM_COLOR: always
jobs:
ci:
runs-on: ubuntu-20.04
strategy:
matrix:
rust:
- stable
- nightly
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
override: true
components: rustfmt, clippy
- name: Configure cache
uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ matrix.rust }}-${{ hashFiles('**/Cargo.toml') }}
- name: cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
- name: cargo clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: -- -D warnings
- run: npm install
- name: cargo test
uses: actions-rs/cargo@v1
with:
command: test
args: --verbose
...@@ -37,3 +37,14 @@ ...@@ -37,3 +37,14 @@
# Vistual Studio Code stuff. # Vistual Studio Code stuff.
/.vscode/ /.vscode/
# JetBrains IDE stuff.
/.idea/
# Rust.
/target
/Cargo.lock
# Rust examples.
/rust/examples-frontend/*/node_modules
/rust/examples-frontend/*/package-lock.json
[workspace]
members = [
"rust"
]
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
[![][npm-shield-mediasoup]][npm-mediasoup] [![][npm-shield-mediasoup]][npm-mediasoup]
[![][github-actions-shield-mediasoup-node]][github-actions-mediasoup-node] [![][github-actions-shield-mediasoup-node]][github-actions-mediasoup-node]
[![][github-actions-shield-mediasoup-worker]][github-actions-mediasoup-worker] [![][github-actions-shield-mediasoup-worker]][github-actions-mediasoup-worker]
[![][github-actions-shield-mediasoup-rust]][github-actions-mediasoup-rust]
[![][codacy-grade-shield-mediasoup]][codacy-grade-mediasoup] [![][codacy-grade-shield-mediasoup]][codacy-grade-mediasoup]
[![][opencollective-shield-mediasoup]][opencollective-mediasoup] [![][opencollective-shield-mediasoup]][opencollective-mediasoup]
...@@ -95,6 +96,8 @@ You can support mediasoup by [sponsoring][sponsor] it. Thanks! ...@@ -95,6 +96,8 @@ You can support mediasoup by [sponsoring][sponsor] it. Thanks!
[github-actions-mediasoup-node]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-node.yaml [github-actions-mediasoup-node]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-node.yaml
[github-actions-shield-mediasoup-worker]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-worker.yaml/badge.svg [github-actions-shield-mediasoup-worker]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-worker.yaml/badge.svg
[github-actions-mediasoup-worker]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-worker.yaml [github-actions-mediasoup-worker]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-worker.yaml
[github-actions-shield-mediasoup-rust]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-rust.yaml/badge.svg
[github-actions-mediasoup-rust]: https://github.com/versatica/mediasoup/actions/workflows/mediasoup-rust.yaml
[codacy-grade-shield-mediasoup]: https://img.shields.io/codacy/grade/3c8b9efc83674b6189707ab4188cfb2b.svg [codacy-grade-shield-mediasoup]: https://img.shields.io/codacy/grade/3c8b9efc83674b6189707ab4188cfb2b.svg
[codacy-grade-mediasoup]: https://www.codacy.com/app/versatica/mediasoup [codacy-grade-mediasoup]: https://www.codacy.com/app/versatica/mediasoup
[opencollective-shield-mediasoup]: https://img.shields.io/opencollective/all/mediasoup.svg [opencollective-shield-mediasoup]: https://img.shields.io/opencollective/all/mediasoup.svg
......
[package]
name = "mediasoup"
version = "0.6.0"
description = "Cutting Edge WebRTC Video Conferencing in Rust"
categories = ["api-bindings", "multimedia", "network-programming"]
authors = ["Nazar Mokrynskyi <nazar@mokrynskyi.com>"]
edition = "2018"
license = "ISC"
keywords = ["webrtc", "ortc", "sfu"]
documentation = "https://docs.rs/mediasoup"
repository = "https://github.com/versatica/mediasoup/tree/v3/rust"
readme = "readme.md"
[dependencies]
async-channel = "1.5.1"
async-executor = "1.4.0"
async-fs = "1.5.0"
async-io = "1.3.1"
async-lock = "2.3.0"
async-oneshot = "0.4.2"
async-process = "1.0.1"
async-trait = "0.1.42"
bytes = "1.0.0"
event-listener-primitives = "0.2.2"
fastrand = "1.4.0"
futures-lite = "1.11.3"
h264-profile-level-id = "0.1.1"
log = "0.4.11"
libc = "0.2.82"
nix = "0.19.1"
once_cell = "1.5.2"
serde_json = "1.0.61"
serde_repr = "0.1.6"
thiserror = "1.0.23"
[dependencies.lru]
default-features = false
version = "0.6.5"
[dependencies.parking_lot]
version = "0.11.1"
features = ["serde"]
[dependencies.regex]
default-features = false
features = ["std", "perf"]
version = "1.4.2"
[dependencies.serde]
features = ["derive"]
version = "1.0.118"
[dependencies.uuid]
features = ["serde", "v4"]
version = "0.8.1"
[dev-dependencies]
actix = "0.10.0"
actix-web = "3.3.2"
actix-web-actors = "3.0.0"
env_logger = "0.8.2"
module.exports = {
env : {
browser : true,
es6 : true
},
parserOptions : {
project : 'tsconfig.json',
sourceType : 'module'
}
};
<!doctype html>
<style>
body {
margin: 0;
}
#container {
display: flex;
}
figure {
margin: 0;
width: 50vw;
}
video {
max-width: 100%;
}
</style>
<div id="container">
<figure>
<video id="preview-send" muted controls></video>
<figcaption>Send preview</figcaption>
</figure>
<figure>
<video id="preview-receive" muted controls></video>
<figcaption>Receive preview</figcaption>
</figure>
</div>
<script src="dist/bundle.js">
</script>
{
"version": "0.0.0",
"private": true,
"engines": {
"node": ">=14"
},
"scripts": {
"start": "webpack serve"
},
"author": "Nazar Mokrynskyi <nazar@mokrynskyi.com>",
"dependencies": {
"mediasoup-client": "^3.6.25"
},
"devDependencies": {
"ts-loader": "^8.0.13",
"typescript": "^4.1.3",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.1",
"webpack-dev-server": "^4.0.0-beta.0"
}
}
/* eslint-disable no-console */
import { Device } from 'mediasoup-client';
import { MediaKind, RtpCapabilities, RtpParameters } from 'mediasoup-client/lib/RtpParameters';
import { DtlsParameters, TransportOptions, Transport } from 'mediasoup-client/lib/Transport';
import { ConsumerOptions } from 'mediasoup-client/lib/Consumer';
interface ServerInit {
action: 'Init';
consumerTransportOptions: TransportOptions;
producerTransportOptions: TransportOptions;
routerRtpCapabilities: RtpCapabilities;
}
interface ServerConnectedProducerTransport {
action: 'ConnectedProducerTransport';
}
interface ServerProduced {
action: 'Produced';
id: string;
}
interface ServerConnectedConsumerTransport {
action: 'ConnectedConsumerTransport';
}
interface ServerConsumed {
action: 'Consumed';
id: string;
kind: MediaKind;
rtpParameters: RtpParameters;
}
type ServerMessage =
ServerInit |
ServerConnectedProducerTransport |
ServerProduced |
ServerConnectedConsumerTransport |
ServerConsumed;
interface ClientInit {
action: 'Init';
rtpCapabilities: RtpCapabilities;
}
interface ClientConnectProducerTransport {
action: 'ConnectProducerTransport';
dtlsParameters: DtlsParameters;
}
interface ClientConnectConsumerTransport {
action: 'ConnectConsumerTransport';
dtlsParameters: DtlsParameters;
}
interface ClientProduce {
action: 'Produce';
kind: MediaKind;
rtpParameters: RtpParameters;
}
interface ClientConsume {
action: 'Consume';
producerId: string;
}
interface ClientConsumerResume {
action: 'ConsumerResume';
id: string;
}
type ClientMessage =
ClientInit |
ClientConnectProducerTransport |
ClientProduce |
ClientConnectConsumerTransport |
ClientConsume |
ClientConsumerResume;
async function init()
{
const sendPreview = document.querySelector('#preview-send') as HTMLVideoElement;
const receivePreview = document.querySelector('#preview-receive') as HTMLVideoElement;
sendPreview.onloadedmetadata = () =>
{
sendPreview.play();
};
receivePreview.onloadedmetadata = () =>
{
receivePreview.play();
};
let receiveMediaStream: MediaStream | undefined;
const ws = new WebSocket('ws://localhost:3000/ws');
function send(message: ClientMessage)
{
ws.send(JSON.stringify(message));
}
const device = new Device();
let producerTransport: Transport | undefined;
let consumerTransport: Transport | undefined;
{
const waitingForResponse: Map<ServerMessage['action'], Function> = new Map();
ws.onmessage = async (message) =>
{
const decodedMessage: ServerMessage = JSON.parse(message.data);
switch (decodedMessage.action)
{
case 'Init': {
await device.load({
routerRtpCapabilities : decodedMessage.routerRtpCapabilities
});
send({
action : 'Init',
rtpCapabilities : device.rtpCapabilities
});
producerTransport = device.createSendTransport(
decodedMessage.producerTransportOptions
);
producerTransport
.on('connect', ({ dtlsParameters }, success) =>
{
send({
action : 'ConnectProducerTransport',
dtlsParameters
});
waitingForResponse.set('ConnectedProducerTransport', () =>
{
success();
console.log('Producer transport connected');
});
})
.on('produce', ({ kind, rtpParameters }, success) =>
{
send({
action : 'Produce',
kind,
rtpParameters
});
waitingForResponse.set('Produced', ({ id }: {id: string}) =>
{
success({ id });
});
});
const mediaStream = await navigator.mediaDevices.getUserMedia({
audio : true,
video : {
width : {
ideal : 1270
},
height : {
ideal : 720
},
frameRate : {
ideal : 60
}
}
});
sendPreview.srcObject = mediaStream;
const producers = [];
for (const track of mediaStream.getTracks())
{
const producer = await producerTransport.produce({ track });
producers.push(producer);
console.log(`${track.kind} producer created:`, producer);
}
consumerTransport = device.createRecvTransport(
decodedMessage.consumerTransportOptions
);
consumerTransport
.on('connect', ({ dtlsParameters }, success) =>
{
send({
action : 'ConnectConsumerTransport',
dtlsParameters
});
waitingForResponse.set('ConnectedConsumerTransport', () =>
{
success();
console.log('Consumer transport connected');
});
});
for (const producer of producers)
{
await new Promise((resolve) =>
{
send({
action : 'Consume',
producerId : producer.id
});
waitingForResponse.set('Consumed', async (consumerOptions: ConsumerOptions) =>
{
const consumer = await (consumerTransport as Transport).consume(
consumerOptions
);
console.log(`${consumer.kind} producer created:`, consumer);
send({
action : 'ConsumerResume',
id : consumer.id
});
if (receiveMediaStream)
{
receiveMediaStream.addTrack(consumer.track);
receivePreview.srcObject = receiveMediaStream;
}
else
{
receiveMediaStream = new MediaStream([ consumer.track ]);
receivePreview.srcObject = receiveMediaStream;
}
resolve(undefined);
});
});
}
break;
}
default: {
const callback = waitingForResponse.get(decodedMessage.action);
if (callback)
{
waitingForResponse.delete(decodedMessage.action);
callback(decodedMessage);
}
else
{
console.error('Received unexpected message', decodedMessage);
}
}
}
};
}
ws.onerror = console.error;
}
init();
{
"compilerOptions": {
"module": "es6",
"target": "es2018",
"sourceMap": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": false,
"sourceRoot": "src",
"baseUrl": "src",
"outDir": "dist",
"strict": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"lib": [
"es5",
"es2015",
"es2019",
"dom"
]
},
"include": [
"src",
".eslintrc.js",
"webpack.config.js"
]
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
module.exports = {
mode : 'development',
entry : './src/index.ts',
module : {
rules : [
{
test : /\.ts$/,
use : 'ts-loader',
exclude : /node_modules/
}
]
},
resolve : {
extensions : [ '.ts', '.js' ]
},
output : {
filename : 'dist/bundle.js',
path : path.resolve(__dirname, 'dist')
},
devServer : {
liveReload : false,
port : 3001
}
};
# Examples
This directory contains complementary frontend examples of using mediasoup Rust library.
NOTE: These examples are simplified and provided for demo purposes only, they are by no means complete or representative
of production-grade software, use for educational purposes only and refer to documentation for all possible options.
In order to run client-side part of examples (this directory) go to the directory with example and run following:
```bash
npm install
npm start
```
差异被折叠。
# Examples
This directory contains examples of using mediasoup Rust library.
NOTE: These examples are simplified and provided for demo purposes only, they are by no means complete or representative
of production-grade software, use for educational purposes only and refer to documentation for all possible options.
Before running server-side examples you need to make sure `mediasoup-worker` is built, for this run `npm i` in the root
of the repository.
In order to run server-side part of examples (this directory) use `cargo run --example EXAMPLE_NAME`.
# Echo
Simple echo example that receives audio+video from the client and sends audio+video back to the client via different
transport. Frontend part of this example is in `examples-frontend/echo` directory.
Check WebSocket messages in browser DevTools for better understanding of what is happening under the hood.
# Rust port of [mediasoup](https://github.com/versatica/mediasoup) TypeScript library
[![Crates.io](https://img.shields.io/crates/v/mediasoup?style=flat-square)](https://crates.io/crates/mediasoup)
[![Docs](https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square)](https://docs.rs/mediasoup)
[![License](https://img.shields.io/github/license/nazar-pc/mediasoup?style=flat-square)](https://github.com/versatica/mediasoup/v3/rust)
# Support forum
* [mediasoup.discourse.group](https://mediasoup.discourse.group/)
# Design Goals
mediasoup and its client side libraries are designed to accomplish with the following goals:
* Be a [SFU](https://webrtcglossary.com/sfu/) (Selective Forwarding Unit).
* Support both WebRTC and plain RTP input and output.
* Be a Rust/Node.js module in server side.
* Be a tiny JavaScript and C++ libraries in client side.
* Be minimalist: just handle the media layer.
* Be signaling agnostic: do not mandate any signaling protocol.
* Be super low level API.
* Support all existing WebRTC endpoints.
* Enable integration with well known multimedia libraries/tools.
## Use Cases
mediasoup and its client side libraries provide a super low level API. They are intended to
enable different use cases and scenarios, without any constraint or assumption. Some of these
use cases are:
* Group video chat applications.
* One-to-many (or few-to-many) broadcasting applications in real-time.
* RTP streaming.
## Features
* Idiomatic Rust/ECMAScript 6 low level API.
* Multi-stream: multiple audio/video streams over a single ICE + DTLS transport.
* IPv6 ready.
* ICE / DTLS / RTP / RTCP over UDP and TCP.
* Simulcast and SVC support.
* Congestion control.
* Sender and receiver bandwidth estimation with spatial/temporal layers distribution algorithm.
* Data message exchange (via WebRTC DataChannels, SCTP over plain UDP, and direct termination in Rust/Node.js).
* Extremely powerful (media worker subprocess coded in C++ on top of [libuv](https://libuv.org)).
## Authors
* Iñaki Baz Castillo [[website](https://inakibaz.me)|[github](https://github.com/ibc/)]
* José Luis Millán [[github](https://github.com/jmillan/)]
* Nazar Mokrynskyi (Rust port) [[github](https://github.com/nazar-pc)]
## License
ISC
差异被折叠。
use super::*;
#[test]
fn dtls_fingerprint() {
{
let dtls_fingerprints = &[
r#"{"algorithm":"sha-1","value":"0D:88:5B:EF:B9:86:F9:66:67:75:7A:C1:7A:78:34:E4:88:DC:44:67"}"#,
r#"{"algorithm":"sha-224","value":"6E:0C:C7:23:DF:36:E1:C7:46:AB:D7:B1:CE:DD:97:C3:C1:17:25:D6:26:0A:8A:B4:50:F1:3E:BC"}"#,
r#"{"algorithm":"sha-256","value":"7A:27:46:F0:7B:09:28:F0:10:E2:EC:84:60:B5:87:9A:D9:C8:8B:F3:6C:C5:5D:C3:F3:BA:2C:5B:4F:8A:3A:E3"}"#,
r#"{"algorithm":"sha-384","value":"D0:B7:F7:3C:71:9F:F4:A1:48:E1:9B:13:25:59:A4:7D:06:BF:E1:1B:DC:0B:8A:8E:45:09:01:22:7E:81:68:EC:DD:B8:DD:CA:1F:F3:F2:E8:15:A5:3C:23:CF:F7:B6:38"}"#,
r#"{"algorithm":"sha-512","value":"36:8B:9B:CA:2B:01:2B:33:FD:06:95:F2:CC:28:56:69:5B:DD:38:5E:88:32:9A:72:F7:B1:5D:87:9E:64:97:0B:66:A1:C7:6C:BE:4D:CD:83:90:04:AE:20:6C:6D:5F:F0:BD:4C:D9:DD:6E:8A:19:C1:C9:F6:C2:46:C8:08:94:39"}"#,
];
for dtls_fingerprint_str in dtls_fingerprints {
let dtls_fingerprint =
serde_json::from_str::<DtlsFingerprint>(dtls_fingerprint_str).unwrap();
assert_eq!(
dtls_fingerprint_str,
&serde_json::to_string(&dtls_fingerprint).unwrap()
);
}
}
{
let bad_dtls_fingerprints = &[
r#"{"algorithm":"sha-1","value":"0D:88:5B:EF:B9:86:F9:66:67::44:67"}"#,
r#"{"algorithm":"sha-200","value":"6E:0C:C7:23:DF:36:E1:C7:46:AB:D7:B1:CE:DD:97:C3:C1:17:25:D6:26:0A:8A:B4:50:F1:3E:BC"}"#,
];
for dtls_fingerprint_str in bad_dtls_fingerprints {
assert!(serde_json::from_str::<DtlsFingerprint>(dtls_fingerprint_str).is_err());
}
}
}
//! Rust port of [mediasoup](https://github.com/versatica/mediasoup) TypeScript library!
//!
//! For general information go to readme in repository.
//!
//! # For TypeScript users
//! If you were using mediasoup in TypeScript before, most of the API should be familiar to you.
//! However, this is not one-to-one port, API was adjusted to more idiomatic Rust style leveraging
//! powerful type system and ownership system to make API more robust and more misuse-resistant.
//!
//! So you will find specific types in most places where plain strings were used, instead of
//! `close()` you will see `Drop` implementation for major entities that will close everything
//! gracefully when it goes out of scope.
//!
//! # Before you start
//! This is very low-level **library**. Which means it doesn't come with a ready to use signaling
//! mechanism or easy to customize app scaffold (see
//! [design goals](https://github.com/versatica/mediasoup/tree/v3/rust/readme.md#design-goals)).
//!
//! It is recommended to visit mediasoup website and read
//! [design overview](https://mediasoup.org/documentation/v3/mediasoup/design/) first.
//!
//! Pre-requisite for using this library is to have mediasoup worker. The simples way to get it is
//! to run `npm i mediasoup` (see
//! [installation instructions](https://mediasoup.org/documentation/v3/mediasoup/installation/)) and
//! get worker binary from `node_modules/mediasoup/worker/out/Release/mediasoup-worker`.
//!
//! If you are hacking on the library just run `npm i` in the root of the repo and tests will pick
//! up the worker binary automatically.
//!
//! # Examples
//! There are some examples in `examples` and `examples-frontend` directories (for server- and
//! client-side respectively), you may want to look at those to get a general idea of what API looks
//! like and what needs to be done in what order (check WebSocket messages in browser DevTools for
//! better understanding of what is happening under the hood).
//!
//! # How to start
//! With that in mind, you want start with creating [`WorkerManager`](worker_manager::WorkerManager)
//! instance and then 1 or more workers. Workers a responsible for low-level job of sending media
//! and data back and forth. Each worker is backed by single-core C++ worker process. On each worker
//! you create one or more routers that enable injection, selection and forwarding of media and data
//! through [`transport`] instances. There are a few different transports available, but most likely
//! you'll want to use [`WebRtcTransport`](webrtc_transport::WebRtcTransport) most often. With
//! transport created you can start creating [`Producer`](producer::Producer)s to send data to
//! [`Router`](router::Router) and [`Consumer`](consumer::Consumer) instances to extract data from
//! [`Router`](router::Router).
//!
//! Some of the more advanced cases involve multiple routers and even workers that can user more
//! than one core on the machine or even scale beyond single host. Check
//! [scalability page](https://mediasoup.org/documentation/v3/scalability/) of the official
//! documentation.
//!
//! Please check integration and unit tests for usage examples, they cover all major functionality
//! and are a good place to start until we have demo apps built in Rust).
pub mod data_structures;
mod macros;
mod messages;
mod ortc;
pub mod router;
pub mod rtp_parameters;
pub mod scalability_modes;
pub mod sctp_parameters;
pub mod srtp_parameters;
pub mod supported_rtp_capabilities;
pub mod worker;
pub mod worker_manager;
// TODO: The mess below is because of https://github.com/rust-lang/rust/issues/59368
#[cfg(not(doc))]
pub use router::audio_level_observer;
#[cfg(doc)]
#[path = "router/audio_level_observer.rs"]
pub mod audio_level_observer;
#[cfg(not(doc))]
pub use router::consumer;
#[cfg(doc)]
#[path = "router/consumer.rs"]
pub mod consumer;
#[cfg(not(doc))]
pub use router::data_consumer;
#[cfg(doc)]
#[path = "router/data_consumer.rs"]
pub mod data_consumer;
#[cfg(not(doc))]
pub use router::producer;
#[cfg(doc)]
#[path = "router/producer.rs"]
pub mod producer;
#[cfg(not(doc))]
pub use router::data_producer;
#[cfg(doc)]
#[path = "router/data_producer.rs"]
pub mod data_producer;
#[cfg(not(doc))]
pub use router::transport;
#[cfg(doc)]
#[path = "router/transport.rs"]
pub mod transport;
#[cfg(not(doc))]
pub use router::direct_transport;
#[cfg(doc)]
#[path = "router/direct_transport.rs"]
pub mod direct_transport;
#[cfg(not(doc))]
pub use router::pipe_transport;
#[cfg(doc)]
#[path = "router/pipe_transport.rs"]
pub mod pipe_transport;
#[cfg(not(doc))]
pub use router::plain_transport;
#[cfg(doc)]
#[path = "router/plain_transport.rs"]
pub mod plain_transport;
#[cfg(not(doc))]
pub use router::rtp_observer;
#[cfg(doc)]
#[path = "router/rtp_observer.rs"]
pub mod rtp_observer;
#[cfg(not(doc))]
pub use router::webrtc_transport;
#[cfg(doc)]
#[path = "router/webrtc_transport.rs"]
pub mod webrtc_transport;
#[doc(hidden)]
#[macro_export]
macro_rules! uuid_based_wrapper_type {
(
$(#[$outer:meta])*
$struct_name: ident
) => {
$(#[$outer])*
#[derive(
Debug,
Copy,
Clone,
serde::Deserialize,
serde::Serialize,
Hash,
Ord,
PartialOrd,
Eq,
PartialEq,
)]
pub struct $struct_name(uuid::Uuid);
impl std::fmt::Display for $struct_name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl From<$struct_name> for uuid::Uuid {
fn from(id: $struct_name) -> Self {
id.0
}
}
impl $struct_name {
pub(super) fn new() -> Self {
$struct_name(uuid::Uuid::new_v4())
}
}
impl From<$struct_name> for crate::worker::SubscriptionTarget {
fn from(id: $struct_name) -> Self {
Self::Uuid(id.0)
}
}
};
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
//! An RTP observer inspects the media received by a set of selected producers.
//!
//! mediasoup implements the following RTP observers:
//! * [`AudioLevelObserver`](crate::audio_level_observer::AudioLevelObserver)
use crate::data_structures::AppData;
use crate::producer::{Producer, ProducerId};
use crate::uuid_based_wrapper_type;
use crate::worker::RequestError;
use async_trait::async_trait;
use event_listener_primitives::HandlerId;
uuid_based_wrapper_type!(
/// RTP observer identifier.
RtpObserverId
);
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RtpObserverAddProducerOptions {
/// The id of the Producer to be added.
pub producer_id: ProducerId,
}
impl RtpObserverAddProducerOptions {
/// * `producer_id` - The id of the Producer to be added.
pub fn new(producer_id: ProducerId) -> Self {
Self { producer_id }
}
}
/// An RTP observer inspects the media received by a set of selected producers.
///
/// mediasoup implements the following RTP observers:
/// * [`AudioLevelObserver`](crate::audio_level_observer::AudioLevelObserver)
#[async_trait(?Send)]
pub trait RtpObserver {
/// RtpObserver id.
fn id(&self) -> RtpObserverId;
/// Whether the RtpObserver is paused.
fn paused(&self) -> bool;
/// Custom application data.
fn app_data(&self) -> &AppData;
/// Whether the RTP observer is closed.
fn closed(&self) -> bool;
/// Pauses the RTP observer. No RTP is inspected until resume() is called.
async fn pause(&self) -> Result<(), RequestError>;
/// Resumes the RTP observer. RTP is inspected again.
async fn resume(&self) -> Result<(), RequestError>;
/// Provides the RTP observer with a new producer to monitor.
async fn add_producer(
&self,
rtp_observer_add_producer_options: RtpObserverAddProducerOptions,
) -> Result<(), RequestError>;
/// Removes the given producer from the RTP observer.
async fn remove_producer(&self, producer_id: ProducerId) -> Result<(), RequestError>;
/// Callback is called when the RTP observer is paused.
fn on_pause(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId;
/// Callback is called when the RTP observer is resumed.
fn on_resume(&self, callback: Box<dyn Fn() + Send + Sync + 'static>) -> HandlerId;
/// Callback is called when a new producer is added into the RTP observer.
fn on_add_producer(
&self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId;
/// Callback is called when a producer is removed from the RTP observer.
fn on_remove_producer(
&self,
callback: Box<dyn Fn(&Producer) + Send + Sync + 'static>,
) -> HandlerId;
/// Callback is called when the router this RTP observer belongs to is closed for whatever reason. The RTP
/// observer itself is also closed.
fn on_router_close(&self, callback: Box<dyn FnOnce() + Send + 'static>) -> HandlerId;
/// Callback is called when the RTP observer is closed for whatever reason.
///
/// NOTE: Callback will be called in place if observer is already closed.
fn on_close(&self, callback: Box<dyn FnOnce() + Send + 'static>) -> HandlerId;
}
差异被折叠。
差异被折叠。
差异被折叠。
use super::*;
#[test]
fn rtcp_feedback_serde() {
{
let nack_pli_str = r#"{"type":"nack","parameter":"pli"}"#;
assert_eq!(
serde_json::from_str::<RtcpFeedback>(nack_pli_str).unwrap(),
RtcpFeedback::NackPli
);
let result = serde_json::to_string(&RtcpFeedback::NackPli).unwrap();
assert_eq!(result.as_str(), nack_pli_str);
}
{
let transport_cc_str = r#"{"type":"transport-cc","parameter":""}"#;
assert_eq!(
serde_json::from_str::<RtcpFeedback>(transport_cc_str).unwrap(),
RtcpFeedback::TransportCc
);
let result = serde_json::to_string(&RtcpFeedback::TransportCc).unwrap();
assert_eq!(result.as_str(), transport_cc_str);
}
{
let nack_bar_str = r#"{"type":"nack","parameter":"bar"}"#;
assert_eq!(
serde_json::from_str::<RtcpFeedback>(nack_bar_str).unwrap(),
RtcpFeedback::Unsupported
);
}
}
//! Scalability mode.
#[cfg(test)]
mod tests;
use once_cell::sync::OnceCell;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use thiserror::Error;
/// Scalability mode.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
pub struct ScalabilityMode {
/// Number of spatial layers.
pub spatial_layers: u8,
/// Number of temporal layers.
pub temporal_layers: u8,
/// K-SVC mode.
pub ksvc: bool,
}
impl Default for ScalabilityMode {
fn default() -> Self {
Self {
spatial_layers: 1,
temporal_layers: 1,
ksvc: false,
}
}
}
/// Error that caused [`ScalabilityMode`] parsing error.
#[derive(Debug, Error, Eq, PartialEq)]
pub enum ParseScalabilityModeError {
/// Invalid input string
#[error("Invalid input string")]
InvalidInput,
}
impl FromStr for ScalabilityMode {
type Err = ParseScalabilityModeError;
fn from_str(scalability_mode: &str) -> Result<Self, Self::Err> {
static SCALABILITY_MODE_REGEX: OnceCell<Regex> = OnceCell::new();
SCALABILITY_MODE_REGEX
.get_or_init(|| Regex::new(r"^[LS]([1-9][0-9]?)T([1-9][0-9]?)(_KEY)?").unwrap())
.captures(scalability_mode)
.map(|captures| ScalabilityMode {
spatial_layers: captures.get(1).unwrap().as_str().parse().unwrap(),
temporal_layers: captures.get(2).unwrap().as_str().parse().unwrap(),
ksvc: captures.get(3).is_some(),
})
.ok_or(ParseScalabilityModeError::InvalidInput)
}
}
use super::*;
#[test]
fn parse_scalability_modes() {
assert_eq!(
"L1T3".parse(),
Ok(ScalabilityMode {
spatial_layers: 1,
temporal_layers: 3,
ksvc: false
}),
);
assert_eq!(
"L3T2_KEY".parse(),
Ok(ScalabilityMode {
spatial_layers: 3,
temporal_layers: 2,
ksvc: true
}),
);
assert_eq!(
"S2T3".parse(),
Ok(ScalabilityMode {
spatial_layers: 2,
temporal_layers: 3,
ksvc: false
}),
);
assert_eq!(
"foo".parse::<ScalabilityMode>(),
Err(ParseScalabilityModeError::InvalidInput),
);
assert_eq!(
"ull".parse::<ScalabilityMode>(),
Err(ParseScalabilityModeError::InvalidInput),
);
assert_eq!(
"S0T3".parse::<ScalabilityMode>(),
Err(ParseScalabilityModeError::InvalidInput),
);
assert_eq!(
"S1T0".parse::<ScalabilityMode>(),
Err(ParseScalabilityModeError::InvalidInput),
);
assert_eq!(
"L20T3".parse(),
Ok(ScalabilityMode {
spatial_layers: 20,
temporal_layers: 3,
ksvc: false
}),
);
assert_eq!(
"S200T3".parse::<ScalabilityMode>(),
Err(ParseScalabilityModeError::InvalidInput),
);
assert_eq!(
"L4T7_KEY_SHIFT".parse(),
Ok(ScalabilityMode {
spatial_layers: 4,
temporal_layers: 7,
ksvc: true
}),
);
}
差异被折叠。
//! Collection of SRTP-related data structures that are used to specify SRTP encryption/decryption
//! parameters.
use serde::{Deserialize, Serialize};
/// SRTP parameters.
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SrtpParameters {
/// Encryption and authentication transforms to be used.
pub crypto_suite: SrtpCryptoSuite,
/// SRTP keying material (master key and salt) in Base64.
pub key_base64: String,
}
/// SRTP crypto suite.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum SrtpCryptoSuite {
/// AES_CM_128_HMAC_SHA1_80
#[serde(rename = "AES_CM_128_HMAC_SHA1_80")]
AesCm128HmacSha180,
/// AES_CM_128_HMAC_SHA1_32
#[serde(rename = "AES_CM_128_HMAC_SHA1_32")]
AesCm128HmacSha132,
}
impl Default for SrtpCryptoSuite {
fn default() -> Self {
Self::AesCm128HmacSha180
}
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论