Unverified 提交 a7d46d81 authored 作者: José Luis Millán's avatar José Luis Millán 提交者: GitHub

flatbuffers (#1064)

Flatbuffers

WIP to remove JSON in favour of flatbuffers for as the worker communication format.

- JSON parsing is CPU intensive.
- JSON is not type safe.
- flatbuffers does not parse the buffer. Reading the message takes 0ms.
- flatbuffers is type safe since code (C++, Typescript, Rust, etc) is autogenerated out of the schema definitions.

Extras that come along with this changes:
- There is now a single Channel for worker communication.
- Previously there were 2 (Channel and PayloadChannel)
- Each message sent Node->Worker requires a single write() call to Channel.
- Previously 2 calls per message were needed for Channel and 4 for PayloadChannel.
- Each message sent Worker->Node previously executed two extra calls to memcpy that are not executed now.

---------
Co-authored-by: 's avatarIñaki Baz Castillo <ibc@aliax.net>
Co-authored-by: 's avatarNazar Mokrynskyi <nazar@mokrynskyi.com>
上级 0b4d4ef9
......@@ -13,6 +13,8 @@ jobs:
strategy:
matrix:
ci:
- os: ubuntu-20.04
node: 16
- os: ubuntu-20.04
node: 18
- os: ubuntu-22.04
......@@ -45,6 +47,8 @@ jobs:
restore-keys: |
${{ matrix.ci.os }}-node-
- run: npm ci
# NOTE: Add --force since otherwise `npm ci` fails in Node 26 because
# @octokit/auth-token dev dependency requires Node >= 16.
- run: npm ci --force
- run: npm run lint:node
- run: npm run test:node
......@@ -7,15 +7,18 @@
## Node.
/node_modules
/node/lib
# flatc generated files.
/node/src/fbs
## Rust.
/Cargo.lock
/rust/examples-frontend/*/node_modules
/rust/examples-frontend/*/package-lock.json
/target
## Worker.
/worker/scripts/node_modules
# Flatc generated files.
/worker/include/FBS
/worker/prebuild
# Vistual Studio generated Stuff.
/worker/**/Debug
......@@ -30,14 +33,5 @@
## Others.
/coverage
/.cache
/NO_GIT
*.swp
*.swo
.DS_Store
# Vistual Studio Code stuff.
/.vscode
# JetBrains IDE stuff.
/.idea
# Packaged module.
*.tgz
# Changelog
### Next
* Switch from JSON based messages to `flatbuffers` ([PR #1064](https://github.com/versatica/mediasoup/pull/1064)).
* Add `ListenInfo` in all transports and send/recv buffer size options ([PR #1084](https://github.com/versatica/mediasoup/pull/1084)).
* Add optional `rtcpListenInfo` in `PlainTransportOptions` ([PR #1099](https://github.com/versatica/mediasoup/pull/1099)).
* Add pause/resume API in `DataProducer` and `DataConsumer` ([PR #1104](https://github.com/versatica/mediasoup/pull/1104)).
* DataChannel subchannels feature ([PR #1152](https://github.com/versatica/mediasoup/pull/1152)).
* `Worker`: Make DTLS fragment stay within MTU size range ([PR #1156](https://github.com/versatica/mediasoup/pull/1156), based on [PR #1143](https://github.com/versatica/mediasoup/pull/1143) by @vpnts-se).
### 3.12.16
* Fix `IceServer` crash when client uses ICE renomination ([PR #1182](https://github.com/versatica/mediasoup/pull/1182)).
......
差异被折叠。
[workspace]
resolver = "2"
members = [
"rust",
"worker"
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -183,6 +183,7 @@ const eslintConfig =
}
],
'space-in-parens' : [ 2, 'never' ],
'space-infix-ops' : [ 2, { 'int32Hint': false } ],
'spaced-comment' : [ 2, 'always' ],
'strict' : 2,
'valid-typeof' : 2,
......
......@@ -8,6 +8,8 @@ import {
} from './RtpObserver';
import { Producer } from './Producer';
import { AppData } from './types';
import { Event, Notification } from './fbs/notification';
import * as FbsActiveSpeakerObserver from './fbs/active-speaker-observer';
export type ActiveSpeakerObserverOptions<ActiveSpeakerObserverAppData extends AppData = AppData> =
{
......@@ -65,13 +67,17 @@ export class ActiveSpeakerObserver<ActiveSpeakerObserverAppData extends AppData
private handleWorkerNotifications(): void
{
this.channel.on(this.internal.rtpObserverId, (event: string, data?: any) =>
this.channel.on(this.internal.rtpObserverId, (event: Event, data?: Notification) =>
{
switch (event)
{
case 'dominantspeaker':
case Event.ACTIVESPEAKEROBSERVER_DOMINANT_SPEAKER:
{
const producer = this.getProducerById(data.producerId);
const notification = new FbsActiveSpeakerObserver.DominantSpeakerNotification();
data!.body(notification);
const producer = this.getProducerById(notification.producerId()!);
if (!producer)
{
......
......@@ -8,6 +8,9 @@ import {
} from './RtpObserver';
import { Producer } from './Producer';
import { AppData } from './types';
import * as utils from './utils';
import { Event, Notification } from './fbs/notification';
import * as FbsAudioLevelObserver from './fbs/audio-level-observer';
export type AudioLevelObserverOptions<AudioLevelObserverAppData extends AppData = AppData> =
{
......@@ -87,22 +90,27 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD
private handleWorkerNotifications(): void
{
this.channel.on(this.internal.rtpObserverId, (event: string, data?: any) =>
this.channel.on(this.internal.rtpObserverId, (event: Event, data?: Notification) =>
{
switch (event)
{
case 'volumes':
case Event.AUDIOLEVELOBSERVER_VOLUMES:
{
const notification = new FbsAudioLevelObserver.VolumesNotification();
data!.body(notification);
// Get the corresponding Producer instance and remove entries with
// no Producer (it may have been closed in the meanwhile).
const volumes: AudioLevelObserverVolume[] = data
.map(({ producerId, volume }: { producerId: string; volume: number }) => (
{
producer : this.getProducerById(producerId),
volume
}
))
.filter(({ producer }: { producer: Producer }) => producer);
const volumes: AudioLevelObserverVolume[] =
utils.parseVector(notification, 'volumes', parseVolume)
.map(({ producerId, volume }: { producerId: string; volume: number }) => (
{
producer : this.getProducerById(producerId)!,
volume
}
))
.filter(({ producer }: { producer: Producer }) => producer);
if (volumes.length > 0)
{
......@@ -115,7 +123,7 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD
break;
}
case 'silence':
case Event.AUDIOLEVELOBSERVER_SILENCE:
{
this.safeEmit('silence');
......@@ -133,3 +141,14 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD
});
}
}
function parseVolume(binary: FbsAudioLevelObserver.Volume): {
producerId: string;
volume: number;
}
{
return {
producerId : binary.producerId()!,
volume : binary.volume()
};
}
差异被折叠。
差异被折叠。
差异被折叠。
import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { TransportInternal } from './Transport';
import { SctpStreamParameters } from './SctpParameters';
import { parseSctpStreamParameters, SctpStreamParameters } from './SctpParameters';
import { AppData } from './types';
import * as FbsTransport from './fbs/transport';
import * as FbsNotification from './fbs/notification';
import * as FbsRequest from './fbs/request';
import * as FbsDataProducer from './fbs/data-producer';
export type DataProducerOptions<DataProducerAppData extends AppData = AppData> =
{
......@@ -29,6 +32,11 @@ export type DataProducerOptions<DataProducerAppData extends AppData = AppData> =
*/
protocol?: string;
/**
* Whether the data producer must start in paused mode. Default false.
*/
paused?: boolean;
/**
* Custom application data.
*/
......@@ -60,6 +68,14 @@ export type DataProducerEvents =
export type DataProducerObserverEvents =
{
close: [];
pause: [];
resume: [];
};
type DataProducerDump = DataProducerData &
{
id: string;
paused: boolean;
};
type DataProducerInternal = TransportInternal &
......@@ -89,12 +105,12 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// Channel instance.
readonly #channel: Channel;
// PayloadChannel instance.
readonly #payloadChannel: PayloadChannel;
// Closed flag.
#closed = false;
// Paused flag.
#paused = false;
// Custom app data.
#appData: DataProducerAppData;
......@@ -109,14 +125,14 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
internal,
data,
channel,
payloadChannel,
paused,
appData
}:
{
internal: DataProducerInternal;
data: DataProducerData;
channel: Channel;
payloadChannel: PayloadChannel;
paused: boolean;
appData?: DataProducerAppData;
}
)
......@@ -128,7 +144,7 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
this.#internal = internal;
this.#data = data;
this.#channel = channel;
this.#payloadChannel = payloadChannel;
this.#paused = paused;
this.#appData = appData || {} as DataProducerAppData;
this.handleWorkerNotifications();
......@@ -182,6 +198,14 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
return this.#data.protocol;
}
/**
* Whether the DataProducer is paused.
*/
get paused(): boolean
{
return this.#paused;
}
/**
* App custom data.
*/
......@@ -222,12 +246,18 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataProducerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataProducerId);
const reqData = { dataProducerId: this.#internal.dataProducerId };
/* Build Request. */
const requestOffset = new FbsTransport.CloseDataProducerRequestT(
this.#internal.dataProducerId
).pack(this.#channel.bufferBuilder);
this.#channel.request('transport.closeDataProducer', this.#internal.transportId, reqData)
.catch(() => {});
this.#channel.request(
FbsRequest.Method.TRANSPORT_CLOSE_DATAPRODUCER,
FbsRequest.Body.Transport_CloseDataProducerRequest,
requestOffset,
this.#internal.transportId
).catch(() => {});
this.emit('@close');
......@@ -253,7 +283,6 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataProducerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataProducerId);
this.safeEmit('transportclose');
......@@ -264,11 +293,23 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
/**
* Dump DataProducer.
*/
async dump(): Promise<any>
async dump(): Promise<DataProducerDump>
{
logger.debug('dump()');
return this.#channel.request('dataProducer.dump', this.#internal.dataProducerId);
const response = await this.#channel.request(
FbsRequest.Method.DATAPRODUCER_DUMP,
undefined,
undefined,
this.#internal.dataProducerId
);
/* Decode Response. */
const produceResponse = new FbsDataProducer.DumpResponse();
response.body(produceResponse);
return parseDataProducerDumpResponse(produceResponse);
}
/**
......@@ -278,13 +319,80 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
{
logger.debug('getStats()');
return this.#channel.request('dataProducer.getStats', this.#internal.dataProducerId);
const response = await this.#channel.request(
FbsRequest.Method.DATAPRODUCER_GET_STATS,
undefined,
undefined,
this.#internal.dataProducerId
);
/* Decode Response. */
const data = new FbsDataProducer.GetStatsResponse();
response.body(data);
return [ parseDataProducerStats(data) ];
}
/**
* Pause the DataProducer.
*/
async pause(): Promise<void>
{
logger.debug('pause()');
const wasPaused = this.#paused;
await this.#channel.request(
FbsRequest.Method.DATAPRODUCER_PAUSE,
undefined,
undefined,
this.#internal.dataProducerId
);
this.#paused = true;
// Emit observer event.
if (!wasPaused)
{
this.#observer.safeEmit('pause');
}
}
/**
* Resume the DataProducer.
*/
async resume(): Promise<void>
{
logger.debug('resume()');
const wasPaused = this.#paused;
await this.#channel.request(
FbsRequest.Method.DATAPRODUCER_RESUME,
undefined,
undefined,
this.#internal.dataProducerId
);
this.#paused = false;
// Emit observer event.
if (wasPaused)
{
this.#observer.safeEmit('resume');
}
}
/**
* Send data (just valid for DataProducers created on a DirectTransport).
*/
send(message: string | Buffer, ppid?: number): void
send(
message: string | Buffer,
ppid?: number,
subchannels?: number[],
requiredSubchannel?: number
): void
{
if (typeof message !== 'string' && !Buffer.isBuffer(message))
{
......@@ -324,10 +432,35 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
message = Buffer.alloc(1);
}
const notifData = String(ppid);
const builder = this.#channel.bufferBuilder;
let dataOffset = 0;
const subchannelsOffset = FbsDataProducer.SendNotification.createSubchannelsVector(
builder, subchannels ?? []
);
if (typeof message === 'string')
{
message = Buffer.from(message);
}
this.#payloadChannel.notify(
'dataProducer.send', this.#internal.dataProducerId, notifData, message);
dataOffset = FbsDataProducer.SendNotification.createDataVector(builder, message);
const notificationOffset = FbsDataProducer.SendNotification.createSendNotification(
builder,
ppid,
dataOffset,
subchannelsOffset,
requiredSubchannel ?? null
);
this.#channel.notify(
FbsNotification.Event.DATAPRODUCER_SEND,
FbsNotification.Body.DataProducer_SendNotification,
notificationOffset,
this.#internal.dataProducerId
);
}
private handleWorkerNotifications(): void
......@@ -335,3 +468,57 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// No need to subscribe to any event.
}
}
export function dataProducerTypeToFbs(type: DataProducerType): FbsDataProducer.Type
{
switch (type)
{
case 'sctp':
return FbsDataProducer.Type.SCTP;
case 'direct':
return FbsDataProducer.Type.DIRECT;
default:
throw new TypeError('invalid DataConsumerType: ${type}');
}
}
export function dataProducerTypeFromFbs(type: FbsDataProducer.Type): DataProducerType
{
switch (type)
{
case FbsDataProducer.Type.SCTP:
return 'sctp';
case FbsDataProducer.Type.DIRECT:
return 'direct';
}
}
export function parseDataProducerDumpResponse(
data: FbsDataProducer.DumpResponse
): DataProducerDump
{
return {
id : data.id()!,
type : dataProducerTypeFromFbs(data.type()),
sctpStreamParameters : data.sctpStreamParameters() !== null ?
parseSctpStreamParameters(data.sctpStreamParameters()!) :
undefined,
label : data.label()!,
protocol : data.protocol()!,
paused : data.paused()
};
}
function parseDataProducerStats(
binary: FbsDataProducer.GetStatsResponse
): DataProducerStat
{
return {
type : 'data-producer',
timestamp : Number(binary.timestamp()),
label : binary.label()!,
protocol : binary.protocol()!,
messagesReceived : Number(binary.messagesReceived()),
bytesReceived : Number(binary.bytesReceived())
};
}
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论