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: ...@@ -13,6 +13,8 @@ jobs:
strategy: strategy:
matrix: matrix:
ci: ci:
- os: ubuntu-20.04
node: 16
- os: ubuntu-20.04 - os: ubuntu-20.04
node: 18 node: 18
- os: ubuntu-22.04 - os: ubuntu-22.04
...@@ -45,6 +47,8 @@ jobs: ...@@ -45,6 +47,8 @@ jobs:
restore-keys: | restore-keys: |
${{ matrix.ci.os }}-node- ${{ 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 lint:node
- run: npm run test:node - run: npm run test:node
...@@ -7,15 +7,18 @@ ...@@ -7,15 +7,18 @@
## Node. ## Node.
/node_modules /node_modules
/node/lib /node/lib
# flatc generated files.
/node/src/fbs
## Rust. ## Rust.
/Cargo.lock
/rust/examples-frontend/*/node_modules /rust/examples-frontend/*/node_modules
/rust/examples-frontend/*/package-lock.json /rust/examples-frontend/*/package-lock.json
/target /target
## Worker. ## Worker.
/worker/scripts/node_modules /worker/scripts/node_modules
# Flatc generated files.
/worker/include/FBS
/worker/prebuild /worker/prebuild
# Vistual Studio generated Stuff. # Vistual Studio generated Stuff.
/worker/**/Debug /worker/**/Debug
...@@ -30,14 +33,5 @@ ...@@ -30,14 +33,5 @@
## Others. ## Others.
/coverage /coverage
/.cache /.cache
/NO_GIT
*.swp
*.swo
.DS_Store
# Vistual Studio Code stuff.
/.vscode
# JetBrains IDE stuff.
/.idea
# Packaged module. # Packaged module.
*.tgz *.tgz
# Changelog # 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 ### 3.12.16
* Fix `IceServer` crash when client uses ICE renomination ([PR #1182](https://github.com/versatica/mediasoup/pull/1182)). * Fix `IceServer` crash when client uses ICE renomination ([PR #1182](https://github.com/versatica/mediasoup/pull/1182)).
......
差异被折叠。
[workspace] [workspace]
resolver = "2"
members = [ members = [
"rust", "rust",
"worker" "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 = ...@@ -183,6 +183,7 @@ const eslintConfig =
} }
], ],
'space-in-parens' : [ 2, 'never' ], 'space-in-parens' : [ 2, 'never' ],
'space-infix-ops' : [ 2, { 'int32Hint': false } ],
'spaced-comment' : [ 2, 'always' ], 'spaced-comment' : [ 2, 'always' ],
'strict' : 2, 'strict' : 2,
'valid-typeof' : 2, 'valid-typeof' : 2,
......
...@@ -8,6 +8,8 @@ import { ...@@ -8,6 +8,8 @@ import {
} from './RtpObserver'; } from './RtpObserver';
import { Producer } from './Producer'; import { Producer } from './Producer';
import { AppData } from './types'; 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> = export type ActiveSpeakerObserverOptions<ActiveSpeakerObserverAppData extends AppData = AppData> =
{ {
...@@ -65,13 +67,17 @@ export class ActiveSpeakerObserver<ActiveSpeakerObserverAppData extends AppData ...@@ -65,13 +67,17 @@ export class ActiveSpeakerObserver<ActiveSpeakerObserverAppData extends AppData
private handleWorkerNotifications(): void 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) 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) if (!producer)
{ {
......
...@@ -8,6 +8,9 @@ import { ...@@ -8,6 +8,9 @@ import {
} from './RtpObserver'; } from './RtpObserver';
import { Producer } from './Producer'; import { Producer } from './Producer';
import { AppData } from './types'; 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> = export type AudioLevelObserverOptions<AudioLevelObserverAppData extends AppData = AppData> =
{ {
...@@ -87,18 +90,23 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD ...@@ -87,18 +90,23 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD
private handleWorkerNotifications(): void 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) 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 // Get the corresponding Producer instance and remove entries with
// no Producer (it may have been closed in the meanwhile). // no Producer (it may have been closed in the meanwhile).
const volumes: AudioLevelObserverVolume[] = data const volumes: AudioLevelObserverVolume[] =
utils.parseVector(notification, 'volumes', parseVolume)
.map(({ producerId, volume }: { producerId: string; volume: number }) => ( .map(({ producerId, volume }: { producerId: string; volume: number }) => (
{ {
producer : this.getProducerById(producerId), producer : this.getProducerById(producerId)!,
volume volume
} }
)) ))
...@@ -115,7 +123,7 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD ...@@ -115,7 +123,7 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD
break; break;
} }
case 'silence': case Event.AUDIOLEVELOBSERVER_SILENCE:
{ {
this.safeEmit('silence'); this.safeEmit('silence');
...@@ -133,3 +141,14 @@ export class AudioLevelObserver<AudioLevelObserverAppData extends AppData = AppD ...@@ -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 * as os from 'os'; import * as os from 'node:os';
import { Duplex } from 'stream'; import { Duplex } from 'node:stream';
import * as flatbuffers from 'flatbuffers';
import { Logger } from './Logger'; import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { InvalidStateError } from './errors'; import { InvalidStateError } from './errors';
import { Body as RequestBody, Method, Request } from './fbs/request';
import { Response } from './fbs/response';
import { Message, Body as MessageBody } from './fbs/message';
import { Notification, Body as NotificationBody, Event } from './fbs/notification';
import { Log } from './fbs/log';
const IS_LITTLE_ENDIAN = os.endianness() === 'LE';
const littleEndian = os.endianness() == 'LE';
const logger = new Logger('Channel'); const logger = new Logger('Channel');
type Sent = type Sent =
...@@ -40,6 +47,9 @@ export class Channel extends EnhancedEventEmitter ...@@ -40,6 +47,9 @@ export class Channel extends EnhancedEventEmitter
// Buffer for reading messages from the worker. // Buffer for reading messages from the worker.
#recvBuffer = Buffer.alloc(0); #recvBuffer = Buffer.alloc(0);
// flatbuffers builder.
#bufferBuilder:flatbuffers.Builder = new flatbuffers.Builder(1024);
/** /**
* @private * @private
*/ */
...@@ -101,7 +111,7 @@ export class Channel extends EnhancedEventEmitter ...@@ -101,7 +111,7 @@ export class Channel extends EnhancedEventEmitter
const dataView = new DataView( const dataView = new DataView(
this.#recvBuffer.buffer, this.#recvBuffer.buffer,
this.#recvBuffer.byteOffset + msgStart); this.#recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian); const msgLen = dataView.getUint32(0, IS_LITTLE_ENDIAN);
if (readLen < 4 + msgLen) if (readLen < 4 + msgLen)
{ {
...@@ -113,36 +123,45 @@ export class Channel extends EnhancedEventEmitter ...@@ -113,36 +123,45 @@ export class Channel extends EnhancedEventEmitter
msgStart += 4 + msgLen; msgStart += 4 + msgLen;
const buf = new flatbuffers.ByteBuffer(new Uint8Array(payload));
const message = Message.getRootAsMessage(buf);
try try
{ {
// We can receive JSON messages (Channel messages) or log strings. switch (message.dataType())
switch (payload[0])
{ {
// 123 = '{' (a Channel JSON message). case MessageBody.Response:
case 123: {
this.processMessage(JSON.parse(payload.toString('utf8'))); const response = new Response();
break;
// 68 = 'D' (a debug log). message.data(response);
case 68:
logger.debug(`[pid:${pid}] ${payload.toString('utf8', 1)}`); this.processResponse(response);
break;
// 87 = 'W' (a warn log).
case 87:
logger.warn(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break; break;
}
case MessageBody.Notification:
{
const notification = new Notification();
message.data(notification);
this.processNotification(notification);
// 69 = 'E' (an error log).
case 69:
logger.error(`[pid:${pid} ${payload.toString('utf8', 1)}`);
break; break;
}
case MessageBody.Log:
{
const log = new Log();
message.data(log);
this.processLog(pid, log);
// 88 = 'X' (a dump log).
case 88:
// eslint-disable-next-line no-console
console.log(payload.toString('utf8', 1));
break; break;
}
default: default:
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
...@@ -182,6 +201,14 @@ export class Channel extends EnhancedEventEmitter ...@@ -182,6 +201,14 @@ export class Channel extends EnhancedEventEmitter
)); ));
} }
/**
* flatbuffer builder.
*/
get bufferBuilder(): flatbuffers.Builder
{
return this.#bufferBuilder;
}
/** /**
* @private * @private
*/ */
...@@ -225,37 +252,129 @@ export class Channel extends EnhancedEventEmitter ...@@ -225,37 +252,129 @@ export class Channel extends EnhancedEventEmitter
/** /**
* @private * @private
*/ */
async request(method: string, handlerId?: string, data?: any): Promise<any> notify(
event: Event,
bodyType?: NotificationBody,
bodyOffset?: number,
handlerId?: string
): void
{ {
this.#nextId < 4294967295 ? ++this.#nextId : (this.#nextId = 1); logger.debug('notify() [event:%s]', Event[event]);
const id = this.#nextId; if (this.#closed)
{
throw new InvalidStateError('Channel closed');
}
const handlerIdOffset = this.#bufferBuilder.createString(handlerId);
let notificationOffset: number;
if (bodyType && bodyOffset)
{
notificationOffset = Notification.createNotification(
this.#bufferBuilder, handlerIdOffset, event, bodyType, bodyOffset);
}
else
{
notificationOffset = Notification.createNotification(
this.#bufferBuilder, handlerIdOffset, event, NotificationBody.NONE, 0);
}
const messageOffset = Message.createMessage(
this.#bufferBuilder,
MessageBody.Notification,
notificationOffset
);
logger.debug('request() [method:%s, id:%s]', method, id); // Finalizes the buffer and adds a 4 byte prefix with the size of the buffer.
this.#bufferBuilder.finishSizePrefixed(messageOffset);
// Create a new buffer with this data so multiple contiguous flatbuffers
// do not point to the builder buffer overriding others info.
const buffer = new Uint8Array(this.#bufferBuilder.asUint8Array());
// Clear the buffer builder so it's reused for the next request.
this.#bufferBuilder.clear();
if (buffer.byteLength > MESSAGE_MAX_LEN)
{
throw new Error('Channel request too big');
}
try
{
// This may throw if closed or remote side ended.
this.#producerSocket.write(buffer, 'binary');
}
catch (error)
{
logger.warn('notify() | sending notification failed: %s', String(error));
return;
}
}
async request(
method: Method,
bodyType?: RequestBody,
bodyOffset?: number,
handlerId?: string): Promise<Response>
{
if (this.#closed) if (this.#closed)
{ {
throw new InvalidStateError('Channel closed'); throw new InvalidStateError('Channel closed');
} }
const request = `${id}:${method}:${handlerId}:${JSON.stringify(data)}`; this.#nextId < 4294967295 ? ++this.#nextId : (this.#nextId = 1);
const id = this.#nextId;
const handlerIdOffset = this.#bufferBuilder.createString(handlerId ?? '');
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN) let requestOffset: number;
if (bodyType && bodyOffset)
{
requestOffset = Request.createRequest(
this.#bufferBuilder, id, method, handlerIdOffset, bodyType, bodyOffset);
}
else
{
requestOffset = Request.createRequest(
this.#bufferBuilder, id, method, handlerIdOffset, RequestBody.NONE, 0);
}
const messageOffset = Message.createMessage(
this.#bufferBuilder,
MessageBody.Request,
requestOffset
);
// Finalizes the buffer and adds a 4 byte prefix with the size of the buffer.
this.#bufferBuilder.finishSizePrefixed(messageOffset);
// Create a new buffer with this data so multiple contiguous flatbuffers
// do not point to the builder buffer overriding others info.
const buffer = new Uint8Array(this.#bufferBuilder.asUint8Array());
// Clear the buffer builder so it's reused for the next request.
this.#bufferBuilder.clear();
if (buffer.byteLength > MESSAGE_MAX_LEN)
{ {
throw new Error('Channel request too big'); throw new Error('Channel request too big');
} }
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this.#producerSocket.write( this.#producerSocket.write(buffer, 'binary');
Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this.#producerSocket.write(request);
return new Promise((pResolve, pReject) => return new Promise((pResolve, pReject) =>
{ {
const sent: Sent = const sent: Sent =
{ {
id : id, id : id,
method : method, method : Method[method],
resolve : (data2) => resolve : (data2) =>
{ {
if (!this.#sents.delete(id)) if (!this.#sents.delete(id))
...@@ -285,42 +404,39 @@ export class Channel extends EnhancedEventEmitter ...@@ -285,42 +404,39 @@ export class Channel extends EnhancedEventEmitter
}); });
} }
private processMessage(msg: any): void private processResponse(response: Response): void
{ {
// If a response, retrieve its associated request. const sent = this.#sents.get(response.id());
if (msg.id)
{
const sent = this.#sents.get(msg.id);
if (!sent) if (!sent)
{ {
logger.error( logger.error(
'received response does not match any sent request [id:%s]', msg.id); 'received response does not match any sent request [id:%s]', response.id);
return; return;
} }
if (msg.accepted) if (response.accepted())
{ {
logger.debug( logger.debug(
'request succeeded [method:%s, id:%s]', sent.method, sent.id); 'request succeeded [method:%s, id:%s]', sent.method, sent.id);
sent.resolve(msg.data); sent.resolve(response);
} }
else if (msg.error) else if (response.error())
{ {
logger.warn( logger.warn(
'request failed [method:%s, id:%s]: %s', 'request failed [method:%s, id:%s]: %s',
sent.method, sent.id, msg.reason); sent.method, sent.id, response.reason());
switch (msg.error) switch (response.error()!)
{ {
case 'TypeError': case 'TypeError':
sent.reject(new TypeError(msg.reason)); sent.reject(new TypeError(response.reason()!));
break; break;
default: default:
sent.reject(new Error(msg.reason)); sent.reject(new Error(response.reason()!));
} }
} }
else else
...@@ -330,8 +446,8 @@ export class Channel extends EnhancedEventEmitter ...@@ -330,8 +446,8 @@ export class Channel extends EnhancedEventEmitter
sent.method, sent.id); sent.method, sent.id);
} }
} }
// If a notification emit it to the corresponding entity.
else if (msg.targetId && msg.event) private processNotification(notification: Notification): void
{ {
// Due to how Promises work, it may happen that we receive a response // Due to how Promises work, it may happen that we receive a response
// from the worker followed by a notification from the worker. If we // from the worker followed by a notification from the worker. If we
...@@ -339,13 +455,39 @@ export class Channel extends EnhancedEventEmitter ...@@ -339,13 +455,39 @@ 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(String(msg.targetId), msg.event, msg.data)); setImmediate(() => this.emit(
notification.handlerId()!,
notification.event(),
notification)
);
} }
// Otherwise unexpected message.
else private processLog(pid: number, log: Log): void
{ {
logger.error( const logData = log.data()!;
'received message is not a response nor a notification');
switch (logData[0])
{
// 'D' (a debug log).
case 'D':
logger.debug(`[pid:${pid}] ${logData.slice(1)}`);
break;
// 'W' (a warn log).
case 'W':
logger.warn(`[pid:${pid}] ${logData.slice(1)}`);
break;
// 'E' (a error log).
case 'E':
logger.error(`[pid:${pid}] ${logData.slice(1)}`);
break;
// 'X' (a dump log).
case 'X':
// eslint-disable-next-line no-console
console.log(logData.slice(1));
break;
} }
} }
} }
差异被折叠。
差异被折叠。
import { Logger } from './Logger'; import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel'; import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { TransportInternal } from './Transport'; import { TransportInternal } from './Transport';
import { SctpStreamParameters } from './SctpParameters'; import { parseSctpStreamParameters, SctpStreamParameters } from './SctpParameters';
import { AppData } from './types'; 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> = export type DataProducerOptions<DataProducerAppData extends AppData = AppData> =
{ {
...@@ -29,6 +32,11 @@ export type DataProducerOptions<DataProducerAppData extends AppData = AppData> = ...@@ -29,6 +32,11 @@ export type DataProducerOptions<DataProducerAppData extends AppData = AppData> =
*/ */
protocol?: string; protocol?: string;
/**
* Whether the data producer must start in paused mode. Default false.
*/
paused?: boolean;
/** /**
* Custom application data. * Custom application data.
*/ */
...@@ -60,6 +68,14 @@ export type DataProducerEvents = ...@@ -60,6 +68,14 @@ export type DataProducerEvents =
export type DataProducerObserverEvents = export type DataProducerObserverEvents =
{ {
close: []; close: [];
pause: [];
resume: [];
};
type DataProducerDump = DataProducerData &
{
id: string;
paused: boolean;
}; };
type DataProducerInternal = TransportInternal & type DataProducerInternal = TransportInternal &
...@@ -89,12 +105,12 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -89,12 +105,12 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// Channel instance. // Channel instance.
readonly #channel: Channel; readonly #channel: Channel;
// PayloadChannel instance.
readonly #payloadChannel: PayloadChannel;
// Closed flag. // Closed flag.
#closed = false; #closed = false;
// Paused flag.
#paused = false;
// Custom app data. // Custom app data.
#appData: DataProducerAppData; #appData: DataProducerAppData;
...@@ -109,14 +125,14 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -109,14 +125,14 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
internal, internal,
data, data,
channel, channel,
payloadChannel, paused,
appData appData
}: }:
{ {
internal: DataProducerInternal; internal: DataProducerInternal;
data: DataProducerData; data: DataProducerData;
channel: Channel; channel: Channel;
payloadChannel: PayloadChannel; paused: boolean;
appData?: DataProducerAppData; appData?: DataProducerAppData;
} }
) )
...@@ -128,7 +144,7 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -128,7 +144,7 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
this.#internal = internal; this.#internal = internal;
this.#data = data; this.#data = data;
this.#channel = channel; this.#channel = channel;
this.#payloadChannel = payloadChannel; this.#paused = paused;
this.#appData = appData || {} as DataProducerAppData; this.#appData = appData || {} as DataProducerAppData;
this.handleWorkerNotifications(); this.handleWorkerNotifications();
...@@ -182,6 +198,14 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -182,6 +198,14 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
return this.#data.protocol; return this.#data.protocol;
} }
/**
* Whether the DataProducer is paused.
*/
get paused(): boolean
{
return this.#paused;
}
/** /**
* App custom data. * App custom data.
*/ */
...@@ -222,12 +246,18 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -222,12 +246,18 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// Remove notification subscriptions. // Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataProducerId); 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) this.#channel.request(
.catch(() => {}); FbsRequest.Method.TRANSPORT_CLOSE_DATAPRODUCER,
FbsRequest.Body.Transport_CloseDataProducerRequest,
requestOffset,
this.#internal.transportId
).catch(() => {});
this.emit('@close'); this.emit('@close');
...@@ -253,7 +283,6 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -253,7 +283,6 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// Remove notification subscriptions. // Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataProducerId); this.#channel.removeAllListeners(this.#internal.dataProducerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataProducerId);
this.safeEmit('transportclose'); this.safeEmit('transportclose');
...@@ -264,11 +293,23 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -264,11 +293,23 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
/** /**
* Dump DataProducer. * Dump DataProducer.
*/ */
async dump(): Promise<any> async dump(): Promise<DataProducerDump>
{ {
logger.debug('dump()'); 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> ...@@ -278,13 +319,80 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
{ {
logger.debug('getStats()'); 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 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)) if (typeof message !== 'string' && !Buffer.isBuffer(message))
{ {
...@@ -324,10 +432,35 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -324,10 +432,35 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
message = Buffer.alloc(1); 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( dataOffset = FbsDataProducer.SendNotification.createDataVector(builder, message);
'dataProducer.send', this.#internal.dataProducerId, notifData, 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 private handleWorkerNotifications(): void
...@@ -335,3 +468,57 @@ export class DataProducer<DataProducerAppData extends AppData = AppData> ...@@ -335,3 +468,57 @@ export class DataProducer<DataProducerAppData extends AppData = AppData>
// No need to subscribe to any event. // 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())
};
}
import { EventEmitter } from 'events'; import { EventEmitter } from 'node:events';
import { Logger } from './Logger'; import { Logger } from './Logger';
const logger = new Logger('EnhancedEventEmitter'); const logger = new Logger('EnhancedEventEmitter');
......
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
import * as fs from 'node:fs';
import * as path from 'node:path';
import { Logger } from './Logger'; import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { workerBin, Worker, WorkerSettings } from './Worker'; import { workerBin, Worker, WorkerSettings } from './Worker';
...@@ -5,7 +7,6 @@ import * as utils from './utils'; ...@@ -5,7 +7,6 @@ import * as utils from './utils';
import { supportedRtpCapabilities } from './supportedRtpCapabilities'; import { supportedRtpCapabilities } from './supportedRtpCapabilities';
import { RtpCapabilities } from './RtpParameters'; import { RtpCapabilities } from './RtpParameters';
import * as types from './types'; import * as types from './types';
import { AppData } from './types';
/** /**
* Expose all types. * Expose all types.
...@@ -15,15 +16,15 @@ export { types }; ...@@ -15,15 +16,15 @@ export { types };
/** /**
* Expose mediasoup version. * Expose mediasoup version.
*/ */
export const version = '__MEDIASOUP_VERSION__'; export const { version } = JSON.parse(fs.readFileSync(
path.join(__dirname, '..', '..', 'package.json'), { encoding: 'utf-8' }
));
/** /**
* Expose parseScalabilityMode() function. * Expose parseScalabilityMode() function.
*/ */
export { parse as parseScalabilityMode } from './scalabilityModes'; export { parse as parseScalabilityMode } from './scalabilityModes';
const logger = new Logger();
export type ObserverEvents = export type ObserverEvents =
{ {
newworker: [Worker]; newworker: [Worker];
...@@ -41,10 +42,12 @@ export { observer }; ...@@ -41,10 +42,12 @@ export { observer };
*/ */
export { workerBin }; export { workerBin };
const logger = new Logger();
/** /**
* Create a Worker. * Create a Worker.
*/ */
export async function createWorker<WorkerAppData extends AppData = AppData>( export async function createWorker<WorkerAppData extends types.AppData = types.AppData>(
{ {
logLevel = 'error', logLevel = 'error',
logTags, logTags,
......
差异被折叠。
import * as mediasoup from '../'; import * as mediasoup from '../';
const { createWorker } = mediasoup;
let worker: mediasoup.types.Worker; let worker: mediasoup.types.Worker;
let router: mediasoup.types.Router; let router: mediasoup.types.Router;
let activeSpeakerObserver: mediasoup.types.ActiveSpeakerObserver; let activeSpeakerObserver: mediasoup.types.ActiveSpeakerObserver;
...@@ -23,7 +21,7 @@ const mediaCodecs: mediasoup.types.RtpCodecCapability[] = ...@@ -23,7 +21,7 @@ const mediaCodecs: mediasoup.types.RtpCodecCapability[] =
beforeAll(async () => beforeAll(async () =>
{ {
worker = await createWorker(); worker = await mediasoup.createWorker();
router = await worker.createRouter({ mediaCodecs }); router = await worker.createRouter({ mediaCodecs });
}); });
......
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论