Unverified 提交 c8a71130 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo 提交者: GitHub

Node: Remove compiled JavaScript from repository and compile TypeScript code on…

Node: Remove compiled JavaScript from repository and compile TypeScript code on NPM `prepare` script on demand when installed via git (#954)
上级 47147afe
# Tell GitHub to ignore some folders when detecting the project language.
art/* linguist-vendored=true
doc/* linguist-vendored=true
node/lib/* linguist-vendored=true
node/test/* linguist-vendored=true
rust/benches/* linguist-vendored=true
rust/examples/* linguist-vendored=true
......
......@@ -41,5 +41,4 @@ jobs:
- run: npm install
- run: npm run lint:node
if: runner.os == 'Linux'
- run: npm run typescript:build
- run: npm run test:node
......@@ -3,34 +3,35 @@
!/worker/subprojects/*.wrap
## Node.
/node_modules/
/node_modules
/node/lib
## Rust.
/Cargo.lock
/rust/examples-frontend/*/node_modules/
/rust/examples-frontend/*/node_modules
/rust/examples-frontend/*/package-lock.json
/target/
/target
## Worker.
/worker/out/
/worker/scripts/node_modules/
/worker/out
/worker/scripts/node_modules
# Vistual Studio generated Stuff.
/worker/**/Debug/
/worker/**/Release/
/worker/.vs/
/worker/**/Debug
/worker/**/Release
/worker/.vs
# clang-fuzzer stuff is too big.
/worker/deps/clang-fuzzer/
/worker/deps/clang-fuzzer
# Ignore all fuzzer generated test inputs.
/worker/fuzzer/new-corpus/*
!/worker/fuzzer/new-corpus/.placeholder
## Others.
/coverage/
/NO_GIT/
/coverage
/NO_GIT
*.swp
*.swo
.DS_Store/
.DS_Store
# Vistual Studio Code stuff.
/.vscode/
/.vscode
# JetBrains IDE stuff.
/.idea/
/.idea
package-lock=false
# Generate package-lock.json.
package-lock=true
# For bad node/npm version to throw actual error.
engine-strict=true
......@@ -3,6 +3,7 @@
### NEXT
* Node: Remove compiled JavaScript from repository and compile TypeScript code on NPM `prepare` script on demand when installed via git (PR #954).
* `Worker`: Add `RTC::Shared` singleton for RTC entities (PR #953).
......
......@@ -17,6 +17,12 @@ Compiles mediasoup TypeScript code (`lib` folder) JavaScript and places it into
Compiles mediasoup TypeScript code (`lib` folder) JavaScript, places it into the `lib` directory an watches for changes in the TypeScript files.
### `npm run worker:build`
Builds the `mediasoup-worker` binary. It invokes `make`below.
### `npm run lint`
Runs both `npm run lint:node` and `npm run lint:worker`.
......@@ -57,41 +63,30 @@ Runs [Catch2](https://github.com/catchorg/Catch2) test units located at `worker/
Same as `npm run test:node` but it also opens a browser window with JavaScript coverage results.
## Makefile
### `npm run install-deps:node`
The `worker` folder contains a `Makefile` for the mediasoup-worker C++ subproject. It includes the following tasks:
Installs NPM dependencies and updates `package-lock.json`.
### `make` or `make mediasoup-worker`
### `npm run install-clang-tools`
Builds the `mediasoup-worker` binary at `worker/out/Release/`.
Installs clang tools needed for local development.
If the "MEDIASOUP_MAX_CORES" environment variable is set, the build process will use that number of CPU cores. Otherwise it will auto-detect the number of cores in the machine.
"MEDIASOUP_BUILDTYPE" environment variable controls build types, `Release` and `Debug` are presets optimized for those use cases.
Other build types are possible too, but they are not presets and will require "MESON_ARGS" use to customize build configuration.
Check the meaning of useful macros in the `worker/include/Logger.hpp` header file if you want to enable tracing or other debug information.
Binary is built at `worker/out/MEDIASOUP_BUILDTYPE/build`.
## Makefile
In order to instruct the mediasoup Node.js module to use the `Debug` mediasoup-worker binary, an environment variable must be set before running the Node.js application:
The `worker` folder contains a `Makefile` for the mediasoup-worker C++ subproject. It includes the following tasks:
```bash
$ MEDIASOUP_BUILDTYPE=Debug node myapp.js
```
If the "MEDIASOUP_WORKER_BIN" environment variable is set, mediasoup will use the it as mediasoup-worker binary and **won't** compile the binary:
### `make` or `make mediasoup-worker`
```bash
$ MEDIASOUP_WORKER_BIN="/home/xxx/src/foo/mediasoup-worker" node myapp.js
```
Alias of ``make mediasoup-worker` below.
### `make libmediasoup-worker`
### `make meson-ninja`
Builds the `libmediasoup-worker` static library at `worker/out/Release/`.
Installs `meson` and `ninja`.
`MEDIASOUP_MAX_CORES` and `MEDIASOUP_BUILDTYPE` environment variables from above still apply for static library build.
### `make clean`
......@@ -128,6 +123,39 @@ $ make update-wrap-file SUBPROJECT=openssl
```
### `make mediasoup-worker`
Builds the `mediasoup-worker` binary at `worker/out/Release/`.
If the "MEDIASOUP_MAX_CORES" environment variable is set, the build process will use that number of CPU cores. Otherwise it will auto-detect the number of cores in the machine.
"MEDIASOUP_BUILDTYPE" environment variable controls build types, `Release` and `Debug` are presets optimized for those use cases.
Other build types are possible too, but they are not presets and will require "MESON_ARGS" use to customize build configuration.
Check the meaning of useful macros in the `worker/include/Logger.hpp` header file if you want to enable tracing or other debug information.
Binary is built at `worker/out/MEDIASOUP_BUILDTYPE/build`.
In order to instruct the mediasoup Node.js module to use the `Debug` mediasoup-worker binary, an environment variable must be set before running the Node.js application:
```bash
$ MEDIASOUP_BUILDTYPE=Debug node myapp.js
```
If the "MEDIASOUP_WORKER_BIN" environment variable is set, mediasoup will use the it as mediasoup-worker binary and **won't** compile the binary:
```bash
$ MEDIASOUP_WORKER_BIN="/home/xxx/src/foo/mediasoup-worker" node myapp.js
```
### `make libmediasoup-worker`
Builds the `libmediasoup-worker` static library at `worker/out/Release/`.
`MEDIASOUP_MAX_CORES` and `MEDIASOUP_BUILDTYPE` environment variables from above still apply for static library build.
### `make xcode`
Builds a Xcode project for the mediasoup-worker subproject.
......
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { RtpObserver, RtpObserverEvents, RtpObserverObserverEvents, RtpObserverConstructorOptions } from './RtpObserver';
import { Producer } from './Producer';
export declare type ActiveSpeakerObserverOptions = {
interval?: number;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type ActiveSpeakerObserverDominantSpeaker = {
/**
* The audio Producer instance.
*/
producer: Producer;
};
export declare type ActiveSpeakerObserverEvents = RtpObserverEvents & {
dominantspeaker: [ActiveSpeakerObserverDominantSpeaker];
};
export declare type ActiveSpeakerObserverObserverEvents = RtpObserverObserverEvents & {
dominantspeaker: [ActiveSpeakerObserverDominantSpeaker];
};
declare type RtpObserverObserverConstructorOptions = RtpObserverConstructorOptions;
export declare class ActiveSpeakerObserver extends RtpObserver<ActiveSpeakerObserverEvents> {
/**
* @private
*/
constructor(options: RtpObserverObserverConstructorOptions);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<ActiveSpeakerObserverObserverEvents>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=ActiveSpeakerObserver.d.ts.map
\ No newline at end of file
{"version":3,"file":"ActiveSpeakerObserver.d.ts","sourceRoot":"","sources":["../src/ActiveSpeakerObserver.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EACN,WAAW,EACX,iBAAiB,EACjB,yBAAyB,EACzB,6BAA6B,EAC7B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,oBAAY,4BAA4B,GACxC;IACC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF,oBAAY,oCAAoC,GAChD;IACC;;OAEG;IACH,QAAQ,EAAE,QAAQ,CAAC;CACnB,CAAC;AAEF,oBAAY,2BAA2B,GAAG,iBAAiB,GAC3D;IACC,eAAe,EAAE,CAAC,oCAAoC,CAAC,CAAC;CACxD,CAAC;AAEF,oBAAY,mCAAmC,GAAG,yBAAyB,GAC3E;IACC,eAAe,EAAE,CAAC,oCAAoC,CAAC,CAAC;CACxD,CAAC;AAEF,aAAK,qCAAqC,GAAG,6BAA6B,CAAC;AAI3E,qBAAa,qBAAsB,SAAQ,WAAW,CAAC,2BAA2B,CAAC;IAElF;;OAEG;gBACS,OAAO,EAAE,qCAAqC;IAO1D;;OAEG;IACH,IAAI,QAAQ,IAAI,oBAAoB,CAAC,mCAAmC,CAAC,CAGxE;IAED,OAAO,CAAC,yBAAyB;CA+BjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActiveSpeakerObserver = void 0;
const Logger_1 = require("./Logger");
const RtpObserver_1 = require("./RtpObserver");
const logger = new Logger_1.Logger('ActiveSpeakerObserver');
class ActiveSpeakerObserver extends RtpObserver_1.RtpObserver {
/**
* @private
*/
constructor(options) {
super(options);
this.handleWorkerNotifications();
}
/**
* Observer.
*/
get observer() {
return super.observer;
}
handleWorkerNotifications() {
this.channel.on(this.internal.rtpObserverId, (event, data) => {
switch (event) {
case 'dominantspeaker':
{
const producer = this.getProducerById(data.producerId);
if (!producer)
break;
const dominantSpeaker = {
producer
};
this.safeEmit('dominantspeaker', dominantSpeaker);
this.observer.safeEmit('dominantspeaker', dominantSpeaker);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.ActiveSpeakerObserver = ActiveSpeakerObserver;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { RtpObserver, RtpObserverEvents, RtpObserverObserverEvents, RtpObserverConstructorOptions } from './RtpObserver';
import { Producer } from './Producer';
export declare type AudioLevelObserverOptions = {
/**
* Maximum number of entries in the 'volumes”' event. Default 1.
*/
maxEntries?: number;
/**
* Minimum average volume (in dBvo from -127 to 0) for entries in the
* 'volumes' event. Default -80.
*/
threshold?: number;
/**
* Interval in ms for checking audio volumes. Default 1000.
*/
interval?: number;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type AudioLevelObserverVolume = {
/**
* The audio Producer instance.
*/
producer: Producer;
/**
* The average volume (in dBvo from -127 to 0) of the audio Producer in the
* last interval.
*/
volume: number;
};
export declare type AudioLevelObserverEvents = RtpObserverEvents & {
volumes: [AudioLevelObserverVolume[]];
silence: [];
};
export declare type AudioLevelObserverObserverEvents = RtpObserverObserverEvents & {
volumes: [AudioLevelObserverVolume[]];
silence: [];
};
declare type AudioLevelObserverConstructorOptions = RtpObserverConstructorOptions;
export declare class AudioLevelObserver extends RtpObserver<AudioLevelObserverEvents> {
/**
* @private
*/
constructor(options: AudioLevelObserverConstructorOptions);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<AudioLevelObserverObserverEvents>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=AudioLevelObserver.d.ts.map
\ No newline at end of file
{"version":3,"file":"AudioLevelObserver.d.ts","sourceRoot":"","sources":["../src/AudioLevelObserver.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EACN,WAAW,EACX,iBAAiB,EACjB,yBAAyB,EACzB,6BAA6B,EAC7B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,oBAAY,yBAAyB,GACrC;IACC;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF,oBAAY,wBAAwB,GACpC;IACC;;OAEG;IACH,QAAQ,EAAE,QAAQ,CAAC;IAEnB;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,oBAAY,wBAAwB,GAAG,iBAAiB,GACxD;IACC,OAAO,EAAE,CAAC,wBAAwB,EAAE,CAAC,CAAC;IACtC,OAAO,EAAE,EAAE,CAAC;CACZ,CAAC;AAEF,oBAAY,gCAAgC,GAAG,yBAAyB,GACxE;IACC,OAAO,EAAE,CAAC,wBAAwB,EAAE,CAAC,CAAC;IACtC,OAAO,EAAE,EAAE,CAAC;CACZ,CAAC;AAEF,aAAK,oCAAoC,GAAG,6BAA6B,CAAC;AAI1E,qBAAa,kBAAmB,SAAQ,WAAW,CAAC,wBAAwB,CAAC;IAE5E;;OAEG;gBACS,OAAO,EAAE,oCAAoC;IAOzD;;OAEG;IACH,IAAI,QAAQ,IAAI,oBAAoB,CAAC,gCAAgC,CAAC,CAGrE;IAED,OAAO,CAAC,yBAAyB;CA+CjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioLevelObserver = void 0;
const Logger_1 = require("./Logger");
const RtpObserver_1 = require("./RtpObserver");
const logger = new Logger_1.Logger('AudioLevelObserver');
class AudioLevelObserver extends RtpObserver_1.RtpObserver {
/**
* @private
*/
constructor(options) {
super(options);
this.handleWorkerNotifications();
}
/**
* Observer.
*/
get observer() {
return super.observer;
}
handleWorkerNotifications() {
this.channel.on(this.internal.rtpObserverId, (event, data) => {
switch (event) {
case 'volumes':
{
// Get the corresponding Producer instance and remove entries with
// no Producer (it may have been closed in the meanwhile).
const volumes = data
.map(({ producerId, volume }) => ({
producer: this.getProducerById(producerId),
volume
}))
.filter(({ producer }) => producer);
if (volumes.length > 0) {
this.safeEmit('volumes', volumes);
// Emit observer event.
this.observer.safeEmit('volumes', volumes);
}
break;
}
case 'silence':
{
this.safeEmit('silence');
// Emit observer event.
this.observer.safeEmit('silence');
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.AudioLevelObserver = AudioLevelObserver;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
export declare class Channel extends EnhancedEventEmitter {
#private;
/**
* @private
*/
constructor({ producerSocket, consumerSocket, pid }: {
producerSocket: any;
consumerSocket: any;
pid: number;
});
/**
* @private
*/
close(): void;
/**
* @private
*/
request(method: string, handlerId?: string, data?: any): Promise<any>;
private processMessage;
}
//# sourceMappingURL=Channel.d.ts.map
\ No newline at end of file
{"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,OAAQ,SAAQ,oBAAoB;;IAoBhD;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,GAAG,EACH,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;QACpB,GAAG,EAAE,MAAM,CAAC;KACZ;IAiIF;;OAEG;IACH,KAAK,IAAI,IAAI;IAmCb;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAoD3E,OAAO,CAAC,cAAc;CA+DtB"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Channel = void 0;
const os = require("os");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const errors_1 = require("./errors");
const littleEndian = os.endianness() == 'LE';
const logger = new Logger_1.Logger('Channel');
// Binary length for a 4194304 bytes payload.
const MESSAGE_MAX_LEN = 4194308;
const PAYLOAD_MAX_LEN = 4194304;
class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Closed flag.
#closed = false;
// Unix Socket instance for sending messages to the worker process.
#producerSocket;
// Unix Socket instance for receiving messages to the worker process.
#consumerSocket;
// Next id for messages sent to the worker process.
#nextId = 0;
// Map of pending sent requests.
#sents = new Map();
// Buffer for reading messages from the worker.
#recvBuffer = Buffer.alloc(0);
/**
* @private
*/
constructor({ producerSocket, consumerSocket, pid }) {
super();
logger.debug('constructor()');
this.#producerSocket = producerSocket;
this.#consumerSocket = consumerSocket;
// Read Channel responses/notifications from the worker.
this.#consumerSocket.on('data', (buffer) => {
if (!this.#recvBuffer.length) {
this.#recvBuffer = buffer;
}
else {
this.#recvBuffer = Buffer.concat([this.#recvBuffer, buffer], this.#recvBuffer.length + buffer.length);
}
if (this.#recvBuffer.length > PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit.
this.#recvBuffer = Buffer.alloc(0);
return;
}
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition
{
const readLen = this.#recvBuffer.length - msgStart;
if (readLen < 4) {
// Incomplete data.
break;
}
const dataView = new DataView(this.#recvBuffer.buffer, this.#recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
if (readLen < 4 + msgLen) {
// Incomplete data.
break;
}
const payload = this.#recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
msgStart += 4 + msgLen;
try {
// We can receive JSON messages (Channel messages) or log strings.
switch (payload[0]) {
// 123 = '{' (a Channel JSON message).
case 123:
this.processMessage(JSON.parse(payload.toString('utf8')));
break;
// 68 = 'D' (a debug log).
case 68:
logger.debug(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break;
// 87 = 'W' (a warn log).
case 87:
logger.warn(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break;
// 69 = 'E' (an error log).
case 69:
logger.error(`[pid:${pid} ${payload.toString('utf8', 1)}`);
break;
// 88 = 'X' (a dump log).
case 88:
// eslint-disable-next-line no-console
console.log(payload.toString('utf8', 1));
break;
default:
// eslint-disable-next-line no-console
console.warn(`worker[pid:${pid}] unexpected data: %s`, payload.toString('utf8', 1));
}
}
catch (error) {
logger.error('received invalid message from the worker process: %s', String(error));
}
}
if (msgStart != 0) {
this.#recvBuffer = this.#recvBuffer.slice(msgStart);
}
});
this.#consumerSocket.on('end', () => (logger.debug('Consumer Channel ended by the worker process')));
this.#consumerSocket.on('error', (error) => (logger.error('Consumer Channel error: %s', String(error))));
this.#producerSocket.on('end', () => (logger.debug('Producer Channel ended by the worker process')));
this.#producerSocket.on('error', (error) => (logger.error('Producer Channel error: %s', String(error))));
}
/**
* @private
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Close every pending sent.
for (const sent of this.#sents.values()) {
sent.close();
}
// Remove event listeners but leave a fake 'error' hander to avoid
// propagation.
this.#consumerSocket.removeAllListeners('end');
this.#consumerSocket.removeAllListeners('error');
this.#consumerSocket.on('error', () => { });
this.#producerSocket.removeAllListeners('end');
this.#producerSocket.removeAllListeners('error');
this.#producerSocket.on('error', () => { });
// Destroy the socket after a while to allow pending incoming messages.
setTimeout(() => {
try {
this.#producerSocket.destroy();
}
catch (error) { }
try {
this.#consumerSocket.destroy();
}
catch (error) { }
}, 200);
}
/**
* @private
*/
async request(method, handlerId, data) {
this.#nextId < 4294967295 ? ++this.#nextId : (this.#nextId = 1);
const id = this.#nextId;
logger.debug('request() [method:%s, id:%s]', method, id);
if (this.#closed)
throw new errors_1.InvalidStateError('Channel closed');
const request = `${id}:${method}:${handlerId}:${JSON.stringify(data)}`;
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
// This may throw if closed or remote side ended.
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this.#producerSocket.write(request);
return new Promise((pResolve, pReject) => {
const sent = {
id: id,
method: method,
resolve: (data2) => {
if (!this.#sents.delete(id))
return;
pResolve(data2);
},
reject: (error) => {
if (!this.#sents.delete(id))
return;
pReject(error);
},
close: () => {
pReject(new errors_1.InvalidStateError('Channel closed'));
}
};
// Add sent stuff to the map.
this.#sents.set(id, sent);
});
}
processMessage(msg) {
// If a response, retrieve its associated request.
if (msg.id) {
const sent = this.#sents.get(msg.id);
if (!sent) {
logger.error('received response does not match any sent request [id:%s]', msg.id);
return;
}
if (msg.accepted) {
logger.debug('request succeeded [method:%s, id:%s]', sent.method, sent.id);
sent.resolve(msg.data);
}
else if (msg.error) {
logger.warn('request failed [method:%s, id:%s]: %s', sent.method, sent.id, msg.reason);
switch (msg.error) {
case 'TypeError':
sent.reject(new TypeError(msg.reason));
break;
default:
sent.reject(new Error(msg.reason));
}
}
else {
logger.error('received response is not accepted nor rejected [method:%s, id:%s]', sent.method, sent.id);
}
}
// If a notification emit it to the corresponding entity.
else if (msg.targetId && msg.event) {
// 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
// emit the notification immediately it may reach its target **before**
// the response, destroying the ordered delivery. So we must wait a bit
// here.
// See https://github.com/versatica/mediasoup/issues/510
setImmediate(() => this.emit(String(msg.targetId), msg.event, msg.data));
}
// Otherwise unexpected message.
else {
logger.error('received message is not a response nor a notification');
}
}
}
exports.Channel = Channel;
/// <reference types="node" />
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { TransportInternal } from './Transport';
import { ProducerStat } from './Producer';
import { MediaKind, RtpCapabilities, RtpParameters } from './RtpParameters';
export declare type ConsumerOptions = {
/**
* The id of the Producer to consume.
*/
producerId: string;
/**
* RTP capabilities of the consuming endpoint.
*/
rtpCapabilities: RtpCapabilities;
/**
* Whether the Consumer must start in paused mode. Default false.
*
* When creating a video Consumer, it's recommended to set paused to true,
* then transmit the Consumer parameters to the consuming endpoint and, once
* the consuming endpoint has created its local side Consumer, unpause the
* server side Consumer using the resume() method. This is an optimization
* to make it possible for the consuming endpoint to render the video as far
* as possible. If the server side Consumer was created with paused: false,
* mediasoup will immediately request a key frame to the remote Producer and
* suych a key frame may reach the consuming endpoint even before it's ready
* to consume it, generating “black” video until the device requests a keyframe
* by itself.
*/
paused?: boolean;
/**
* The MID for the Consumer. If not specified, a sequentially growing
* number will be assigned.
*/
mid?: string;
/**
* Preferred spatial and temporal layer for simulcast or SVC media sources.
* If unset, the highest ones are selected.
*/
preferredLayers?: ConsumerLayers;
/**
* Whether this Consumer should ignore DTX packets (only valid for Opus codec).
* If set, DTX packets are not forwarded to the remote Consumer.
*/
ignoreDtx?: Boolean;
/**
* Whether this Consumer should consume all RTP streams generated by the
* Producer.
*/
pipe?: boolean;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
/**
* Valid types for 'trace' event.
*/
export declare type ConsumerTraceEventType = 'rtp' | 'keyframe' | 'nack' | 'pli' | 'fir';
/**
* 'trace' event data.
*/
export declare type ConsumerTraceEventData = {
/**
* Trace type.
*/
type: ConsumerTraceEventType;
/**
* Event timestamp.
*/
timestamp: number;
/**
* Event direction.
*/
direction: 'in' | 'out';
/**
* Per type information.
*/
info: any;
};
export declare type ConsumerScore = {
/**
* The score of the RTP stream of the consumer.
*/
score: number;
/**
* The score of the currently selected RTP stream of the producer.
*/
producerScore: number;
/**
* The scores of all RTP streams in the producer ordered by encoding (just
* useful when the producer uses simulcast).
*/
producerScores: number[];
};
export declare type ConsumerLayers = {
/**
* The spatial layer index (from 0 to N).
*/
spatialLayer: number;
/**
* The temporal layer index (from 0 to N).
*/
temporalLayer?: number;
};
export declare type ConsumerStat = {
type: string;
timestamp: number;
ssrc: number;
rtxSsrc?: number;
kind: string;
mimeType: string;
packetsLost: number;
fractionLost: number;
packetsDiscarded: number;
packetsRetransmitted: number;
packetsRepaired: number;
nackCount: number;
nackPacketCount: number;
pliCount: number;
firCount: number;
score: number;
packetCount: number;
byteCount: number;
bitrate: number;
roundTripTime?: number;
};
/**
* Consumer type.
*/
export declare type ConsumerType = 'simple' | 'simulcast' | 'svc' | 'pipe';
export declare type ConsumerEvents = {
transportclose: [];
producerclose: [];
producerpause: [];
producerresume: [];
score: [ConsumerScore];
layerschange: [ConsumerLayers?];
trace: [ConsumerTraceEventData];
rtp: [Buffer];
'@close': [];
'@producerclose': [];
};
export declare type ConsumerObserverEvents = {
close: [];
pause: [];
resume: [];
score: [ConsumerScore];
layerschange: [ConsumerLayers?];
trace: [ConsumerTraceEventData];
};
declare type ConsumerInternal = TransportInternal & {
consumerId: string;
};
declare type ConsumerData = {
producerId: string;
kind: MediaKind;
rtpParameters: RtpParameters;
type: ConsumerType;
};
export declare class Consumer extends EnhancedEventEmitter<ConsumerEvents> {
#private;
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData, paused, producerPaused, score, preferredLayers }: {
internal: ConsumerInternal;
data: ConsumerData;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
paused: boolean;
producerPaused: boolean;
score?: ConsumerScore;
preferredLayers?: ConsumerLayers;
});
/**
* Consumer id.
*/
get id(): string;
/**
* Associated Producer id.
*/
get producerId(): string;
/**
* Whether the Consumer is closed.
*/
get closed(): boolean;
/**
* Media kind.
*/
get kind(): MediaKind;
/**
* RTP parameters.
*/
get rtpParameters(): RtpParameters;
/**
* Consumer type.
*/
get type(): ConsumerType;
/**
* Whether the Consumer is paused.
*/
get paused(): boolean;
/**
* Whether the associate Producer is paused.
*/
get producerPaused(): boolean;
/**
* Current priority.
*/
get priority(): number;
/**
* Consumer score.
*/
get score(): ConsumerScore;
/**
* Preferred video layers.
*/
get preferredLayers(): ConsumerLayers | undefined;
/**
* Current video layers.
*/
get currentLayers(): ConsumerLayers | undefined;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<ConsumerObserverEvents>;
/**
* @private
* Just for testing purposes.
*/
get channelForTesting(): Channel;
/**
* Close the Consumer.
*/
close(): void;
/**
* Transport was closed.
*
* @private
*/
transportClosed(): void;
/**
* Dump Consumer.
*/
dump(): Promise<any>;
/**
* Get Consumer stats.
*/
getStats(): Promise<Array<ConsumerStat | ProducerStat>>;
/**
* Pause the Consumer.
*/
pause(): Promise<void>;
/**
* Resume the Consumer.
*/
resume(): Promise<void>;
/**
* Set preferred video layers.
*/
setPreferredLayers({ spatialLayer, temporalLayer }: ConsumerLayers): Promise<void>;
/**
* Set priority.
*/
setPriority(priority: number): Promise<void>;
/**
* Unset priority.
*/
unsetPriority(): Promise<void>;
/**
* Request a key frame to the Producer.
*/
requestKeyFrame(): Promise<void>;
/**
* Enable 'trace' event.
*/
enableTraceEvent(types?: ConsumerTraceEventType[]): Promise<void>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=Consumer.d.ts.map
\ No newline at end of file
{"version":3,"file":"Consumer.d.ts","sourceRoot":"","sources":["../src/Consumer.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,WA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AO,CAAC,IAAI,CAAC;IAYpC;;OAEG;IACG,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtC;;OAEG;IACG,gBAAgB,CAAC,KAAK,GAAE,sBAAsB,EAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAU3E,OAAO,CAAC,yBAAyB;CAsIjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Consumer = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const logger = new Logger_1.Logger('Consumer');
class Consumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
#internal;
// Consumer data.
#data;
// Channel instance.
#channel;
// PayloadChannel instance.
#payloadChannel;
// Closed flag.
#closed = false;
// Custom app data.
#appData;
// Paused flag.
#paused = false;
// Associated Producer paused flag.
#producerPaused = false;
// Current priority.
#priority = 1;
// Current score.
#score;
// Preferred layers.
#preferredLayers;
// Curent layers.
#currentLayers;
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData, paused, producerPaused, score = { score: 10, producerScore: 10, producerScores: [] }, preferredLayers }) {
super();
logger.debug('constructor()');
this.#internal = internal;
this.#data = data;
this.#channel = channel;
this.#payloadChannel = payloadChannel;
this.#appData = appData || {};
this.#paused = paused;
this.#producerPaused = producerPaused;
this.#score = score;
this.#preferredLayers = preferredLayers;
this.handleWorkerNotifications();
}
/**
* Consumer id.
*/
get id() {
return this.#internal.consumerId;
}
/**
* Associated Producer id.
*/
get producerId() {
return this.#data.producerId;
}
/**
* Whether the Consumer is closed.
*/
get closed() {
return this.#closed;
}
/**
* Media kind.
*/
get kind() {
return this.#data.kind;
}
/**
* RTP parameters.
*/
get rtpParameters() {
return this.#data.rtpParameters;
}
/**
* Consumer type.
*/
get type() {
return this.#data.type;
}
/**
* Whether the Consumer is paused.
*/
get paused() {
return this.#paused;
}
/**
* Whether the associate Producer is paused.
*/
get producerPaused() {
return this.#producerPaused;
}
/**
* Current priority.
*/
get priority() {
return this.#priority;
}
/**
* Consumer score.
*/
get score() {
return this.#score;
}
/**
* Preferred video layers.
*/
get preferredLayers() {
return this.#preferredLayers;
}
/**
* Current video layers.
*/
get currentLayers() {
return this.#currentLayers;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* @private
* Just for testing purposes.
*/
get channelForTesting() {
return this.#channel;
}
/**
* Close the Consumer.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.consumerId);
this.#payloadChannel.removeAllListeners(this.#internal.consumerId);
const reqData = { consumerId: this.#internal.consumerId };
this.#channel.request('transport.closeConsumer', this.#internal.transportId, reqData)
.catch(() => { });
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Transport was closed.
*
* @private
*/
transportClosed() {
if (this.#closed)
return;
logger.debug('transportClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.consumerId);
this.#payloadChannel.removeAllListeners(this.#internal.consumerId);
this.safeEmit('transportclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump Consumer.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('consumer.dump', this.#internal.consumerId);
}
/**
* Get Consumer stats.
*/
async getStats() {
logger.debug('getStats()');
return this.#channel.request('consumer.getStats', this.#internal.consumerId);
}
/**
* Pause the Consumer.
*/
async pause() {
logger.debug('pause()');
const wasPaused = this.#paused || this.#producerPaused;
await this.#channel.request('consumer.pause', this.#internal.consumerId);
this.#paused = true;
// Emit observer event.
if (!wasPaused)
this.#observer.safeEmit('pause');
}
/**
* Resume the Consumer.
*/
async resume() {
logger.debug('resume()');
const wasPaused = this.#paused || this.#producerPaused;
await this.#channel.request('consumer.resume', this.#internal.consumerId);
this.#paused = false;
// Emit observer event.
if (wasPaused && !this.#producerPaused)
this.#observer.safeEmit('resume');
}
/**
* Set preferred video layers.
*/
async setPreferredLayers({ spatialLayer, temporalLayer }) {
logger.debug('setPreferredLayers()');
const reqData = { spatialLayer, temporalLayer };
const data = await this.#channel.request('consumer.setPreferredLayers', this.#internal.consumerId, reqData);
this.#preferredLayers = data || undefined;
}
/**
* Set priority.
*/
async setPriority(priority) {
logger.debug('setPriority()');
const reqData = { priority };
const data = await this.#channel.request('consumer.setPriority', this.#internal.consumerId, reqData);
this.#priority = data.priority;
}
/**
* Unset priority.
*/
async unsetPriority() {
logger.debug('unsetPriority()');
const reqData = { priority: 1 };
const data = await this.#channel.request('consumer.setPriority', this.#internal.consumerId, reqData);
this.#priority = data.priority;
}
/**
* Request a key frame to the Producer.
*/
async requestKeyFrame() {
logger.debug('requestKeyFrame()');
await this.#channel.request('consumer.requestKeyFrame', this.#internal.consumerId);
}
/**
* Enable 'trace' event.
*/
async enableTraceEvent(types = []) {
logger.debug('enableTraceEvent()');
const reqData = { types };
await this.#channel.request('consumer.enableTraceEvent', this.#internal.consumerId, reqData);
}
handleWorkerNotifications() {
this.#channel.on(this.#internal.consumerId, (event, data) => {
switch (event) {
case 'producerclose':
{
if (this.#closed)
break;
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.consumerId);
this.#payloadChannel.removeAllListeners(this.#internal.consumerId);
this.emit('@producerclose');
this.safeEmit('producerclose');
// Emit observer event.
this.#observer.safeEmit('close');
break;
}
case 'producerpause':
{
if (this.#producerPaused)
break;
const wasPaused = this.#paused || this.#producerPaused;
this.#producerPaused = true;
this.safeEmit('producerpause');
// Emit observer event.
if (!wasPaused)
this.#observer.safeEmit('pause');
break;
}
case 'producerresume':
{
if (!this.#producerPaused)
break;
const wasPaused = this.#paused || this.#producerPaused;
this.#producerPaused = false;
this.safeEmit('producerresume');
// Emit observer event.
if (wasPaused && !this.#paused)
this.#observer.safeEmit('resume');
break;
}
case 'score':
{
const score = data;
this.#score = score;
this.safeEmit('score', score);
// Emit observer event.
this.#observer.safeEmit('score', score);
break;
}
case 'layerschange':
{
const layers = data;
this.#currentLayers = layers;
this.safeEmit('layerschange', layers);
// Emit observer event.
this.#observer.safeEmit('layerschange', layers);
break;
}
case 'trace':
{
const trace = data;
this.safeEmit('trace', trace);
// Emit observer event.
this.#observer.safeEmit('trace', trace);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
this.#payloadChannel.on(this.#internal.consumerId, (event, data, payload) => {
switch (event) {
case 'rtp':
{
if (this.#closed)
break;
const packet = payload;
this.safeEmit('rtp', packet);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.Consumer = Consumer;
/// <reference types="node" />
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { TransportInternal } from './Transport';
import { SctpStreamParameters } from './SctpParameters';
export declare type DataConsumerOptions = {
/**
* The id of the DataProducer to consume.
*/
dataProducerId: string;
/**
* Just if consuming over SCTP.
* Whether data messages must be received in order. If true the messages will
* be sent reliably. Defaults to the value in the DataProducer if it has type
* 'sctp' or to true if it has type 'direct'.
*/
ordered?: boolean;
/**
* Just if consuming over SCTP.
* When ordered is false indicates the time (in milliseconds) after which a
* SCTP packet will stop being retransmitted. Defaults to the value in the
* DataProducer if it has type 'sctp' or unset if it has type 'direct'.
*/
maxPacketLifeTime?: number;
/**
* Just if consuming over SCTP.
* When ordered is false indicates the maximum number of times a packet will
* be retransmitted. Defaults to the value in the DataProducer if it has type
* 'sctp' or unset if it has type 'direct'.
*/
maxRetransmits?: number;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type DataConsumerStat = {
type: string;
timestamp: number;
label: string;
protocol: string;
messagesSent: number;
bytesSent: number;
bufferedAmount: number;
};
/**
* DataConsumer type.
*/
export declare type DataConsumerType = 'sctp' | 'direct';
export declare type DataConsumerEvents = {
transportclose: [];
dataproducerclose: [];
message: [Buffer, number];
sctpsendbufferfull: [];
bufferedamountlow: [number];
'@close': [];
'@dataproducerclose': [];
};
export declare type DataConsumerObserverEvents = {
close: [];
};
declare type DataConsumerInternal = TransportInternal & {
dataConsumerId: string;
};
declare type DataConsumerData = {
dataProducerId: string;
type: DataConsumerType;
sctpStreamParameters?: SctpStreamParameters;
label: string;
protocol: string;
};
export declare class DataConsumer extends EnhancedEventEmitter<DataConsumerEvents> {
#private;
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData }: {
internal: DataConsumerInternal;
data: DataConsumerData;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
});
/**
* DataConsumer id.
*/
get id(): string;
/**
* Associated DataProducer id.
*/
get dataProducerId(): string;
/**
* Whether the DataConsumer is closed.
*/
get closed(): boolean;
/**
* DataConsumer type.
*/
get type(): DataConsumerType;
/**
* SCTP stream parameters.
*/
get sctpStreamParameters(): SctpStreamParameters | undefined;
/**
* DataChannel label.
*/
get label(): string;
/**
* DataChannel protocol.
*/
get protocol(): string;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<DataConsumerObserverEvents>;
/**
* Close the DataConsumer.
*/
close(): void;
/**
* Transport was closed.
*
* @private
*/
transportClosed(): void;
/**
* Dump DataConsumer.
*/
dump(): Promise<any>;
/**
* Get DataConsumer stats.
*/
getStats(): Promise<DataConsumerStat[]>;
/**
* Set buffered amount low threshold.
*/
setBufferedAmountLowThreshold(threshold: number): Promise<void>;
/**
* Send data.
*/
send(message: string | Buffer, ppid?: number): Promise<void>;
/**
* Get buffered amount size.
*/
getBufferedAmount(): Promise<number>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=DataConsumer.d.ts.map
\ No newline at end of file
{"version":3,"file":"DataConsumer.d.ts","sourceRoot":"","sources":["../src/DataCon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,IAAI,oBAAoB,CAAC,0BAA0B,CAAC,CAG/D;IAED;;OAEG;IACH,KAAK,IAAI,IAAI;IAwBb;;;;OAIG;IACH,eAAe,IAAI,IAAI;IAmBvB;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAO1B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAO7C;;OAEG;IACG,6BAA6B,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUrE;;OAEG;IACG,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0ClE;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC;IAU1C,OAAO,CAAC,yBAAyB;CA2EjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataConsumer = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const logger = new Logger_1.Logger('DataConsumer');
class DataConsumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
#internal;
// DataConsumer data.
#data;
// Channel instance.
#channel;
// PayloadChannel instance.
#payloadChannel;
// Closed flag.
#closed = false;
// Custom app data.
#appData;
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData }) {
super();
logger.debug('constructor()');
this.#internal = internal;
this.#data = data;
this.#channel = channel;
this.#payloadChannel = payloadChannel;
this.#appData = appData || {};
this.handleWorkerNotifications();
}
/**
* DataConsumer id.
*/
get id() {
return this.#internal.dataConsumerId;
}
/**
* Associated DataProducer id.
*/
get dataProducerId() {
return this.#data.dataProducerId;
}
/**
* Whether the DataConsumer is closed.
*/
get closed() {
return this.#closed;
}
/**
* DataConsumer type.
*/
get type() {
return this.#data.type;
}
/**
* SCTP stream parameters.
*/
get sctpStreamParameters() {
return this.#data.sctpStreamParameters;
}
/**
* DataChannel label.
*/
get label() {
return this.#data.label;
}
/**
* DataChannel protocol.
*/
get protocol() {
return this.#data.protocol;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* Close the DataConsumer.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataConsumerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataConsumerId);
const reqData = { dataConsumerId: this.#internal.dataConsumerId };
this.#channel.request('transport.closeDataConsumer', this.#internal.transportId, reqData)
.catch(() => { });
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Transport was closed.
*
* @private
*/
transportClosed() {
if (this.#closed)
return;
logger.debug('transportClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataConsumerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataConsumerId);
this.safeEmit('transportclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump DataConsumer.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('dataConsumer.dump', this.#internal.dataConsumerId);
}
/**
* Get DataConsumer stats.
*/
async getStats() {
logger.debug('getStats()');
return this.#channel.request('dataConsumer.getStats', this.#internal.dataConsumerId);
}
/**
* Set buffered amount low threshold.
*/
async setBufferedAmountLowThreshold(threshold) {
logger.debug('setBufferedAmountLowThreshold() [threshold:%s]', threshold);
const reqData = { threshold };
await this.#channel.request('dataConsumer.setBufferedAmountLowThreshold', this.#internal.dataConsumerId, reqData);
}
/**
* Send data.
*/
async send(message, ppid) {
if (typeof message !== 'string' && !Buffer.isBuffer(message)) {
throw new TypeError('message must be a string or a Buffer');
}
/*
* +-------------------------------+----------+
* | Value | SCTP |
* | | PPID |
* +-------------------------------+----------+
* | WebRTC String | 51 |
* | WebRTC Binary Partial | 52 |
* | (Deprecated) | |
* | WebRTC Binary | 53 |
* | WebRTC String Partial | 54 |
* | (Deprecated) | |
* | WebRTC String Empty | 56 |
* | WebRTC Binary Empty | 57 |
* +-------------------------------+----------+
*/
if (typeof ppid !== 'number') {
ppid = (typeof message === 'string')
? message.length > 0 ? 51 : 56
: message.length > 0 ? 53 : 57;
}
// Ensure we honor PPIDs.
if (ppid === 56)
message = ' ';
else if (ppid === 57)
message = Buffer.alloc(1);
const requestData = String(ppid);
await this.#payloadChannel.request('dataConsumer.send', this.#internal.dataConsumerId, requestData, message);
}
/**
* Get buffered amount size.
*/
async getBufferedAmount() {
logger.debug('getBufferedAmount()');
const { bufferedAmount } = await this.#channel.request('dataConsumer.getBufferedAmount', this.#internal.dataConsumerId);
return bufferedAmount;
}
handleWorkerNotifications() {
this.#channel.on(this.#internal.dataConsumerId, (event, data) => {
switch (event) {
case 'dataproducerclose':
{
if (this.#closed)
break;
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataConsumerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataConsumerId);
this.emit('@dataproducerclose');
this.safeEmit('dataproducerclose');
// Emit observer event.
this.#observer.safeEmit('close');
break;
}
case 'sctpsendbufferfull':
{
this.safeEmit('sctpsendbufferfull');
break;
}
case 'bufferedamountlow':
{
const { bufferedAmount } = data;
this.safeEmit('bufferedamountlow', bufferedAmount);
break;
}
default:
{
logger.error('ignoring unknown event "%s" in channel listener', event);
}
}
});
this.#payloadChannel.on(this.#internal.dataConsumerId, (event, data, payload) => {
switch (event) {
case 'message':
{
if (this.#closed)
break;
const ppid = data.ppid;
const message = payload;
this.safeEmit('message', message, ppid);
break;
}
default:
{
logger.error('ignoring unknown event "%s" in payload channel listener', event);
}
}
});
}
}
exports.DataConsumer = DataConsumer;
/// <reference types="node" />
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { TransportInternal } from './Transport';
import { SctpStreamParameters } from './SctpParameters';
export declare type DataProducerOptions = {
/**
* DataProducer id (just for Router.pipeToRouter() method).
*/
id?: string;
/**
* SCTP parameters defining how the endpoint is sending the data.
* Just if messages are sent over SCTP.
*/
sctpStreamParameters?: SctpStreamParameters;
/**
* A label which can be used to distinguish this DataChannel from others.
*/
label?: string;
/**
* Name of the sub-protocol used by this DataChannel.
*/
protocol?: string;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type DataProducerStat = {
type: string;
timestamp: number;
label: string;
protocol: string;
messagesReceived: number;
bytesReceived: number;
};
/**
* DataProducer type.
*/
export declare type DataProducerType = 'sctp' | 'direct';
export declare type DataProducerEvents = {
transportclose: [];
'@close': [];
};
export declare type DataProducerObserverEvents = {
close: [];
};
declare type DataProducerInternal = TransportInternal & {
dataProducerId: string;
};
declare type DataProducerData = {
type: DataProducerType;
sctpStreamParameters?: SctpStreamParameters;
label: string;
protocol: string;
};
export declare class DataProducer extends EnhancedEventEmitter<DataProducerEvents> {
#private;
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData }: {
internal: DataProducerInternal;
data: DataProducerData;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
});
/**
* DataProducer id.
*/
get id(): string;
/**
* Whether the DataProducer is closed.
*/
get closed(): boolean;
/**
* DataProducer type.
*/
get type(): DataProducerType;
/**
* SCTP stream parameters.
*/
get sctpStreamParameters(): SctpStreamParameters | undefined;
/**
* DataChannel label.
*/
get label(): string;
/**
* DataChannel protocol.
*/
get protocol(): string;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<DataProducerObserverEvents>;
/**
* Close the DataProducer.
*/
close(): void;
/**
* Transport was closed.
*
* @private
*/
transportClosed(): void;
/**
* Dump DataProducer.
*/
dump(): Promise<any>;
/**
* Get DataProducer stats.
*/
getStats(): Promise<DataProducerStat[]>;
/**
* Send data (just valid for DataProducers created on a DirectTransport).
*/
send(message: string | Buffer, ppid?: number): void;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=DataProducer.d.ts.map
\ No newline at end of file
{"version":3,"file":"DataProducer.d.ts","sourceRoot":"","sources":["../src/DataProducer.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,oBAAY,mBAAmB,GAC/B;IACC;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ;;;OAGG;IACH,oBAAoB,CAAC,EAAE,oBAAoB,CAAC;IAE5C;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF,oBAAY,gBAAgB,GAC5B;IACC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,EAAE,MAAM,CAAC;IACzB,aAAa,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,oBAAY,gBAAgB,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEjD,oBAAY,kBAAkB,GAC9B;IACC,cAAc,EAAE,EAAE,CAAC;IAEnB,QAAQ,EAAE,EAAE,CAAC;CACb,CAAC;AAEF,oBAAY,0BAA0B,GACtC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b;;;;OAIG;IACH,eAAe,IAAI,IAAI;IAmBvB;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAO1B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAO7C;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;IA0CnD,OAAO,CAAC,yBAAyB;CAIjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataProducer = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const logger = new Logger_1.Logger('DataProducer');
class DataProducer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
#internal;
// DataProducer data.
#data;
// Channel instance.
#channel;
// PayloadChannel instance.
#payloadChannel;
// Closed flag.
#closed = false;
// Custom app data.
#appData;
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData }) {
super();
logger.debug('constructor()');
this.#internal = internal;
this.#data = data;
this.#channel = channel;
this.#payloadChannel = payloadChannel;
this.#appData = appData || {};
this.handleWorkerNotifications();
}
/**
* DataProducer id.
*/
get id() {
return this.#internal.dataProducerId;
}
/**
* Whether the DataProducer is closed.
*/
get closed() {
return this.#closed;
}
/**
* DataProducer type.
*/
get type() {
return this.#data.type;
}
/**
* SCTP stream parameters.
*/
get sctpStreamParameters() {
return this.#data.sctpStreamParameters;
}
/**
* DataChannel label.
*/
get label() {
return this.#data.label;
}
/**
* DataChannel protocol.
*/
get protocol() {
return this.#data.protocol;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* Close the DataProducer.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataProducerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataProducerId);
const reqData = { dataProducerId: this.#internal.dataProducerId };
this.#channel.request('transport.closeDataProducer', this.#internal.transportId, reqData)
.catch(() => { });
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Transport was closed.
*
* @private
*/
transportClosed() {
if (this.#closed)
return;
logger.debug('transportClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.dataProducerId);
this.#payloadChannel.removeAllListeners(this.#internal.dataProducerId);
this.safeEmit('transportclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump DataProducer.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('dataProducer.dump', this.#internal.dataProducerId);
}
/**
* Get DataProducer stats.
*/
async getStats() {
logger.debug('getStats()');
return this.#channel.request('dataProducer.getStats', this.#internal.dataProducerId);
}
/**
* Send data (just valid for DataProducers created on a DirectTransport).
*/
send(message, ppid) {
if (typeof message !== 'string' && !Buffer.isBuffer(message)) {
throw new TypeError('message must be a string or a Buffer');
}
/*
* +-------------------------------+----------+
* | Value | SCTP |
* | | PPID |
* +-------------------------------+----------+
* | WebRTC String | 51 |
* | WebRTC Binary Partial | 52 |
* | (Deprecated) | |
* | WebRTC Binary | 53 |
* | WebRTC String Partial | 54 |
* | (Deprecated) | |
* | WebRTC String Empty | 56 |
* | WebRTC Binary Empty | 57 |
* +-------------------------------+----------+
*/
if (typeof ppid !== 'number') {
ppid = (typeof message === 'string')
? message.length > 0 ? 51 : 56
: message.length > 0 ? 53 : 57;
}
// Ensure we honor PPIDs.
if (ppid === 56)
message = ' ';
else if (ppid === 57)
message = Buffer.alloc(1);
const notifData = String(ppid);
this.#payloadChannel.notify('dataProducer.send', this.#internal.dataProducerId, notifData, message);
}
handleWorkerNotifications() {
// No need to subscribe to any event.
}
}
exports.DataProducer = DataProducer;
/// <reference types="node" />
import { Transport, TransportEvents, TransportObserverEvents, TransportConstructorOptions } from './Transport';
import { SctpParameters } from './SctpParameters';
export declare type DirectTransportOptions = {
/**
* Maximum allowed size for direct messages sent from DataProducers.
* Default 262144.
*/
maxMessageSize: number;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type DirectTransportStat = {
type: string;
transportId: string;
timestamp: number;
bytesReceived: number;
recvBitrate: number;
bytesSent: number;
sendBitrate: number;
rtpBytesReceived: number;
rtpRecvBitrate: number;
rtpBytesSent: number;
rtpSendBitrate: number;
rtxBytesReceived: number;
rtxRecvBitrate: number;
rtxBytesSent: number;
rtxSendBitrate: number;
probationBytesSent: number;
probationSendBitrate: number;
availableOutgoingBitrate?: number;
availableIncomingBitrate?: number;
maxIncomingBitrate?: number;
};
export declare type DirectTransportEvents = TransportEvents & {
rtcp: [Buffer];
};
export declare type DirectTransportObserverEvents = TransportObserverEvents & {
rtcp: [Buffer];
};
declare type DirectTransportConstructorOptions = TransportConstructorOptions & {
data: DirectTransportData;
};
export declare type DirectTransportData = {
sctpParameters?: SctpParameters;
};
export declare class DirectTransport extends Transport<DirectTransportEvents, DirectTransportObserverEvents> {
#private;
/**
* @private
*/
constructor(options: DirectTransportConstructorOptions);
/**
* Close the DirectTransport.
*
* @override
*/
close(): void;
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed(): void;
/**
* Get DirectTransport stats.
*
* @override
*/
getStats(): Promise<DirectTransportStat[]>;
/**
* NO-OP method in DirectTransport.
*
* @override
*/
connect(): Promise<void>;
/**
* @override
*/
setMaxIncomingBitrate(bitrate: number): Promise<void>;
/**
* @override
*/
setMaxOutgoingBitrate(bitrate: number): Promise<void>;
/**
* Send RTCP packet.
*/
sendRtcp(rtcpPacket: Buffer): void;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=DirectTransport.d.ts.map
\ No newline at end of file
{"version":3,"file":"DirectTransport.d.ts","sourceRoot":"","sources":["../src/DirectTransport.ts"],"names":[],"mappings":";AAEA,O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1B,CAAC;AAEF,oBAAY,mBAAmB,GAC/B;IACC,cAAc,CAAC,EAAE,cAAc,CAAC;CAChC,CAAC;AAIF,qBAAa,eAAgB,SAC5B,SAAS,CAAC,qBAAqB,EAAE,6BAA6B,CAAC;;IAK/D;;OAEG;gBACS,OAAO,EAAE,iCAAiC;IActD;;;;OAIG;IACH,KAAK,IAAI,IAAI;IAQb;;;;;OAKG;IACH,YAAY,IAAI,IAAI;IAQpB;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,mBAAmB,EAAE,CAAC;IAOhD;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;OAEG;IAEG,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAM3D;;OAEG;IAEG,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAM3D;;OAEG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM;IAW3B,OAAO,CAAC,yBAAyB;CAkDjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DirectTransport = void 0;
const Logger_1 = require("./Logger");
const errors_1 = require("./errors");
const Transport_1 = require("./Transport");
const logger = new Logger_1.Logger('DirectTransport');
class DirectTransport extends Transport_1.Transport {
// DirectTransport data.
#data;
/**
* @private
*/
constructor(options) {
super(options);
logger.debug('constructor()');
this.#data =
{
// Nothing.
};
this.handleWorkerNotifications();
}
/**
* Close the DirectTransport.
*
* @override
*/
close() {
if (this.closed)
return;
super.close();
}
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed() {
if (this.closed)
return;
super.routerClosed();
}
/**
* Get DirectTransport stats.
*
* @override
*/
async getStats() {
logger.debug('getStats()');
return this.channel.request('transport.getStats', this.internal.transportId);
}
/**
* NO-OP method in DirectTransport.
*
* @override
*/
async connect() {
logger.debug('connect()');
}
/**
* @override
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async setMaxIncomingBitrate(bitrate) {
throw new errors_1.UnsupportedError('setMaxIncomingBitrate() not implemented in DirectTransport');
}
/**
* @override
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async setMaxOutgoingBitrate(bitrate) {
throw new errors_1.UnsupportedError('setMaxOutgoingBitrate() not implemented in DirectTransport');
}
/**
* Send RTCP packet.
*/
sendRtcp(rtcpPacket) {
if (!Buffer.isBuffer(rtcpPacket)) {
throw new TypeError('rtcpPacket must be a Buffer');
}
this.payloadChannel.notify('transport.sendRtcp', this.internal.transportId, undefined, rtcpPacket);
}
handleWorkerNotifications() {
this.channel.on(this.internal.transportId, (event, data) => {
switch (event) {
case 'trace':
{
const trace = data;
this.safeEmit('trace', trace);
// Emit observer event.
this.observer.safeEmit('trace', trace);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
this.payloadChannel.on(this.internal.transportId, (event, data, payload) => {
switch (event) {
case 'rtcp':
{
if (this.closed)
break;
const packet = payload;
this.safeEmit('rtcp', packet);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.DirectTransport = DirectTransport;
/// <reference types="node" />
import { EventEmitter } from 'events';
declare type Events = Record<string, any[]>;
export declare class EnhancedEventEmitter<E extends Events = Events> extends EventEmitter {
constructor();
emit<K extends keyof E & string>(eventName: K, ...args: E[K]): boolean;
/**
* Special addition to the EventEmitter API.
*/
safeEmit<K extends keyof E & string>(eventName: K, ...args: E[K]): boolean;
on<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
off<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
addListener<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
prependListener<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
once<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
prependOnceListener<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
removeListener<K extends keyof E & string>(eventName: K, listener: (...args: E[K]) => void): this;
removeAllListeners<K extends keyof E & string>(eventName?: K): this;
listenerCount<K extends keyof E & string>(eventName: K): number;
listeners<K extends keyof E & string>(eventName: K): Function[];
rawListeners<K extends keyof E & string>(eventName: K): Function[];
}
export {};
//# sourceMappingURL=EnhancedEventEmitter.d.ts.map
\ No newline at end of file
{"version":3,"file":"EnhancedEventEmitter.d.ts","sourceRoot":"","sources":["../src/EnhancedEventEmitter.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAKtC,aAAK,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC;AAEpC,qBAAa,oBAAoB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,CAAE,SAAQ,YAAY;;IAQhF,IAAI,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO;IAKtE;;OAEG;IACH,QAAQ,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO;IAkB1E,EAAE,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAC5B,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAC7B,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EACrC,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,eAAe,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EACzC,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,IAAI,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAC9B,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,mBAAmB,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAC7C,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EACxC,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,GAC/B,IAAI;IAOP,kBAAkB,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,SAAS,CAAC,EAAE,CAAC,GAAG,IAAI;IAOnE,aAAa,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,MAAM;IAK/D,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,QAAQ,EAAE;IAK/D,YAAY,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,CAAC,GAAG,QAAQ,EAAE;CAIlE"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnhancedEventEmitter = void 0;
const events_1 = require("events");
const Logger_1 = require("./Logger");
const logger = new Logger_1.Logger('EnhancedEventEmitter');
class EnhancedEventEmitter extends events_1.EventEmitter {
constructor() {
super();
this.setMaxListeners(Infinity);
}
emit(eventName, ...args) {
return super.emit(eventName, ...args);
}
/**
* Special addition to the EventEmitter API.
*/
safeEmit(eventName, ...args) {
const numListeners = super.listenerCount(eventName);
try {
return super.emit(eventName, ...args);
}
catch (error) {
logger.error('safeEmit() | event listener threw an error [eventName:%s]:%o', eventName, error);
return Boolean(numListeners);
}
}
on(eventName, listener) {
super.on(eventName, listener);
return this;
}
off(eventName, listener) {
super.off(eventName, listener);
return this;
}
addListener(eventName, listener) {
super.on(eventName, listener);
return this;
}
prependListener(eventName, listener) {
super.prependListener(eventName, listener);
return this;
}
once(eventName, listener) {
super.once(eventName, listener);
return this;
}
prependOnceListener(eventName, listener) {
super.prependOnceListener(eventName, listener);
return this;
}
removeListener(eventName, listener) {
super.off(eventName, listener);
return this;
}
removeAllListeners(eventName) {
super.removeAllListeners(eventName);
return this;
}
listenerCount(eventName) {
return super.listenerCount(eventName);
}
listeners(eventName) {
return super.listeners(eventName);
}
rawListeners(eventName) {
return super.rawListeners(eventName);
}
}
exports.EnhancedEventEmitter = EnhancedEventEmitter;
/// <reference types="debug" />
export declare class Logger {
#private;
constructor(prefix?: string);
get debug(): debug.Debugger;
get warn(): debug.Debugger;
get error(): debug.Debugger;
}
//# sourceMappingURL=Logger.d.ts.map
\ No newline at end of file
{"version":3,"file":"Logger.d.ts","sourceRoot":"","sources":["../src/Logger.ts"],"names":[],"mappings":";AAIA,qBAAa,MAAM;;gBAMN,MAAM,CAAC,EAAE,MAAM;IAsB3B,IAAI,KAAK,IAAI,KAAK,CAAC,QAAQ,CAG1B;IAED,IAAI,IAAI,IAAI,KAAK,CAAC,QAAQ,CAGzB;IAED,IAAI,KAAK,IAAI,KAAK,CAAC,QAAQ,CAG1B;CACD"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
const debug_1 = require("debug");
const APP_NAME = 'mediasoup';
class Logger {
#debug;
#warn;
#error;
constructor(prefix) {
if (prefix) {
this.#debug = (0, debug_1.default)(`${APP_NAME}:${prefix}`);
this.#warn = (0, debug_1.default)(`${APP_NAME}:WARN:${prefix}`);
this.#error = (0, debug_1.default)(`${APP_NAME}:ERROR:${prefix}`);
}
else {
this.#debug = (0, debug_1.default)(APP_NAME);
this.#warn = (0, debug_1.default)(`${APP_NAME}:WARN`);
this.#error = (0, debug_1.default)(`${APP_NAME}:ERROR`);
}
/* eslint-disable no-console */
this.#debug.log = console.info.bind(console);
this.#warn.log = console.warn.bind(console);
this.#error.log = console.error.bind(console);
/* eslint-enable no-console */
}
get debug() {
return this.#debug;
}
get warn() {
return this.#warn;
}
get error() {
return this.#error;
}
}
exports.Logger = Logger;
/// <reference types="node" />
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
export declare class PayloadChannel extends EnhancedEventEmitter {
#private;
/**
* @private
*/
constructor({ producerSocket, consumerSocket }: {
producerSocket: any;
consumerSocket: any;
});
/**
* @private
*/
close(): void;
/**
* @private
*/
notify(event: string, handlerId: string, data: string | undefined, payload: string | Buffer): void;
/**
* @private
*/
request(method: string, handlerId: string, data: string, payload: string | Buffer): Promise<any>;
private processData;
}
//# sourceMappingURL=PayloadChannel.d.ts.map
\ No newline at end of file
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,cAAe,SAAQ,oBAAoB;;IAuBvD;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;KACpB;IAsFF;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Bb;;OAEG;IACH,MAAM,CACL,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IA2CP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAyDxC,OAAO,CAAC,WAAW;CA8FnB"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PayloadChannel = void 0;
const os = require("os");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const errors_1 = require("./errors");
const littleEndian = os.endianness() == 'LE';
const logger = new Logger_1.Logger('PayloadChannel');
// Binary length for a 4194304 bytes payload.
const MESSAGE_MAX_LEN = 4194308;
const PAYLOAD_MAX_LEN = 4194304;
class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Closed flag.
#closed = false;
// Unix Socket instance for sending messages to the worker process.
#producerSocket;
// Unix Socket instance for receiving messages to the worker process.
#consumerSocket;
// Next id for messages sent to the worker process.
#nextId = 0;
// Map of pending sent requests.
#sents = new Map();
// Buffer for reading messages from the worker.
#recvBuffer = Buffer.alloc(0);
// Ongoing notification (waiting for its payload).
#ongoingNotification;
/**
* @private
*/
constructor({ producerSocket, consumerSocket }) {
super();
logger.debug('constructor()');
this.#producerSocket = producerSocket;
this.#consumerSocket = consumerSocket;
// Read PayloadChannel notifications from the worker.
this.#consumerSocket.on('data', (buffer) => {
if (!this.#recvBuffer.length) {
this.#recvBuffer = buffer;
}
else {
this.#recvBuffer = Buffer.concat([this.#recvBuffer, buffer], this.#recvBuffer.length + buffer.length);
}
if (this.#recvBuffer.length > PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit.
this.#recvBuffer = Buffer.alloc(0);
return;
}
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition
{
const readLen = this.#recvBuffer.length - msgStart;
if (readLen < 4) {
// Incomplete data.
break;
}
const dataView = new DataView(this.#recvBuffer.buffer, this.#recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
if (readLen < 4 + msgLen) {
// Incomplete data.
break;
}
const payload = this.#recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
msgStart += 4 + msgLen;
this.processData(payload);
}
if (msgStart != 0) {
this.#recvBuffer = this.#recvBuffer.slice(msgStart);
}
});
this.#consumerSocket.on('end', () => (logger.debug('Consumer PayloadChannel ended by the worker process')));
this.#consumerSocket.on('error', (error) => (logger.error('Consumer PayloadChannel error: %s', String(error))));
this.#producerSocket.on('end', () => (logger.debug('Producer PayloadChannel ended by the worker process')));
this.#producerSocket.on('error', (error) => (logger.error('Producer PayloadChannel error: %s', String(error))));
}
/**
* @private
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove event listeners but leave a fake 'error' handler to avoid
// propagation.
this.#consumerSocket.removeAllListeners('end');
this.#consumerSocket.removeAllListeners('error');
this.#consumerSocket.on('error', () => { });
this.#producerSocket.removeAllListeners('end');
this.#producerSocket.removeAllListeners('error');
this.#producerSocket.on('error', () => { });
// Destroy the socket after a while to allow pending incoming messages.
setTimeout(() => {
try {
this.#producerSocket.destroy();
}
catch (error) { }
try {
this.#consumerSocket.destroy();
}
catch (error) { }
}, 200);
}
/**
* @private
*/
notify(event, handlerId, data, payload) {
logger.debug('notify() [event:%s]', event);
if (this.#closed)
throw new errors_1.InvalidStateError('PayloadChannel closed');
const notification = `n:${event}:${handlerId}:${data}`;
if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big');
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
try {
// This may throw if closed or remote side ended.
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(notification)).buffer));
this.#producerSocket.write(notification);
}
catch (error) {
logger.warn('notify() | sending notification failed: %s', String(error));
return;
}
try {
// This may throw if closed or remote side ended.
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this.#producerSocket.write(payload);
}
catch (error) {
logger.warn('notify() | sending payload failed: %s', String(error));
return;
}
}
/**
* @private
*/
async request(method, handlerId, data, payload) {
this.#nextId < 4294967295 ? ++this.#nextId : (this.#nextId = 1);
const id = this.#nextId;
logger.debug('request() [method:%s, id:%s]', method, id);
if (this.#closed)
throw new errors_1.InvalidStateError('PayloadChannel closed');
const request = `r:${id}:${method}:${handlerId}:${data}`;
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel request too big');
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended.
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this.#producerSocket.write(request);
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this.#producerSocket.write(payload);
return new Promise((pResolve, pReject) => {
const sent = {
id: id,
method: method,
resolve: (data2) => {
if (!this.#sents.delete(id))
return;
pResolve(data2);
},
reject: (error) => {
if (!this.#sents.delete(id))
return;
pReject(error);
},
close: () => {
pReject(new errors_1.InvalidStateError('PayloadChannel closed'));
}
};
// Add sent stuff to the map.
this.#sents.set(id, sent);
});
}
processData(data) {
if (!this.#ongoingNotification) {
let msg;
try {
msg = JSON.parse(data.toString('utf8'));
}
catch (error) {
logger.error('received invalid data from the worker process: %s', String(error));
return;
}
// If a response, retrieve its associated request.
if (msg.id) {
const sent = this.#sents.get(msg.id);
if (!sent) {
logger.error('received response does not match any sent request [id:%s]', msg.id);
return;
}
if (msg.accepted) {
logger.debug('request succeeded [method:%s, id:%s]', sent.method, sent.id);
sent.resolve(msg.data);
}
else if (msg.error) {
logger.warn('request failed [method:%s, id:%s]: %s', sent.method, sent.id, msg.reason);
switch (msg.error) {
case 'TypeError':
sent.reject(new TypeError(msg.reason));
break;
default:
sent.reject(new Error(msg.reason));
}
}
else {
logger.error('received response is not accepted nor rejected [method:%s, id:%s]', sent.method, sent.id);
}
}
// If a notification, create the ongoing notification instance.
else if (msg.targetId && msg.event) {
this.#ongoingNotification =
{
targetId: String(msg.targetId),
event: msg.event,
data: msg.data
};
}
else {
logger.error('received data is not a notification nor a response');
return;
}
}
else {
const payload = data;
// Emit the corresponding event.
this.emit(this.#ongoingNotification.targetId, this.#ongoingNotification.event, this.#ongoingNotification.data, payload);
// Unset ongoing notification.
this.#ongoingNotification = undefined;
}
}
}
exports.PayloadChannel = PayloadChannel;
import { Transport, TransportListenIp, TransportTuple, TransportEvents, TransportObserverEvents, TransportConstructorOptions, SctpState } from './Transport';
import { Consumer } from './Consumer';
import { SctpParameters, NumSctpStreams } from './SctpParameters';
import { SrtpParameters } from './SrtpParameters';
export declare type PipeTransportOptions = {
/**
* Listening IP address.
*/
listenIp: TransportListenIp | string;
/**
* Fixed port to listen on instead of selecting automatically from Worker's port
* range.
*/
port?: number;
/**
* Create a SCTP association. Default false.
*/
enableSctp?: boolean;
/**
* SCTP streams number.
*/
numSctpStreams?: NumSctpStreams;
/**
* Maximum allowed size for SCTP messages sent by DataProducers.
* Default 268435456.
*/
maxSctpMessageSize?: number;
/**
* Maximum SCTP send buffer used by DataConsumers.
* Default 268435456.
*/
sctpSendBufferSize?: number;
/**
* Enable RTX and NACK for RTP retransmission. Useful if both Routers are
* located in different hosts and there is packet lost in the link. For this
* to work, both PipeTransports must enable this setting. Default false.
*/
enableRtx?: boolean;
/**
* Enable SRTP. Useful to protect the RTP and RTCP traffic if both Routers
* are located in different hosts. For this to work, connect() must be called
* with remote SRTP parameters. Default false.
*/
enableSrtp?: boolean;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type PipeTransportStat = {
type: string;
transportId: string;
timestamp: number;
sctpState?: SctpState;
bytesReceived: number;
recvBitrate: number;
bytesSent: number;
sendBitrate: number;
rtpBytesReceived: number;
rtpRecvBitrate: number;
rtpBytesSent: number;
rtpSendBitrate: number;
rtxBytesReceived: number;
rtxRecvBitrate: number;
rtxBytesSent: number;
rtxSendBitrate: number;
probationBytesSent: number;
probationSendBitrate: number;
availableOutgoingBitrate?: number;
availableIncomingBitrate?: number;
maxIncomingBitrate?: number;
tuple: TransportTuple;
};
export declare type PipeConsumerOptions = {
/**
* The id of the Producer to consume.
*/
producerId: string;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type PipeTransportEvents = TransportEvents & {
sctpstatechange: [SctpState];
};
export declare type PipeTransportObserverEvents = TransportObserverEvents & {
sctpstatechange: [SctpState];
};
declare type PipeTransportConstructorOptions = TransportConstructorOptions & {
data: PipeTransportData;
};
export declare type PipeTransportData = {
tuple: TransportTuple;
sctpParameters?: SctpParameters;
sctpState?: SctpState;
rtx: boolean;
srtpParameters?: SrtpParameters;
};
export declare class PipeTransport extends Transport<PipeTransportEvents, PipeTransportObserverEvents> {
#private;
/**
* @private
*/
constructor(options: PipeTransportConstructorOptions);
/**
* Transport tuple.
*/
get tuple(): TransportTuple;
/**
* SCTP parameters.
*/
get sctpParameters(): SctpParameters | undefined;
/**
* SCTP state.
*/
get sctpState(): SctpState | undefined;
/**
* SRTP parameters.
*/
get srtpParameters(): SrtpParameters | undefined;
/**
* Close the PipeTransport.
*
* @override
*/
close(): void;
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed(): void;
/**
* Get PipeTransport stats.
*
* @override
*/
getStats(): Promise<PipeTransportStat[]>;
/**
* Provide the PipeTransport remote parameters.
*
* @override
*/
connect({ ip, port, srtpParameters }: {
ip: string;
port: number;
srtpParameters?: SrtpParameters;
}): Promise<void>;
/**
* Create a pipe Consumer.
*
* @override
*/
consume({ producerId, appData }: PipeConsumerOptions): Promise<Consumer>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=PipeTransport.d.ts.map
\ No newline at end of file
{"version":3,"file":"Pipe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GAAG,SAAS,CAG/C;IAED;;OAEG;IACH,IAAI,SAAS,IAAI,SAAS,GAAG,SAAS,CAGrC;IAED;;OAEG;IACH,IAAI,cAAc,IAAI,cAAc,GAAG,SAAS,CAG/C;IAED;;;;OAIG;IACH,KAAK,IAAI,IAAI;IAWb;;;;;OAKG;IACH,YAAY,IAAI,IAAI;IAWpB;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAO9C;;;;OAIG;IACG,OAAO,CACZ,EACC,EAAE,EACF,IAAI,EACJ,cAAc,EACd,EACD;QACC,EAAE,EAAE,MAAM,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,cAAc,CAAC,EAAE,cAAc,CAAC;KAChC,GACC,OAAO,CAAC,IAAI,CAAC;IAahB;;;;OAIG;IACG,OAAO,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,EAAE,mBAAmB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgE9E,OAAO,CAAC,yBAAyB;CAuCjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PipeTransport = void 0;
const uuid_1 = require("uuid");
const Logger_1 = require("./Logger");
const ortc = require("./ortc");
const Transport_1 = require("./Transport");
const Consumer_1 = require("./Consumer");
const logger = new Logger_1.Logger('PipeTransport');
class PipeTransport extends Transport_1.Transport {
// PipeTransport data.
#data;
/**
* @private
*/
constructor(options) {
super(options);
logger.debug('constructor()');
const { data } = options;
this.#data =
{
tuple: data.tuple,
sctpParameters: data.sctpParameters,
sctpState: data.sctpState,
rtx: data.rtx,
srtpParameters: data.srtpParameters
};
this.handleWorkerNotifications();
}
/**
* Transport tuple.
*/
get tuple() {
return this.#data.tuple;
}
/**
* SCTP parameters.
*/
get sctpParameters() {
return this.#data.sctpParameters;
}
/**
* SCTP state.
*/
get sctpState() {
return this.#data.sctpState;
}
/**
* SRTP parameters.
*/
get srtpParameters() {
return this.#data.srtpParameters;
}
/**
* Close the PipeTransport.
*
* @override
*/
close() {
if (this.closed)
return;
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.close();
}
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed() {
if (this.closed)
return;
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.routerClosed();
}
/**
* Get PipeTransport stats.
*
* @override
*/
async getStats() {
logger.debug('getStats()');
return this.channel.request('transport.getStats', this.internal.transportId);
}
/**
* Provide the PipeTransport remote parameters.
*
* @override
*/
async connect({ ip, port, srtpParameters }) {
logger.debug('connect()');
const reqData = { ip, port, srtpParameters };
const data = await this.channel.request('transport.connect', this.internal.transportId, reqData);
// Update data.
this.#data.tuple = data.tuple;
}
/**
* Create a pipe Consumer.
*
* @override
*/
async consume({ producerId, appData }) {
logger.debug('consume()');
if (!producerId || typeof producerId !== 'string')
throw new TypeError('missing producerId');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const producer = this.getProducerById(producerId);
if (!producer)
throw Error(`Producer with id "${producerId}" not found`);
// This may throw.
const rtpParameters = ortc.getPipeConsumerRtpParameters(producer.consumableRtpParameters, this.#data.rtx);
const reqData = {
consumerId: (0, uuid_1.v4)(),
producerId,
kind: producer.kind,
rtpParameters,
type: 'pipe',
consumableRtpEncodings: producer.consumableRtpParameters.encodings
};
const status = await this.channel.request('transport.consume', this.internal.transportId, reqData);
const data = {
producerId,
kind: producer.kind,
rtpParameters,
type: 'pipe'
};
const consumer = new Consumer_1.Consumer({
internal: {
...this.internal,
consumerId: reqData.consumerId
},
data,
channel: this.channel,
payloadChannel: this.payloadChannel,
appData,
paused: status.paused,
producerPaused: status.producerPaused
});
this.consumers.set(consumer.id, consumer);
consumer.on('@close', () => this.consumers.delete(consumer.id));
consumer.on('@producerclose', () => this.consumers.delete(consumer.id));
// Emit observer event.
this.observer.safeEmit('newconsumer', consumer);
return consumer;
}
handleWorkerNotifications() {
this.channel.on(this.internal.transportId, (event, data) => {
switch (event) {
case 'sctpstatechange':
{
const sctpState = data.sctpState;
this.#data.sctpState = sctpState;
this.safeEmit('sctpstatechange', sctpState);
// Emit observer event.
this.observer.safeEmit('sctpstatechange', sctpState);
break;
}
case 'trace':
{
const trace = data;
this.safeEmit('trace', trace);
// Emit observer event.
this.observer.safeEmit('trace', trace);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.PipeTransport = PipeTransport;
import { Transport, TransportListenIp, TransportTuple, TransportEvents, TransportObserverEvents, TransportConstructorOptions, SctpState } from './Transport';
import { SctpParameters, NumSctpStreams } from './SctpParameters';
import { SrtpParameters, SrtpCryptoSuite } from './SrtpParameters';
export declare type PlainTransportOptions = {
/**
* Listening IP address.
*/
listenIp: TransportListenIp | string;
/**
* Fixed port to listen on instead of selecting automatically from Worker's port
* range.
*/
port?: number;
/**
* Use RTCP-mux (RTP and RTCP in the same port). Default true.
*/
rtcpMux?: boolean;
/**
* Whether remote IP:port should be auto-detected based on first RTP/RTCP
* packet received. If enabled, connect() method must not be called unless
* SRTP is enabled. If so, it must be called with just remote SRTP parameters.
* Default false.
*/
comedia?: boolean;
/**
* Create a SCTP association. Default false.
*/
enableSctp?: boolean;
/**
* SCTP streams number.
*/
numSctpStreams?: NumSctpStreams;
/**
* Maximum allowed size for SCTP messages sent by DataProducers.
* Default 262144.
*/
maxSctpMessageSize?: number;
/**
* Maximum SCTP send buffer used by DataConsumers.
* Default 262144.
*/
sctpSendBufferSize?: number;
/**
* Enable SRTP. For this to work, connect() must be called
* with remote SRTP parameters. Default false.
*/
enableSrtp?: boolean;
/**
* The SRTP crypto suite to be used if enableSrtp is set. Default
* 'AES_CM_128_HMAC_SHA1_80'.
*/
srtpCryptoSuite?: SrtpCryptoSuite;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type PlainTransportStat = {
type: string;
transportId: string;
timestamp: number;
sctpState?: SctpState;
bytesReceived: number;
recvBitrate: number;
bytesSent: number;
sendBitrate: number;
rtpBytesReceived: number;
rtpRecvBitrate: number;
rtpBytesSent: number;
rtpSendBitrate: number;
rtxBytesReceived: number;
rtxRecvBitrate: number;
rtxBytesSent: number;
rtxSendBitrate: number;
probationBytesSent: number;
probationSendBitrate: number;
availableOutgoingBitrate?: number;
availableIncomingBitrate?: number;
maxIncomingBitrate?: number;
rtcpMux: boolean;
comedia: boolean;
tuple: TransportTuple;
rtcpTuple?: TransportTuple;
};
export declare type PlainTransportEvents = TransportEvents & {
tuple: [TransportTuple];
rtcptuple: [TransportTuple];
sctpstatechange: [SctpState];
};
export declare type PlainTransportObserverEvents = TransportObserverEvents & {
tuple: [TransportTuple];
rtcptuple: [TransportTuple];
sctpstatechange: [SctpState];
};
declare type PlainTransportConstructorOptions = TransportConstructorOptions & {
data: PlainTransportData;
};
export declare type PlainTransportData = {
rtcpMux?: boolean;
comedia?: boolean;
tuple: TransportTuple;
rtcpTuple?: TransportTuple;
sctpParameters?: SctpParameters;
sctpState?: SctpState;
srtpParameters?: SrtpParameters;
};
export declare class PlainTransport extends Transport<PlainTransportEvents, PlainTransportObserverEvents> {
#private;
/**
* @private
*/
constructor(options: PlainTransportConstructorOptions);
/**
* Transport tuple.
*/
get tuple(): TransportTuple;
/**
* Transport RTCP tuple.
*/
get rtcpTuple(): TransportTuple | undefined;
/**
* SCTP parameters.
*/
get sctpParameters(): SctpParameters | undefined;
/**
* SCTP state.
*/
get sctpState(): SctpState | undefined;
/**
* SRTP parameters.
*/
get srtpParameters(): SrtpParameters | undefined;
/**
* Close the PlainTransport.
*
* @override
*/
close(): void;
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed(): void;
/**
* Get PlainTransport stats.
*
* @override
*/
getStats(): Promise<PlainTransportStat[]>;
/**
* Provide the PlainTransport remote parameters.
*
* @override
*/
connect({ ip, port, rtcpPort, srtpParameters }: {
ip?: string;
port?: number;
rtcpPort?: number;
srtpParameters?: SrtpParameters;
}): Promise<void>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=PlainTransport.d.ts.map
\ No newline at end of file
{"version":3,"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C;IACtB,cAAc,CAAC,EAAE,cAAc,CAAC;CAChC,CAAC;AAIF,qBAAa,cAAe,SAC3B,SAAS,CAAC,oBAAoB,EAAE,4BAA4B,CAAC;;IAK7D;;OAEG;gBACS,OAAO,EAAE,gCAAgC;IAsBrD;;OAEG;IACH,IAAI,KAAK,IAAI,cAAc,CAG1B;IAED;;OAEG;IACH,IAAI,SAAS,IAAI,cAAc,GAAG,SAAS,CAG1C;IAED;;OAEG;IACH,IAAI,cAAc,IAAI,cAAc,GAAG,SAAS,CAG/C;IAED;;OAEG;IACH,IAAI,SAAS,IAAI,SAAS,GAAG,SAAS,CAGrC;IAED;;OAEG;IACH,IAAI,cAAc,IAAI,cAAc,GAAG,SAAS,CAG/C;IAED;;;;OAIG;IACH,KAAK,IAAI,IAAI;IAWb;;;;;OAKG;IACH,YAAY,IAAI,IAAI;IAWpB;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAO/C;;;;OAIG;IACG,OAAO,CACZ,EACC,EAAE,EACF,IAAI,EACJ,QAAQ,EACR,cAAc,EACd,EACD;QACC,EAAE,CAAC,EAAE,MAAM,CAAC;QACZ,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,cAAc,CAAC,EAAE,cAAc,CAAC;KAChC,GACC,OAAO,CAAC,IAAI,CAAC;IAmBhB,OAAO,CAAC,yBAAyB;CAmEjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlainTransport = void 0;
const Logger_1 = require("./Logger");
const Transport_1 = require("./Transport");
const logger = new Logger_1.Logger('PlainTransport');
class PlainTransport extends Transport_1.Transport {
// PlainTransport data.
#data;
/**
* @private
*/
constructor(options) {
super(options);
logger.debug('constructor()');
const { data } = options;
this.#data =
{
rtcpMux: data.rtcpMux,
comedia: data.comedia,
tuple: data.tuple,
rtcpTuple: data.rtcpTuple,
sctpParameters: data.sctpParameters,
sctpState: data.sctpState,
srtpParameters: data.srtpParameters
};
this.handleWorkerNotifications();
}
/**
* Transport tuple.
*/
get tuple() {
return this.#data.tuple;
}
/**
* Transport RTCP tuple.
*/
get rtcpTuple() {
return this.#data.rtcpTuple;
}
/**
* SCTP parameters.
*/
get sctpParameters() {
return this.#data.sctpParameters;
}
/**
* SCTP state.
*/
get sctpState() {
return this.#data.sctpState;
}
/**
* SRTP parameters.
*/
get srtpParameters() {
return this.#data.srtpParameters;
}
/**
* Close the PlainTransport.
*
* @override
*/
close() {
if (this.closed)
return;
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.close();
}
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed() {
if (this.closed)
return;
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.routerClosed();
}
/**
* Get PlainTransport stats.
*
* @override
*/
async getStats() {
logger.debug('getStats()');
return this.channel.request('transport.getStats', this.internal.transportId);
}
/**
* Provide the PlainTransport remote parameters.
*
* @override
*/
async connect({ ip, port, rtcpPort, srtpParameters }) {
logger.debug('connect()');
const reqData = { ip, port, rtcpPort, srtpParameters };
const data = await this.channel.request('transport.connect', this.internal.transportId, reqData);
// Update data.
if (data.tuple)
this.#data.tuple = data.tuple;
if (data.rtcpTuple)
this.#data.rtcpTuple = data.rtcpTuple;
this.#data.srtpParameters = data.srtpParameters;
}
handleWorkerNotifications() {
this.channel.on(this.internal.transportId, (event, data) => {
switch (event) {
case 'tuple':
{
const tuple = data.tuple;
this.#data.tuple = tuple;
this.safeEmit('tuple', tuple);
// Emit observer event.
this.observer.safeEmit('tuple', tuple);
break;
}
case 'rtcptuple':
{
const rtcpTuple = data.rtcpTuple;
this.#data.rtcpTuple = rtcpTuple;
this.safeEmit('rtcptuple', rtcpTuple);
// Emit observer event.
this.observer.safeEmit('rtcptuple', rtcpTuple);
break;
}
case 'sctpstatechange':
{
const sctpState = data.sctpState;
this.#data.sctpState = sctpState;
this.safeEmit('sctpstatechange', sctpState);
// Emit observer event.
this.observer.safeEmit('sctpstatechange', sctpState);
break;
}
case 'trace':
{
const trace = data;
this.safeEmit('trace', trace);
// Emit observer event.
this.observer.safeEmit('trace', trace);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.PlainTransport = PlainTransport;
/// <reference types="node" />
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { TransportInternal } from './Transport';
import { MediaKind, RtpParameters } from './RtpParameters';
export declare type ProducerOptions = {
/**
* Producer id (just for Router.pipeToRouter() method).
*/
id?: string;
/**
* Media kind ('audio' or 'video').
*/
kind: MediaKind;
/**
* RTP parameters defining what the endpoint is sending.
*/
rtpParameters: RtpParameters;
/**
* Whether the producer must start in paused mode. Default false.
*/
paused?: boolean;
/**
* Just for video. Time (in ms) before asking the sender for a new key frame
* after having asked a previous one. Default 0.
*/
keyFrameRequestDelay?: number;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
/**
* Valid types for 'trace' event.
*/
export declare type ProducerTraceEventType = 'rtp' | 'keyframe' | 'nack' | 'pli' | 'fir';
/**
* 'trace' event data.
*/
export declare type ProducerTraceEventData = {
/**
* Trace type.
*/
type: ProducerTraceEventType;
/**
* Event timestamp.
*/
timestamp: number;
/**
* Event direction.
*/
direction: 'in' | 'out';
/**
* Per type information.
*/
info: any;
};
export declare type ProducerScore = {
/**
* SSRC of the RTP stream.
*/
ssrc: number;
/**
* RID of the RTP stream.
*/
rid?: string;
/**
* The score of the RTP stream.
*/
score: number;
};
export declare type ProducerVideoOrientation = {
/**
* Whether the source is a video camera.
*/
camera: boolean;
/**
* Whether the video source is flipped.
*/
flip: boolean;
/**
* Rotation degrees (0, 90, 180 or 270).
*/
rotation: number;
};
export declare type ProducerStat = {
type: string;
timestamp: number;
ssrc: number;
rtxSsrc?: number;
rid?: string;
kind: string;
mimeType: string;
packetsLost: number;
fractionLost: number;
packetsDiscarded: number;
packetsRetransmitted: number;
packetsRepaired: number;
nackCount: number;
nackPacketCount: number;
pliCount: number;
firCount: number;
score: number;
packetCount: number;
byteCount: number;
bitrate: number;
roundTripTime?: number;
rtxPacketsDiscarded?: number;
jitter: number;
bitrateByLayer?: any;
};
/**
* Producer type.
*/
export declare type ProducerType = 'simple' | 'simulcast' | 'svc';
export declare type ProducerEvents = {
transportclose: [];
score: [ProducerScore[]];
videoorientationchange: [ProducerVideoOrientation];
trace: [ProducerTraceEventData];
'@close': [];
};
export declare type ProducerObserverEvents = {
close: [];
pause: [];
resume: [];
score: [ProducerScore[]];
videoorientationchange: [ProducerVideoOrientation];
trace: [ProducerTraceEventData];
};
declare type ProducerInternal = TransportInternal & {
producerId: string;
};
declare type ProducerData = {
kind: MediaKind;
rtpParameters: RtpParameters;
type: ProducerType;
consumableRtpParameters: RtpParameters;
};
export declare class Producer extends EnhancedEventEmitter<ProducerEvents> {
#private;
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData, paused }: {
internal: ProducerInternal;
data: ProducerData;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
paused: boolean;
});
/**
* Producer id.
*/
get id(): string;
/**
* Whether the Producer is closed.
*/
get closed(): boolean;
/**
* Media kind.
*/
get kind(): MediaKind;
/**
* RTP parameters.
*/
get rtpParameters(): RtpParameters;
/**
* Producer type.
*/
get type(): ProducerType;
/**
* Consumable RTP parameters.
*
* @private
*/
get consumableRtpParameters(): RtpParameters;
/**
* Whether the Producer is paused.
*/
get paused(): boolean;
/**
* Producer score list.
*/
get score(): ProducerScore[];
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<ProducerObserverEvents>;
/**
* @private
* Just for testing purposes.
*/
get channelForTesting(): Channel;
/**
* Close the Producer.
*/
close(): void;
/**
* Transport was closed.
*
* @private
*/
transportClosed(): void;
/**
* Dump Producer.
*/
dump(): Promise<any>;
/**
* Get Producer stats.
*/
getStats(): Promise<ProducerStat[]>;
/**
* Pause the Producer.
*/
pause(): Promise<void>;
/**
* Resume the Producer.
*/
resume(): Promise<void>;
/**
* Enable 'trace' event.
*/
enableTraceEvent(types?: ProducerTraceEventType[]): Promise<void>;
/**
* Send RTP packet (just valid for Producers created on a DirectTransport).
*/
send(rtpPacket: Buffer): void;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=Producer.d.ts.map
\ No newline at end of file
{"version":3,"file":"Producer.d.ts","sourceRoot":"","sources":["../src/Producer.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAE3D,oBAAY,eAAe,GAC3B;IACC;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,IAAI,EAAE,SAAS,CAAC;IAEhB;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IAEjB;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;AAEF;;GAEG;AACH,oBAAY,sBAAsB,GAAG,KAAK,GAAG,UAAU,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,CAAC;AAEjF;;GAEG;AACH,oBAAY,sBAAsB,GAClC;IACC;;OAEG;IACH,IAAI,EAAE,sBAAsB,CAAC;IAE7B;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,SAAS,EAAE,IAAI,GAA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IAAI,MAAM,IAAI,OAAO,CAGpB;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,SAAS,CAGpB;IAED;;OAEG;IACH,IAAI,aAAa,IAAI,aAAa,CAGjC;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,YAAY,CAGvB;IAED;;;;OAIG;IACH,IAAI,uBAAuB,IAAI,aAAa,CAG3C;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,OAAO,CAGpB;IAED;;OAEG;IACH,IAAI,KAAK,IAAI,aAAa,EAAE,CAG3B;IAED;;OAEG;IACH,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGrC;IAED;;OAEG;IACH,IAAI,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAG3C;IAED;;OAEG;IACH,IAAI,QAAQ,IAAI,oBAAoB,CAAC,sBAAsB,CAAC,CAG3D;IAED;;;OAGG;IACH,IAAI,iBAAiB,IAAI,OAAO,CAG/B;IAED;;OAEG;IACH,KAAK,IAAI,IAAI;IAwBb;;;;OAIG;IACH,eAAe,IAAI,IAAI;IAmBvB;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAO1B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAe5B;;OAEG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAe7B;;OAEG;IACG,gBAAgB,CAAC,KAAK,GAAE,sBAAsB,EAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAU3E;;OAEG;IACH,IAAI,CAAC,SAAS,EAAE,MAAM;IAWtB,OAAO,CAAC,yBAAyB;CAmDjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Producer = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const logger = new Logger_1.Logger('Producer');
class Producer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
#internal;
// Producer data.
#data;
// Channel instance.
#channel;
// PayloadChannel instance.
#payloadChannel;
// Closed flag.
#closed = false;
// Custom app data.
#appData;
// Paused flag.
#paused = false;
// Current score.
#score = [];
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData, paused }) {
super();
logger.debug('constructor()');
this.#internal = internal;
this.#data = data;
this.#channel = channel;
this.#payloadChannel = payloadChannel;
this.#appData = appData || {};
this.#paused = paused;
this.handleWorkerNotifications();
}
/**
* Producer id.
*/
get id() {
return this.#internal.producerId;
}
/**
* Whether the Producer is closed.
*/
get closed() {
return this.#closed;
}
/**
* Media kind.
*/
get kind() {
return this.#data.kind;
}
/**
* RTP parameters.
*/
get rtpParameters() {
return this.#data.rtpParameters;
}
/**
* Producer type.
*/
get type() {
return this.#data.type;
}
/**
* Consumable RTP parameters.
*
* @private
*/
get consumableRtpParameters() {
return this.#data.consumableRtpParameters;
}
/**
* Whether the Producer is paused.
*/
get paused() {
return this.#paused;
}
/**
* Producer score list.
*/
get score() {
return this.#score;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* @private
* Just for testing purposes.
*/
get channelForTesting() {
return this.#channel;
}
/**
* Close the Producer.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.producerId);
this.#payloadChannel.removeAllListeners(this.#internal.producerId);
const reqData = { producerId: this.#internal.producerId };
this.#channel.request('transport.closeProducer', this.#internal.transportId, reqData)
.catch(() => { });
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Transport was closed.
*
* @private
*/
transportClosed() {
if (this.#closed)
return;
logger.debug('transportClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.#channel.removeAllListeners(this.#internal.producerId);
this.#payloadChannel.removeAllListeners(this.#internal.producerId);
this.safeEmit('transportclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump Producer.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('producer.dump', this.#internal.producerId);
}
/**
* Get Producer stats.
*/
async getStats() {
logger.debug('getStats()');
return this.#channel.request('producer.getStats', this.#internal.producerId);
}
/**
* Pause the Producer.
*/
async pause() {
logger.debug('pause()');
const wasPaused = this.#paused;
await this.#channel.request('producer.pause', this.#internal.producerId);
this.#paused = true;
// Emit observer event.
if (!wasPaused)
this.#observer.safeEmit('pause');
}
/**
* Resume the Producer.
*/
async resume() {
logger.debug('resume()');
const wasPaused = this.#paused;
await this.#channel.request('producer.resume', this.#internal.producerId);
this.#paused = false;
// Emit observer event.
if (wasPaused)
this.#observer.safeEmit('resume');
}
/**
* Enable 'trace' event.
*/
async enableTraceEvent(types = []) {
logger.debug('enableTraceEvent()');
const reqData = { types };
await this.#channel.request('producer.enableTraceEvent', this.#internal.producerId, reqData);
}
/**
* Send RTP packet (just valid for Producers created on a DirectTransport).
*/
send(rtpPacket) {
if (!Buffer.isBuffer(rtpPacket)) {
throw new TypeError('rtpPacket must be a Buffer');
}
this.#payloadChannel.notify('producer.send', this.#internal.producerId, undefined, rtpPacket);
}
handleWorkerNotifications() {
this.#channel.on(this.#internal.producerId, (event, data) => {
switch (event) {
case 'score':
{
const score = data;
this.#score = score;
this.safeEmit('score', score);
// Emit observer event.
this.#observer.safeEmit('score', score);
break;
}
case 'videoorientationchange':
{
const videoOrientation = data;
this.safeEmit('videoorientationchange', videoOrientation);
// Emit observer event.
this.#observer.safeEmit('videoorientationchange', videoOrientation);
break;
}
case 'trace':
{
const trace = data;
this.safeEmit('trace', trace);
// Emit observer event.
this.#observer.safeEmit('trace', trace);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.Producer = Producer;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { Transport, TransportListenIp } from './Transport';
import { WebRtcTransport, WebRtcTransportOptions } from './WebRtcTransport';
import { PlainTransport, PlainTransportOptions } from './PlainTransport';
import { PipeTransport, PipeTransportOptions } from './PipeTransport';
import { DirectTransport, DirectTransportOptions } from './DirectTransport';
import { Producer } from './Producer';
import { Consumer } from './Consumer';
import { DataProducer } from './DataProducer';
import { DataConsumer } from './DataConsumer';
import { RtpObserver } from './RtpObserver';
import { ActiveSpeakerObserver, ActiveSpeakerObserverOptions } from './ActiveSpeakerObserver';
import { AudioLevelObserver, AudioLevelObserverOptions } from './AudioLevelObserver';
import { RtpCapabilities, RtpCodecCapability } from './RtpParameters';
import { NumSctpStreams } from './SctpParameters';
export declare type RouterOptions = {
/**
* Router media codecs.
*/
mediaCodecs?: RtpCodecCapability[];
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type PipeToRouterOptions = {
/**
* The id of the Producer to consume.
*/
producerId?: string;
/**
* The id of the DataProducer to consume.
*/
dataProducerId?: string;
/**
* Target Router instance.
*/
router: Router;
/**
* IP used in the PipeTransport pair. Default '127.0.0.1'.
*/
listenIp?: TransportListenIp | string;
/**
* Create a SCTP association. Default true.
*/
enableSctp?: boolean;
/**
* SCTP streams number.
*/
numSctpStreams?: NumSctpStreams;
/**
* Enable RTX and NACK for RTP retransmission.
*/
enableRtx?: boolean;
/**
* Enable SRTP.
*/
enableSrtp?: boolean;
};
export declare type PipeToRouterResult = {
/**
* The Consumer created in the current Router.
*/
pipeConsumer?: Consumer;
/**
* The Producer created in the target Router.
*/
pipeProducer?: Producer;
/**
* The DataConsumer created in the current Router.
*/
pipeDataConsumer?: DataConsumer;
/**
* The DataProducer created in the target Router.
*/
pipeDataProducer?: DataProducer;
};
declare type PipeTransportPair = {
[key: string]: PipeTransport;
};
export declare type RouterEvents = {
workerclose: [];
'@close': [];
};
export declare type RouterObserverEvents = {
close: [];
newtransport: [Transport];
newrtpobserver: [RtpObserver];
};
export declare type RouterInternal = {
routerId: string;
};
export declare class Router extends EnhancedEventEmitter<RouterEvents> {
#private;
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData }: {
internal: RouterInternal;
data: any;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
});
/**
* Router id.
*/
get id(): string;
/**
* Whether the Router is closed.
*/
get closed(): boolean;
/**
* RTP capabilities of the Router.
*/
get rtpCapabilities(): RtpCapabilities;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<RouterObserverEvents>;
/**
* @private
* Just for testing purposes.
*/
get transportsForTesting(): Map<string, Transport>;
/**
* Close the Router.
*/
close(): void;
/**
* Worker was closed.
*
* @private
*/
workerClosed(): void;
/**
* Dump Router.
*/
dump(): Promise<any>;
/**
* Create a WebRtcTransport.
*/
createWebRtcTransport({ webRtcServer, listenIps, port, enableUdp, enableTcp, preferUdp, preferTcp, initialAvailableOutgoingBitrate, enableSctp, numSctpStreams, maxSctpMessageSize, sctpSendBufferSize, appData }: WebRtcTransportOptions): Promise<WebRtcTransport>;
/**
* Create a PlainTransport.
*/
createPlainTransport({ listenIp, port, rtcpMux, comedia, enableSctp, numSctpStreams, maxSctpMessageSize, sctpSendBufferSize, enableSrtp, srtpCryptoSuite, appData }: PlainTransportOptions): Promise<PlainTransport>;
/**
* Create a PipeTransport.
*/
createPipeTransport({ listenIp, port, enableSctp, numSctpStreams, maxSctpMessageSize, sctpSendBufferSize, enableRtx, enableSrtp, appData }: PipeTransportOptions): Promise<PipeTransport>;
/**
* Create a DirectTransport.
*/
createDirectTransport({ maxMessageSize, appData }?: DirectTransportOptions): Promise<DirectTransport>;
/**
* Pipes the given Producer or DataProducer into another Router in same host.
*/
pipeToRouter({ producerId, dataProducerId, router, listenIp, enableSctp, numSctpStreams, enableRtx, enableSrtp }: PipeToRouterOptions): Promise<PipeToRouterResult>;
/**
* @private
*/
addPipeTransportPair(pipeTransportPairKey: string, pipeTransportPairPromise: Promise<PipeTransportPair>): void;
/**
* Create an ActiveSpeakerObserver
*/
createActiveSpeakerObserver({ interval, appData }?: ActiveSpeakerObserverOptions): Promise<ActiveSpeakerObserver>;
/**
* Create an AudioLevelObserver.
*/
createAudioLevelObserver({ maxEntries, threshold, interval, appData }?: AudioLevelObserverOptions): Promise<AudioLevelObserver>;
/**
* Check whether the given RTP capabilities can consume the given Producer.
*/
canConsume({ producerId, rtpCapabilities }: {
producerId: string;
rtpCapabilities: RtpCapabilities;
}): boolean;
}
export {};
//# sourceMappingURL=Router.d.ts.map
\ No newline at end of file
{"version":3,"file":"Router.d.ts","sourceRoot":"","sources":["../src/Router.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAG9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,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G,wBAAwB,CAC7B,EACC,UAAc,EACd,SAAe,EACf,QAAe,EACf,OAAO,EACP,GAAE,yBAA8B,GAC/B,OAAO,CAAC,kBAAkB,CAAC;IA4C9B;;OAEG;IACH,UAAU,CACT,EACC,UAAU,EACV,eAAe,EACf,EACD;QACC,UAAU,EAAE,MAAM,CAAC;QACnB,eAAe,EAAE,eAAe,CAAC;KACjC,GACC,OAAO;CAuBV"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Router = void 0;
const uuid_1 = require("uuid");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const ortc = require("./ortc");
const errors_1 = require("./errors");
const WebRtcTransport_1 = require("./WebRtcTransport");
const PlainTransport_1 = require("./PlainTransport");
const PipeTransport_1 = require("./PipeTransport");
const DirectTransport_1 = require("./DirectTransport");
const ActiveSpeakerObserver_1 = require("./ActiveSpeakerObserver");
const AudioLevelObserver_1 = require("./AudioLevelObserver");
const logger = new Logger_1.Logger('Router');
class Router extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
#internal;
// Router data.
#data;
// Channel instance.
#channel;
// PayloadChannel instance.
#payloadChannel;
// Closed flag.
#closed = false;
// Custom app data.
#appData;
// Transports map.
#transports = new Map();
// Producers map.
#producers = new Map();
// RtpObservers map.
#rtpObservers = new Map();
// DataProducers map.
#dataProducers = new Map();
// Map of PipeTransport pair Promises indexed by the id of the Router in
// which pipeToRouter() was called.
#mapRouterPairPipeTransportPairPromise = new Map();
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ internal, data, channel, payloadChannel, appData }) {
super();
logger.debug('constructor()');
this.#internal = internal;
this.#data = data;
this.#channel = channel;
this.#payloadChannel = payloadChannel;
this.#appData = appData || {};
}
/**
* Router id.
*/
get id() {
return this.#internal.routerId;
}
/**
* Whether the Router is closed.
*/
get closed() {
return this.#closed;
}
/**
* RTP capabilities of the Router.
*/
get rtpCapabilities() {
return this.#data.rtpCapabilities;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* @private
* Just for testing purposes.
*/
get transportsForTesting() {
return this.#transports;
}
/**
* Close the Router.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
const reqData = { routerId: this.#internal.routerId };
this.#channel.request('worker.closeRouter', undefined, reqData)
.catch(() => { });
// Close every Transport.
for (const transport of this.#transports.values()) {
transport.routerClosed();
}
this.#transports.clear();
// Clear the Producers map.
this.#producers.clear();
// Close every RtpObserver.
for (const rtpObserver of this.#rtpObservers.values()) {
rtpObserver.routerClosed();
}
this.#rtpObservers.clear();
// Clear the DataProducers map.
this.#dataProducers.clear();
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Worker was closed.
*
* @private
*/
workerClosed() {
if (this.#closed)
return;
logger.debug('workerClosed()');
this.#closed = true;
// Close every Transport.
for (const transport of this.#transports.values()) {
transport.routerClosed();
}
this.#transports.clear();
// Clear the Producers map.
this.#producers.clear();
// Close every RtpObserver.
for (const rtpObserver of this.#rtpObservers.values()) {
rtpObserver.routerClosed();
}
this.#rtpObservers.clear();
// Clear the DataProducers map.
this.#dataProducers.clear();
this.safeEmit('workerclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump Router.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('router.dump', this.#internal.routerId);
}
/**
* Create a WebRtcTransport.
*/
async createWebRtcTransport({ webRtcServer, listenIps, port, enableUdp = true, enableTcp = false, preferUdp = false, preferTcp = false, initialAvailableOutgoingBitrate = 600000, enableSctp = false, numSctpStreams = { OS: 1024, MIS: 1024 }, maxSctpMessageSize = 262144, sctpSendBufferSize = 262144, appData }) {
logger.debug('createWebRtcTransport()');
if (!webRtcServer && !Array.isArray(listenIps))
throw new TypeError('missing webRtcServer and listenIps (one of them is mandatory)');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
if (listenIps) {
listenIps = listenIps.map((listenIp) => {
if (typeof listenIp === 'string' && listenIp) {
return { ip: listenIp };
}
else if (typeof listenIp === 'object') {
return {
ip: listenIp.ip,
announcedIp: listenIp.announcedIp || undefined
};
}
else {
throw new TypeError('wrong listenIp');
}
});
}
const reqData = {
transportId: (0, uuid_1.v4)(),
webRtcServerId: webRtcServer ? webRtcServer.id : undefined,
listenIps,
port,
enableUdp,
enableTcp,
preferUdp,
preferTcp,
initialAvailableOutgoingBitrate,
enableSctp,
numSctpStreams,
maxSctpMessageSize,
sctpSendBufferSize,
isDataChannel: true
};
const data = webRtcServer
? await this.#channel.request('router.createWebRtcTransportWithServer', this.#internal.routerId, reqData)
: await this.#channel.request('router.createWebRtcTransport', this.#internal.routerId, reqData);
const transport = new WebRtcTransport_1.WebRtcTransport({
internal: {
...this.#internal,
transportId: reqData.transportId
},
data,
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData,
getRouterRtpCapabilities: () => this.#data.rtpCapabilities,
getProducerById: (producerId) => (this.#producers.get(producerId)),
getDataProducerById: (dataProducerId) => (this.#dataProducers.get(dataProducerId))
});
this.#transports.set(transport.id, transport);
transport.on('@close', () => this.#transports.delete(transport.id));
transport.on('@listenserverclose', () => this.#transports.delete(transport.id));
transport.on('@newproducer', (producer) => this.#producers.set(producer.id, producer));
transport.on('@producerclose', (producer) => this.#producers.delete(producer.id));
transport.on('@newdataproducer', (dataProducer) => (this.#dataProducers.set(dataProducer.id, dataProducer)));
transport.on('@dataproducerclose', (dataProducer) => (this.#dataProducers.delete(dataProducer.id)));
if (webRtcServer)
webRtcServer.handleWebRtcTransport(transport);
// Emit observer event.
this.#observer.safeEmit('newtransport', transport);
return transport;
}
/**
* Create a PlainTransport.
*/
async createPlainTransport({ listenIp, port, rtcpMux = true, comedia = false, enableSctp = false, numSctpStreams = { OS: 1024, MIS: 1024 }, maxSctpMessageSize = 262144, sctpSendBufferSize = 262144, enableSrtp = false, srtpCryptoSuite = 'AES_CM_128_HMAC_SHA1_80', appData }) {
logger.debug('createPlainTransport()');
if (!listenIp)
throw new TypeError('missing listenIp');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
if (typeof listenIp === 'string' && listenIp) {
listenIp = { ip: listenIp };
}
else if (typeof listenIp === 'object') {
listenIp =
{
ip: listenIp.ip,
announcedIp: listenIp.announcedIp || undefined
};
}
else {
throw new TypeError('wrong listenIp');
}
const reqData = {
transportId: (0, uuid_1.v4)(),
listenIp,
port,
rtcpMux,
comedia,
enableSctp,
numSctpStreams,
maxSctpMessageSize,
sctpSendBufferSize,
isDataChannel: false,
enableSrtp,
srtpCryptoSuite
};
const data = await this.#channel.request('router.createPlainTransport', this.#internal.routerId, reqData);
const transport = new PlainTransport_1.PlainTransport({
internal: {
...this.#internal,
transportId: reqData.transportId
},
data,
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData,
getRouterRtpCapabilities: () => this.#data.rtpCapabilities,
getProducerById: (producerId) => (this.#producers.get(producerId)),
getDataProducerById: (dataProducerId) => (this.#dataProducers.get(dataProducerId))
});
this.#transports.set(transport.id, transport);
transport.on('@close', () => this.#transports.delete(transport.id));
transport.on('@listenserverclose', () => this.#transports.delete(transport.id));
transport.on('@newproducer', (producer) => this.#producers.set(producer.id, producer));
transport.on('@producerclose', (producer) => this.#producers.delete(producer.id));
transport.on('@newdataproducer', (dataProducer) => (this.#dataProducers.set(dataProducer.id, dataProducer)));
transport.on('@dataproducerclose', (dataProducer) => (this.#dataProducers.delete(dataProducer.id)));
// Emit observer event.
this.#observer.safeEmit('newtransport', transport);
return transport;
}
/**
* Create a PipeTransport.
*/
async createPipeTransport({ listenIp, port, enableSctp = false, numSctpStreams = { OS: 1024, MIS: 1024 }, maxSctpMessageSize = 268435456, sctpSendBufferSize = 268435456, enableRtx = false, enableSrtp = false, appData }) {
logger.debug('createPipeTransport()');
if (!listenIp)
throw new TypeError('missing listenIp');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
if (typeof listenIp === 'string' && listenIp) {
listenIp = { ip: listenIp };
}
else if (typeof listenIp === 'object') {
listenIp =
{
ip: listenIp.ip,
announcedIp: listenIp.announcedIp || undefined
};
}
else {
throw new TypeError('wrong listenIp');
}
const reqData = {
transportId: (0, uuid_1.v4)(),
listenIp,
port,
enableSctp,
numSctpStreams,
maxSctpMessageSize,
sctpSendBufferSize,
isDataChannel: false,
enableRtx,
enableSrtp
};
const data = await this.#channel.request('router.createPipeTransport', this.#internal.routerId, reqData);
const transport = new PipeTransport_1.PipeTransport({
internal: {
...this.#internal,
transportId: reqData.transportId
},
data,
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData,
getRouterRtpCapabilities: () => this.#data.rtpCapabilities,
getProducerById: (producerId) => (this.#producers.get(producerId)),
getDataProducerById: (dataProducerId) => (this.#dataProducers.get(dataProducerId))
});
this.#transports.set(transport.id, transport);
transport.on('@close', () => this.#transports.delete(transport.id));
transport.on('@listenserverclose', () => this.#transports.delete(transport.id));
transport.on('@newproducer', (producer) => this.#producers.set(producer.id, producer));
transport.on('@producerclose', (producer) => this.#producers.delete(producer.id));
transport.on('@newdataproducer', (dataProducer) => (this.#dataProducers.set(dataProducer.id, dataProducer)));
transport.on('@dataproducerclose', (dataProducer) => (this.#dataProducers.delete(dataProducer.id)));
// Emit observer event.
this.#observer.safeEmit('newtransport', transport);
return transport;
}
/**
* Create a DirectTransport.
*/
async createDirectTransport({ maxMessageSize = 262144, appData } = {
maxMessageSize: 262144
}) {
logger.debug('createDirectTransport()');
const reqData = {
transportId: (0, uuid_1.v4)(),
direct: true,
maxMessageSize
};
const data = await this.#channel.request('router.createDirectTransport', this.#internal.routerId, reqData);
const transport = new DirectTransport_1.DirectTransport({
internal: {
...this.#internal,
transportId: reqData.transportId
},
data,
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData,
getRouterRtpCapabilities: () => this.#data.rtpCapabilities,
getProducerById: (producerId) => (this.#producers.get(producerId)),
getDataProducerById: (dataProducerId) => (this.#dataProducers.get(dataProducerId))
});
this.#transports.set(transport.id, transport);
transport.on('@close', () => this.#transports.delete(transport.id));
transport.on('@listenserverclose', () => this.#transports.delete(transport.id));
transport.on('@newproducer', (producer) => this.#producers.set(producer.id, producer));
transport.on('@producerclose', (producer) => this.#producers.delete(producer.id));
transport.on('@newdataproducer', (dataProducer) => (this.#dataProducers.set(dataProducer.id, dataProducer)));
transport.on('@dataproducerclose', (dataProducer) => (this.#dataProducers.delete(dataProducer.id)));
// Emit observer event.
this.#observer.safeEmit('newtransport', transport);
return transport;
}
/**
* Pipes the given Producer or DataProducer into another Router in same host.
*/
async pipeToRouter({ producerId, dataProducerId, router, listenIp = '127.0.0.1', enableSctp = true, numSctpStreams = { OS: 1024, MIS: 1024 }, enableRtx = false, enableSrtp = false }) {
logger.debug('pipeToRouter()');
if (!producerId && !dataProducerId)
throw new TypeError('missing producerId or dataProducerId');
else if (producerId && dataProducerId)
throw new TypeError('just producerId or dataProducerId can be given');
else if (!router)
throw new TypeError('Router not found');
else if (router === this)
throw new TypeError('cannot use this Router as destination');
let producer;
let dataProducer;
if (producerId) {
producer = this.#producers.get(producerId);
if (!producer)
throw new TypeError('Producer not found');
}
else if (dataProducerId) {
dataProducer = this.#dataProducers.get(dataProducerId);
if (!dataProducer)
throw new TypeError('DataProducer not found');
}
const pipeTransportPairKey = router.id;
let pipeTransportPairPromise = this.#mapRouterPairPipeTransportPairPromise.get(pipeTransportPairKey);
let pipeTransportPair;
let localPipeTransport;
let remotePipeTransport;
if (pipeTransportPairPromise) {
pipeTransportPair = await pipeTransportPairPromise;
localPipeTransport = pipeTransportPair[this.id];
remotePipeTransport = pipeTransportPair[router.id];
}
else {
pipeTransportPairPromise = new Promise((resolve, reject) => {
Promise.all([
this.createPipeTransport({ listenIp, enableSctp, numSctpStreams, enableRtx, enableSrtp }),
router.createPipeTransport({ listenIp, enableSctp, numSctpStreams, enableRtx, enableSrtp })
])
.then((pipeTransports) => {
localPipeTransport = pipeTransports[0];
remotePipeTransport = pipeTransports[1];
})
.then(() => {
return Promise.all([
localPipeTransport.connect({
ip: remotePipeTransport.tuple.localIp,
port: remotePipeTransport.tuple.localPort,
srtpParameters: remotePipeTransport.srtpParameters
}),
remotePipeTransport.connect({
ip: localPipeTransport.tuple.localIp,
port: localPipeTransport.tuple.localPort,
srtpParameters: localPipeTransport.srtpParameters
})
]);
})
.then(() => {
localPipeTransport.observer.on('close', () => {
remotePipeTransport.close();
this.#mapRouterPairPipeTransportPairPromise.delete(pipeTransportPairKey);
});
remotePipeTransport.observer.on('close', () => {
localPipeTransport.close();
this.#mapRouterPairPipeTransportPairPromise.delete(pipeTransportPairKey);
});
resolve({
[this.id]: localPipeTransport,
[router.id]: remotePipeTransport
});
})
.catch((error) => {
logger.error('pipeToRouter() | error creating PipeTransport pair:%o', error);
if (localPipeTransport)
localPipeTransport.close();
if (remotePipeTransport)
remotePipeTransport.close();
reject(error);
});
});
this.#mapRouterPairPipeTransportPairPromise.set(pipeTransportPairKey, pipeTransportPairPromise);
router.addPipeTransportPair(this.id, pipeTransportPairPromise);
await pipeTransportPairPromise;
}
if (producer) {
let pipeConsumer;
let pipeProducer;
try {
pipeConsumer = await localPipeTransport.consume({
producerId: producerId
});
pipeProducer = await remotePipeTransport.produce({
id: producer.id,
kind: pipeConsumer.kind,
rtpParameters: pipeConsumer.rtpParameters,
paused: pipeConsumer.producerPaused,
appData: producer.appData
});
// Ensure that the producer has not been closed in the meanwhile.
if (producer.closed)
throw new errors_1.InvalidStateError('original Producer closed');
// Ensure that producer.paused has not changed in the meanwhile and, if
// so, sync the pipeProducer.
if (pipeProducer.paused !== producer.paused) {
if (producer.paused)
await pipeProducer.pause();
else
await pipeProducer.resume();
}
// Pipe events from the pipe Consumer to the pipe Producer.
pipeConsumer.observer.on('close', () => pipeProducer.close());
pipeConsumer.observer.on('pause', () => pipeProducer.pause());
pipeConsumer.observer.on('resume', () => pipeProducer.resume());
// Pipe events from the pipe Producer to the pipe Consumer.
pipeProducer.observer.on('close', () => pipeConsumer.close());
return { pipeConsumer, pipeProducer };
}
catch (error) {
logger.error('pipeToRouter() | error creating pipe Consumer/Producer pair:%o', error);
if (pipeConsumer)
pipeConsumer.close();
if (pipeProducer)
pipeProducer.close();
throw error;
}
}
else if (dataProducer) {
let pipeDataConsumer;
let pipeDataProducer;
try {
pipeDataConsumer = await localPipeTransport.consumeData({
dataProducerId: dataProducerId
});
pipeDataProducer = await remotePipeTransport.produceData({
id: dataProducer.id,
sctpStreamParameters: pipeDataConsumer.sctpStreamParameters,
label: pipeDataConsumer.label,
protocol: pipeDataConsumer.protocol,
appData: dataProducer.appData
});
// Ensure that the dataProducer has not been closed in the meanwhile.
if (dataProducer.closed)
throw new errors_1.InvalidStateError('original DataProducer closed');
// Pipe events from the pipe DataConsumer to the pipe DataProducer.
pipeDataConsumer.observer.on('close', () => pipeDataProducer.close());
// Pipe events from the pipe DataProducer to the pipe DataConsumer.
pipeDataProducer.observer.on('close', () => pipeDataConsumer.close());
return { pipeDataConsumer, pipeDataProducer };
}
catch (error) {
logger.error('pipeToRouter() | error creating pipe DataConsumer/DataProducer pair:%o', error);
if (pipeDataConsumer)
pipeDataConsumer.close();
if (pipeDataProducer)
pipeDataProducer.close();
throw error;
}
}
else {
throw new Error('internal error');
}
}
/**
* @private
*/
addPipeTransportPair(pipeTransportPairKey, pipeTransportPairPromise) {
if (this.#mapRouterPairPipeTransportPairPromise.has(pipeTransportPairKey)) {
throw new Error('given pipeTransportPairKey already exists in this Router');
}
this.#mapRouterPairPipeTransportPairPromise.set(pipeTransportPairKey, pipeTransportPairPromise);
pipeTransportPairPromise
.then((pipeTransportPair) => {
const localPipeTransport = pipeTransportPair[this.id];
// NOTE: No need to do any other cleanup here since that is done by the
// Router calling this method on us.
localPipeTransport.observer.on('close', () => {
this.#mapRouterPairPipeTransportPairPromise.delete(pipeTransportPairKey);
});
})
.catch(() => {
this.#mapRouterPairPipeTransportPairPromise.delete(pipeTransportPairKey);
});
}
/**
* Create an ActiveSpeakerObserver
*/
async createActiveSpeakerObserver({ interval = 300, appData } = {}) {
logger.debug('createActiveSpeakerObserver()');
if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const reqData = {
rtpObserverId: (0, uuid_1.v4)(),
interval
};
await this.#channel.request('router.createActiveSpeakerObserver', this.#internal.routerId, reqData);
const activeSpeakerObserver = new ActiveSpeakerObserver_1.ActiveSpeakerObserver({
internal: {
...this.#internal,
rtpObserverId: reqData.rtpObserverId
},
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData,
getProducerById: (producerId) => (this.#producers.get(producerId))
});
this.#rtpObservers.set(activeSpeakerObserver.id, activeSpeakerObserver);
activeSpeakerObserver.on('@close', () => {
this.#rtpObservers.delete(activeSpeakerObserver.id);
});
// Emit observer event.
this.#observer.safeEmit('newrtpobserver', activeSpeakerObserver);
return activeSpeakerObserver;
}
/**
* Create an AudioLevelObserver.
*/
async createAudioLevelObserver({ maxEntries = 1, threshold = -80, interval = 1000, appData } = {}) {
logger.debug('createAudioLevelObserver()');
if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const reqData = {
rtpObserverId: (0, uuid_1.v4)(),
maxEntries,
threshold,
interval
};
await this.#channel.request('router.createAudioLevelObserver', this.#internal.routerId, reqData);
const audioLevelObserver = new AudioLevelObserver_1.AudioLevelObserver({
internal: {
...this.#internal,
rtpObserverId: reqData.rtpObserverId
},
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData,
getProducerById: (producerId) => (this.#producers.get(producerId))
});
this.#rtpObservers.set(audioLevelObserver.id, audioLevelObserver);
audioLevelObserver.on('@close', () => {
this.#rtpObservers.delete(audioLevelObserver.id);
});
// Emit observer event.
this.#observer.safeEmit('newrtpobserver', audioLevelObserver);
return audioLevelObserver;
}
/**
* Check whether the given RTP capabilities can consume the given Producer.
*/
canConsume({ producerId, rtpCapabilities }) {
const producer = this.#producers.get(producerId);
if (!producer) {
logger.error('canConsume() | Producer with id "%s" not found', producerId);
return false;
}
try {
return ortc.canConsume(producer.consumableRtpParameters, rtpCapabilities);
}
catch (error) {
logger.error('canConsume() | unexpected error: %s', String(error));
return false;
}
}
}
exports.Router = Router;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { RouterInternal } from './Router';
import { Producer } from './Producer';
export declare type RtpObserverEvents = {
routerclose: [];
'@close': [];
};
export declare type RtpObserverObserverEvents = {
close: [];
pause: [];
resume: [];
addproducer: [Producer];
removeproducer: [Producer];
};
export declare type RtpObserverConstructorOptions = {
internal: RtpObserverObserverInternal;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
getProducerById: (producerId: string) => Producer | undefined;
};
export declare type RtpObserverObserverInternal = RouterInternal & {
rtpObserverId: string;
};
export declare type RtpObserverAddRemoveProducerOptions = {
/**
* The id of the Producer to be added or removed.
*/
producerId: string;
};
export declare class RtpObserver<E extends RtpObserverEvents = RtpObserverEvents> extends EnhancedEventEmitter<E> {
#private;
protected readonly internal: RtpObserverObserverInternal;
protected readonly channel: Channel;
protected readonly payloadChannel: PayloadChannel;
protected readonly getProducerById: (producerId: string) => Producer | undefined;
/**
* @private
* @interface
*/
constructor({ internal, channel, payloadChannel, appData, getProducerById }: RtpObserverConstructorOptions);
/**
* RtpObserver id.
*/
get id(): string;
/**
* Whether the RtpObserver is closed.
*/
get closed(): boolean;
/**
* Whether the RtpObserver is paused.
*/
get paused(): boolean;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<RtpObserverObserverEvents>;
/**
* Close the RtpObserver.
*/
close(): void;
/**
* Router was closed.
*
* @private
*/
routerClosed(): void;
/**
* Pause the RtpObserver.
*/
pause(): Promise<void>;
/**
* Resume the RtpObserver.
*/
resume(): Promise<void>;
/**
* Add a Producer to the RtpObserver.
*/
addProducer({ producerId }: RtpObserverAddRemoveProducerOptions): Promise<void>;
/**
* Remove a Producer from the RtpObserver.
*/
removeProducer({ producerId }: RtpObserverAddRemoveProducerOptions): Promise<void>;
}
//# sourceMappingURL=RtpObserver.d.ts.map
\ No newline at end of file
{"version":3,"file":"RtpObserver.d.ts","sourceRoot":"","sources":["../src/RtpObserver.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,oBAAY,iBAAiB,GAC7B;IACC,WAAW,EAAE,EAAE,CAAC;IAEhB,QAAQ,EAAE,EAAE,CAAC;CACb,CAAC;AAEF,oBAAY,yBAAyB,GACrC;IACC,KAAK,EAAE,EAAE,CAAC;IACV,KAAK,EAAE,EAAE,CAAC;IACV,MAAM,EAAE,EAAE,CAAC;IACX,WAAW,EAAE,CAAC,QAAQ,CAAC,CAAC;IACxB,cAAc,EAAE,CAAC,QAAQ,CAAC,CAAC;CAC3B,CAAC;AAEF,oBAAY,6BAA6B,GACzC;IACC,QAAQ,EAAE,2BAA2B,CAAC;IACtC,OAAO,EAAE,OAAO,CAAC;IACjB,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,eAAe,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,QAAQ,GAAG,SAAS,CAAC;CAC9D,CAAC;AAEF,oBAAY,2BAA2B,GAAG,cAAc,GACxD;IACC,aAAa,EAAE,MAAM,CAAC;CACtB,CAAC;AAIF,oBAAY,mCAAmC,GAC/C;IACC;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AAE,EAAE,mCAAmC,GAAG,OAAO,CAAC,IAAI,CAAC;CAgBxF"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RtpObserver = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const logger = new Logger_1.Logger('RtpObserver');
class RtpObserver extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
internal;
// Channel instance.
channel;
// PayloadChannel instance.
payloadChannel;
// Closed flag.
#closed = false;
// Paused flag.
#paused = false;
// Custom app data.
#appData;
// Method to retrieve a Producer.
getProducerById;
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
* @interface
*/
constructor({ internal, channel, payloadChannel, appData, getProducerById }) {
super();
logger.debug('constructor()');
this.internal = internal;
this.channel = channel;
this.payloadChannel = payloadChannel;
this.#appData = appData || {};
this.getProducerById = getProducerById;
}
/**
* RtpObserver id.
*/
get id() {
return this.internal.rtpObserverId;
}
/**
* Whether the RtpObserver is closed.
*/
get closed() {
return this.#closed;
}
/**
* Whether the RtpObserver is paused.
*/
get paused() {
return this.#paused;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* Close the RtpObserver.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove notification subscriptions.
this.channel.removeAllListeners(this.internal.rtpObserverId);
this.payloadChannel.removeAllListeners(this.internal.rtpObserverId);
const reqData = { rtpObserverId: this.internal.rtpObserverId };
this.channel.request('router.closeRtpObserver', this.internal.routerId, reqData)
.catch(() => { });
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Router was closed.
*
* @private
*/
routerClosed() {
if (this.#closed)
return;
logger.debug('routerClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.channel.removeAllListeners(this.internal.rtpObserverId);
this.payloadChannel.removeAllListeners(this.internal.rtpObserverId);
this.safeEmit('routerclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Pause the RtpObserver.
*/
async pause() {
logger.debug('pause()');
const wasPaused = this.#paused;
await this.channel.request('rtpObserver.pause', this.internal.rtpObserverId);
this.#paused = true;
// Emit observer event.
if (!wasPaused)
this.#observer.safeEmit('pause');
}
/**
* Resume the RtpObserver.
*/
async resume() {
logger.debug('resume()');
const wasPaused = this.#paused;
await this.channel.request('rtpObserver.resume', this.internal.rtpObserverId);
this.#paused = false;
// Emit observer event.
if (wasPaused)
this.#observer.safeEmit('resume');
}
/**
* Add a Producer to the RtpObserver.
*/
async addProducer({ producerId }) {
logger.debug('addProducer()');
const producer = this.getProducerById(producerId);
if (!producer)
throw Error(`Producer with id "${producerId}" not found`);
const reqData = { producerId };
await this.channel.request('rtpObserver.addProducer', this.internal.rtpObserverId, reqData);
// Emit observer event.
this.#observer.safeEmit('addproducer', producer);
}
/**
* Remove a Producer from the RtpObserver.
*/
async removeProducer({ producerId }) {
logger.debug('removeProducer()');
const producer = this.getProducerById(producerId);
if (!producer)
throw Error(`Producer with id "${producerId}" not found`);
const reqData = { producerId };
await this.channel.request('rtpObserver.removeProducer', this.internal.rtpObserverId, reqData);
// Emit observer event.
this.#observer.safeEmit('removeproducer', producer);
}
}
exports.RtpObserver = RtpObserver;
/**
* The RTP capabilities define what mediasoup or an endpoint can receive at
* media level.
*/
export declare type RtpCapabilities = {
/**
* Supported media and RTX codecs.
*/
codecs?: RtpCodecCapability[];
/**
* Supported RTP header extensions.
*/
headerExtensions?: RtpHeaderExtension[];
};
/**
* Media kind ('audio' or 'video').
*/
export declare type MediaKind = 'audio' | 'video';
/**
* Provides information on the capabilities of a codec within the RTP
* capabilities. The list of media codecs supported by mediasoup and their
* settings is defined in the supportedRtpCapabilities.ts file.
*
* Exactly one RtpCodecCapability will be present for each supported combination
* of parameters that requires a distinct value of preferredPayloadType. For
* example:
*
* - Multiple H264 codecs, each with their own distinct 'packetization-mode' and
* 'profile-level-id' values.
* - Multiple VP9 codecs, each with their own distinct 'profile-id' value.
*
* RtpCodecCapability entries in the mediaCodecs array of RouterOptions do not
* require preferredPayloadType field (if unset, mediasoup will choose a random
* one). If given, make sure it's in the 96-127 range.
*/
export declare type RtpCodecCapability = {
/**
* Media kind.
*/
kind: MediaKind;
/**
* The codec MIME media type/subtype (e.g. 'audio/opus', 'video/VP8').
*/
mimeType: string;
/**
* The preferred RTP payload type.
*/
preferredPayloadType?: number;
/**
* Codec clock rate expressed in Hertz.
*/
clockRate: number;
/**
* The number of channels supported (e.g. two for stereo). Just for audio.
* Default 1.
*/
channels?: number;
/**
* Codec specific parameters. Some parameters (such as 'packetization-mode'
* and 'profile-level-id' in H264 or 'profile-id' in VP9) are critical for
* codec matching.
*/
parameters?: any;
/**
* Transport layer and codec-specific feedback messages for this codec.
*/
rtcpFeedback?: RtcpFeedback[];
};
/**
* Direction of RTP header extension.
*/
export declare type RtpHeaderExtensionDirection = 'sendrecv' | 'sendonly' | 'recvonly' | 'inactive';
/**
* Provides information relating to supported header extensions. The list of
* RTP header extensions supported by mediasoup is defined in the
* supportedRtpCapabilities.ts file.
*
* mediasoup does not currently support encrypted RTP header extensions. The
* direction field is just present in mediasoup RTP capabilities (retrieved via
* router.rtpCapabilities or mediasoup.getSupportedRtpCapabilities()). It's
* ignored if present in endpoints' RTP capabilities.
*/
export declare type RtpHeaderExtension = {
/**
* Media kind.
*/
kind: MediaKind;
uri: string;
/**
* The preferred numeric identifier that goes in the RTP packet. Must be
* unique.
*/
preferredId: number;
/**
* If true, it is preferred that the value in the header be encrypted as per
* RFC 6904. Default false.
*/
preferredEncrypt?: boolean;
/**
* If 'sendrecv', mediasoup supports sending and receiving this RTP extension.
* 'sendonly' means that mediasoup can send (but not receive) it. 'recvonly'
* means that mediasoup can receive (but not send) it.
*/
direction?: RtpHeaderExtensionDirection;
};
/**
* The RTP send parameters describe a media stream received by mediasoup from
* an endpoint through its corresponding mediasoup Producer. These parameters
* may include a mid value that the mediasoup transport will use to match
* received RTP packets based on their MID RTP extension value.
*
* mediasoup allows RTP send parameters with a single encoding and with multiple
* encodings (simulcast). In the latter case, each entry in the encodings array
* must include a ssrc field or a rid field (the RID RTP extension value). Check
* the Simulcast and SVC sections for more information.
*
* The RTP receive parameters describe a media stream as sent by mediasoup to
* an endpoint through its corresponding mediasoup Consumer. The mid value is
* unset (mediasoup does not include the MID RTP extension into RTP packets
* being sent to endpoints).
*
* There is a single entry in the encodings array (even if the corresponding
* producer uses simulcast). The consumer sends a single and continuous RTP
* stream to the endpoint and spatial/temporal layer selection is possible via
* consumer.setPreferredLayers().
*
* As an exception, previous bullet is not true when consuming a stream over a
* PipeTransport, in which all RTP streams from the associated producer are
* forwarded verbatim through the consumer.
*
* The RTP receive parameters will always have their ssrc values randomly
* generated for all of its encodings (and optional rtx: { ssrc: XXXX } if the
* endpoint supports RTX), regardless of the original RTP send parameters in
* the associated producer. This applies even if the producer's encodings have
* rid set.
*/
export declare type RtpParameters = {
/**
* The MID RTP extension value as defined in the BUNDLE specification.
*/
mid?: string;
/**
* Media and RTX codecs in use.
*/
codecs: RtpCodecParameters[];
/**
* RTP header extensions in use.
*/
headerExtensions?: RtpHeaderExtensionParameters[];
/**
* Transmitted RTP streams and their settings.
*/
encodings?: RtpEncodingParameters[];
/**
* Parameters used for RTCP.
*/
rtcp?: RtcpParameters;
};
/**
* Provides information on codec settings within the RTP parameters. The list
* of media codecs supported by mediasoup and their settings is defined in the
* supportedRtpCapabilities.ts file.
*/
export declare type RtpCodecParameters = {
/**
* The codec MIME media type/subtype (e.g. 'audio/opus', 'video/VP8').
*/
mimeType: string;
/**
* The value that goes in the RTP Payload Type Field. Must be unique.
*/
payloadType: number;
/**
* Codec clock rate expressed in Hertz.
*/
clockRate: number;
/**
* The number of channels supported (e.g. two for stereo). Just for audio.
* Default 1.
*/
channels?: number;
/**
* Codec-specific parameters available for signaling. Some parameters (such
* as 'packetization-mode' and 'profile-level-id' in H264 or 'profile-id' in
* VP9) are critical for codec matching.
*/
parameters?: any;
/**
* Transport layer and codec-specific feedback messages for this codec.
*/
rtcpFeedback?: RtcpFeedback[];
};
/**
* Provides information on RTCP feedback messages for a specific codec. Those
* messages can be transport layer feedback messages or codec-specific feedback
* messages. The list of RTCP feedbacks supported by mediasoup is defined in the
* supportedRtpCapabilities.ts file.
*/
export declare type RtcpFeedback = {
/**
* RTCP feedback type.
*/
type: string;
/**
* RTCP feedback parameter.
*/
parameter?: string;
};
/**
* Provides information relating to an encoding, which represents a media RTP
* stream and its associated RTX stream (if any).
*/
export declare type RtpEncodingParameters = {
/**
* The media SSRC.
*/
ssrc?: number;
/**
* The RID RTP extension value. Must be unique.
*/
rid?: string;
/**
* Codec payload type this encoding affects. If unset, first media codec is
* chosen.
*/
codecPayloadType?: number;
/**
* RTX stream information. It must contain a numeric ssrc field indicating
* the RTX SSRC.
*/
rtx?: {
ssrc: number;
};
/**
* It indicates whether discontinuous RTP transmission will be used. Useful
* for audio (if the codec supports it) and for video screen sharing (when
* static content is being transmitted, this option disables the RTP
* inactivity checks in mediasoup). Default false.
*/
dtx?: boolean;
/**
* Number of spatial and temporal layers in the RTP stream (e.g. 'L1T3').
* See webrtc-svc.
*/
scalabilityMode?: string;
/**
* Others.
*/
scaleResolutionDownBy?: number;
maxBitrate?: number;
};
/**
* Defines a RTP header extension within the RTP parameters. The list of RTP
* header extensions supported by mediasoup is defined in the
* supportedRtpCapabilities.ts file.
*
* mediasoup does not currently support encrypted RTP header extensions and no
* parameters are currently considered.
*/
export declare type RtpHeaderExtensionParameters = {
/**
* The URI of the RTP header extension, as defined in RFC 5285.
*/
uri: string;
/**
* The numeric identifier that goes in the RTP packet. Must be unique.
*/
id: number;
/**
* If true, the value in the header is encrypted as per RFC 6904. Default false.
*/
encrypt?: boolean;
/**
* Configuration parameters for the header extension.
*/
parameters?: any;
};
/**
* Provides information on RTCP settings within the RTP parameters.
*
* If no cname is given in a producer's RTP parameters, the mediasoup transport
* will choose a random one that will be used into RTCP SDES messages sent to
* all its associated consumers.
*
* mediasoup assumes reducedSize to always be true.
*/
export declare type RtcpParameters = {
/**
* The Canonical Name (CNAME) used by RTCP (e.g. in SDES messages).
*/
cname?: string;
/**
* Whether reduced size RTCP RFC 5506 is configured (if true) or compound RTCP
* as specified in RFC 3550 (if false). Default true.
*/
reducedSize?: boolean;
/**
* Whether RTCP-mux is used. Default true.
*/
mux?: boolean;
};
//# sourceMappingURL=RtpParameters.d.ts.map
\ No newline at end of file
{"version":3,"file":"RtpParameters.d.ts","sourceRoot":"","sources":["../src/RtpParameters.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,oBAAY,eAAe,GAC3B;IACC;;OAEG;IACH,MAAM,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAE9B;;OAEG;IACH,gBAAgB,CAAC,EAAE,kBAAkB,EAAE,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,oBAAY,SAAS,GAAG,OAAO,GAAG,OAAO,CAAC;AAE1C;;;;;;;;;;;;;;;;GAgBG;AACH,oBAAY,kBAAkB,GAC9B;IACC;;OAEG;IACH,IAAI,EAAE,SAAS,CAAC;IAEhB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;OAIG;IACH,UAAU,CAAC,EAAE,GAAG,CAAC;IAEjB;;OAEG;IACH,YAAY,CAAC,EAAE,YAAY,EAAE,CAAC;CAC9B,CAAC;AAEF;;GAEG;AACH,oBAAY,2BAA2B,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;AAE5F;;;;;;;;;GASG;AACH,oBAAY,kBAAkB,GAC9B;IACC;;OAEG;IACH,IAAI,EAAE,SAAS,CAAC;IAKhB,GAAG,E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EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAEvB;;;;;OAKG;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;IAEd;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;GAOG;AACH,oBAAY,4BAA4B,GACxC;IACC;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;OAEG;IACH,UAAU,CAAC,EAAE,GAAG,CAAC;CACjB,CAAC;AAEF;;;;;;;;GAQG;AACH,oBAAY,cAAc,GAC1B;IACC;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;OAEG;IACH,GAAG,CAAC,EAAE,OAAO,CAAC;CACd,CAAC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export declare type SctpCapabilities = {
numStreams: NumSctpStreams;
};
/**
* Both OS and MIS are part of the SCTP INIT+ACK handshake. OS refers to the
* initial number of outgoing SCTP streams that the server side transport creates
* (to be used by DataConsumers), while MIS refers to the maximum number of
* incoming SCTP streams that the server side transport can receive (to be used
* by DataProducers). So, if the server side transport will just be used to
* create data producers (but no data consumers), OS can be low (~1). However,
* if data consumers are desired on the server side transport, OS must have a
* proper value and such a proper value depends on whether the remote endpoint
* supports SCTP_ADD_STREAMS extension or not.
*
* libwebrtc (Chrome, Safari, etc) does not enable SCTP_ADD_STREAMS so, if data
* consumers are required, OS should be 1024 (the maximum number of DataChannels
* that libwebrtc enables).
*
* Firefox does enable SCTP_ADD_STREAMS so, if data consumers are required, OS
* can be lower (16 for instance). The mediasoup transport will allocate and
* announce more outgoing SCTM streams when needed.
*
* mediasoup-client provides specific per browser/version OS and MIS values via
* the device.sctpCapabilities getter.
*/
export declare type NumSctpStreams = {
/**
* Initially requested number of outgoing SCTP streams.
*/
OS: number;
/**
* Maximum number of incoming SCTP streams.
*/
MIS: number;
};
export declare type SctpParameters = {
/**
* Must always equal 5000.
*/
port: number;
/**
* Initially requested number of outgoing SCTP streams.
*/
OS: number;
/**
* Maximum number of incoming SCTP streams.
*/
MIS: number;
/**
* Maximum allowed size for SCTP messages.
*/
maxMessageSize: number;
};
/**
* SCTP stream parameters describe the reliability of a certain SCTP stream.
* If ordered is true then maxPacketLifeTime and maxRetransmits must be
* false.
* If ordered if false, only one of maxPacketLifeTime or maxRetransmits
* can be true.
*/
export declare type SctpStreamParameters = {
/**
* SCTP stream id.
*/
streamId: number;
/**
* Whether data messages must be received in order. If true the messages will
* be sent reliably. Default true.
*/
ordered?: boolean;
/**
* When ordered is false indicates the time (in milliseconds) after which a
* SCTP packet will stop being retransmitted.
*/
maxPacketLifeTime?: number;
/**
* When ordered is false indicates the maximum number of times a packet will
* be retransmitted.
*/
maxRetransmits?: number;
};
//# sourceMappingURL=SctpParameters.d.ts.map
\ No newline at end of file
{"version":3,"file":"SctpParameters.d.ts","sourceRoot":"","sources":["../src/SctpParameters.ts"],"names":[],"mappings":"AAAA,oBAAY,gBAAgB,GAC5B;IACE,UAAU,EAAE,cAAc,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,oBAAY,cAAc,GAC1B;IACC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,oBAAY,cAAc,GAC1B;IACC;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF;;;;;;GAMG;AACH,oBAAY,oBAAoB,GAChC;IACC;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* SRTP parameters.
*/
export declare type SrtpParameters = {
/**
* Encryption and authentication transforms to be used.
*/
cryptoSuite: SrtpCryptoSuite;
/**
* SRTP keying material (master key and salt) in Base64.
*/
keyBase64: string;
};
/**
* SRTP crypto suite.
*/
export declare type SrtpCryptoSuite = 'AEAD_AES_256_GCM' | 'AEAD_AES_128_GCM' | 'AES_CM_128_HMAC_SHA1_80' | 'AES_CM_128_HMAC_SHA1_32';
//# sourceMappingURL=SrtpParameters.d.ts.map
\ No newline at end of file
{"version":3,"file":"SrtpParameters.d.ts","sourceRoot":"","sources":["../src/SrtpParameters.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,cAAc,GAC1B;IACC;;OAEG;IACH,WAAW,EAAE,eAAe,CAAC;IAE7B;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,oBAAY,eAAe,GACxB,kBAAkB,GAClB,kBAAkB,GAClB,yBAAyB,GACzB,yBAAyB,CAAC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
import { RouterInternal } from './Router';
import { WebRtcTransportData } from './WebRtcTransport';
import { PlainTransportData } from './PlainTransport';
import { PipeTransportData } from './PipeTransport';
import { DirectTransportData } from './DirectTransport';
import { Producer, ProducerOptions } from './Producer';
import { Consumer, ConsumerOptions } from './Consumer';
import { DataProducer, DataProducerOptions } from './DataProducer';
import { DataConsumer, DataConsumerOptions } from './DataConsumer';
import { RtpCapabilities } from './RtpParameters';
export declare type TransportListenIp = {
/**
* Listening IPv4 or IPv6.
*/
ip: string;
/**
* Announced IPv4 or IPv6 (useful when running mediasoup behind NAT with
* private IP).
*/
announcedIp?: string;
};
/**
* Transport protocol.
*/
export declare type TransportProtocol = 'udp' | 'tcp';
export declare type TransportTuple = {
localIp: string;
localPort: number;
remoteIp?: string;
remotePort?: number;
protocol: TransportProtocol;
};
/**
* Valid types for 'trace' event.
*/
export declare type TransportTraceEventType = 'probation' | 'bwe';
/**
* 'trace' event data.
*/
export declare type TransportTraceEventData = {
/**
* Trace type.
*/
type: TransportTraceEventType;
/**
* Event timestamp.
*/
timestamp: number;
/**
* Event direction.
*/
direction: 'in' | 'out';
/**
* Per type information.
*/
info: any;
};
export declare type SctpState = 'new' | 'connecting' | 'connected' | 'failed' | 'closed';
export declare type TransportEvents = {
routerclose: [];
listenserverclose: [];
trace: [TransportTraceEventData];
'@close': [];
'@newproducer': [Producer];
'@producerclose': [Producer];
'@newdataproducer': [DataProducer];
'@dataproducerclose': [DataProducer];
'@listenserverclose': [];
};
export declare type TransportObserverEvents = {
close: [];
newproducer: [Producer];
newconsumer: [Consumer];
newdataproducer: [DataProducer];
newdataconsumer: [DataConsumer];
trace: [TransportTraceEventData];
};
export declare type TransportConstructorOptions = {
internal: TransportInternal;
data: TransportData;
channel: Channel;
payloadChannel: PayloadChannel;
appData?: Record<string, unknown>;
getRouterRtpCapabilities: () => RtpCapabilities;
getProducerById: (producerId: string) => Producer | undefined;
getDataProducerById: (dataProducerId: string) => DataProducer | undefined;
};
export declare type TransportInternal = RouterInternal & {
transportId: string;
};
declare type TransportData = WebRtcTransportData | PlainTransportData | PipeTransportData | DirectTransportData;
export declare class Transport<Events extends TransportEvents = TransportEvents, ObserverEvents extends TransportObserverEvents = TransportObserverEvents> extends EnhancedEventEmitter<Events> {
#private;
protected readonly internal: TransportInternal;
protected readonly channel: Channel;
protected readonly payloadChannel: PayloadChannel;
protected readonly getProducerById: (producerId: string) => Producer | undefined;
protected readonly getDataProducerById: (dataProducerId: string) => DataProducer | undefined;
protected readonly consumers: Map<string, Consumer>;
protected readonly dataProducers: Map<string, DataProducer>;
protected readonly dataConsumers: Map<string, DataConsumer>;
/**
* @private
* @interface
*/
constructor({ internal, data, channel, payloadChannel, appData, getRouterRtpCapabilities, getProducerById, getDataProducerById }: TransportConstructorOptions);
/**
* Transport id.
*/
get id(): string;
/**
* Whether the Transport is closed.
*/
get closed(): boolean;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<ObserverEvents>;
/**
* @private
* Just for testing purposes.
*/
get channelForTesting(): Channel;
/**
* Close the Transport.
*/
close(): void;
/**
* Router was closed.
*
* @private
* @virtual
*/
routerClosed(): void;
/**
* Listen server was closed (this just happens in WebRtcTransports when their
* associated WebRtcServer is closed).
*
* @private
*/
listenServerClosed(): void;
/**
* Dump Transport.
*/
dump(): Promise<any>;
/**
* Get Transport stats.
*
* @abstract
*/
getStats(): Promise<any[]>;
/**
* Provide the Transport remote parameters.
*
* @abstract
*/
connect(params: any): Promise<void>;
/**
* Set maximum incoming bitrate for receiving media.
*/
setMaxIncomingBitrate(bitrate: number): Promise<void>;
/**
* Set maximum outgoing bitrate for sending media.
*/
setMaxOutgoingBitrate(bitrate: number): Promise<void>;
/**
* Create a Producer.
*/
produce({ id, kind, rtpParameters, paused, keyFrameRequestDelay, appData }: ProducerOptions): Promise<Producer>;
/**
* Create a Consumer.
*
* @virtual
*/
consume({ producerId, rtpCapabilities, paused, mid, preferredLayers, ignoreDtx, pipe, appData }: ConsumerOptions): Promise<Consumer>;
/**
* Create a DataProducer.
*/
produceData({ id, sctpStreamParameters, label, protocol, appData }?: DataProducerOptions): Promise<DataProducer>;
/**
* Create a DataConsumer.
*/
consumeData({ dataProducerId, ordered, maxPacketLifeTime, maxRetransmits, appData }: DataConsumerOptions): Promise<DataConsumer>;
/**
* Enable 'trace' event.
*/
enableTraceEvent(types?: TransportTraceEventType[]): Promise<void>;
private getNextSctpStreamId;
}
export {};
//# sourceMappingURL=Transport.d.ts.map
\ No newline at end of file
{"version":3,"file":"Transport.d.ts","sourceRoot":"","sources":["../src/Transport.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAG9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAgB,MAAM,YAAY,CAAC;AACrE,OAAO,EACN,YAAY,EACZ,mBAAmB,EAEnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,YAAY,EACZ,mBAAmB,EAEnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGlD,oBAAY,iBAAiB,GAC7B;IACC;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;GAEG;AACH,oBAAY,iBAAiB,GAAG,KAAK,GAAG,KAAK,CAAC;AAE9C,oBAAY,cAAc,GAC1B;IACC,OAAO,EAAE,MA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,EAAE,eAAe,GAChB,OAAO,CAAC,QAAQ,CAAC;IA0GpB;;;;OAIG;IACG,OAAO,CACZ,EACC,UAAU,EACV,eAAe,EACf,MAAc,EACd,GAAG,EACH,eAAe,EACf,SAAiB,EACjB,IAAY,EACZ,OAAO,EACP,EAAE,eAAe,GAChB,OAAO,CAAC,QAAQ,CAAC;IAgGpB;;OAEG;IACG,WAAW,CAChB,EACC,EAAc,EACd,oBAAoB,EACpB,KAAU,EACV,QAAa,EACb,OAAO,EACP,GAAE,mBAAwB,GACzB,OAAO,CAAC,YAAY,CAAC;IAuExB;;OAEG;IACG,WAAW,CAChB,EACC,cAAc,EACd,OAAO,EACP,iBAAiB,EACjB,cAAc,EACd,OAAO,EACP,EAAE,mBAAmB,GACpB,OAAO,CAAC,YAAY,CAAC;IA4GxB;;OAEG;IACG,gBAAgB,CAAC,KAAK,GAAE,uBAAuB,EAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAU5E,OAAO,CAAC,mBAAmB;CA+B3B"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Transport = void 0;
const uuid_1 = require("uuid");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const utils = require("./utils");
const ortc = require("./ortc");
const Producer_1 = require("./Producer");
const Consumer_1 = require("./Consumer");
const DataProducer_1 = require("./DataProducer");
const DataConsumer_1 = require("./DataConsumer");
const logger = new Logger_1.Logger('Transport');
class Transport extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
internal;
// Transport data. This is set by the subclass.
#data;
// Channel instance.
channel;
// PayloadChannel instance.
payloadChannel;
// Close flag.
#closed = false;
// Custom app data.
#appData;
// Method to retrieve Router RTP capabilities.
#getRouterRtpCapabilities;
// Method to retrieve a Producer.
getProducerById;
// Method to retrieve a DataProducer.
getDataProducerById;
// Producers map.
#producers = new Map();
// Consumers map.
consumers = new Map();
// DataProducers map.
dataProducers = new Map();
// DataConsumers map.
dataConsumers = new Map();
// RTCP CNAME for Producers.
#cnameForProducers;
// Next MID for Consumers. It's converted into string when used.
#nextMidForConsumers = 0;
// Buffer with available SCTP stream ids.
#sctpStreamIds;
// Next SCTP stream id.
#nextSctpStreamId = 0;
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
* @interface
*/
constructor({ internal, data, channel, payloadChannel, appData, getRouterRtpCapabilities, getProducerById, getDataProducerById }) {
super();
logger.debug('constructor()');
this.internal = internal;
this.#data = data;
this.channel = channel;
this.payloadChannel = payloadChannel;
this.#appData = appData || {};
this.#getRouterRtpCapabilities = getRouterRtpCapabilities;
this.getProducerById = getProducerById;
this.getDataProducerById = getDataProducerById;
}
/**
* Transport id.
*/
get id() {
return this.internal.transportId;
}
/**
* Whether the Transport is closed.
*/
get closed() {
return this.#closed;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* @private
* Just for testing purposes.
*/
get channelForTesting() {
return this.channel;
}
/**
* Close the Transport.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Remove notification subscriptions.
this.channel.removeAllListeners(this.internal.transportId);
this.payloadChannel.removeAllListeners(this.internal.transportId);
const reqData = { transportId: this.internal.transportId };
this.channel.request('router.closeTransport', this.internal.routerId, reqData)
.catch(() => { });
// Close every Producer.
for (const producer of this.#producers.values()) {
producer.transportClosed();
// Must tell the Router.
this.emit('@producerclose', producer);
}
this.#producers.clear();
// Close every Consumer.
for (const consumer of this.consumers.values()) {
consumer.transportClosed();
}
this.consumers.clear();
// Close every DataProducer.
for (const dataProducer of this.dataProducers.values()) {
dataProducer.transportClosed();
// Must tell the Router.
this.emit('@dataproducerclose', dataProducer);
}
this.dataProducers.clear();
// Close every DataConsumer.
for (const dataConsumer of this.dataConsumers.values()) {
dataConsumer.transportClosed();
}
this.dataConsumers.clear();
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Router was closed.
*
* @private
* @virtual
*/
routerClosed() {
if (this.#closed)
return;
logger.debug('routerClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.channel.removeAllListeners(this.internal.transportId);
this.payloadChannel.removeAllListeners(this.internal.transportId);
// Close every Producer.
for (const producer of this.#producers.values()) {
producer.transportClosed();
// NOTE: No need to tell the Router since it already knows (it has
// been closed in fact).
}
this.#producers.clear();
// Close every Consumer.
for (const consumer of this.consumers.values()) {
consumer.transportClosed();
}
this.consumers.clear();
// Close every DataProducer.
for (const dataProducer of this.dataProducers.values()) {
dataProducer.transportClosed();
// NOTE: No need to tell the Router since it already knows (it has
// been closed in fact).
}
this.dataProducers.clear();
// Close every DataConsumer.
for (const dataConsumer of this.dataConsumers.values()) {
dataConsumer.transportClosed();
}
this.dataConsumers.clear();
this.safeEmit('routerclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Listen server was closed (this just happens in WebRtcTransports when their
* associated WebRtcServer is closed).
*
* @private
*/
listenServerClosed() {
if (this.#closed)
return;
logger.debug('listenServerClosed()');
this.#closed = true;
// Remove notification subscriptions.
this.channel.removeAllListeners(this.internal.transportId);
this.payloadChannel.removeAllListeners(this.internal.transportId);
// Close every Producer.
for (const producer of this.#producers.values()) {
producer.transportClosed();
// NOTE: No need to tell the Router since it already knows (it has
// been closed in fact).
}
this.#producers.clear();
// Close every Consumer.
for (const consumer of this.consumers.values()) {
consumer.transportClosed();
}
this.consumers.clear();
// Close every DataProducer.
for (const dataProducer of this.dataProducers.values()) {
dataProducer.transportClosed();
// NOTE: No need to tell the Router since it already knows (it has
// been closed in fact).
}
this.dataProducers.clear();
// Close every DataConsumer.
for (const dataConsumer of this.dataConsumers.values()) {
dataConsumer.transportClosed();
}
this.dataConsumers.clear();
// Need to emit this event to let the parent Router know since
// transport.listenServerClosed() is called by the listen server.
// NOTE: Currently there is just WebRtcServer for WebRtcTransports.
this.emit('@listenserverclose');
this.safeEmit('listenserverclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump Transport.
*/
async dump() {
logger.debug('dump()');
return this.channel.request('transport.dump', this.internal.transportId);
}
/**
* Get Transport stats.
*
* @abstract
*/
async getStats() {
// Should not happen.
throw new Error('method not implemented in the subclass');
}
/**
* Provide the Transport remote parameters.
*
* @abstract
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async connect(params) {
// Should not happen.
throw new Error('method not implemented in the subclass');
}
/**
* Set maximum incoming bitrate for receiving media.
*/
async setMaxIncomingBitrate(bitrate) {
logger.debug('setMaxIncomingBitrate() [bitrate:%s]', bitrate);
const reqData = { bitrate };
await this.channel.request('transport.setMaxIncomingBitrate', this.internal.transportId, reqData);
}
/**
* Set maximum outgoing bitrate for sending media.
*/
async setMaxOutgoingBitrate(bitrate) {
logger.debug('setMaxOutgoingBitrate() [bitrate:%s]', bitrate);
const reqData = { bitrate };
await this.channel.request('transport.setMaxOutgoingBitrate', this.internal.transportId, reqData);
}
/**
* Create a Producer.
*/
async produce({ id = undefined, kind, rtpParameters, paused = false, keyFrameRequestDelay, appData }) {
logger.debug('produce()');
if (id && this.#producers.has(id))
throw new TypeError(`a Producer with same id "${id}" already exists`);
else if (!['audio', 'video'].includes(kind))
throw new TypeError(`invalid kind "${kind}"`);
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
// This may throw.
ortc.validateRtpParameters(rtpParameters);
// If missing or empty encodings, add one.
if (!rtpParameters.encodings ||
!Array.isArray(rtpParameters.encodings) ||
rtpParameters.encodings.length === 0) {
rtpParameters.encodings = [{}];
}
// Don't do this in PipeTransports since there we must keep CNAME value in
// each Producer.
if (this.constructor.name !== 'PipeTransport') {
// If CNAME is given and we don't have yet a CNAME for Producers in this
// Transport, take it.
if (!this.#cnameForProducers && rtpParameters.rtcp && rtpParameters.rtcp.cname) {
this.#cnameForProducers = rtpParameters.rtcp.cname;
}
// Otherwise if we don't have yet a CNAME for Producers and the RTP parameters
// do not include CNAME, create a random one.
else if (!this.#cnameForProducers) {
this.#cnameForProducers = (0, uuid_1.v4)().substr(0, 8);
}
// Override Producer's CNAME.
rtpParameters.rtcp = rtpParameters.rtcp || {};
rtpParameters.rtcp.cname = this.#cnameForProducers;
}
const routerRtpCapabilities = this.#getRouterRtpCapabilities();
// This may throw.
const rtpMapping = ortc.getProducerRtpParametersMapping(rtpParameters, routerRtpCapabilities);
// This may throw.
const consumableRtpParameters = ortc.getConsumableRtpParameters(kind, rtpParameters, routerRtpCapabilities, rtpMapping);
const reqData = {
producerId: id || (0, uuid_1.v4)(),
kind,
rtpParameters,
rtpMapping,
keyFrameRequestDelay,
paused
};
const status = await this.channel.request('transport.produce', this.internal.transportId, reqData);
const data = {
kind,
rtpParameters,
type: status.type,
consumableRtpParameters
};
const producer = new Producer_1.Producer({
internal: {
...this.internal,
producerId: reqData.producerId
},
data,
channel: this.channel,
payloadChannel: this.payloadChannel,
appData,
paused
});
this.#producers.set(producer.id, producer);
producer.on('@close', () => {
this.#producers.delete(producer.id);
this.emit('@producerclose', producer);
});
this.emit('@newproducer', producer);
// Emit observer event.
this.#observer.safeEmit('newproducer', producer);
return producer;
}
/**
* Create a Consumer.
*
* @virtual
*/
async consume({ producerId, rtpCapabilities, paused = false, mid, preferredLayers, ignoreDtx = false, pipe = false, appData }) {
logger.debug('consume()');
if (!producerId || typeof producerId !== 'string')
throw new TypeError('missing producerId');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
else if (mid && (typeof mid !== 'string' || mid.length === 0))
throw new TypeError('if given, mid must be non empty string');
// This may throw.
ortc.validateRtpCapabilities(rtpCapabilities);
const producer = this.getProducerById(producerId);
if (!producer)
throw Error(`Producer with id "${producerId}" not found`);
// This may throw.
const rtpParameters = ortc.getConsumerRtpParameters(producer.consumableRtpParameters, rtpCapabilities, pipe);
// Set MID.
if (!pipe) {
if (mid) {
rtpParameters.mid = mid;
}
else {
rtpParameters.mid = `${this.#nextMidForConsumers++}`;
// We use up to 8 bytes for MID (string).
if (this.#nextMidForConsumers === 100000000) {
logger.error(`consume() | reaching max MID value "${this.#nextMidForConsumers}"`);
this.#nextMidForConsumers = 0;
}
}
}
const reqData = {
consumerId: (0, uuid_1.v4)(),
producerId,
kind: producer.kind,
rtpParameters,
type: pipe ? 'pipe' : producer.type,
consumableRtpEncodings: producer.consumableRtpParameters.encodings,
paused,
preferredLayers,
ignoreDtx
};
const status = await this.channel.request('transport.consume', this.internal.transportId, reqData);
const data = {
producerId,
kind: producer.kind,
rtpParameters,
type: pipe ? 'pipe' : producer.type
};
const consumer = new Consumer_1.Consumer({
internal: {
...this.internal,
consumerId: reqData.consumerId
},
data,
channel: this.channel,
payloadChannel: this.payloadChannel,
appData,
paused: status.paused,
producerPaused: status.producerPaused,
score: status.score,
preferredLayers: status.preferredLayers
});
this.consumers.set(consumer.id, consumer);
consumer.on('@close', () => this.consumers.delete(consumer.id));
consumer.on('@producerclose', () => this.consumers.delete(consumer.id));
// Emit observer event.
this.#observer.safeEmit('newconsumer', consumer);
return consumer;
}
/**
* Create a DataProducer.
*/
async produceData({ id = undefined, sctpStreamParameters, label = '', protocol = '', appData } = {}) {
logger.debug('produceData()');
if (id && this.dataProducers.has(id))
throw new TypeError(`a DataProducer with same id "${id}" already exists`);
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
let type;
// If this is not a DirectTransport, sctpStreamParameters are required.
if (this.constructor.name !== 'DirectTransport') {
type = 'sctp';
// This may throw.
ortc.validateSctpStreamParameters(sctpStreamParameters);
}
// If this is a DirectTransport, sctpStreamParameters must not be given.
else {
type = 'direct';
if (sctpStreamParameters) {
logger.warn('produceData() | sctpStreamParameters are ignored when producing data on a DirectTransport');
}
}
const reqData = {
dataProducerId: id || (0, uuid_1.v4)(),
type,
sctpStreamParameters,
label,
protocol
};
const data = await this.channel.request('transport.produceData', this.internal.transportId, reqData);
const dataProducer = new DataProducer_1.DataProducer({
internal: {
...this.internal,
dataProducerId: reqData.dataProducerId
},
data,
channel: this.channel,
payloadChannel: this.payloadChannel,
appData
});
this.dataProducers.set(dataProducer.id, dataProducer);
dataProducer.on('@close', () => {
this.dataProducers.delete(dataProducer.id);
this.emit('@dataproducerclose', dataProducer);
});
this.emit('@newdataproducer', dataProducer);
// Emit observer event.
this.#observer.safeEmit('newdataproducer', dataProducer);
return dataProducer;
}
/**
* Create a DataConsumer.
*/
async consumeData({ dataProducerId, ordered, maxPacketLifeTime, maxRetransmits, appData }) {
logger.debug('consumeData()');
if (!dataProducerId || typeof dataProducerId !== 'string')
throw new TypeError('missing dataProducerId');
else if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const dataProducer = this.getDataProducerById(dataProducerId);
if (!dataProducer)
throw Error(`DataProducer with id "${dataProducerId}" not found`);
let type;
let sctpStreamParameters;
let sctpStreamId;
// If this is not a DirectTransport, use sctpStreamParameters from the
// DataProducer (if type 'sctp') unless they are given in method parameters.
if (this.constructor.name !== 'DirectTransport') {
type = 'sctp';
sctpStreamParameters =
utils.clone(dataProducer.sctpStreamParameters);
// Override if given.
if (ordered !== undefined)
sctpStreamParameters.ordered = ordered;
if (maxPacketLifeTime !== undefined)
sctpStreamParameters.maxPacketLifeTime = maxPacketLifeTime;
if (maxRetransmits !== undefined)
sctpStreamParameters.maxRetransmits = maxRetransmits;
// This may throw.
sctpStreamId = this.getNextSctpStreamId();
this.#sctpStreamIds[sctpStreamId] = 1;
sctpStreamParameters.streamId = sctpStreamId;
}
// If this is a DirectTransport, sctpStreamParameters must not be used.
else {
type = 'direct';
if (ordered !== undefined ||
maxPacketLifeTime !== undefined ||
maxRetransmits !== undefined) {
logger.warn('consumeData() | ordered, maxPacketLifeTime and maxRetransmits are ignored when consuming data on a DirectTransport');
}
}
const { label, protocol } = dataProducer;
const reqData = {
dataConsumerId: (0, uuid_1.v4)(),
dataProducerId,
type,
sctpStreamParameters,
label,
protocol
};
const data = await this.channel.request('transport.consumeData', this.internal.transportId, reqData);
const dataConsumer = new DataConsumer_1.DataConsumer({
internal: {
...this.internal,
dataConsumerId: reqData.dataConsumerId
},
data,
channel: this.channel,
payloadChannel: this.payloadChannel,
appData
});
this.dataConsumers.set(dataConsumer.id, dataConsumer);
dataConsumer.on('@close', () => {
this.dataConsumers.delete(dataConsumer.id);
if (this.#sctpStreamIds)
this.#sctpStreamIds[sctpStreamId] = 0;
});
dataConsumer.on('@dataproducerclose', () => {
this.dataConsumers.delete(dataConsumer.id);
if (this.#sctpStreamIds)
this.#sctpStreamIds[sctpStreamId] = 0;
});
// Emit observer event.
this.#observer.safeEmit('newdataconsumer', dataConsumer);
return dataConsumer;
}
/**
* Enable 'trace' event.
*/
async enableTraceEvent(types = []) {
logger.debug('pause()');
const reqData = { types };
await this.channel.request('transport.enableTraceEvent', this.internal.transportId, reqData);
}
getNextSctpStreamId() {
if (!this.#data.sctpParameters ||
typeof this.#data.sctpParameters.MIS !== 'number') {
throw new TypeError('missing sctpParameters.MIS');
}
const numStreams = this.#data.sctpParameters.MIS;
if (!this.#sctpStreamIds)
this.#sctpStreamIds = Buffer.alloc(numStreams, 0);
let sctpStreamId;
for (let idx = 0; idx < this.#sctpStreamIds.length; ++idx) {
sctpStreamId = (this.#nextSctpStreamId + idx) % this.#sctpStreamIds.length;
if (!this.#sctpStreamIds[sctpStreamId]) {
this.#nextSctpStreamId = sctpStreamId + 1;
return sctpStreamId;
}
}
throw new Error('no sctpStreamId available');
}
}
exports.Transport = Transport;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { TransportProtocol } from './Transport';
import { WebRtcTransport } from './WebRtcTransport';
export declare type WebRtcServerListenInfo = {
/**
* Network protocol.
*/
protocol: TransportProtocol;
/**
* Listening IPv4 or IPv6.
*/
ip: string;
/**
* Announced IPv4 or IPv6 (useful when running mediasoup behind NAT with
* private IP).
*/
announcedIp?: string;
/**
* Listening port.
*/
port?: number;
};
export declare type WebRtcServerOptions = {
/**
* Listen infos.
*/
listenInfos: WebRtcServerListenInfo[];
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type WebRtcServerEvents = {
workerclose: [];
'@close': [];
};
export declare type WebRtcServerObserverEvents = {
close: [];
webrtctransporthandled: [WebRtcTransport];
webrtctransportunhandled: [WebRtcTransport];
};
declare type WebRtcServerInternal = {
webRtcServerId: string;
};
export declare class WebRtcServer extends EnhancedEventEmitter<WebRtcServerEvents> {
#private;
/**
* @private
*/
constructor({ internal, channel, appData }: {
internal: WebRtcServerInternal;
channel: Channel;
appData?: Record<string, unknown>;
});
/**
* WebRtcServer id.
*/
get id(): string;
/**
* Whether the WebRtcServer is closed.
*/
get closed(): boolean;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<WebRtcServerObserverEvents>;
/**
* @private
* Just for testing purposes.
*/
get webRtcTransportsForTesting(): Map<string, WebRtcTransport>;
/**
* Close the WebRtcServer.
*/
close(): void;
/**
* Worker was closed.
*
* @private
*/
workerClosed(): void;
/**
* Dump WebRtcServer.
*/
dump(): Promise<any>;
/**
* @private
*/
handleWebRtcTransport(webRtcTransport: WebRtcTransport): void;
}
export {};
//# sourceMappingURL=WebRtcServer.d.ts.map
\ No newline at end of file
{"version":3,"file":"WebRtcServer.d.ts","sourceRoot":"","sources":["../src/WebRtcServer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD,oBAAY,sBAAsB,GAClC;IACC;;OAEG;IACH,QAAQ,EAAE,iBAAiB,CAAC;IAE5B;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IAEX;;;OAGG;IACH,WAAW,CAAC,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eAAe,CAAC,CAG7D;IAED;;OAEG;IACH,KAAK,IAAI,IAAI;IA8Bb;;;;OAIG;IACH,YAAY,IAAI,IAAI;IAmBpB;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAO1B;;OAEG;IACH,qBAAqB,CAAC,eAAe,EAAE,eAAe,GAAG,IAAI;CAe7D"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebRtcServer = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const logger = new Logger_1.Logger('WebRtcServer');
class WebRtcServer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// Internal data.
#internal;
// Channel instance.
#channel;
// Closed flag.
#closed = false;
// Custom app data.
#appData;
// Transports map.
#webRtcTransports = new Map();
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ internal, channel, appData }) {
super();
logger.debug('constructor()');
this.#internal = internal;
this.#channel = channel;
this.#appData = appData || {};
}
/**
* WebRtcServer id.
*/
get id() {
return this.#internal.webRtcServerId;
}
/**
* Whether the WebRtcServer is closed.
*/
get closed() {
return this.#closed;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* @private
* Just for testing purposes.
*/
get webRtcTransportsForTesting() {
return this.#webRtcTransports;
}
/**
* Close the WebRtcServer.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
const reqData = { webRtcServerId: this.#internal.webRtcServerId };
this.#channel.request('worker.closeWebRtcServer', undefined, reqData)
.catch(() => { });
// Close every WebRtcTransport.
for (const webRtcTransport of this.#webRtcTransports.values()) {
webRtcTransport.listenServerClosed();
// Emit observer event.
this.#observer.safeEmit('webrtctransportunhandled', webRtcTransport);
}
this.#webRtcTransports.clear();
this.emit('@close');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Worker was closed.
*
* @private
*/
workerClosed() {
if (this.#closed)
return;
logger.debug('workerClosed()');
this.#closed = true;
// NOTE: No need to close WebRtcTransports since they are closed by their
// respective Router parents.
this.#webRtcTransports.clear();
this.safeEmit('workerclose');
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump WebRtcServer.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('webRtcServer.dump', this.#internal.webRtcServerId);
}
/**
* @private
*/
handleWebRtcTransport(webRtcTransport) {
this.#webRtcTransports.set(webRtcTransport.id, webRtcTransport);
// Emit observer event.
this.#observer.safeEmit('webrtctransporthandled', webRtcTransport);
webRtcTransport.on('@close', () => {
this.#webRtcTransports.delete(webRtcTransport.id);
// Emit observer event.
this.#observer.safeEmit('webrtctransportunhandled', webRtcTransport);
});
}
}
exports.WebRtcServer = WebRtcServer;
import { Transport, TransportListenIp, TransportProtocol, TransportTuple, TransportEvents, TransportObserverEvents, TransportConstructorOptions, SctpState } from './Transport';
import { WebRtcServer } from './WebRtcServer';
import { SctpParameters, NumSctpStreams } from './SctpParameters';
import { Either } from './utils';
export declare type WebRtcTransportListenIndividual = {
/**
* Listening IP address or addresses in order of preference (first one is the
* preferred one). Mandatory unless webRtcServer is given.
*/
listenIps: (TransportListenIp | string)[];
/**
* Fixed port to listen on instead of selecting automatically from Worker's port
* range.
*/
port?: number;
};
export declare type WebRtcTransportListenServer = {
/**
* Instance of WebRtcServer. Mandatory unless listenIps is given.
*/
webRtcServer: WebRtcServer;
};
export declare type WebRtcTransportListen = Either<WebRtcTransportListenIndividual, WebRtcTransportListenServer>;
export declare type WebRtcTransportOptionsBase = {
/**
* Listen in UDP. Default true.
*/
enableUdp?: boolean;
/**
* Listen in TCP. Default false.
*/
enableTcp?: boolean;
/**
* Prefer UDP. Default false.
*/
preferUdp?: boolean;
/**
* Prefer TCP. Default false.
*/
preferTcp?: boolean;
/**
* Initial available outgoing bitrate (in bps). Default 600000.
*/
initialAvailableOutgoingBitrate?: number;
/**
* Create a SCTP association. Default false.
*/
enableSctp?: boolean;
/**
* SCTP streams number.
*/
numSctpStreams?: NumSctpStreams;
/**
* Maximum allowed size for SCTP messages sent by DataProducers.
* Default 262144.
*/
maxSctpMessageSize?: number;
/**
* Maximum SCTP send buffer used by DataConsumers.
* Default 262144.
*/
sctpSendBufferSize?: number;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type WebRtcTransportOptions = WebRtcTransportOptionsBase & WebRtcTransportListen;
export declare type IceParameters = {
usernameFragment: string;
password: string;
iceLite?: boolean;
};
export declare type IceCandidate = {
foundation: string;
priority: number;
ip: string;
protocol: TransportProtocol;
port: number;
type: 'host';
tcpType: 'passive' | undefined;
};
export declare type DtlsParameters = {
role?: DtlsRole;
fingerprints: DtlsFingerprint[];
};
/**
* The hash function algorithm (as defined in the "Hash function Textual Names"
* registry initially specified in RFC 4572 Section 8) and its corresponding
* certificate fingerprint value (in lowercase hex string as expressed utilizing
* the syntax of "fingerprint" in RFC 4572 Section 5).
*/
export declare type DtlsFingerprint = {
algorithm: string;
value: string;
};
export declare type IceState = 'new' | 'connected' | 'completed' | 'disconnected' | 'closed';
export declare type DtlsRole = 'auto' | 'client' | 'server';
export declare type DtlsState = 'new' | 'connecting' | 'connected' | 'failed' | 'closed';
export declare type WebRtcTransportStat = {
type: string;
transportId: string;
timestamp: number;
sctpState?: SctpState;
bytesReceived: number;
recvBitrate: number;
bytesSent: number;
sendBitrate: number;
rtpBytesReceived: number;
rtpRecvBitrate: number;
rtpBytesSent: number;
rtpSendBitrate: number;
rtxBytesReceived: number;
rtxRecvBitrate: number;
rtxBytesSent: number;
rtxSendBitrate: number;
probationBytesSent: number;
probationSendBitrate: number;
availableOutgoingBitrate?: number;
availableIncomingBitrate?: number;
maxIncomingBitrate?: number;
iceRole: string;
iceState: IceState;
iceSelectedTuple?: TransportTuple;
dtlsState: DtlsState;
};
export declare type WebRtcTransportEvents = TransportEvents & {
icestatechange: [IceState];
iceselectedtuplechange: [TransportTuple];
dtlsstatechange: [DtlsState];
sctpstatechange: [SctpState];
};
export declare type WebRtcTransportObserverEvents = TransportObserverEvents & {
icestatechange: [IceState];
iceselectedtuplechange: [TransportTuple];
dtlsstatechange: [DtlsState];
sctpstatechange: [SctpState];
};
declare type WebRtcTransportConstructorOptions = TransportConstructorOptions & {
data: WebRtcTransportData;
};
export declare type WebRtcTransportData = {
iceRole: 'controlled';
iceParameters: IceParameters;
iceCandidates: IceCandidate[];
iceState: IceState;
iceSelectedTuple?: TransportTuple;
dtlsParameters: DtlsParameters;
dtlsState: DtlsState;
dtlsRemoteCert?: string;
sctpParameters?: SctpParameters;
sctpState?: SctpState;
};
export declare class WebRtcTransport extends Transport<WebRtcTransportEvents, WebRtcTransportObserverEvents> {
#private;
/**
* @private
*/
constructor(options: WebRtcTransportConstructorOptions);
/**
* ICE role.
*/
get iceRole(): 'controlled';
/**
* ICE parameters.
*/
get iceParameters(): IceParameters;
/**
* ICE candidates.
*/
get iceCandidates(): IceCandidate[];
/**
* ICE state.
*/
get iceState(): IceState;
/**
* ICE selected tuple.
*/
get iceSelectedTuple(): TransportTuple | undefined;
/**
* DTLS parameters.
*/
get dtlsParameters(): DtlsParameters;
/**
* DTLS state.
*/
get dtlsState(): DtlsState;
/**
* Remote certificate in PEM format.
*/
get dtlsRemoteCert(): string | undefined;
/**
* SCTP parameters.
*/
get sctpParameters(): SctpParameters | undefined;
/**
* SCTP state.
*/
get sctpState(): SctpState | undefined;
/**
* Close the WebRtcTransport.
*
* @override
*/
close(): void;
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed(): void;
/**
* Called when closing the associated WebRtcServer.
*
* @private
*/
webRtcServerClosed(): void;
/**
* Get WebRtcTransport stats.
*
* @override
*/
getStats(): Promise<WebRtcTransportStat[]>;
/**
* Provide the WebRtcTransport remote parameters.
*
* @override
*/
connect({ dtlsParameters }: {
dtlsParameters: DtlsParameters;
}): Promise<void>;
/**
* Restart ICE.
*/
restartIce(): Promise<IceParameters>;
private handleWorkerNotifications;
}
export {};
//# sourceMappingURL=WebRtcTransport.d.ts.map
\ No newline at end of file
{"version":3,"file":"WebRtcTransport.d.ts","sourceRoot":"","sources":["../src/WebRtcTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACN,SAAS,EACT,iBAAiB,EACjB,iBAAiB,EACjB,cAAc,EAEd,eAAe,EACf,uBAAuB,EACvB,2BAA2B,EAC3B,SAAS,EACT,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,oBAAY,+BAA+B,GAC3C;IACC;;;OAGG;IACH,SAAS,EAAE,CAAC,iBAAiB,GAAG,MAAM,CAAC,EAAE,CAAC;IAE1C;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,oBAAY,2BAA2B,GACvC;IACC;;OAEG;IACH,YAAY,EAAE,YAAY,CAAC;CAC3B,CAAC;AAEF,oBAAY,qBAAqB,GAChC,MAAM,CAAC,+BAA+B,EAAE,2BAA2B,CAAC,CAAC;AAEtE,oBAAY,0BAA0B,GACtC;IACC;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,+BAA+B,CAAC,EAAE,MAAM,CAAC;IAEzC;;OAEG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;IAEhC;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B;;;OAGG;IACH,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EAAE,EAAE;QAAE,cAAc,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAapF;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,aAAa,CAAC;IAc1C,OAAO,CAAC,yBAAyB;CAqFjC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebRtcTransport = void 0;
const Logger_1 = require("./Logger");
const Transport_1 = require("./Transport");
const logger = new Logger_1.Logger('WebRtcTransport');
class WebRtcTransport extends Transport_1.Transport {
// WebRtcTransport data.
#data;
/**
* @private
*/
constructor(options) {
super(options);
logger.debug('constructor()');
const { data } = options;
this.#data =
{
iceRole: data.iceRole,
iceParameters: data.iceParameters,
iceCandidates: data.iceCandidates,
iceState: data.iceState,
iceSelectedTuple: data.iceSelectedTuple,
dtlsParameters: data.dtlsParameters,
dtlsState: data.dtlsState,
dtlsRemoteCert: data.dtlsRemoteCert,
sctpParameters: data.sctpParameters,
sctpState: data.sctpState
};
this.handleWorkerNotifications();
}
/**
* ICE role.
*/
get iceRole() {
return this.#data.iceRole;
}
/**
* ICE parameters.
*/
get iceParameters() {
return this.#data.iceParameters;
}
/**
* ICE candidates.
*/
get iceCandidates() {
return this.#data.iceCandidates;
}
/**
* ICE state.
*/
get iceState() {
return this.#data.iceState;
}
/**
* ICE selected tuple.
*/
get iceSelectedTuple() {
return this.#data.iceSelectedTuple;
}
/**
* DTLS parameters.
*/
get dtlsParameters() {
return this.#data.dtlsParameters;
}
/**
* DTLS state.
*/
get dtlsState() {
return this.#data.dtlsState;
}
/**
* Remote certificate in PEM format.
*/
get dtlsRemoteCert() {
return this.#data.dtlsRemoteCert;
}
/**
* SCTP parameters.
*/
get sctpParameters() {
return this.#data.sctpParameters;
}
/**
* SCTP state.
*/
get sctpState() {
return this.#data.sctpState;
}
/**
* Close the WebRtcTransport.
*
* @override
*/
close() {
if (this.closed)
return;
this.#data.iceState = 'closed';
this.#data.iceSelectedTuple = undefined;
this.#data.dtlsState = 'closed';
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.close();
}
/**
* Router was closed.
*
* @private
* @override
*/
routerClosed() {
if (this.closed)
return;
this.#data.iceState = 'closed';
this.#data.iceSelectedTuple = undefined;
this.#data.dtlsState = 'closed';
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.routerClosed();
}
/**
* Called when closing the associated WebRtcServer.
*
* @private
*/
webRtcServerClosed() {
if (this.closed)
return;
this.#data.iceState = 'closed';
this.#data.iceSelectedTuple = undefined;
this.#data.dtlsState = 'closed';
if (this.#data.sctpState)
this.#data.sctpState = 'closed';
super.listenServerClosed();
}
/**
* Get WebRtcTransport stats.
*
* @override
*/
async getStats() {
logger.debug('getStats()');
return this.channel.request('transport.getStats', this.internal.transportId);
}
/**
* Provide the WebRtcTransport remote parameters.
*
* @override
*/
async connect({ dtlsParameters }) {
logger.debug('connect()');
const reqData = { dtlsParameters };
const data = await this.channel.request('transport.connect', this.internal.transportId, reqData);
// Update data.
this.#data.dtlsParameters.role = data.dtlsLocalRole;
}
/**
* Restart ICE.
*/
async restartIce() {
logger.debug('restartIce()');
const data = await this.channel.request('transport.restartIce', this.internal.transportId);
const { iceParameters } = data;
this.#data.iceParameters = iceParameters;
return iceParameters;
}
handleWorkerNotifications() {
this.channel.on(this.internal.transportId, (event, data) => {
switch (event) {
case 'icestatechange':
{
const iceState = data.iceState;
this.#data.iceState = iceState;
this.safeEmit('icestatechange', iceState);
// Emit observer event.
this.observer.safeEmit('icestatechange', iceState);
break;
}
case 'iceselectedtuplechange':
{
const iceSelectedTuple = data.iceSelectedTuple;
this.#data.iceSelectedTuple = iceSelectedTuple;
this.safeEmit('iceselectedtuplechange', iceSelectedTuple);
// Emit observer event.
this.observer.safeEmit('iceselectedtuplechange', iceSelectedTuple);
break;
}
case 'dtlsstatechange':
{
const dtlsState = data.dtlsState;
const dtlsRemoteCert = data.dtlsRemoteCert;
this.#data.dtlsState = dtlsState;
if (dtlsState === 'connected')
this.#data.dtlsRemoteCert = dtlsRemoteCert;
this.safeEmit('dtlsstatechange', dtlsState);
// Emit observer event.
this.observer.safeEmit('dtlsstatechange', dtlsState);
break;
}
case 'sctpstatechange':
{
const sctpState = data.sctpState;
this.#data.sctpState = sctpState;
this.safeEmit('sctpstatechange', sctpState);
// Emit observer event.
this.observer.safeEmit('sctpstatechange', sctpState);
break;
}
case 'trace':
{
const trace = data;
this.safeEmit('trace', trace);
// Emit observer event.
this.observer.safeEmit('trace', trace);
break;
}
default:
{
logger.error('ignoring unknown event "%s"', event);
}
}
});
}
}
exports.WebRtcTransport = WebRtcTransport;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Router, RouterOptions } from './Router';
import { WebRtcServer, WebRtcServerOptions } from './WebRtcServer';
export declare type WorkerLogLevel = 'debug' | 'warn' | 'error' | 'none';
export declare type WorkerLogTag = 'info' | 'ice' | 'dtls' | 'rtp' | 'srtp' | 'rtcp' | 'rtx' | 'bwe' | 'score' | 'simulcast' | 'svc' | 'sctp' | 'message';
export declare type WorkerSettings = {
/**
* Logging level for logs generated by the media worker subprocesses (check
* the Debugging documentation). Valid values are 'debug', 'warn', 'error' and
* 'none'. Default 'error'.
*/
logLevel?: WorkerLogLevel;
/**
* Log tags for debugging. Check the meaning of each available tag in the
* Debugging documentation.
*/
logTags?: WorkerLogTag[];
/**
* Minimun RTC port for ICE, DTLS, RTP, etc. Default 10000.
*/
rtcMinPort?: number;
/**
* Maximum RTC port for ICE, DTLS, RTP, etc. Default 59999.
*/
rtcMaxPort?: number;
/**
* Path to the DTLS public certificate file in PEM format. If unset, a
* certificate is dynamically created.
*/
dtlsCertificateFile?: string;
/**
* Path to the DTLS certificate private key file in PEM format. If unset, a
* certificate is dynamically created.
*/
dtlsPrivateKeyFile?: string;
/**
* Custom application data.
*/
appData?: Record<string, unknown>;
};
export declare type WorkerUpdateableSettings = Pick<WorkerSettings, 'logLevel' | 'logTags'>;
/**
* An object with the fields of the uv_rusage_t struct.
*
* - http://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t
* - https://linux.die.net/man/2/getrusage
*/
export declare type WorkerResourceUsage = {
/**
* User CPU time used (in ms).
*/
ru_utime: number;
/**
* System CPU time used (in ms).
*/
ru_stime: number;
/**
* Maximum resident set size.
*/
ru_maxrss: number;
/**
* Integral shared memory size.
*/
ru_ixrss: number;
/**
* Integral unshared data size.
*/
ru_idrss: number;
/**
* Integral unshared stack size.
*/
ru_isrss: number;
/**
* Page reclaims (soft page faults).
*/
ru_minflt: number;
/**
* Page faults (hard page faults).
*/
ru_majflt: number;
/**
* Swaps.
*/
ru_nswap: number;
/**
* Block input operations.
*/
ru_inblock: number;
/**
* Block output operations.
*/
ru_oublock: number;
/**
* IPC messages sent.
*/
ru_msgsnd: number;
/**
* IPC messages received.
*/
ru_msgrcv: number;
/**
* Signals received.
*/
ru_nsignals: number;
/**
* Voluntary context switches.
*/
ru_nvcsw: number;
/**
* Involuntary context switches.
*/
ru_nivcsw: number;
};
export declare type WorkerEvents = {
died: [Error];
'@success': [];
'@failure': [Error];
};
export declare type WorkerObserverEvents = {
close: [];
newwebrtcserver: [WebRtcServer];
newrouter: [Router];
};
export declare class Worker extends EnhancedEventEmitter<WorkerEvents> {
#private;
/**
* @private
*/
constructor({ logLevel, logTags, rtcMinPort, rtcMaxPort, dtlsCertificateFile, dtlsPrivateKeyFile, appData }: WorkerSettings);
/**
* Worker process identifier (PID).
*/
get pid(): number;
/**
* Whether the Worker is closed.
*/
get closed(): boolean;
/**
* Whether the Worker died.
*/
get died(): boolean;
/**
* App custom data.
*/
get appData(): Record<string, unknown>;
/**
* Invalid setter.
*/
set appData(appData: Record<string, unknown>);
/**
* Observer.
*/
get observer(): EnhancedEventEmitter<WorkerObserverEvents>;
/**
* @private
* Just for testing purposes.
*/
get webRtcServersForTesting(): Set<WebRtcServer>;
/**
* @private
* Just for testing purposes.
*/
get routersForTesting(): Set<Router>;
/**
* Close the Worker.
*/
close(): void;
/**
* Dump Worker.
*/
dump(): Promise<any>;
/**
* Get mediasoup-worker process resource usage.
*/
getResourceUsage(): Promise<WorkerResourceUsage>;
/**
* Update settings.
*/
updateSettings({ logLevel, logTags }?: WorkerUpdateableSettings): Promise<void>;
/**
* Create a WebRtcServer.
*/
createWebRtcServer({ listenInfos, appData }: WebRtcServerOptions): Promise<WebRtcServer>;
/**
* Create a Router.
*/
createRouter({ mediaCodecs, appData }?: RouterOptions): Promise<Router>;
private workerDied;
}
//# sourceMappingURL=Worker.d.ts.map
\ No newline at end of file
{"version":3,"file":"Worker.d.ts","sourceRoot":"","sources":["../src/Worker.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAI9D,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAEnE,oBAAY,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAEjE,oBAAY,YAAY,GACpB,MAAM,GACN,KAAK,GACL,MAAM,GACN,KAAK,GACL,MAAM,GACN,MAAM,GACN,KAAK,GACL,KAAK,GACL,OAAO,GACP,WAAW,GACX,KAAK,GACL,MAAM,GACN,SAAS,CAAC;AAEd,oBAAY,cAAc,GAC1B;IACC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,cAAc,CAAC;IAE1B;;;OAGG;IACH,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;IAEzB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;A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O,EACP,UAAU,EACV,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,OAAO,EACP,EAAE,cAAc;IAgMlB;;OAEG;IACH,IAAI,GAAG,IAAI,MAAM,CAGhB;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,OAAO,CAGpB;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,OAAO,CAGlB;IAED;;OAEG;IACH,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGrC;IAED;;OAEG;IACH,IAAI,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAG3C;IAED;;OAEG;IACH,IAAI,QAAQ,IAAI,oBAAoB,CAAC,oBAAoB,CAAC,CAGzD;IAED;;;OAGG;IACH,IAAI,uBAAuB,IAAI,GAAG,CAAC,YAAY,CAAC,CAG/C;IAED;;;OAGG;IACH,IAAI,iBAAiB,IAAI,GAAG,CAAC,MAAM,CAAC,CAGnC;IAED;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Cb;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAO1B;;OAEG;IACG,gBAAgB,IAAI,OAAO,CAAC,mBAAmB,CAAC;IAOtD;;OAEG;IACG,cAAc,CACnB,EACC,QAAQ,EACR,OAAO,EACP,GAAE,wBAA6B,GAC9B,OAAO,CAAC,IAAI,CAAC;IAShB;;OAEG;IACG,kBAAkB,CACvB,EACC,WAAW,EACX,OAAO,EACP,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;IA+B/C;;OAEG;IACG,YAAY,CACjB,EACC,WAAW,EACX,OAAO,EACP,GAAE,aAAkB,GAAG,OAAO,CAAC,MAAM,CAAC;IAoCxC,OAAO,CAAC,UAAU;CAmClB"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Worker = void 0;
const process = require("process");
const path = require("path");
const child_process_1 = require("child_process");
const uuid_1 = require("uuid");
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const ortc = require("./ortc");
const Channel_1 = require("./Channel");
const PayloadChannel_1 = require("./PayloadChannel");
const Router_1 = require("./Router");
const WebRtcServer_1 = require("./WebRtcServer");
// If env MEDIASOUP_WORKER_BIN is given, use it as worker binary.
// Otherwise if env MEDIASOUP_BUILDTYPE is 'Debug' use the Debug binary.
// Otherwise use the Release binary.
const workerBin = process.env.MEDIASOUP_WORKER_BIN
? process.env.MEDIASOUP_WORKER_BIN
: process.env.MEDIASOUP_BUILDTYPE === 'Debug'
? path.join(__dirname, '..', '..', 'worker', 'out', 'Debug', 'mediasoup-worker')
: path.join(__dirname, '..', '..', 'worker', 'out', 'Release', 'mediasoup-worker');
const logger = new Logger_1.Logger('Worker');
const workerLogger = new Logger_1.Logger('Worker');
class Worker extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// mediasoup-worker child process.
#child;
// Worker process PID.
#pid;
// Channel instance.
#channel;
// PayloadChannel instance.
#payloadChannel;
// Closed flag.
#closed = false;
// Died dlag.
#died = false;
// Custom app data.
#appData;
// WebRtcServers set.
#webRtcServers = new Set();
// Routers set.
#routers = new Set();
// Observer instance.
#observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
/**
* @private
*/
constructor({ logLevel, logTags, rtcMinPort, rtcMaxPort, dtlsCertificateFile, dtlsPrivateKeyFile, appData }) {
super();
logger.debug('constructor()');
let spawnBin = workerBin;
let spawnArgs = [];
if (process.env.MEDIASOUP_USE_VALGRIND === 'true') {
spawnBin = process.env.MEDIASOUP_VALGRIND_BIN || 'valgrind';
if (process.env.MEDIASOUP_VALGRIND_OPTIONS) {
spawnArgs = spawnArgs.concat(process.env.MEDIASOUP_VALGRIND_OPTIONS.split(/\s+/));
}
spawnArgs.push(workerBin);
}
if (typeof logLevel === 'string' && logLevel)
spawnArgs.push(`--logLevel=${logLevel}`);
for (const logTag of (Array.isArray(logTags) ? logTags : [])) {
if (typeof logTag === 'string' && logTag)
spawnArgs.push(`--logTag=${logTag}`);
}
if (typeof rtcMinPort === 'number' && !Number.isNaN(rtcMinPort))
spawnArgs.push(`--rtcMinPort=${rtcMinPort}`);
if (typeof rtcMaxPort === 'number' && !Number.isNaN(rtcMaxPort))
spawnArgs.push(`--rtcMaxPort=${rtcMaxPort}`);
if (typeof dtlsCertificateFile === 'string' && dtlsCertificateFile)
spawnArgs.push(`--dtlsCertificateFile=${dtlsCertificateFile}`);
if (typeof dtlsPrivateKeyFile === 'string' && dtlsPrivateKeyFile)
spawnArgs.push(`--dtlsPrivateKeyFile=${dtlsPrivateKeyFile}`);
logger.debug('spawning worker process: %s %s', spawnBin, spawnArgs.join(' '));
this.#child = (0, child_process_1.spawn)(
// command
spawnBin,
// args
spawnArgs,
// options
{
env: {
MEDIASOUP_VERSION: '3.11.3',
// Let the worker process inherit all environment variables, useful
// if a custom and not in the path GCC is used so the user can set
// LD_LIBRARY_PATH environment variable for runtime.
...process.env
},
detached: false,
// fd 0 (stdin) : Just ignore it.
// fd 1 (stdout) : Pipe it for 3rd libraries that log their own stuff.
// fd 2 (stderr) : Same as stdout.
// fd 3 (channel) : Producer Channel fd.
// fd 4 (channel) : Consumer Channel fd.
// fd 5 (channel) : Producer PayloadChannel fd.
// fd 6 (channel) : Consumer PayloadChannel fd.
stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe', 'pipe', 'pipe'],
windowsHide: true
});
this.#pid = this.#child.pid;
this.#channel = new Channel_1.Channel({
producerSocket: this.#child.stdio[3],
consumerSocket: this.#child.stdio[4],
pid: this.#pid
});
this.#payloadChannel = new PayloadChannel_1.PayloadChannel({
// NOTE: TypeScript does not like more than 5 fds.
// @ts-ignore
producerSocket: this.#child.stdio[5],
// @ts-ignore
consumerSocket: this.#child.stdio[6]
});
this.#appData = appData || {};
let spawnDone = false;
// Listen for 'running' notification.
this.#channel.once(String(this.#pid), (event) => {
if (!spawnDone && event === 'running') {
spawnDone = true;
logger.debug('worker process running [pid:%s]', this.#pid);
this.emit('@success');
}
});
this.#child.on('exit', (code, signal) => {
this.#child = undefined;
if (!spawnDone) {
spawnDone = true;
if (code === 42) {
logger.error('worker process failed due to wrong settings [pid:%s]', this.#pid);
this.close();
this.emit('@failure', new TypeError('wrong settings'));
}
else {
logger.error('worker process failed unexpectedly [pid:%s, code:%s, signal:%s]', this.#pid, code, signal);
this.close();
this.emit('@failure', new Error(`[pid:${this.#pid}, code:${code}, signal:${signal}]`));
}
}
else {
logger.error('worker process died unexpectedly [pid:%s, code:%s, signal:%s]', this.#pid, code, signal);
this.workerDied(new Error(`[pid:${this.#pid}, code:${code}, signal:${signal}]`));
}
});
this.#child.on('error', (error) => {
this.#child = undefined;
if (!spawnDone) {
spawnDone = true;
logger.error('worker process failed [pid:%s]: %s', this.#pid, error.message);
this.close();
this.emit('@failure', error);
}
else {
logger.error('worker process error [pid:%s]: %s', this.#pid, error.message);
this.workerDied(error);
}
});
// Be ready for 3rd party worker libraries logging to stdout.
this.#child.stdout.on('data', (buffer) => {
for (const line of buffer.toString('utf8').split('\n')) {
if (line)
workerLogger.debug(`(stdout) ${line}`);
}
});
// In case of a worker bug, mediasoup will log to stderr.
this.#child.stderr.on('data', (buffer) => {
for (const line of buffer.toString('utf8').split('\n')) {
if (line)
workerLogger.error(`(stderr) ${line}`);
}
});
}
/**
* Worker process identifier (PID).
*/
get pid() {
return this.#pid;
}
/**
* Whether the Worker is closed.
*/
get closed() {
return this.#closed;
}
/**
* Whether the Worker died.
*/
get died() {
return this.#died;
}
/**
* App custom data.
*/
get appData() {
return this.#appData;
}
/**
* Invalid setter.
*/
set appData(appData) {
throw new Error('cannot override appData object');
}
/**
* Observer.
*/
get observer() {
return this.#observer;
}
/**
* @private
* Just for testing purposes.
*/
get webRtcServersForTesting() {
return this.#webRtcServers;
}
/**
* @private
* Just for testing purposes.
*/
get routersForTesting() {
return this.#routers;
}
/**
* Close the Worker.
*/
close() {
if (this.#closed)
return;
logger.debug('close()');
this.#closed = true;
// Kill the worker process.
if (this.#child) {
// Remove event listeners but leave a fake 'error' hander to avoid
// propagation.
this.#child.removeAllListeners('exit');
this.#child.removeAllListeners('error');
this.#child.on('error', () => { });
this.#child.kill('SIGTERM');
this.#child = undefined;
}
// Close the Channel instance.
this.#channel.close();
// Close the PayloadChannel instance.
this.#payloadChannel.close();
// Close every Router.
for (const router of this.#routers) {
router.workerClosed();
}
this.#routers.clear();
// Close every WebRtcServer.
for (const webRtcServer of this.#webRtcServers) {
webRtcServer.workerClosed();
}
this.#webRtcServers.clear();
// Emit observer event.
this.#observer.safeEmit('close');
}
/**
* Dump Worker.
*/
async dump() {
logger.debug('dump()');
return this.#channel.request('worker.dump');
}
/**
* Get mediasoup-worker process resource usage.
*/
async getResourceUsage() {
logger.debug('getResourceUsage()');
return this.#channel.request('worker.getResourceUsage');
}
/**
* Update settings.
*/
async updateSettings({ logLevel, logTags } = {}) {
logger.debug('updateSettings()');
const reqData = { logLevel, logTags };
await this.#channel.request('worker.updateSettings', undefined, reqData);
}
/**
* Create a WebRtcServer.
*/
async createWebRtcServer({ listenInfos, appData }) {
logger.debug('createWebRtcServer()');
if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const reqData = {
webRtcServerId: (0, uuid_1.v4)(),
listenInfos
};
await this.#channel.request('worker.createWebRtcServer', undefined, reqData);
const webRtcServer = new WebRtcServer_1.WebRtcServer({
internal: { webRtcServerId: reqData.webRtcServerId },
channel: this.#channel,
appData
});
this.#webRtcServers.add(webRtcServer);
webRtcServer.on('@close', () => this.#webRtcServers.delete(webRtcServer));
// Emit observer event.
this.#observer.safeEmit('newwebrtcserver', webRtcServer);
return webRtcServer;
}
/**
* Create a Router.
*/
async createRouter({ mediaCodecs, appData } = {}) {
logger.debug('createRouter()');
if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
// This may throw.
const rtpCapabilities = ortc.generateRouterRtpCapabilities(mediaCodecs);
const reqData = { routerId: (0, uuid_1.v4)() };
await this.#channel.request('worker.createRouter', undefined, reqData);
const data = { rtpCapabilities };
const router = new Router_1.Router({
internal: {
routerId: reqData.routerId
},
data,
channel: this.#channel,
payloadChannel: this.#payloadChannel,
appData
});
this.#routers.add(router);
router.on('@close', () => this.#routers.delete(router));
// Emit observer event.
this.#observer.safeEmit('newrouter', router);
return router;
}
workerDied(error) {
if (this.#closed)
return;
logger.debug(`died() [error:${error}]`);
this.#closed = true;
this.#died = true;
// Close the Channel instance.
this.#channel.close();
// Close the PayloadChannel instance.
this.#payloadChannel.close();
// Close every Router.
for (const router of this.#routers) {
router.workerClosed();
}
this.#routers.clear();
// Close every WebRtcServer.
for (const webRtcServer of this.#webRtcServers) {
webRtcServer.workerClosed();
}
this.#webRtcServers.clear();
this.safeEmit('died', error);
// Emit observer event.
this.#observer.safeEmit('close');
}
}
exports.Worker = Worker;
/**
* Error indicating not support for something.
*/
export declare class UnsupportedError extends Error {
constructor(message: string);
}
/**
* Error produced when calling a method in an invalid state.
*/
export declare class InvalidStateError extends Error {
constructor(message: string);
}
//# sourceMappingURL=errors.d.ts.map
\ No newline at end of file
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;gBAE9B,OAAO,EAAE,MAAM;CAW3B;AAED;;GAEG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;gBAE/B,OAAO,EAAE,MAAM;CAW3B"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidStateError = exports.UnsupportedError = void 0;
/**
* Error indicating not support for something.
*/
class UnsupportedError extends Error {
constructor(message) {
super(message);
this.name = 'UnsupportedError';
if (Error.hasOwnProperty('captureStackTrace')) // Just in V8.
Error.captureStackTrace(this, UnsupportedError);
else
this.stack = (new Error(message)).stack;
}
}
exports.UnsupportedError = UnsupportedError;
/**
* Error produced when calling a method in an invalid state.
*/
class InvalidStateError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidStateError';
if (Error.hasOwnProperty('captureStackTrace')) // Just in V8.
Error.captureStackTrace(this, InvalidStateError);
else
this.stack = (new Error(message)).stack;
}
}
exports.InvalidStateError = InvalidStateError;
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Worker, WorkerSettings } from './Worker';
import { RtpCapabilities } from './RtpParameters';
import * as types from './types';
/**
* Expose all types.
*/
export { types };
/**
* Expose mediasoup version.
*/
export declare const version = "3.11.3";
/**
* Expose parseScalabilityMode() function.
*/
export { parse as parseScalabilityMode } from './scalabilityModes';
export declare type ObserverEvents = {
newworker: [Worker];
};
declare const observer: EnhancedEventEmitter<ObserverEvents>;
/**
* Observer.
*/
export { observer };
/**
* Create a Worker.
*/
export declare function createWorker({ logLevel, logTags, rtcMinPort, rtcMaxPort, dtlsCertificateFile, dtlsPrivateKeyFile, appData }?: WorkerSettings): Promise<Worker>;
/**
* Get a cloned copy of the mediasoup supported RTP capabilities.
*/
export declare function getSupportedRtpCapabilities(): RtpCapabilities;
//# sourceMappingURL=index.d.ts.map
\ No newline at end of file
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAGlD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAEjC;;GAEG;AACH,OAAO,EAAE,KAAK,EAAE,CAAC;AAEjB;;GAEG;AACH,eAAO,MAAM,OAAO,0BAA0B,CAAC;AAE/C;;GAEG;AACH,OAAO,EAAE,KAAK,IAAI,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAInE,oBAAY,cAAc,GAC1B;IACC,SAAS,EAAE,CAAC,MAAM,CAAC,CAAC;CACpB,CAAC;AAEF,QAAA,MAAM,QAAQ,sCAA6C,CAAC;AAE5D;;GAEG;AACH,OAAO,EAAE,QAAQ,EAAE,CAAC;AAEpB;;GAEG;AACH,wBAAsB,YAAY,CACjC,EACC,QAAkB,EAClB,OAAO,EACP,UAAkB,EAClB,UAAkB,EAClB,mBAAmB,EACnB,kBAAkB,EAClB,OAAO,EACP,GAAE,cAAmB,GACpB,OAAO,CAAC,MAAM,CAAC,CA8BjB;AAED;;GAEG;AACH,wBAAgB,2BAA2B,IAAI,eAAe,CAG7D"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSupportedRtpCapabilities = exports.createWorker = exports.observer = exports.parseScalabilityMode = exports.version = exports.types = void 0;
const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const Worker_1 = require("./Worker");
const utils = require("./utils");
const supportedRtpCapabilities_1 = require("./supportedRtpCapabilities");
const types = require("./types");
exports.types = types;
/**
* Expose mediasoup version.
*/
exports.version = '3.11.3';
/**
* Expose parseScalabilityMode() function.
*/
var scalabilityModes_1 = require("./scalabilityModes");
Object.defineProperty(exports, "parseScalabilityMode", { enumerable: true, get: function () { return scalabilityModes_1.parse; } });
const logger = new Logger_1.Logger();
const observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
exports.observer = observer;
/**
* Create a Worker.
*/
async function createWorker({ logLevel = 'error', logTags, rtcMinPort = 10000, rtcMaxPort = 59999, dtlsCertificateFile, dtlsPrivateKeyFile, appData } = {}) {
logger.debug('createWorker()');
if (appData && typeof appData !== 'object')
throw new TypeError('if given, appData must be an object');
const worker = new Worker_1.Worker({
logLevel,
logTags,
rtcMinPort,
rtcMaxPort,
dtlsCertificateFile,
dtlsPrivateKeyFile,
appData
});
return new Promise((resolve, reject) => {
worker.on('@success', () => {
// Emit observer event.
observer.safeEmit('newworker', worker);
resolve(worker);
});
worker.on('@failure', reject);
});
}
exports.createWorker = createWorker;
/**
* Get a cloned copy of the mediasoup supported RTP capabilities.
*/
function getSupportedRtpCapabilities() {
return utils.clone(supportedRtpCapabilities_1.supportedRtpCapabilities);
}
exports.getSupportedRtpCapabilities = getSupportedRtpCapabilities;
import { RtpCapabilities, RtpCodecCapability, RtpHeaderExtension, RtpParameters, RtpCodecParameters, RtcpFeedback, RtpEncodingParameters, RtpHeaderExtensionParameters, RtcpParameters } from './RtpParameters';
import { SctpCapabilities, NumSctpStreams, SctpParameters, SctpStreamParameters } from './SctpParameters';
declare type RtpMapping = {
codecs: {
payloadType: number;
mappedPayloadType: number;
}[];
encodings: {
ssrc?: number;
rid?: string;
scalabilityMode?: string;
mappedSsrc: number;
}[];
};
/**
* Validates RtpCapabilities. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpCapabilities(caps: RtpCapabilities): void;
/**
* Validates RtpCodecCapability. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpCodecCapability(codec: RtpCodecCapability): void;
/**
* Validates RtcpFeedback. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtcpFeedback(fb: RtcpFeedback): void;
/**
* Validates RtpHeaderExtension. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpHeaderExtension(ext: RtpHeaderExtension): void;
/**
* Validates RtpParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpParameters(params: RtpParameters): void;
/**
* Validates RtpCodecParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpCodecParameters(codec: RtpCodecParameters): void;
/**
* Validates RtpHeaderExtensionParameteters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpHeaderExtensionParameters(ext: RtpHeaderExtensionParameters): void;
/**
* Validates RtpEncodingParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtpEncodingParameters(encoding: RtpEncodingParameters): void;
/**
* Validates RtcpParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateRtcpParameters(rtcp: RtcpParameters): void;
/**
* Validates SctpCapabilities. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateSctpCapabilities(caps: SctpCapabilities): void;
/**
* Validates NumSctpStreams. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateNumSctpStreams(numStreams: NumSctpStreams): void;
/**
* Validates SctpParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateSctpParameters(params: SctpParameters): void;
/**
* Validates SctpStreamParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
export declare function validateSctpStreamParameters(params: SctpStreamParameters): void;
/**
* Generate RTP capabilities for the Router based on the given media codecs and
* mediasoup supported RTP capabilities.
*/
export declare function generateRouterRtpCapabilities(mediaCodecs?: RtpCodecCapability[]): RtpCapabilities;
/**
* Get a mapping of codec payloads and encodings of the given Producer RTP
* parameters as values expected by the Router.
*
* It may throw if invalid or non supported RTP parameters are given.
*/
export declare function getProducerRtpParametersMapping(params: RtpParameters, caps: RtpCapabilities): RtpMapping;
/**
* Generate RTP parameters to be internally used by Consumers given the RTP
* parameters of a Producer and the RTP capabilities of the Router.
*/
export declare function getConsumableRtpParameters(kind: string, params: RtpParameters, caps: RtpCapabilities, rtpMapping: RtpMapping): RtpParameters;
/**
* Check whether the given RTP capabilities can consume the given Producer.
*/
export declare function canConsume(consumableParams: RtpParameters, caps: RtpCapabilities): boolean;
/**
* Generate RTP parameters for a specific Consumer.
*
* It reduces encodings to just one and takes into account given RTP capabilities
* to reduce codecs, codecs' RTCP feedback and header extensions, and also enables
* or disabled RTX.
*/
export declare function getConsumerRtpParameters(consumableParams: RtpParameters, caps: RtpCapabilities, pipe: boolean): RtpParameters;
/**
* Generate RTP parameters for a pipe Consumer.
*
* It keeps all original consumable encodings and removes support for BWE. If
* enableRtx is false, it also removes RTX and NACK support.
*/
export declare function getPipeConsumerRtpParameters(consumableParams: RtpParameters, enableRtx?: boolean): RtpParameters;
export {};
//# sourceMappingURL=ortc.d.ts.map
\ No newline at end of file
{"version":3,"file":"ortc.d.ts","sourceRoot":"","sources":["../src/ortc.ts"],"names":[],"mappings":"AAKA,OAAO,EACN,eAAe,EAEf,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,qBAAqB,EACrB,4BAA4B,EAC5B,cAAc,EACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACN,gBAAgB,EAChB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,MAAM,kBAAkB,CAAC;AAE1B,aAAK,UAAU,GACf;IACC,MAAM,EACN;QACC,WAAW,EAAE,MAAM,CAAC;QACpB,iBAAiB,EAAE,MAAM,CAAC;KAC1B,EAAE,CAAC;IAEJ,SAAS,EACT;QACC,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;KACnB,EAAE,CAAC;CACJ,CAAC;AASF;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI,CA0BnE;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI,CA0E1E;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAY3D;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,kBAAkB,GAAG,IAAI,CA4BxE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,CA+CjE;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI,CAyE1E;AAED;;;;GAIG;AACH,wBAAgB,oCAAoC,CACnD,GAAG,EAAE,4BAA4B,GAC/B,IAAI,CAqCN;AAED;;;;GAIG;AACH,wBAAgB,6BAA6B,CAAC,QAAQ,EAAE,qBAAqB,GAAG,IAAI,CAgCnF;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAYjE;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAUrE;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,cAAc,GAAG,IAAI,CAYvE;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAoBnE;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,oBAAoB,GAAG,IAAI,CAwC/E;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC5C,WAAW,GAAE,kBAAkB,EAAO,GACpC,eAAe,CAuGjB;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC9C,MAAM,EAAE,aAAa,EACrB,IAAI,EAAE,eAAe,GACnB,UAAU,CA+FZ;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CACzC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,aAAa,EACrB,IAAI,EAAE,eAAe,EACrB,UAAU,EAAE,UAAU,GACpB,aAAa,CAyGf;AAED;;GAEG;AACH,wBAAgB,UAAU,CACzB,gBAAgB,EAAE,aAAa,EAC/B,IAAI,EAAE,eAAe,GACnB,OAAO,CAuBT;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACvC,gBAAgB,EAAE,aAAa,EAC/B,IAAI,EAAE,eAAe,EACrB,IAAI,EAAE,OAAO,GACX,aAAa,CA6Kf;AAED;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC3C,gBAAgB,EAAE,aAAa,EAC/B,SAAS,UAAQ,GACf,aAAa,CAwDf"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPipeConsumerRtpParameters = exports.getConsumerRtpParameters = exports.canConsume = exports.getConsumableRtpParameters = exports.getProducerRtpParametersMapping = exports.generateRouterRtpCapabilities = exports.validateSctpStreamParameters = exports.validateSctpParameters = exports.validateNumSctpStreams = exports.validateSctpCapabilities = exports.validateRtcpParameters = exports.validateRtpEncodingParameters = exports.validateRtpHeaderExtensionParameters = exports.validateRtpCodecParameters = exports.validateRtpParameters = exports.validateRtpHeaderExtension = exports.validateRtcpFeedback = exports.validateRtpCodecCapability = exports.validateRtpCapabilities = void 0;
const h264 = require("h264-profile-level-id");
const utils = require("./utils");
const errors_1 = require("./errors");
const supportedRtpCapabilities_1 = require("./supportedRtpCapabilities");
const scalabilityModes_1 = require("./scalabilityModes");
const DynamicPayloadTypes = [
100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
122, 123, 124, 125, 126, 127, 96, 97, 98, 99
];
/**
* Validates RtpCapabilities. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpCapabilities(caps) {
if (typeof caps !== 'object')
throw new TypeError('caps is not an object');
// codecs is optional. If unset, fill with an empty array.
if (caps.codecs && !Array.isArray(caps.codecs))
throw new TypeError('caps.codecs is not an array');
else if (!caps.codecs)
caps.codecs = [];
for (const codec of caps.codecs) {
validateRtpCodecCapability(codec);
}
// headerExtensions is optional. If unset, fill with an empty array.
if (caps.headerExtensions && !Array.isArray(caps.headerExtensions))
throw new TypeError('caps.headerExtensions is not an array');
else if (!caps.headerExtensions)
caps.headerExtensions = [];
for (const ext of caps.headerExtensions) {
validateRtpHeaderExtension(ext);
}
}
exports.validateRtpCapabilities = validateRtpCapabilities;
/**
* Validates RtpCodecCapability. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpCodecCapability(codec) {
const MimeTypeRegex = new RegExp('^(audio|video)/(.+)', 'i');
if (typeof codec !== 'object')
throw new TypeError('codec is not an object');
// mimeType is mandatory.
if (!codec.mimeType || typeof codec.mimeType !== 'string')
throw new TypeError('missing codec.mimeType');
const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
if (!mimeTypeMatch)
throw new TypeError('invalid codec.mimeType');
// Just override kind with media component of mimeType.
codec.kind = mimeTypeMatch[1].toLowerCase();
// preferredPayloadType is optional.
if (codec.preferredPayloadType && typeof codec.preferredPayloadType !== 'number')
throw new TypeError('invalid codec.preferredPayloadType');
// clockRate is mandatory.
if (typeof codec.clockRate !== 'number')
throw new TypeError('missing codec.clockRate');
// channels is optional. If unset, set it to 1 (just if audio).
if (codec.kind === 'audio') {
if (typeof codec.channels !== 'number')
codec.channels = 1;
}
else {
delete codec.channels;
}
// parameters is optional. If unset, set it to an empty object.
if (!codec.parameters || typeof codec.parameters !== 'object')
codec.parameters = {};
for (const key of Object.keys(codec.parameters)) {
let value = codec.parameters[key];
if (value === undefined) {
codec.parameters[key] = '';
value = '';
}
if (typeof value !== 'string' && typeof value !== 'number') {
throw new TypeError(`invalid codec parameter [key:${key}s, value:${value}]`);
}
// Specific parameters validation.
if (key === 'apt') {
if (typeof value !== 'number')
throw new TypeError('invalid codec apt parameter');
}
}
// rtcpFeedback is optional. If unset, set it to an empty array.
if (!codec.rtcpFeedback || !Array.isArray(codec.rtcpFeedback))
codec.rtcpFeedback = [];
for (const fb of codec.rtcpFeedback) {
validateRtcpFeedback(fb);
}
}
exports.validateRtpCodecCapability = validateRtpCodecCapability;
/**
* Validates RtcpFeedback. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtcpFeedback(fb) {
if (typeof fb !== 'object')
throw new TypeError('fb is not an object');
// type is mandatory.
if (!fb.type || typeof fb.type !== 'string')
throw new TypeError('missing fb.type');
// parameter is optional. If unset set it to an empty string.
if (!fb.parameter || typeof fb.parameter !== 'string')
fb.parameter = '';
}
exports.validateRtcpFeedback = validateRtcpFeedback;
/**
* Validates RtpHeaderExtension. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpHeaderExtension(ext) {
if (typeof ext !== 'object')
throw new TypeError('ext is not an object');
if (ext.kind !== 'audio' && ext.kind !== 'video')
throw new TypeError('invalid ext.kind');
// uri is mandatory.
if (!ext.uri || typeof ext.uri !== 'string')
throw new TypeError('missing ext.uri');
// preferredId is mandatory.
if (typeof ext.preferredId !== 'number')
throw new TypeError('missing ext.preferredId');
// preferredEncrypt is optional. If unset set it to false.
if (ext.preferredEncrypt && typeof ext.preferredEncrypt !== 'boolean')
throw new TypeError('invalid ext.preferredEncrypt');
else if (!ext.preferredEncrypt)
ext.preferredEncrypt = false;
// direction is optional. If unset set it to sendrecv.
if (ext.direction && typeof ext.direction !== 'string')
throw new TypeError('invalid ext.direction');
else if (!ext.direction)
ext.direction = 'sendrecv';
}
exports.validateRtpHeaderExtension = validateRtpHeaderExtension;
/**
* Validates RtpParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpParameters(params) {
if (typeof params !== 'object')
throw new TypeError('params is not an object');
// mid is optional.
if (params.mid && typeof params.mid !== 'string')
throw new TypeError('params.mid is not a string');
// codecs is mandatory.
if (!Array.isArray(params.codecs))
throw new TypeError('missing params.codecs');
for (const codec of params.codecs) {
validateRtpCodecParameters(codec);
}
// headerExtensions is optional. If unset, fill with an empty array.
if (params.headerExtensions && !Array.isArray(params.headerExtensions))
throw new TypeError('params.headerExtensions is not an array');
else if (!params.headerExtensions)
params.headerExtensions = [];
for (const ext of params.headerExtensions) {
validateRtpHeaderExtensionParameters(ext);
}
// encodings is optional. If unset, fill with an empty array.
if (params.encodings && !Array.isArray(params.encodings))
throw new TypeError('params.encodings is not an array');
else if (!params.encodings)
params.encodings = [];
for (const encoding of params.encodings) {
validateRtpEncodingParameters(encoding);
}
// rtcp is optional. If unset, fill with an empty object.
if (params.rtcp && typeof params.rtcp !== 'object')
throw new TypeError('params.rtcp is not an object');
else if (!params.rtcp)
params.rtcp = {};
validateRtcpParameters(params.rtcp);
}
exports.validateRtpParameters = validateRtpParameters;
/**
* Validates RtpCodecParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpCodecParameters(codec) {
const MimeTypeRegex = new RegExp('^(audio|video)/(.+)', 'i');
if (typeof codec !== 'object')
throw new TypeError('codec is not an object');
// mimeType is mandatory.
if (!codec.mimeType || typeof codec.mimeType !== 'string')
throw new TypeError('missing codec.mimeType');
const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
if (!mimeTypeMatch)
throw new TypeError('invalid codec.mimeType');
// payloadType is mandatory.
if (typeof codec.payloadType !== 'number')
throw new TypeError('missing codec.payloadType');
// clockRate is mandatory.
if (typeof codec.clockRate !== 'number')
throw new TypeError('missing codec.clockRate');
const kind = mimeTypeMatch[1].toLowerCase();
// channels is optional. If unset, set it to 1 (just if audio).
if (kind === 'audio') {
if (typeof codec.channels !== 'number')
codec.channels = 1;
}
else {
delete codec.channels;
}
// parameters is optional. If unset, set it to an empty object.
if (!codec.parameters || typeof codec.parameters !== 'object')
codec.parameters = {};
for (const key of Object.keys(codec.parameters)) {
let value = codec.parameters[key];
if (value === undefined) {
codec.parameters[key] = '';
value = '';
}
if (typeof value !== 'string' && typeof value !== 'number') {
throw new TypeError(`invalid codec parameter [key:${key}s, value:${value}]`);
}
// Specific parameters validation.
if (key === 'apt') {
if (typeof value !== 'number')
throw new TypeError('invalid codec apt parameter');
}
}
// rtcpFeedback is optional. If unset, set it to an empty array.
if (!codec.rtcpFeedback || !Array.isArray(codec.rtcpFeedback))
codec.rtcpFeedback = [];
for (const fb of codec.rtcpFeedback) {
validateRtcpFeedback(fb);
}
}
exports.validateRtpCodecParameters = validateRtpCodecParameters;
/**
* Validates RtpHeaderExtensionParameteters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpHeaderExtensionParameters(ext) {
if (typeof ext !== 'object')
throw new TypeError('ext is not an object');
// uri is mandatory.
if (!ext.uri || typeof ext.uri !== 'string')
throw new TypeError('missing ext.uri');
// id is mandatory.
if (typeof ext.id !== 'number')
throw new TypeError('missing ext.id');
// encrypt is optional. If unset set it to false.
if (ext.encrypt && typeof ext.encrypt !== 'boolean')
throw new TypeError('invalid ext.encrypt');
else if (!ext.encrypt)
ext.encrypt = false;
// parameters is optional. If unset, set it to an empty object.
if (!ext.parameters || typeof ext.parameters !== 'object')
ext.parameters = {};
for (const key of Object.keys(ext.parameters)) {
let value = ext.parameters[key];
if (value === undefined) {
ext.parameters[key] = '';
value = '';
}
if (typeof value !== 'string' && typeof value !== 'number')
throw new TypeError('invalid header extension parameter');
}
}
exports.validateRtpHeaderExtensionParameters = validateRtpHeaderExtensionParameters;
/**
* Validates RtpEncodingParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtpEncodingParameters(encoding) {
if (typeof encoding !== 'object')
throw new TypeError('encoding is not an object');
// ssrc is optional.
if (encoding.ssrc && typeof encoding.ssrc !== 'number')
throw new TypeError('invalid encoding.ssrc');
// rid is optional.
if (encoding.rid && typeof encoding.rid !== 'string')
throw new TypeError('invalid encoding.rid');
// rtx is optional.
if (encoding.rtx && typeof encoding.rtx !== 'object') {
throw new TypeError('invalid encoding.rtx');
}
else if (encoding.rtx) {
// RTX ssrc is mandatory if rtx is present.
if (typeof encoding.rtx.ssrc !== 'number')
throw new TypeError('missing encoding.rtx.ssrc');
}
// dtx is optional. If unset set it to false.
if (!encoding.dtx || typeof encoding.dtx !== 'boolean')
encoding.dtx = false;
// scalabilityMode is optional.
if (encoding.scalabilityMode && typeof encoding.scalabilityMode !== 'string')
throw new TypeError('invalid encoding.scalabilityMode');
}
exports.validateRtpEncodingParameters = validateRtpEncodingParameters;
/**
* Validates RtcpParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateRtcpParameters(rtcp) {
if (typeof rtcp !== 'object')
throw new TypeError('rtcp is not an object');
// cname is optional.
if (rtcp.cname && typeof rtcp.cname !== 'string')
throw new TypeError('invalid rtcp.cname');
// reducedSize is optional. If unset set it to true.
if (!rtcp.reducedSize || typeof rtcp.reducedSize !== 'boolean')
rtcp.reducedSize = true;
}
exports.validateRtcpParameters = validateRtcpParameters;
/**
* Validates SctpCapabilities. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateSctpCapabilities(caps) {
if (typeof caps !== 'object')
throw new TypeError('caps is not an object');
// numStreams is mandatory.
if (!caps.numStreams || typeof caps.numStreams !== 'object')
throw new TypeError('missing caps.numStreams');
validateNumSctpStreams(caps.numStreams);
}
exports.validateSctpCapabilities = validateSctpCapabilities;
/**
* Validates NumSctpStreams. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateNumSctpStreams(numStreams) {
if (typeof numStreams !== 'object')
throw new TypeError('numStreams is not an object');
// OS is mandatory.
if (typeof numStreams.OS !== 'number')
throw new TypeError('missing numStreams.OS');
// MIS is mandatory.
if (typeof numStreams.MIS !== 'number')
throw new TypeError('missing numStreams.MIS');
}
exports.validateNumSctpStreams = validateNumSctpStreams;
/**
* Validates SctpParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateSctpParameters(params) {
if (typeof params !== 'object')
throw new TypeError('params is not an object');
// port is mandatory.
if (typeof params.port !== 'number')
throw new TypeError('missing params.port');
// OS is mandatory.
if (typeof params.OS !== 'number')
throw new TypeError('missing params.OS');
// MIS is mandatory.
if (typeof params.MIS !== 'number')
throw new TypeError('missing params.MIS');
// maxMessageSize is mandatory.
if (typeof params.maxMessageSize !== 'number')
throw new TypeError('missing params.maxMessageSize');
}
exports.validateSctpParameters = validateSctpParameters;
/**
* Validates SctpStreamParameters. It may modify given data by adding missing
* fields with default values.
* It throws if invalid.
*/
function validateSctpStreamParameters(params) {
if (typeof params !== 'object')
throw new TypeError('params is not an object');
// streamId is mandatory.
if (typeof params.streamId !== 'number')
throw new TypeError('missing params.streamId');
// ordered is optional.
let orderedGiven = false;
if (typeof params.ordered === 'boolean')
orderedGiven = true;
else
params.ordered = true;
// maxPacketLifeTime is optional.
if (params.maxPacketLifeTime && typeof params.maxPacketLifeTime !== 'number')
throw new TypeError('invalid params.maxPacketLifeTime');
// maxRetransmits is optional.
if (params.maxRetransmits && typeof params.maxRetransmits !== 'number')
throw new TypeError('invalid params.maxRetransmits');
if (params.maxPacketLifeTime && params.maxRetransmits)
throw new TypeError('cannot provide both maxPacketLifeTime and maxRetransmits');
if (orderedGiven &&
params.ordered &&
(params.maxPacketLifeTime || params.maxRetransmits)) {
throw new TypeError('cannot be ordered with maxPacketLifeTime or maxRetransmits');
}
else if (!orderedGiven && (params.maxPacketLifeTime || params.maxRetransmits)) {
params.ordered = false;
}
}
exports.validateSctpStreamParameters = validateSctpStreamParameters;
/**
* Generate RTP capabilities for the Router based on the given media codecs and
* mediasoup supported RTP capabilities.
*/
function generateRouterRtpCapabilities(mediaCodecs = []) {
// Normalize supported RTP capabilities.
validateRtpCapabilities(supportedRtpCapabilities_1.supportedRtpCapabilities);
if (!Array.isArray(mediaCodecs))
throw new TypeError('mediaCodecs must be an Array');
const clonedSupportedRtpCapabilities = utils.clone(supportedRtpCapabilities_1.supportedRtpCapabilities);
const dynamicPayloadTypes = utils.clone(DynamicPayloadTypes);
const caps = {
codecs: [],
headerExtensions: clonedSupportedRtpCapabilities.headerExtensions
};
for (const mediaCodec of mediaCodecs) {
// This may throw.
validateRtpCodecCapability(mediaCodec);
const matchedSupportedCodec = clonedSupportedRtpCapabilities
.codecs
.find((supportedCodec) => (matchCodecs(mediaCodec, supportedCodec, { strict: false })));
if (!matchedSupportedCodec) {
throw new errors_1.UnsupportedError(`media codec not supported [mimeType:${mediaCodec.mimeType}]`);
}
// Clone the supported codec.
const codec = utils.clone(matchedSupportedCodec);
// If the given media codec has preferredPayloadType, keep it.
if (typeof mediaCodec.preferredPayloadType === 'number') {
codec.preferredPayloadType = mediaCodec.preferredPayloadType;
// Also remove the pt from the list of available dynamic values.
const idx = dynamicPayloadTypes.indexOf(codec.preferredPayloadType);
if (idx > -1)
dynamicPayloadTypes.splice(idx, 1);
}
// Otherwise if the supported codec has preferredPayloadType, use it.
else if (typeof codec.preferredPayloadType === 'number') {
// No need to remove it from the list since it's not a dynamic value.
}
// Otherwise choose a dynamic one.
else {
// Take the first available pt and remove it from the list.
const pt = dynamicPayloadTypes.shift();
if (!pt)
throw new Error('cannot allocate more dynamic codec payload types');
codec.preferredPayloadType = pt;
}
// Ensure there is not duplicated preferredPayloadType values.
if (caps.codecs.some((c) => c.preferredPayloadType === codec.preferredPayloadType))
throw new TypeError('duplicated codec.preferredPayloadType');
// Merge the media codec parameters.
codec.parameters = { ...codec.parameters, ...mediaCodec.parameters };
// Append to the codec list.
caps.codecs.push(codec);
// Add a RTX video codec if video.
if (codec.kind === 'video') {
// Take the first available pt and remove it from the list.
const pt = dynamicPayloadTypes.shift();
if (!pt)
throw new Error('cannot allocate more dynamic codec payload types');
const rtxCodec = {
kind: codec.kind,
mimeType: `${codec.kind}/rtx`,
preferredPayloadType: pt,
clockRate: codec.clockRate,
parameters: {
apt: codec.preferredPayloadType
},
rtcpFeedback: []
};
// Append to the codec list.
caps.codecs.push(rtxCodec);
}
}
return caps;
}
exports.generateRouterRtpCapabilities = generateRouterRtpCapabilities;
/**
* Get a mapping of codec payloads and encodings of the given Producer RTP
* parameters as values expected by the Router.
*
* It may throw if invalid or non supported RTP parameters are given.
*/
function getProducerRtpParametersMapping(params, caps) {
const rtpMapping = {
codecs: [],
encodings: []
};
// Match parameters media codecs to capabilities media codecs.
const codecToCapCodec = new Map();
for (const codec of params.codecs) {
if (isRtxCodec(codec))
continue;
// Search for the same media codec in capabilities.
const matchedCapCodec = caps.codecs
.find((capCodec) => (matchCodecs(codec, capCodec, { strict: true, modify: true })));
if (!matchedCapCodec) {
throw new errors_1.UnsupportedError(`unsupported codec [mimeType:${codec.mimeType}, payloadType:${codec.payloadType}]`);
}
codecToCapCodec.set(codec, matchedCapCodec);
}
// Match parameters RTX codecs to capabilities RTX codecs.
for (const codec of params.codecs) {
if (!isRtxCodec(codec))
continue;
// Search for the associated media codec.
const associatedMediaCodec = params.codecs
.find((mediaCodec) => mediaCodec.payloadType === codec.parameters.apt);
if (!associatedMediaCodec) {
throw new TypeError(`missing media codec found for RTX PT ${codec.payloadType}`);
}
const capMediaCodec = codecToCapCodec.get(associatedMediaCodec);
// Ensure that the capabilities media codec has a RTX codec.
const associatedCapRtxCodec = caps.codecs
.find((capCodec) => (isRtxCodec(capCodec) &&
capCodec.parameters.apt === capMediaCodec.preferredPayloadType));
if (!associatedCapRtxCodec) {
throw new errors_1.UnsupportedError(`no RTX codec for capability codec PT ${capMediaCodec.preferredPayloadType}`);
}
codecToCapCodec.set(codec, associatedCapRtxCodec);
}
// Generate codecs mapping.
for (const [codec, capCodec] of codecToCapCodec) {
rtpMapping.codecs.push({
payloadType: codec.payloadType,
mappedPayloadType: capCodec.preferredPayloadType
});
}
// Generate encodings mapping.
let mappedSsrc = utils.generateRandomNumber();
for (const encoding of params.encodings) {
const mappedEncoding = {};
mappedEncoding.mappedSsrc = mappedSsrc++;
if (encoding.rid)
mappedEncoding.rid = encoding.rid;
if (encoding.ssrc)
mappedEncoding.ssrc = encoding.ssrc;
if (encoding.scalabilityMode)
mappedEncoding.scalabilityMode = encoding.scalabilityMode;
rtpMapping.encodings.push(mappedEncoding);
}
return rtpMapping;
}
exports.getProducerRtpParametersMapping = getProducerRtpParametersMapping;
/**
* Generate RTP parameters to be internally used by Consumers given the RTP
* parameters of a Producer and the RTP capabilities of the Router.
*/
function getConsumableRtpParameters(kind, params, caps, rtpMapping) {
const consumableParams = {
codecs: [],
headerExtensions: [],
encodings: [],
rtcp: {}
};
for (const codec of params.codecs) {
if (isRtxCodec(codec))
continue;
const consumableCodecPt = rtpMapping.codecs
.find((entry) => entry.payloadType === codec.payloadType)
.mappedPayloadType;
const matchedCapCodec = caps.codecs
.find((capCodec) => capCodec.preferredPayloadType === consumableCodecPt);
const consumableCodec = {
mimeType: matchedCapCodec.mimeType,
payloadType: matchedCapCodec.preferredPayloadType,
clockRate: matchedCapCodec.clockRate,
channels: matchedCapCodec.channels,
parameters: codec.parameters,
rtcpFeedback: matchedCapCodec.rtcpFeedback
};
consumableParams.codecs.push(consumableCodec);
const consumableCapRtxCodec = caps.codecs
.find((capRtxCodec) => (isRtxCodec(capRtxCodec) &&
capRtxCodec.parameters.apt === consumableCodec.payloadType));
if (consumableCapRtxCodec) {
const consumableRtxCodec = {
mimeType: consumableCapRtxCodec.mimeType,
payloadType: consumableCapRtxCodec.preferredPayloadType,
clockRate: consumableCapRtxCodec.clockRate,
parameters: consumableCapRtxCodec.parameters,
rtcpFeedback: consumableCapRtxCodec.rtcpFeedback
};
consumableParams.codecs.push(consumableRtxCodec);
}
}
for (const capExt of caps.headerExtensions) {
// Just take RTP header extension that can be used in Consumers.
if (capExt.kind !== kind ||
(capExt.direction !== 'sendrecv' && capExt.direction !== 'sendonly')) {
continue;
}
const consumableExt = {
uri: capExt.uri,
id: capExt.preferredId,
encrypt: capExt.preferredEncrypt,
parameters: {}
};
consumableParams.headerExtensions.push(consumableExt);
}
// Clone Producer encodings since we'll mangle them.
const consumableEncodings = utils.clone(params.encodings);
for (let i = 0; i < consumableEncodings.length; ++i) {
const consumableEncoding = consumableEncodings[i];
const { mappedSsrc } = rtpMapping.encodings[i];
// Remove useless fields.
delete consumableEncoding.rid;
delete consumableEncoding.rtx;
delete consumableEncoding.codecPayloadType;
// Set the mapped ssrc.
consumableEncoding.ssrc = mappedSsrc;
consumableParams.encodings.push(consumableEncoding);
}
consumableParams.rtcp =
{
cname: params.rtcp.cname,
reducedSize: true,
mux: true
};
return consumableParams;
}
exports.getConsumableRtpParameters = getConsumableRtpParameters;
/**
* Check whether the given RTP capabilities can consume the given Producer.
*/
function canConsume(consumableParams, caps) {
// This may throw.
validateRtpCapabilities(caps);
const matchingCodecs = [];
for (const codec of consumableParams.codecs) {
const matchedCapCodec = caps.codecs
.find((capCodec) => matchCodecs(capCodec, codec, { strict: true }));
if (!matchedCapCodec)
continue;
matchingCodecs.push(codec);
}
// Ensure there is at least one media codec.
if (matchingCodecs.length === 0 || isRtxCodec(matchingCodecs[0]))
return false;
return true;
}
exports.canConsume = canConsume;
/**
* Generate RTP parameters for a specific Consumer.
*
* It reduces encodings to just one and takes into account given RTP capabilities
* to reduce codecs, codecs' RTCP feedback and header extensions, and also enables
* or disabled RTX.
*/
function getConsumerRtpParameters(consumableParams, caps, pipe) {
const consumerParams = {
codecs: [],
headerExtensions: [],
encodings: [],
rtcp: consumableParams.rtcp
};
for (const capCodec of caps.codecs) {
validateRtpCodecCapability(capCodec);
}
const consumableCodecs = utils.clone(consumableParams.codecs);
let rtxSupported = false;
for (const codec of consumableCodecs) {
const matchedCapCodec = caps.codecs
.find((capCodec) => matchCodecs(capCodec, codec, { strict: true }));
if (!matchedCapCodec)
continue;
codec.rtcpFeedback = matchedCapCodec.rtcpFeedback;
consumerParams.codecs.push(codec);
}
// Must sanitize the list of matched codecs by removing useless RTX codecs.
for (let idx = consumerParams.codecs.length - 1; idx >= 0; --idx) {
const codec = consumerParams.codecs[idx];
if (isRtxCodec(codec)) {
// Search for the associated media codec.
const associatedMediaCodec = consumerParams.codecs
.find((mediaCodec) => mediaCodec.payloadType === codec.parameters.apt);
if (associatedMediaCodec)
rtxSupported = true;
else
consumerParams.codecs.splice(idx, 1);
}
}
// Ensure there is at least one media codec.
if (consumerParams.codecs.length === 0 || isRtxCodec(consumerParams.codecs[0])) {
throw new errors_1.UnsupportedError('no compatible media codecs');
}
consumerParams.headerExtensions = consumableParams.headerExtensions
.filter((ext) => (caps.headerExtensions
.some((capExt) => (capExt.preferredId === ext.id &&
capExt.uri === ext.uri))));
// Reduce codecs' RTCP feedback. Use Transport-CC if available, REMB otherwise.
if (consumerParams.headerExtensions.some((ext) => (ext.uri === 'http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01'))) {
for (const codec of consumerParams.codecs) {
codec.rtcpFeedback = codec.rtcpFeedback
.filter((fb) => fb.type !== 'goog-remb');
}
}
else if (consumerParams.headerExtensions.some((ext) => (ext.uri === 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time'))) {
for (const codec of consumerParams.codecs) {
codec.rtcpFeedback = codec.rtcpFeedback
.filter((fb) => fb.type !== 'transport-cc');
}
}
else {
for (const codec of consumerParams.codecs) {
codec.rtcpFeedback = codec.rtcpFeedback
.filter((fb) => (fb.type !== 'transport-cc' &&
fb.type !== 'goog-remb'));
}
}
if (!pipe) {
const consumerEncoding = {
ssrc: utils.generateRandomNumber()
};
if (rtxSupported)
consumerEncoding.rtx = { ssrc: consumerEncoding.ssrc + 1 };
// If any of the consumableParams.encodings has scalabilityMode, process it
// (assume all encodings have the same value).
const encodingWithScalabilityMode = consumableParams.encodings.find((encoding) => encoding.scalabilityMode);
let scalabilityMode = encodingWithScalabilityMode
? encodingWithScalabilityMode.scalabilityMode
: undefined;
// If there is simulast, mangle spatial layers in scalabilityMode.
if (consumableParams.encodings.length > 1) {
const { temporalLayers } = (0, scalabilityModes_1.parse)(scalabilityMode);
scalabilityMode = `S${consumableParams.encodings.length}T${temporalLayers}`;
}
if (scalabilityMode)
consumerEncoding.scalabilityMode = scalabilityMode;
// Use the maximum maxBitrate in any encoding and honor it in the Consumer's
// encoding.
const maxEncodingMaxBitrate = consumableParams.encodings.reduce((maxBitrate, encoding) => (encoding.maxBitrate && encoding.maxBitrate > maxBitrate
? encoding.maxBitrate
: maxBitrate), 0);
if (maxEncodingMaxBitrate) {
consumerEncoding.maxBitrate = maxEncodingMaxBitrate;
}
// Set a single encoding for the Consumer.
consumerParams.encodings.push(consumerEncoding);
}
else {
const consumableEncodings = utils.clone(consumableParams.encodings);
const baseSsrc = utils.generateRandomNumber();
const baseRtxSsrc = utils.generateRandomNumber();
for (let i = 0; i < consumableEncodings.length; ++i) {
const encoding = consumableEncodings[i];
encoding.ssrc = baseSsrc + i;
if (rtxSupported)
encoding.rtx = { ssrc: baseRtxSsrc + i };
else
delete encoding.rtx;
consumerParams.encodings.push(encoding);
}
}
return consumerParams;
}
exports.getConsumerRtpParameters = getConsumerRtpParameters;
/**
* Generate RTP parameters for a pipe Consumer.
*
* It keeps all original consumable encodings and removes support for BWE. If
* enableRtx is false, it also removes RTX and NACK support.
*/
function getPipeConsumerRtpParameters(consumableParams, enableRtx = false) {
const consumerParams = {
codecs: [],
headerExtensions: [],
encodings: [],
rtcp: consumableParams.rtcp
};
const consumableCodecs = utils.clone(consumableParams.codecs);
for (const codec of consumableCodecs) {
if (!enableRtx && isRtxCodec(codec))
continue;
codec.rtcpFeedback = codec.rtcpFeedback
.filter((fb) => ((fb.type === 'nack' && fb.parameter === 'pli') ||
(fb.type === 'ccm' && fb.parameter === 'fir') ||
(enableRtx && fb.type === 'nack' && !fb.parameter)));
consumerParams.codecs.push(codec);
}
// Reduce RTP extensions by disabling transport MID and BWE related ones.
consumerParams.headerExtensions = consumableParams.headerExtensions
.filter((ext) => (ext.uri !== 'urn:ietf:params:rtp-hdrext:sdes:mid' &&
ext.uri !== 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time' &&
ext.uri !== 'http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01'));
const consumableEncodings = utils.clone(consumableParams.encodings);
const baseSsrc = utils.generateRandomNumber();
const baseRtxSsrc = utils.generateRandomNumber();
for (let i = 0; i < consumableEncodings.length; ++i) {
const encoding = consumableEncodings[i];
encoding.ssrc = baseSsrc + i;
if (enableRtx)
encoding.rtx = { ssrc: baseRtxSsrc + i };
else
delete encoding.rtx;
consumerParams.encodings.push(encoding);
}
return consumerParams;
}
exports.getPipeConsumerRtpParameters = getPipeConsumerRtpParameters;
function isRtxCodec(codec) {
return /.+\/rtx$/i.test(codec.mimeType);
}
function matchCodecs(aCodec, bCodec, { strict = false, modify = false } = {}) {
const aMimeType = aCodec.mimeType.toLowerCase();
const bMimeType = bCodec.mimeType.toLowerCase();
if (aMimeType !== bMimeType)
return false;
if (aCodec.clockRate !== bCodec.clockRate)
return false;
if (aCodec.channels !== bCodec.channels)
return false;
// Per codec special checks.
switch (aMimeType) {
case 'audio/multiopus':
{
const aNumStreams = aCodec.parameters['num_streams'];
const bNumStreams = bCodec.parameters['num_streams'];
if (aNumStreams !== bNumStreams)
return false;
const aCoupledStreams = aCodec.parameters['coupled_streams'];
const bCoupledStreams = bCodec.parameters['coupled_streams'];
if (aCoupledStreams !== bCoupledStreams)
return false;
break;
}
case 'video/h264':
case 'video/h264-svc':
{
if (strict) {
const aPacketizationMode = aCodec.parameters['packetization-mode'] || 0;
const bPacketizationMode = bCodec.parameters['packetization-mode'] || 0;
if (aPacketizationMode !== bPacketizationMode)
return false;
if (!h264.isSameProfile(aCodec.parameters, bCodec.parameters))
return false;
let selectedProfileLevelId;
try {
selectedProfileLevelId =
h264.generateProfileLevelIdForAnswer(aCodec.parameters, bCodec.parameters);
}
catch (error) {
return false;
}
if (modify) {
if (selectedProfileLevelId)
aCodec.parameters['profile-level-id'] = selectedProfileLevelId;
else
delete aCodec.parameters['profile-level-id'];
}
}
break;
}
case 'video/vp9':
{
if (strict) {
const aProfileId = aCodec.parameters['profile-id'] || 0;
const bProfileId = bCodec.parameters['profile-id'] || 0;
if (aProfileId !== bProfileId)
return false;
}
break;
}
}
return true;
}
export declare type ScalabilityMode = {
spatialLayers: number;
temporalLayers: number;
ksvc: boolean;
};
export declare function parse(scalabilityMode?: string): ScalabilityMode;
//# sourceMappingURL=scalabilityModes.d.ts.map
\ No newline at end of file
{"version":3,"file":"scalabilityModes.d.ts","sourceRoot":"","sources":["../src/scalabilityModes.ts"],"names":[],"mappings":"AAGA,oBAAY,eAAe,GAC3B;IACC,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,OAAO,CAAC;CACd,CAAC;AAEF,wBAAgB,KAAK,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,eAAe,CAoB/D"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = void 0;
const ScalabilityModeRegex = new RegExp('^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})(_KEY)?');
function parse(scalabilityMode) {
const match = ScalabilityModeRegex.exec(scalabilityMode || '');
if (match) {
return {
spatialLayers: Number(match[1]),
temporalLayers: Number(match[2]),
ksvc: Boolean(match[3])
};
}
else {
return {
spatialLayers: 1,
temporalLayers: 1,
ksvc: false
};
}
}
exports.parse = parse;
import { RtpCapabilities } from './RtpParameters';
declare const supportedRtpCapabilities: RtpCapabilities;
export { supportedRtpCapabilities };
//# sourceMappingURL=supportedRtpCapabilities.d.ts.map
\ No newline at end of file
{"version":3,"file":"supportedRtpCapabilities.d.ts","sourceRoot":"","sources":["../src/supportedRtpCapabilities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,QAAA,MAAM,wBAAwB,EAAE,eA+X/B,CAAC;AAEF,OAAO,EAAE,wBAAwB,EAAE,CAAC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.supportedRtpCapabilities = void 0;
const supportedRtpCapabilities = {
codecs: [
{
kind: 'audio',
mimeType: 'audio/opus',
clockRate: 48000,
channels: 2,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/multiopus',
clockRate: 48000,
channels: 4,
// Quad channel.
parameters: {
'channel_mapping': '0,1,2,3',
'num_streams': 2,
'coupled_streams': 2
},
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/multiopus',
clockRate: 48000,
channels: 6,
// 5.1.
parameters: {
'channel_mapping': '0,4,1,2,3,5',
'num_streams': 4,
'coupled_streams': 2
},
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/multiopus',
clockRate: 48000,
channels: 8,
// 7.1.
parameters: {
'channel_mapping': '0,6,1,2,3,4,5,7',
'num_streams': 5,
'coupled_streams': 3
},
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/PCMU',
preferredPayloadType: 0,
clockRate: 8000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/PCMA',
preferredPayloadType: 8,
clockRate: 8000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/ISAC',
clockRate: 32000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/ISAC',
clockRate: 16000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/G722',
preferredPayloadType: 9,
clockRate: 8000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/iLBC',
clockRate: 8000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/SILK',
clockRate: 24000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/SILK',
clockRate: 16000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/SILK',
clockRate: 12000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/SILK',
clockRate: 8000,
rtcpFeedback: [
{ type: 'transport-cc' }
]
},
{
kind: 'audio',
mimeType: 'audio/CN',
preferredPayloadType: 13,
clockRate: 32000
},
{
kind: 'audio',
mimeType: 'audio/CN',
preferredPayloadType: 13,
clockRate: 16000
},
{
kind: 'audio',
mimeType: 'audio/CN',
preferredPayloadType: 13,
clockRate: 8000
},
{
kind: 'audio',
mimeType: 'audio/telephone-event',
clockRate: 48000
},
{
kind: 'audio',
mimeType: 'audio/telephone-event',
clockRate: 32000
},
{
kind: 'audio',
mimeType: 'audio/telephone-event',
clockRate: 16000
},
{
kind: 'audio',
mimeType: 'audio/telephone-event',
clockRate: 8000
},
{
kind: 'video',
mimeType: 'video/VP8',
clockRate: 90000,
rtcpFeedback: [
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' },
{ type: 'transport-cc' }
]
},
{
kind: 'video',
mimeType: 'video/VP9',
clockRate: 90000,
rtcpFeedback: [
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' },
{ type: 'transport-cc' }
]
},
{
kind: 'video',
mimeType: 'video/H264',
clockRate: 90000,
parameters: {
'level-asymmetry-allowed': 1
},
rtcpFeedback: [
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' },
{ type: 'transport-cc' }
]
},
{
kind: 'video',
mimeType: 'video/H264-SVC',
clockRate: 90000,
parameters: {
'level-asymmetry-allowed': 1
},
rtcpFeedback: [
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' },
{ type: 'transport-cc' }
]
},
{
kind: 'video',
mimeType: 'video/H265',
clockRate: 90000,
parameters: {
'level-asymmetry-allowed': 1
},
rtcpFeedback: [
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'goog-remb' },
{ type: 'transport-cc' }
]
}
],
headerExtensions: [
{
kind: 'audio',
uri: 'urn:ietf:params:rtp-hdrext:sdes:mid',
preferredId: 1,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'urn:ietf:params:rtp-hdrext:sdes:mid',
preferredId: 1,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id',
preferredId: 2,
preferredEncrypt: false,
direction: 'recvonly'
},
{
kind: 'video',
uri: 'urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id',
preferredId: 3,
preferredEncrypt: false,
direction: 'recvonly'
},
{
kind: 'audio',
uri: 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time',
preferredId: 4,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time',
preferredId: 4,
preferredEncrypt: false,
direction: 'sendrecv'
},
// NOTE: For audio we just enable transport-wide-cc-01 when receiving media.
{
kind: 'audio',
uri: 'http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01',
preferredId: 5,
preferredEncrypt: false,
direction: 'recvonly'
},
{
kind: 'video',
uri: 'http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01',
preferredId: 5,
preferredEncrypt: false,
direction: 'sendrecv'
},
// NOTE: Remove this once framemarking draft becomes RFC.
{
kind: 'video',
uri: 'http://tools.ietf.org/html/draft-ietf-avtext-framemarking-07',
preferredId: 6,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'urn:ietf:params:rtp-hdrext:framemarking',
preferredId: 7,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'audio',
uri: 'urn:ietf:params:rtp-hdrext:ssrc-audio-level',
preferredId: 10,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'urn:3gpp:video-orientation',
preferredId: 11,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'urn:ietf:params:rtp-hdrext:toffset',
preferredId: 12,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'audio',
uri: 'http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time',
preferredId: 13,
preferredEncrypt: false,
direction: 'sendrecv'
},
{
kind: 'video',
uri: 'http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time',
preferredId: 13,
preferredEncrypt: false,
direction: 'sendrecv'
}
]
};
exports.supportedRtpCapabilities = supportedRtpCapabilities;
export * from './Worker';
export * from './WebRtcServer';
export * from './Router';
export * from './Transport';
export * from './WebRtcTransport';
export * from './PlainTransport';
export * from './PipeTransport';
export * from './DirectTransport';
export * from './Producer';
export * from './Consumer';
export * from './DataProducer';
export * from './DataConsumer';
export * from './RtpObserver';
export * from './ActiveSpeakerObserver';
export * from './AudioLevelObserver';
export * from './RtpParameters';
export * from './SctpParameters';
export * from './SrtpParameters';
export * from './errors';
export { ScalabilityMode } from './scalabilityModes';
//# sourceMappingURL=types.d.ts.map
\ No newline at end of file
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,yBAAyB,CAAC;AACxC,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,kBAAkB,CAAC;AACjC,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC"}
\ No newline at end of file
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./Worker"), exports);
__exportStar(require("./WebRtcServer"), exports);
__exportStar(require("./Router"), exports);
__exportStar(require("./Transport"), exports);
__exportStar(require("./WebRtcTransport"), exports);
__exportStar(require("./PlainTransport"), exports);
__exportStar(require("./PipeTransport"), exports);
__exportStar(require("./DirectTransport"), exports);
__exportStar(require("./Producer"), exports);
__exportStar(require("./Consumer"), exports);
__exportStar(require("./DataProducer"), exports);
__exportStar(require("./DataConsumer"), exports);
__exportStar(require("./RtpObserver"), exports);
__exportStar(require("./ActiveSpeakerObserver"), exports);
__exportStar(require("./AudioLevelObserver"), exports);
__exportStar(require("./RtpParameters"), exports);
__exportStar(require("./SctpParameters"), exports);
__exportStar(require("./SrtpParameters"), exports);
__exportStar(require("./errors"), exports);
/**
* Clones the given object/array.
*/
export declare function clone(data: any): any;
/**
* Generates a random positive integer.
*/
export declare function generateRandomNumber(): number;
declare type Only<T, U> = {
[P in keyof T]: T[P];
} & {
[P in keyof U]?: never;
};
export declare type Either<T, U> = Only<T, U> | Only<U, T>;
export {};
//# sourceMappingURL=utils.d.ts.map
\ No newline at end of file
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,GAAG,GAAG,GAAG,CAMpC;AAED;;GAEG;AACH,wBAAgB,oBAAoB,WAGnC;AAED,aAAK,IAAI,CAAC,CAAC,EAAE,CAAC,IAAI;KAChB,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CACpB,GAAG;KACF,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK;CACtB,CAAC;AAEF,oBAAY,MAAM,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC"}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRandomNumber = exports.clone = void 0;
const crypto_1 = require("crypto");
/**
* Clones the given object/array.
*/
function clone(data) {
if (typeof data !== 'object')
return {};
return JSON.parse(JSON.stringify(data));
}
exports.clone = clone;
/**
* Generates a random positive integer.
*/
function generateRandomNumber() {
return (0, crypto_1.randomInt)(100_000_000, 999_999_999);
}
exports.generateRandomNumber = generateRandomNumber;
/* eslint-disable no-console */
const process = require('process');
const os = require('os');
const fs = require('fs');
......@@ -14,44 +16,61 @@ const MAYOR_VERSION = version.split('.')[0];
// make command to use.
const MAKE = process.env.MAKE || (isFreeBSD ? 'gmake' : 'make');
// eslint-disable-next-line no-console
console.log(`npm-scripts.js [INFO] running task "${task}"`);
switch (task)
{
case 'typescript:build':
// As per NPM documentation (https://docs.npmjs.com/cli/v9/using-npm/scripts)
// `prepare` script:
//
// - Runs BEFORE the package is packed, i.e. during `npm publish` and `npm pack`.
// - Runs on local `npm install` without any arguments.
// - NOTE: If a package being installed through git contains a `prepare` script,
// its dependencies and devDependencies will be installed, and the `prepare`
// script will be run, before the package is packaged and installed.
//
// So here we compile TypeScript and flatbuffers to JavaScript.
case 'prepare':
{
if (!isWindows)
{
execute('rm -rf node/lib');
}
else
buildTypescript(/* force */ false);
// TODO: Compile flatbuffers.
break;
}
case 'postinstall':
{
if (!process.env.MEDIASOUP_WORKER_BIN)
{
execute('rmdir /s /q "node/lib"');
buildWorker();
if (!process.env.MEDIASOUP_LOCAL_DEV)
{
cleanWorker();
}
}
execute('tsc --project node');
taskReplaceVersion();
break;
}
case 'typescript:build':
{
installNodeDeps();
buildTypescript(/* force */ true);
replaceVersion();
break;
}
case 'typescript:watch':
{
const TscWatchClient = require('tsc-watch/client');
if (!isWindows)
{
execute('rm -rf node/lib');
}
else
{
execute('rmdir /s /q "node/lib"');
}
deleteNodeLib();
const TscWatchClient = require('tsc-watch/client');
const watch = new TscWatchClient();
watch.on('success', taskReplaceVersion);
watch.on('success', replaceVersion);
watch.start('--project', 'node', '--pretty');
break;
......@@ -59,95 +78,87 @@ switch (task)
case 'worker:build':
{
execute(`${MAKE} -C worker`);
buildWorker();
break;
}
case 'lint:node':
{
execute('eslint -c node/.eslintrc.js --max-warnings 0 node/src/ node/.eslintrc.js npm-scripts.js node/tests/ worker/scripts/gulpfile.js');
lintNode();
break;
}
case 'lint:worker':
{
execute(`${MAKE} lint -C worker`);
lintWorker();
break;
}
case 'format:worker':
{
execute(`${MAKE} format -C worker`);
executeCmd(`${MAKE} format -C worker`);
break;
}
case 'test:node':
{
taskReplaceVersion();
if (!process.env.TEST_FILE)
{
execute('jest');
}
else
{
execute(`jest --testPathPattern ${process.env.TEST_FILE}`);
}
buildTypescript(/* force */ false);
replaceVersion();
testNode();
break;
}
case 'test:worker':
{
execute(`${MAKE} test -C worker`);
testWorker();
break;
}
case 'coverage':
case 'coverage:node':
{
taskReplaceVersion();
execute('jest --coverage');
execute('open-cli coverage/lcov-report/index.html');
buildTypescript(/* force */ false);
replaceVersion();
executeCmd('jest --coverage');
executeCmd('open-cli coverage/lcov-report/index.html');
break;
}
case 'postinstall':
case 'install-deps:node':
{
if (!process.env.MEDIASOUP_WORKER_BIN)
{
execute('node npm-scripts.js worker:build');
// Clean build artifacts except `mediasoup-worker`.
execute(`${MAKE} clean-build -C worker`);
// Clean downloaded dependencies.
execute(`${MAKE} clean-subprojects -C worker`);
// Clean PIP/Meson/Ninja.
execute(`${MAKE} clean-pip -C worker`);
}
installNodeDeps();
break;
}
case 'release':
{
execute('node npm-scripts.js typescript:build');
execute('npm run lint');
execute('npm run test');
execute(`git commit -am '${version}'`);
execute(`git tag -a ${version} -m '${version}'`);
execute(`git push origin v${MAYOR_VERSION} && git push origin --tags`);
execute('npm publish');
installNodeDeps();
buildTypescript(/* force */ true);
replaceVersion();
buildWorker();
lintNode();
lintWorker();
testNode();
testWorker();
executeCmd(`git commit -am '${version}'`);
executeCmd(`git tag -a ${version} -m '${version}'`);
executeCmd(`git push origin v${MAYOR_VERSION}`);
executeCmd(`git push origin '${version}'`);
executeCmd('npm publish');
break;
}
case 'install-clang-tools':
{
execute('npm ci --prefix worker/scripts');
executeCmd('npm ci --prefix worker/scripts');
break;
}
......@@ -158,8 +169,10 @@ switch (task)
}
}
function taskReplaceVersion()
function replaceVersion()
{
console.log('npm-scripts.js [INFO] replaceVersion()');
const files =
[
'node/lib/index.js',
......@@ -176,10 +189,107 @@ function taskReplaceVersion()
}
}
function execute(command)
function deleteNodeLib()
{
if (!fs.existsSync('node/lib'))
{
return;
}
console.log('npm-scripts.js [INFO] deleteNodeLib()');
if (!isWindows)
{
executeCmd('rm -rf node/lib');
}
else
{
// NOTE: This command fails in Windows if the dir doesn't exist.
executeCmd('rmdir /s /q "node/lib"', /* exitOnError */ false);
}
}
function buildTypescript(force = false)
{
if (!force && fs.existsSync('node/lib'))
{
return;
}
console.log('npm-scripts.js [INFO] buildTypescript()');
deleteNodeLib();
executeCmd('tsc --project node');
}
function buildWorker()
{
console.log('npm-scripts.js [INFO] buildWorker()');
executeCmd(`${MAKE} -C worker`);
}
function cleanWorker()
{
console.log('npm-scripts.js [INFO] cleanWorker()');
// Clean build artifacts except `mediasoup-worker`.
executeCmd(`${MAKE} clean-build -C worker`);
// Clean downloaded dependencies.
executeCmd(`${MAKE} clean-subprojects -C worker`);
// Clean PIP/Meson/Ninja.
executeCmd(`${MAKE} clean-pip -C worker`);
}
function lintNode()
{
console.log('npm-scripts.js [INFO] lintNode()');
executeCmd('eslint -c node/.eslintrc.js --max-warnings 0 node/src node/.eslintrc.js npm-scripts.js node/tests worker/scripts/gulpfile.js');
}
function lintWorker()
{
console.log('npm-scripts.js [INFO] lintWorker()');
executeCmd(`${MAKE} lint -C worker`);
}
function testNode()
{
console.log('npm-scripts.js [INFO] testNode()');
if (!process.env.TEST_FILE)
{
executeCmd('jest');
}
else
{
executeCmd(`jest --testPathPattern ${process.env.TEST_FILE}`);
}
}
function testWorker()
{
console.log('npm-scripts.js [INFO] testWorker()');
executeCmd(`${MAKE} test -C worker`);
}
function installNodeDeps()
{
// eslint-disable-next-line no-console
console.log(`npm-scripts.js [INFO] executing command: ${command}`);
console.log('npm-scripts.js [INFO] installNodeDeps()');
// Install/update Node deps.
executeCmd('npm ci --ignore-scripts');
// Update package-lock.json.
executeCmd('npm install --package-lock-only --ignore-scripts');
}
function executeCmd(command, exitOnError = true)
{
console.log(`npm-scripts.js [INFO] executeCmd(): ${command}`);
try
{
......@@ -187,6 +297,9 @@ function execute(command)
}
catch (error)
{
process.exit(1);
if (exitOnError)
{
process.exit(1);
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -25,14 +25,14 @@
"worker/Makefile",
"worker/meson.build",
"worker/meson_options.txt",
"worker/src/",
"worker/include/",
"worker/test/src/",
"worker/test/include/",
"worker/fuzzer/src/",
"worker/fuzzer/include/",
"worker/src",
"worker/include",
"worker/test/src",
"worker/test/include",
"worker/fuzzer/src",
"worker/fuzzer/include",
"worker/subprojects/*.wrap",
"worker/deps/libwebrtc/",
"worker/deps/libwebrtc",
"worker/scripts/*.py",
"worker/scripts/*.sh",
"worker/scripts/*.js",
......@@ -48,7 +48,8 @@
"node": ">=12"
},
"scripts": {
"install-clang-tools": "node npm-scripts.js install-clang-tools",
"prepare": "node npm-scripts.js prepare",
"postinstall": "node npm-scripts.js postinstall",
"typescript:build": "node npm-scripts.js typescript:build",
"typescript:watch": "node npm-scripts.js typescript:watch",
"worker:build": "node npm-scripts.js worker:build",
......@@ -57,10 +58,11 @@
"lint:worker": "node npm-scripts.js lint:worker",
"format:worker": "node npm-scripts.js format:worker",
"test": "npm run test:node && npm run test:worker",
"test:node": "npm run worker:build && node npm-scripts.js test:node",
"test:node": "node npm-scripts.js test:node",
"test:worker": "node npm-scripts.js test:worker",
"coverage": "npm run worker:build && node npm-scripts.js coverage",
"postinstall": "node npm-scripts.js postinstall",
"coverage:node": "node npm-scripts.js coverage:node",
"install-deps:node": "node npm-scripts.js install-deps:node",
"install-clang-tools": "node npm-scripts.js install-clang-tools",
"release": "node npm-scripts.js release"
},
"jest": {
......@@ -69,7 +71,6 @@
"testRegex": "node/tests/test.*\\.js"
},
"dependencies": {
"@types/node": "^18.11.9",
"debug": "^4.3.4",
"h264-profile-level-id": "^1.0.1",
"supports-color": "^9.2.3",
......@@ -77,17 +78,18 @@
},
"devDependencies": {
"@types/debug": "^4.1.7",
"@types/node": "^18.11.9",
"@types/uuid": "^8.3.4",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"eslint-plugin-jest": "^27.1.4",
"jest": "^29.2.2",
"@typescript-eslint/eslint-plugin": "^5.43.0",
"@typescript-eslint/parser": "^5.43.0",
"eslint": "^8.27.0",
"eslint-plugin-jest": "^27.1.5",
"jest": "^29.3.1",
"jest-tobetype": "^1.2.3",
"open-cli": "^7.1.0",
"pick-port": "^1.0.1",
"sctp": "^1.0.0",
"tsc-watch": "^5.0.3",
"typescript": "^4.8.4"
"typescript": "^4.9.3"
}
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论