提交 2a4891f4 authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi

Merge remote-tracking branch 'upstream/v3' into meson

# Conflicts:
#	worker/Cargo.toml
#	worker/build.rs
#	worker/compile_commands_template.json
#	worker/mediasoup-worker.gyp
# Changelog # Changelog
### WIP
* Worker communication optimization (aka removing netstring dependency) (PR #644).
### 3.8.4
* OPUS multi-channel (Surround sound) support (PR #647).
* Add `packetLoss` stats to transport (PR #648 by @ggarber).
* Fixes for active speaker observer (PR #655 by @ggarber).
* Fix big endian issues (PR #639).
* Update NPM deps.
### 3.8.3 ### 3.8.3
* Fix wrong `size_t*` to `int*` conversion in 64bit Big-Endian hosts (PR #637). * Fix wrong `size_t*` to `int*` conversion in 64bit Big-Endian hosts (PR #637).
......
...@@ -5,7 +5,7 @@ export declare class Channel extends EnhancedEventEmitter { ...@@ -5,7 +5,7 @@ export declare class Channel extends EnhancedEventEmitter {
private readonly _consumerSocket; private readonly _consumerSocket;
private _nextId; private _nextId;
private readonly _sents; private readonly _sents;
private _recvBuffer?; private _recvBuffer;
/** /**
* @private * @private
*/ */
......
{"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,OAAQ,SAAQ,oBAAoB;IAGhD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAC,CAAS;IAE7B;;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;IAoIF;;OAEG;IACH,KAAK,IAAI,IAAI;IAmCb;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IA8D1E,OAAO,CAAC,eAAe;CA+DvB"} {"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAoB9D,qBAAa,OAAQ,SAAQ,oBAAoB;IAGhD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAmB;IAEtC;;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,QAAQ,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAgE1E,OAAO,CAAC,eAAe;CA+DvB"}
\ No newline at end of file \ No newline at end of file
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
// @ts-ignore const os = require("os");
const netstring = require("netstring");
const Logger_1 = require("./Logger"); const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter"); const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const errors_1 = require("./errors"); const errors_1 = require("./errors");
const littleEndian = os.endianness() == 'LE';
const logger = new Logger_1.Logger('Channel'); const logger = new Logger_1.Logger('Channel');
// netstring length for a 4194304 bytes payload. // Binary length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313; const MESSAGE_MAX_LEN = 4194308;
const NS_PAYLOAD_MAX_LEN = 4194304; const PAYLOAD_MAX_LEN = 4194304;
class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter { class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
/** /**
* @private * @private
...@@ -21,77 +21,76 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -21,77 +21,76 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
this._nextId = 0; this._nextId = 0;
// Map of pending sent requests. // Map of pending sent requests.
this._sents = new Map(); this._sents = new Map();
// Buffer for reading messages from the worker.
this._recvBuffer = Buffer.alloc(0);
logger.debug('constructor()'); logger.debug('constructor()');
this._producerSocket = producerSocket; this._producerSocket = producerSocket;
this._consumerSocket = consumerSocket; this._consumerSocket = consumerSocket;
// Read Channel responses/notifications from the worker. // Read Channel responses/notifications from the worker.
this._consumerSocket.on('data', (buffer) => { this._consumerSocket.on('data', (buffer) => {
if (!this._recvBuffer) { if (!this._recvBuffer.length) {
this._recvBuffer = buffer; this._recvBuffer = buffer;
} }
else { else {
this._recvBuffer = Buffer.concat([this._recvBuffer, buffer], this._recvBuffer.length + buffer.length); this._recvBuffer = Buffer.concat([this._recvBuffer, buffer], this._recvBuffer.length + buffer.length);
} }
if (this._recvBuffer.length > NS_PAYLOAD_MAX_LEN) { if (this._recvBuffer.length > PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data into it'); logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit. // Reset the buffer and exit.
this._recvBuffer = undefined; this._recvBuffer = Buffer.alloc(0);
return; return;
} }
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition while (true) // eslint-disable-line no-constant-condition
{ {
let nsPayload; const readLen = this._recvBuffer.length - msgStart;
try { if (readLen < 4) {
nsPayload = netstring.nsPayload(this._recvBuffer); // Incomplete data.
break;
} }
catch (error) { const dataView = new DataView(this._recvBuffer.buffer, this._recvBuffer.byteOffset + msgStart);
logger.error('invalid netstring data received from the worker process: %s', String(error)); const msgLen = dataView.getUint32(0, littleEndian);
// Reset the buffer and exit. if (readLen < 4 + msgLen) {
this._recvBuffer = undefined; // Incomplete data.
return; break;
} }
// Incomplete netstring message. const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
if (nsPayload === -1) msgStart += 4 + msgLen;
return;
try { try {
// We can receive JSON messages (Channel messages) or log strings. // We can receive JSON messages (Channel messages) or log strings.
switch (nsPayload[0]) { switch (payload[0]) {
// 123 = '{' (a Channel JSON messsage). // 123 = '{' (a Channel JSON message).
case 123: case 123:
this._processMessage(JSON.parse(nsPayload.toString('utf8'))); this._processMessage(JSON.parse(payload.toString('utf8')));
break; break;
// 68 = 'D' (a debug log). // 68 = 'D' (a debug log).
case 68: case 68:
logger.debug(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`); logger.debug(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break; break;
// 87 = 'W' (a warn log). // 87 = 'W' (a warn log).
case 87: case 87:
logger.warn(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`); logger.warn(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break; break;
// 69 = 'E' (an error log). // 69 = 'E' (an error log).
case 69: case 69:
logger.error(`[pid:${pid} ${nsPayload.toString('utf8', 1)}`); logger.error(`[pid:${pid} ${payload.toString('utf8', 1)}`);
break; break;
// 88 = 'X' (a dump log). // 88 = 'X' (a dump log).
case 88: case 88:
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(nsPayload.toString('utf8', 1)); console.log(payload.toString('utf8', 1));
break; break;
default: default:
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.warn(`worker[pid:${pid}] unexpected data: %s`, nsPayload.toString('utf8', 1)); console.warn(`worker[pid:${pid}] unexpected data: %s`, payload.toString('utf8', 1));
} }
} }
catch (error) { catch (error) {
logger.error('received invalid message from the worker process: %s', String(error)); logger.error('received invalid message from the worker process: %s', String(error));
} }
// Remove the read payload from the buffer.
this._recvBuffer =
this._recvBuffer.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length) {
this._recvBuffer = undefined;
return;
} }
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('end', () => (logger.debug('Consumer Channel ended by the worker process')));
...@@ -141,11 +140,12 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -141,11 +140,12 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
if (this._closed) if (this._closed)
throw new errors_1.InvalidStateError('Channel closed'); throw new errors_1.InvalidStateError('Channel closed');
const request = { id, method, internal, data }; const request = { id, method, internal, data };
const ns = netstring.nsWrite(JSON.stringify(request)); const payload = JSON.stringify(request);
if (Buffer.byteLength(ns) > NS_MESSAGE_MAX_LEN) if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big'); throw new Error('Channel request too big');
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns); this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) => { return new Promise((pResolve, pReject) => {
const timeout = 1000 * (15 + (0.1 * this._sents.size)); const timeout = 1000 * (15 + (0.1 * this._sents.size));
const sent = { const sent = {
......
...@@ -6,7 +6,7 @@ export declare class PayloadChannel extends EnhancedEventEmitter { ...@@ -6,7 +6,7 @@ export declare class PayloadChannel extends EnhancedEventEmitter {
private readonly _consumerSocket; private readonly _consumerSocket;
private _nextId; private _nextId;
private readonly _sents; private readonly _sents;
private _recvBuffer?; private _recvBuffer;
private _ongoingNotification?; private _ongoingNotification?;
/** /**
* @private * @private
......
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,cAAe,SAAQ,oBAAoB;IAGvD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAC,CAAS;IAG7B,OAAO,CAAC,oBAAoB,CAAC,CAAkD;IAE/E;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;KACpB;IAyFF;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Bb;;OAEG;IACH,MAAM,CACL,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,GAAG,SAAS,EACrB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IAyCP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAkExC,OAAO,CAAC,YAAY;CA8FpB"} {"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAoB9D,qBAAa,cAAe,SAAQ,oBAAoB;IAGvD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAGzC,OAAO,CAAC,OAAO,CAAK;IAGpB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgC;IAGvD,OAAO,CAAC,WAAW,CAAmB;IAGtC,OAAO,CAAC,oBAAoB,CAAC,CAAkD;IAE/E;;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,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,GAAG,SAAS,EACrB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IA2CP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAoExC,OAAO,CAAC,YAAY;CA8FpB"}
\ No newline at end of file \ No newline at end of file
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
// @ts-ignore const os = require("os");
const netstring = require("netstring");
const Logger_1 = require("./Logger"); const Logger_1 = require("./Logger");
const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter"); const EnhancedEventEmitter_1 = require("./EnhancedEventEmitter");
const errors_1 = require("./errors"); const errors_1 = require("./errors");
const littleEndian = os.endianness() == 'LE';
const logger = new Logger_1.Logger('PayloadChannel'); const logger = new Logger_1.Logger('PayloadChannel');
// netstring length for a 4194304 bytes payload. // Binary length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313; const MESSAGE_MAX_LEN = 4194308;
const NS_PAYLOAD_MAX_LEN = 4194304; const PAYLOAD_MAX_LEN = 4194304;
class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
/** /**
* @private * @private
...@@ -21,46 +21,45 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -21,46 +21,45 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
this._nextId = 0; this._nextId = 0;
// Map of pending sent requests. // Map of pending sent requests.
this._sents = new Map(); this._sents = new Map();
// Buffer for reading messages from the worker.
this._recvBuffer = Buffer.alloc(0);
logger.debug('constructor()'); logger.debug('constructor()');
this._producerSocket = producerSocket; this._producerSocket = producerSocket;
this._consumerSocket = consumerSocket; this._consumerSocket = consumerSocket;
// Read PayloadChannel notifications from the worker. // Read PayloadChannel notifications from the worker.
this._consumerSocket.on('data', (buffer) => { this._consumerSocket.on('data', (buffer) => {
if (!this._recvBuffer) { if (!this._recvBuffer.length) {
this._recvBuffer = buffer; this._recvBuffer = buffer;
} }
else { else {
this._recvBuffer = Buffer.concat([this._recvBuffer, buffer], this._recvBuffer.length + buffer.length); this._recvBuffer = Buffer.concat([this._recvBuffer, buffer], this._recvBuffer.length + buffer.length);
} }
if (this._recvBuffer.length > NS_PAYLOAD_MAX_LEN) { if (this._recvBuffer.length > PAYLOAD_MAX_LEN) {
logger.error('receiving buffer is full, discarding all data into it'); logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit. // Reset the buffer and exit.
this._recvBuffer = undefined; this._recvBuffer = Buffer.alloc(0);
return; return;
} }
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition while (true) // eslint-disable-line no-constant-condition
{ {
let nsPayload; const readLen = this._recvBuffer.length - msgStart;
try { if (readLen < 4) {
nsPayload = netstring.nsPayload(this._recvBuffer); // Incomplete data.
break;
} }
catch (error) { const dataView = new DataView(this._recvBuffer.buffer, this._recvBuffer.byteOffset + msgStart);
logger.error('invalid netstring data received from the worker process: %s', String(error)); const msgLen = dataView.getUint32(0, littleEndian);
// Reset the buffer and exit. if (readLen < 4 + msgLen) {
this._recvBuffer = undefined; // Incomplete data.
return; break;
} }
// Incomplete netstring message. const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
if (nsPayload === -1) msgStart += 4 + msgLen;
return; this._processData(payload);
this._processData(nsPayload);
// Remove the read payload from the buffer.
this._recvBuffer =
this._recvBuffer.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length) {
this._recvBuffer = undefined;
return;
} }
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('end', () => (logger.debug('Consumer PayloadChannel ended by the worker process')));
...@@ -103,16 +102,15 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -103,16 +102,15 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('notify() [event:%s]', event); logger.debug('notify() [event:%s]', event);
if (this._closed) if (this._closed)
throw new errors_1.InvalidStateError('PayloadChannel closed'); throw new errors_1.InvalidStateError('PayloadChannel closed');
const notification = { event, internal, data }; const notification = JSON.stringify({ event, internal, data });
const ns1 = netstring.nsWrite(JSON.stringify(notification)); if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big'); throw new Error('PayloadChannel notification too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN) else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big'); throw new Error('PayloadChannel payload too big');
try { try {
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns1); this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(notification)).buffer));
this._producerSocket.write(notification);
} }
catch (error) { catch (error) {
logger.warn('notify() | sending notification failed: %s', String(error)); logger.warn('notify() | sending notification failed: %s', String(error));
...@@ -120,7 +118,8 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -120,7 +118,8 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
} }
try { try {
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns2); this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
} }
catch (error) { catch (error) {
logger.warn('notify() | sending payload failed: %s', String(error)); logger.warn('notify() | sending payload failed: %s', String(error));
...@@ -136,16 +135,16 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -136,16 +135,16 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('request() [method:%s, id:%s]', method, id); logger.debug('request() [method:%s, id:%s]', method, id);
if (this._closed) if (this._closed)
throw new errors_1.InvalidStateError('Channel closed'); throw new errors_1.InvalidStateError('Channel closed');
const request = { id, method, internal, data }; const request = JSON.stringify({ id, method, internal, data });
const ns1 = netstring.nsWrite(JSON.stringify(request)); if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
throw new Error('Channel request too big'); throw new Error('Channel request too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN) else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big'); throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns1); this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this._producerSocket.write(ns2); this._producerSocket.write(request);
this._producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) => { return new Promise((pResolve, pReject) => {
const timeout = 1000 * (15 + (0.1 * this._sents.size)); const timeout = 1000 * (15 + (0.1 * this._sents.size));
const sent = { const sent = {
......
...@@ -68,7 +68,7 @@ class Worker extends EnhancedEventEmitter_1.EnhancedEventEmitter { ...@@ -68,7 +68,7 @@ class Worker extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// options // options
{ {
env: { env: {
MEDIASOUP_VERSION: '3.8.3', MEDIASOUP_VERSION: '3.8.4',
// Let the worker process inherit all environment variables, useful // 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 // if a custom and not in the path GCC is used so the user can set
// LD_LIBRARY_PATH environment variable for runtime. // LD_LIBRARY_PATH environment variable for runtime.
......
...@@ -9,7 +9,7 @@ export { types }; ...@@ -9,7 +9,7 @@ export { types };
/** /**
* Expose mediasoup version. * Expose mediasoup version.
*/ */
export declare const version = "3.8.3"; export declare const version = "3.8.4";
/** /**
* Expose parseScalabilityMode() function. * Expose parseScalabilityMode() function.
*/ */
......
...@@ -10,7 +10,7 @@ exports.types = types; ...@@ -10,7 +10,7 @@ exports.types = types;
/** /**
* Expose mediasoup version. * Expose mediasoup version.
*/ */
exports.version = '3.8.3'; exports.version = '3.8.4';
/** /**
* Expose parseScalabilityMode() function. * Expose parseScalabilityMode() function.
*/ */
......
...@@ -814,6 +814,18 @@ function matchCodecs(aCodec, bCodec, { strict = false, modify = false } = {}) { ...@@ -814,6 +814,18 @@ function matchCodecs(aCodec, bCodec, { strict = false, modify = false } = {}) {
return false; return false;
// Per codec special checks. // Per codec special checks.
switch (aMimeType) { 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':
{ {
const aPacketizationMode = aCodec.parameters['packetization-mode'] || 0; const aPacketizationMode = aCodec.parameters['packetization-mode'] || 0;
......
{"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,eAqV/B,CAAC;AAEF,OAAO,EAAE,wBAAwB,EAAE,CAAC"} {"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,eAwY/B,CAAC;AAEF,OAAO,EAAE,wBAAwB,EAAE,CAAC"}
\ No newline at end of file \ No newline at end of file
...@@ -11,6 +11,51 @@ const supportedRtpCapabilities = { ...@@ -11,6 +11,51 @@ const supportedRtpCapabilities = {
{ type: 'transport-cc' } { 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', kind: 'audio',
mimeType: 'audio/PCMU', mimeType: 'audio/PCMU',
......
{ {
"name": "mediasoup", "name": "mediasoup",
"version": "3.8.3", "version": "3.8.4",
"description": "Cutting Edge WebRTC Video Conferencing", "description": "Cutting Edge WebRTC Video Conferencing",
"contributors": [ "contributors": [
"Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)", "Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)",
...@@ -68,11 +68,10 @@ ...@@ -68,11 +68,10 @@
"testRegex": "test/test.*\\.js" "testRegex": "test/test.*\\.js"
}, },
"dependencies": { "dependencies": {
"@types/node": "^14.14.43", "@types/node": "^16.9.1",
"awaitqueue": "^2.3.3", "awaitqueue": "^2.3.3",
"debug": "^4.3.2", "debug": "^4.3.2",
"h264-profile-level-id": "^1.0.1", "h264-profile-level-id": "^1.0.1",
"netstring": "^0.3.0",
"random-number": "^0.0.9", "random-number": "^0.0.9",
"supports-color": "^9.0.2", "supports-color": "^9.0.2",
"uuid": "^8.3.2" "uuid": "^8.3.2"
...@@ -81,17 +80,17 @@ ...@@ -81,17 +80,17 @@
"@types/debug": "^4.1.7", "@types/debug": "^4.1.7",
"@types/random-number": "^0.0.1", "@types/random-number": "^0.0.1",
"@types/uuid": "^8.3.1", "@types/uuid": "^8.3.1",
"@typescript-eslint/eslint-plugin": "^4.29.1", "@typescript-eslint/eslint-plugin": "^4.31.0",
"@typescript-eslint/parser": "^4.29.1", "@typescript-eslint/parser": "^4.31.0",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-plugin-jest": "^24.4.0", "eslint-plugin-jest": "^24.4.0",
"jest": "^27.0.6", "jest": "^27.2.0",
"jest-tobetype": "^1.2.3", "jest-tobetype": "^1.2.3",
"open-cli": "^7.0.0", "open-cli": "^7.0.1",
"pick-port": "^1.0.0", "pick-port": "^1.0.0",
"sctp": "^1.0.0", "sctp": "^1.0.0",
"tsc-watch": "^4.4.0", "tsc-watch": "^4.5.0",
"typescript": "~3.8.3" "typescript": "~3.8.3"
} }
} }
# Changelog # Changelog
# Unreleased
* Fix for receiving data over payload channel
# 0.8.5
* Fix types for `round_trip_time` and `bitrate_by_layer` fields `ProducerStat` and `ConsumerStat`
* Accumulation of worker fixes
# 0.8.4 # 0.8.4
* Add Active Speaker Observer to prelude * Add Active Speaker Observer to prelude
......
[package] [package]
name = "mediasoup" name = "mediasoup"
version = "0.8.4" version = "0.8.5"
description = "Cutting Edge WebRTC Video Conferencing in Rust" description = "Cutting Edge WebRTC Video Conferencing in Rust"
categories = ["api-bindings", "multimedia", "network-programming"] categories = ["api-bindings", "multimedia", "network-programming"]
authors = ["Nazar Mokrynskyi <nazar@mokrynskyi.com>"] authors = ["Nazar Mokrynskyi <nazar@mokrynskyi.com>"]
...@@ -45,7 +45,7 @@ version = "0.6.5" ...@@ -45,7 +45,7 @@ version = "0.6.5"
[dependencies.mediasoup-sys] [dependencies.mediasoup-sys]
path = "../worker" path = "../worker"
version = "0.2.4" version = "0.2.5"
[dependencies.parking_lot] [dependencies.parking_lot]
version = "0.11.1" version = "0.11.1"
...@@ -69,3 +69,11 @@ actix = "0.12.0" ...@@ -69,3 +69,11 @@ actix = "0.12.0"
actix-web = "4.0.0-beta.8" actix-web = "4.0.0-beta.8"
actix-web-actors = "4.0.0-beta.6" actix-web-actors = "4.0.0-beta.6"
env_logger = "0.9.0" env_logger = "0.9.0"
[dev-dependencies.criterion]
version = "0.3.5"
features = ["async_futures"]
[[bench]]
name = "direct_data"
harness = false
use bytes::Bytes;
use criterion::async_executor::FuturesExecutor;
use criterion::{criterion_group, criterion_main, Criterion};
use futures_lite::StreamExt;
use mediasoup::prelude::*;
async fn create_data_producer_consumer_pair(
) -> Result<(DataProducer, DataConsumer), Box<dyn std::error::Error>> {
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await?;
let router = worker.create_router(RouterOptions::default()).await?;
let direct_transport = router
.create_direct_transport(DirectTransportOptions::default())
.await?;
let data_producer = direct_transport
.produce_data(DataProducerOptions::new_direct())
.await?;
let data_consumer = direct_transport
.consume_data(DataConsumerOptions::new_direct(data_producer.id()))
.await?;
Ok((data_producer, data_consumer))
}
pub fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("direct_data");
let data = Bytes::from(
std::iter::repeat_with(|| fastrand::u8(..))
.take(512)
.collect::<Vec<u8>>(),
);
{
let (data_producer, _data_consumer) = futures_lite::future::block_on(async {
create_data_producer_consumer_pair().await.unwrap()
});
let direct_data_producer =
if let DataProducer::Direct(direct_data_producer) = data_producer.clone() {
direct_data_producer
} else {
unreachable!()
};
group.bench_with_input("send", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async {
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.await;
})
});
}
{
let (data_producer, data_consumer) = futures_lite::future::block_on(async {
create_data_producer_consumer_pair().await.unwrap()
});
let direct_data_producer =
if let DataProducer::Direct(direct_data_producer) = data_producer.clone() {
direct_data_producer
} else {
unreachable!()
};
group.bench_with_input("recv", &data, |b, data| {
b.to_async(FuturesExecutor).iter(|| async {
let (sender, mut receiver) = async_channel::unbounded::<()>();
let _handler_id = data_consumer.on_message(move |_message| {
let _ = sender.try_send(());
});
let _ = direct_data_producer
.send(WebRtcMessage::Binary(data.clone()))
.await;
let _ = receiver.next().await;
})
});
}
group.finish();
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
...@@ -4,6 +4,11 @@ import { MediaKind, RtpCapabilities, RtpParameters } from 'mediasoup-client/lib/ ...@@ -4,6 +4,11 @@ import { MediaKind, RtpCapabilities, RtpParameters } from 'mediasoup-client/lib/
import { DtlsParameters, TransportOptions, Transport } from 'mediasoup-client/lib/Transport'; import { DtlsParameters, TransportOptions, Transport } from 'mediasoup-client/lib/Transport';
import { ConsumerOptions } from 'mediasoup-client/lib/Consumer'; import { ConsumerOptions } from 'mediasoup-client/lib/Consumer';
type Brand<K, T> = K & { __brand: T };
type ConsumerId = Brand<string, 'ConsumerId'>;
type ProducerId = Brand<string, 'ProducerId'>;
interface ServerInit { interface ServerInit {
action: 'Init'; action: 'Init';
consumerTransportOptions: TransportOptions; consumerTransportOptions: TransportOptions;
...@@ -17,7 +22,7 @@ interface ServerConnectedProducerTransport { ...@@ -17,7 +22,7 @@ interface ServerConnectedProducerTransport {
interface ServerProduced { interface ServerProduced {
action: 'Produced'; action: 'Produced';
id: string; id: ProducerId;
} }
interface ServerConnectedConsumerTransport { interface ServerConnectedConsumerTransport {
...@@ -26,7 +31,7 @@ interface ServerConnectedConsumerTransport { ...@@ -26,7 +31,7 @@ interface ServerConnectedConsumerTransport {
interface ServerConsumed { interface ServerConsumed {
action: 'Consumed'; action: 'Consumed';
id: string; id: ConsumerId;
kind: MediaKind; kind: MediaKind;
rtpParameters: RtpParameters; rtpParameters: RtpParameters;
} }
...@@ -61,12 +66,12 @@ interface ClientProduce { ...@@ -61,12 +66,12 @@ interface ClientProduce {
interface ClientConsume { interface ClientConsume {
action: 'Consume'; action: 'Consume';
producerId: string; producerId: ProducerId;
} }
interface ClientConsumerResume { interface ClientConsumerResume {
action: 'ConsumerResume'; action: 'ConsumerResume';
id: string; id: ConsumerId;
} }
type ClientMessage = type ClientMessage =
...@@ -91,7 +96,7 @@ async function init() ...@@ -91,7 +96,7 @@ async function init()
receivePreview.play(); receivePreview.play();
}; };
let receiveMediaStream: MediaStream | undefined; const receiveMediaStream = new MediaStream();
const ws = new WebSocket('ws://localhost:3000/ws'); const ws = new WebSocket('ws://localhost:3000/ws');
...@@ -195,7 +200,7 @@ async function init() ...@@ -195,7 +200,7 @@ async function init()
console.log(`${track.kind} producer created:`, producer); console.log(`${track.kind} producer created:`, producer);
} }
// Producer transport is now needed to receive previously produced // Consumer transport is now needed to receive previously produced
// tracks back // tracks back
consumerTransport = device.createRecvTransport( consumerTransport = device.createRecvTransport(
decodedMessage.consumerTransportOptions decodedMessage.consumerTransportOptions
...@@ -227,7 +232,7 @@ async function init() ...@@ -227,7 +232,7 @@ async function init()
// Send request to consume producer // Send request to consume producer
send({ send({
action : 'Consume', action : 'Consume',
producerId : producer.id producerId : producer.id as ProducerId
}); });
// And wait for confirmation, but, obviously, no error handling, // And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications // which you should definitely have in real-world applications
...@@ -246,19 +251,12 @@ async function init() ...@@ -246,19 +251,12 @@ async function init()
// https://mediasoup.org/documentation/v3/mediasoup/api/#transport-consume) // https://mediasoup.org/documentation/v3/mediasoup/api/#transport-consume)
send({ send({
action : 'ConsumerResume', action : 'ConsumerResume',
id : consumer.id id : consumer.id as ConsumerId
}); });
if (receiveMediaStream)
{
receiveMediaStream.addTrack(consumer.track); receiveMediaStream.addTrack(consumer.track);
receivePreview.srcObject = receiveMediaStream; receivePreview.srcObject = receiveMediaStream;
}
else
{
receiveMediaStream = new MediaStream([ consumer.track ]);
receivePreview.srcObject = receiveMediaStream;
}
resolve(undefined); resolve(undefined);
}); });
}); });
......
module.exports = {
env : {
browser : true,
es6 : true
},
parserOptions : {
project : 'tsconfig.json',
sourceType : 'module'
}
};
<!doctype html>
<style>
body {
margin: 0;
}
#container {
display: flex;
}
button {
display: none;
}
figure {
margin: 0;
width: 50vw;
}
audio {
max-width: 100%;
}
#container[waiting-for-click] button {
display: block;
}
#container[waiting-for-click] figure {
display: none;
}
</style>
<div id="container" waiting-for-click>
<button id="connect">Connect</button>
<figure>
<audio id="preview-receive" controls></audio>
<figcaption>Receive preview (see server-side example logs for sending audio instructions)</figcaption>
</figure>
</div>
<script src="dist/bundle.js">
</script>
{
"version": "0.0.0",
"private": true,
"engines": {
"node": ">=14.8"
},
"scripts": {
"start": "webpack serve"
},
"author": "Nazar Mokrynskyi <nazar@mokrynskyi.com>",
"dependencies": {
"mediasoup-client": "^3.6.36"
},
"devDependencies": {
"ts-loader": "^9.2.4",
"typescript": "^4.3.5",
"webpack": "^5.46.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
}
}
/* eslint-disable no-console */
import { Device } from 'mediasoup-client';
import { MediaKind, RtpCapabilities, RtpParameters } from 'mediasoup-client/lib/RtpParameters';
import { DtlsParameters, TransportOptions, Transport } from 'mediasoup-client/lib/Transport';
import { ConsumerOptions } from 'mediasoup-client/lib/Consumer';
import { getExtendedRtpCapabilities } from 'mediasoup-client/lib/ortc';
type Brand<K, T> = K & { __brand: T };
type ConsumerId = Brand<string, 'ConsumerId'>;
type ProducerId = Brand<string, 'ProducerId'>;
interface ServerInit {
action: 'Init';
consumerTransportOptions: TransportOptions;
routerRtpCapabilities: RtpCapabilities;
rtpProducerId: ProducerId;
}
interface ServerConnectedConsumerTransport {
action: 'ConnectedConsumerTransport';
}
interface ServerConsumed {
action: 'Consumed';
id: ConsumerId;
kind: MediaKind;
rtpParameters: RtpParameters;
}
type ServerMessage =
ServerInit |
ServerConnectedConsumerTransport |
ServerConsumed;
interface ClientInit {
action: 'Init';
rtpCapabilities: RtpCapabilities;
}
interface ClientConnectConsumerTransport {
action: 'ConnectConsumerTransport';
dtlsParameters: DtlsParameters;
}
interface ClientConsume {
action: 'Consume';
producerId: ProducerId;
}
type ClientMessage =
ClientInit |
ClientConnectConsumerTransport |
ClientConsume;
async function init()
{
const receivePreview = document.querySelector('#preview-receive') as HTMLAudioElement;
receivePreview.onloadedmetadata = () =>
{
console.log('onloadedmetadata');
receivePreview.play();
};
const receiveMediaStream = new MediaStream();
const ws = new WebSocket('ws://localhost:3000/ws');
function send(message: ClientMessage)
{
ws.send(JSON.stringify(message));
}
const device = new Device();
let consumerTransport: Transport | undefined;
{
const waitingForResponse: Map<ServerMessage['action'], Function> = new Map();
ws.onmessage = async (message) =>
{
const decodedMessage: ServerMessage = JSON.parse(message.data);
switch (decodedMessage.action)
{
case 'Init': {
// It is expected that server will send initialization message right after
// WebSocket connection is established
await device.load({
routerRtpCapabilities : decodedMessage.routerRtpCapabilities
});
// TODO: Here we hardcode RTP capabilities, as Chromium doesn't really expose
// multiopus support in a meaningful way, so we need to hack it like this for
// now until `mediasoup-client` is updated to handle this case properly
{
// @ts-ignore
device._recvRtpCapabilities = {
codecs : [
{
kind : 'audio',
mimeType : 'audio/multiopus',
clockRate : 48000,
channels : 6,
parameters : {
useinbandfec : 1,
'channel_mapping' : '0,1,4,5,2,3',
'num_streams' : 4,
'coupled_streams' : 2
},
rtcpFeedback : [
{
type : 'transport-cc',
parameter : ''
}
]
}
],
headerExtensions : device.rtpCapabilities.headerExtensions
};
// @ts-ignore
device._extendedRtpCapabilities = getExtendedRtpCapabilities(
device.rtpCapabilities,
decodedMessage.routerRtpCapabilities
);
}
// Send client-side initialization message back right away.
send({
action : 'Init',
rtpCapabilities : device.rtpCapabilities
});
// Consumer transport is now needed to receive producer created on the server
consumerTransport = device.createRecvTransport(
decodedMessage.consumerTransportOptions
);
// TODO: Here we patch RTCPeerConnection in such a way that we can intercept
// and munge SDP answer until until `mediasoup-client` is updated to handle
// this case properly
{
// @ts-ignore
const pc = consumerTransport._handler._pc as RTCPeerConnection;
const setLocalDescription = pc.setLocalDescription;
pc.setLocalDescription = (answer: {type: 'answer'; sdp: string}) =>
{
answer.sdp = answer.sdp.replace(
'm=audio 9 UDP/TLS/RTP/SAVPF 0',
`m=audio 9 UDP/TLS/RTP/SAVPF 100
a=rtpmap:100 multiopus/48000/6
a=fmtp:100 channel_mapping=0,4,1,2,3,5;coupled_streams=2;num_streams=4;useinbandfec=1`
);
return setLocalDescription.call(pc, answer);
};
}
consumerTransport
.on('connect', ({ dtlsParameters }, success) =>
{
// Send request to establish consumer transport connection
send({
action : 'ConnectConsumerTransport',
dtlsParameters
});
// And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications
waitingForResponse.set('ConnectedConsumerTransport', () =>
{
success();
console.log('Consumer transport connected');
});
});
// We have just one producer and it is already created, so consuming is easy
await new Promise((resolve) =>
{
// Send request to consume producer
send({
action : 'Consume',
producerId : decodedMessage.rtpProducerId
});
// And wait for confirmation, but, obviously, no error handling,
// which you should definitely have in real-world applications
waitingForResponse.set('Consumed', async (consumerOptions: ConsumerOptions) =>
{
// Once confirmation is received, corresponding consumer
// can be created client-side
const consumer = await (consumerTransport as Transport).consume(
consumerOptions
);
console.log(`${consumer.kind} consumer created:`, consumer);
receiveMediaStream.addTrack(consumer.track);
receivePreview.srcObject = receiveMediaStream;
resolve(undefined);
});
});
break;
}
default: {
// All messages other than initialization go here and are assumed
// to be notifications that correspond to previously sent requests
const callback = waitingForResponse.get(decodedMessage.action);
if (callback)
{
waitingForResponse.delete(decodedMessage.action);
callback(decodedMessage);
}
else
{
console.error('Received unexpected message', decodedMessage);
}
}
}
};
}
ws.onerror = console.error;
}
document.querySelector('#connect')!
.addEventListener('click', () =>
{
const container = document.querySelector('#container')!;
container.removeAttribute('waiting-for-click');
init();
});
{
"compilerOptions": {
"module": "es6",
"target": "es2018",
"sourceMap": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": false,
"sourceRoot": "src",
"baseUrl": "src",
"outDir": "dist",
"strict": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"lib": [
"es5",
"es2015",
"es2019",
"dom"
]
},
"include": [
"src",
".eslintrc.js",
"webpack.config.js"
]
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
module.exports = {
mode : 'development',
entry : './src/index.ts',
module : {
rules : [
{
test : /\.ts$/,
use : 'ts-loader',
exclude : /node_modules/
}
]
},
resolve : {
extensions : [ '.ts', '.js' ]
},
output : {
filename : 'dist/bundle.js',
path : path.resolve(__dirname, 'dist')
},
devServer : {
liveReload : false,
port : 3001
}
};
...@@ -3,6 +3,7 @@ use actix_web::web::{Data, Payload}; ...@@ -3,6 +3,7 @@ use actix_web::web::{Data, Payload};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer}; use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws; use actix_web_actors::ws;
use mediasoup::prelude::*; use mediasoup::prelude::*;
use mediasoup::worker::{WorkerLogLevel, WorkerLogTag};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::num::{NonZeroU32, NonZeroU8}; use std::num::{NonZeroU32, NonZeroU8};
...@@ -137,7 +138,7 @@ struct EchoConnection { ...@@ -137,7 +138,7 @@ struct EchoConnection {
consumers: HashMap<ConsumerId, Consumer>, consumers: HashMap<ConsumerId, Consumer>,
/// Producers associated with this client, preventing them from being destroyed /// Producers associated with this client, preventing them from being destroyed
producers: Vec<Producer>, producers: Vec<Producer>,
/// Producers associated with this client, useful to get its RTP capabilities later /// Router associated with this client, useful to get its RTP capabilities later
router: Router, router: Router,
/// Consumer and producer transports associated with this client /// Consumer and producer transports associated with this client
transports: Transports, transports: Transports,
...@@ -147,7 +148,27 @@ impl EchoConnection { ...@@ -147,7 +148,27 @@ impl EchoConnection {
/// Create a new instance representing WebSocket connection /// Create a new instance representing WebSocket connection
async fn new(worker_manager: &WorkerManager) -> Result<Self, String> { async fn new(worker_manager: &WorkerManager) -> Result<Self, String> {
let worker = worker_manager let worker = worker_manager
.create_worker(WorkerSettings::default()) .create_worker({
let mut settings = WorkerSettings::default();
settings.log_level = WorkerLogLevel::Debug;
settings.log_tags = vec![
WorkerLogTag::Info,
WorkerLogTag::Ice,
WorkerLogTag::Dtls,
WorkerLogTag::Rtp,
WorkerLogTag::Srtp,
WorkerLogTag::Rtcp,
WorkerLogTag::Rtx,
WorkerLogTag::Bwe,
WorkerLogTag::Score,
WorkerLogTag::Simulcast,
WorkerLogTag::Svc,
WorkerLogTag::Sctp,
WorkerLogTag::Message,
];
settings
})
.await .await
.map_err(|error| format!("Failed to create worker: {}", error))?; .map_err(|error| format!("Failed to create worker: {}", error))?;
let router = worker let router = worker
......
差异被折叠。
...@@ -20,3 +20,15 @@ other participants, resulting in a simple video conferencing setup. Frontend par ...@@ -20,3 +20,15 @@ other participants, resulting in a simple video conferencing setup. Frontend par
Check WebSocket messages in browser DevTools for better understanding of what is happening under the hood, also source Check WebSocket messages in browser DevTools for better understanding of what is happening under the hood, also source
code has a bunch of comments about what is happening and where changes would be needed for production use. code has a bunch of comments about what is happening and where changes would be needed for production use.
# Multiopus
Demonstration of surround sound in WebRTC using Chromium-specific "multiopus" audio.
This one is very simple in a sense that it only supports one participant playing back sample audio and nothing else.
NOTE: This requires GStreamer 1.20, which at the moment of writing isn't released yet. On Linux
`docker run --rm -it --net=host restreamio/gstreamer:latest-prod-dbg` can be used to enter environment with working
GStreamer version, or you can compile one from upstream sources.
Check WebSocket messages in browser DevTools for better understanding of what is happening under the hood, also source
code has a bunch of comments about what is happening and where changes would be needed for production use.
...@@ -12,6 +12,7 @@ mod room { ...@@ -12,6 +12,7 @@ mod room {
use crate::participant::ParticipantId; use crate::participant::ParticipantId;
use event_listener_primitives::{Bag, BagOnce, HandlerId}; use event_listener_primitives::{Bag, BagOnce, HandlerId};
use mediasoup::prelude::*; use mediasoup::prelude::*;
use mediasoup::worker::{WorkerLogLevel, WorkerLogTag};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
...@@ -85,7 +86,27 @@ mod room { ...@@ -85,7 +86,27 @@ mod room {
id: RoomId, id: RoomId,
) -> Result<Room, String> { ) -> Result<Room, String> {
let worker = worker_manager let worker = worker_manager
.create_worker(WorkerSettings::default()) .create_worker({
let mut settings = WorkerSettings::default();
settings.log_level = WorkerLogLevel::Debug;
settings.log_tags = vec![
WorkerLogTag::Info,
WorkerLogTag::Ice,
WorkerLogTag::Dtls,
WorkerLogTag::Rtp,
WorkerLogTag::Srtp,
WorkerLogTag::Rtcp,
WorkerLogTag::Rtx,
WorkerLogTag::Bwe,
WorkerLogTag::Score,
WorkerLogTag::Simulcast,
WorkerLogTag::Svc,
WorkerLogTag::Sctp,
WorkerLogTag::Message,
];
settings
})
.await .await
.map_err(|error| format!("Failed to create worker: {}", error))?; .map_err(|error| format!("Failed to create worker: {}", error))?;
let router = worker let router = worker
......
use crate::rtp_parameters::{ use crate::rtp_parameters::{
MediaKind, MimeType, MimeTypeVideo, RtcpFeedback, RtcpParameters, RtpCapabilities, MediaKind, MimeType, MimeTypeAudio, MimeTypeVideo, RtcpFeedback, RtcpParameters,
RtpCapabilitiesFinalized, RtpCodecCapability, RtpCodecCapabilityFinalized, RtpCodecParameters, RtpCapabilities, RtpCapabilitiesFinalized, RtpCodecCapability, RtpCodecCapabilityFinalized,
RtpCodecParametersParameters, RtpCodecParametersParametersValue, RtpEncodingParameters, RtpCodecParameters, RtpCodecParametersParameters, RtpCodecParametersParametersValue,
RtpEncodingParametersRtx, RtpHeaderExtensionDirection, RtpHeaderExtensionParameters, RtpEncodingParameters, RtpEncodingParametersRtx, RtpHeaderExtensionDirection,
RtpHeaderExtensionUri, RtpParameters, RtpHeaderExtensionParameters, RtpHeaderExtensionUri, RtpParameters,
}; };
use crate::scalability_modes::ScalabilityMode; use crate::scalability_modes::ScalabilityMode;
use crate::supported_rtp_capabilities; use crate::supported_rtp_capabilities;
...@@ -984,6 +984,21 @@ fn match_codecs( ...@@ -984,6 +984,21 @@ fn match_codecs(
} }
// Per codec special checks. // Per codec special checks.
match codec_a.mime_type { match codec_a.mime_type {
MimeType::Audio(MimeTypeAudio::MultiChannelOpus) => {
let num_streams_a = codec_a.parameters.get("num_streams");
let num_streams_b = codec_b.parameters.get("num_streams");
if num_streams_a != num_streams_b {
return Err(());
}
let coupled_streams_a = codec_a.parameters.get("coupled_streams");
let coupled_streams_b = codec_b.parameters.get("coupled_streams");
if coupled_streams_a != coupled_streams_b {
return Err(());
}
}
MimeType::Video(MimeTypeVideo::H264) => { MimeType::Video(MimeTypeVideo::H264) => {
let packetization_mode_a = codec_a let packetization_mode_a = codec_a
.parameters .parameters
...@@ -1054,7 +1069,6 @@ fn match_codecs( ...@@ -1054,7 +1069,6 @@ fn match_codecs(
}; };
} }
} }
MimeType::Video(MimeTypeVideo::Vp9) => { MimeType::Video(MimeTypeVideo::Vp9) => {
// If strict matching check profile-id. // If strict matching check profile-id.
if strict { if strict {
......
...@@ -239,7 +239,7 @@ pub struct ConsumerStat { ...@@ -239,7 +239,7 @@ pub struct ConsumerStat {
pub packet_count: usize, pub packet_count: usize,
pub byte_count: usize, pub byte_count: usize,
pub bitrate: u32, pub bitrate: u32,
pub round_trip_time: Option<u32>, pub round_trip_time: Option<f32>,
} }
/// RTC statistics of the consumer, may or may not include producer statistics. /// RTC statistics of the consumer, may or may not include producer statistics.
......
...@@ -105,6 +105,10 @@ pub struct DirectTransportStat { ...@@ -105,6 +105,10 @@ pub struct DirectTransportStat {
pub available_incoming_bitrate: Option<u32>, pub available_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max_incoming_bitrate: Option<u32>, pub max_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_received: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_sent: Option<f64>,
} }
#[derive(Default)] #[derive(Default)]
......
...@@ -140,6 +140,10 @@ pub struct PipeTransportStat { ...@@ -140,6 +140,10 @@ pub struct PipeTransportStat {
pub available_incoming_bitrate: Option<u32>, pub available_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max_incoming_bitrate: Option<u32>, pub max_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_received: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_sent: Option<f64>,
// PipeTransport specific. // PipeTransport specific.
pub tuple: Option<TransportTuple>, pub tuple: Option<TransportTuple>,
} }
......
...@@ -158,6 +158,10 @@ pub struct PlainTransportStat { ...@@ -158,6 +158,10 @@ pub struct PlainTransportStat {
pub available_incoming_bitrate: Option<u32>, pub available_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max_incoming_bitrate: Option<u32>, pub max_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_received: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_sent: Option<f64>,
// PlainTransport specific. // PlainTransport specific.
pub rtcp_mux: bool, pub rtcp_mux: bool,
pub comedia: bool, pub comedia: bool,
......
...@@ -198,11 +198,11 @@ pub struct ProducerStat { ...@@ -198,11 +198,11 @@ pub struct ProducerStat {
pub packet_count: usize, pub packet_count: usize,
pub byte_count: usize, pub byte_count: usize,
pub bitrate: u32, pub bitrate: u32,
pub round_trip_time: Option<u32>, pub round_trip_time: Option<f32>,
pub rtx_packets_discarded: Option<u32>, pub rtx_packets_discarded: Option<u32>,
// RtpStreamRecv specific. // RtpStreamRecv specific.
pub jitter: u32, pub jitter: u32,
pub bitrate_by_layer: HashMap<String, u32>, pub bitrate_by_layer: Option<HashMap<String, u32>>,
} }
/// 'trace' event data. /// 'trace' event data.
......
...@@ -209,6 +209,10 @@ pub struct WebRtcTransportStat { ...@@ -209,6 +209,10 @@ pub struct WebRtcTransportStat {
pub available_incoming_bitrate: Option<u32>, pub available_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max_incoming_bitrate: Option<u32>, pub max_incoming_bitrate: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_received: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rtp_packet_loss_sent: Option<f64>,
// WebRtcTransport specific. // WebRtcTransport specific.
pub ice_role: IceRole, pub ice_role: IceRole,
pub ice_state: IceState, pub ice_state: IceState,
......
...@@ -214,6 +214,9 @@ pub enum MimeTypeAudio { ...@@ -214,6 +214,9 @@ pub enum MimeTypeAudio {
/// Opus /// Opus
#[serde(rename = "audio/opus")] #[serde(rename = "audio/opus")]
Opus, Opus,
/// Multi-channel Opus (Surround sound in Chromium)
#[serde(rename = "audio/multiopus")]
MultiChannelOpus,
/// PCMU /// PCMU
#[serde(rename = "audio/PCMU")] #[serde(rename = "audio/PCMU")]
Pcmu, Pcmu,
......
...@@ -28,6 +28,45 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities { ...@@ -28,6 +28,45 @@ pub fn get_supported_rtp_capabilities() -> RtpCapabilities {
parameters: RtpCodecParametersParameters::default(), parameters: RtpCodecParametersParameters::default(),
rtcp_feedback: vec![RtcpFeedback::TransportCc], rtcp_feedback: vec![RtcpFeedback::TransportCc],
}, },
RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(4).unwrap(),
// Quad channel
parameters: RtpCodecParametersParameters::from([
("channel_mapping", "0,1,2,3".into()),
("num_streams", 2_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![RtcpFeedback::TransportCc],
},
RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
// 5.1
parameters: RtpCodecParametersParameters::from([
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![RtcpFeedback::TransportCc],
},
RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(8).unwrap(),
// 7.1
parameters: RtpCodecParametersParameters::from([
("channel_mapping", "0,6,1,2,3,4,5,7".into()),
("num_streams", 5_u32.into()),
("coupled_streams", 3_u32.into()),
]),
rtcp_feedback: vec![RtcpFeedback::TransportCc],
},
RtpCodecCapability::Audio { RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::Pcmu, mime_type: MimeTypeAudio::Pcmu,
preferred_payload_type: Some(0), preferred_payload_type: Some(0),
......
...@@ -5,7 +5,7 @@ use async_executor::Executor; ...@@ -5,7 +5,7 @@ use async_executor::Executor;
use async_fs::File; use async_fs::File;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures_lite::io::BufReader; use futures_lite::io::BufReader;
use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; use futures_lite::{future, AsyncReadExt, AsyncWriteExt};
use log::{debug, trace, warn}; use log::{debug, trace, warn};
use lru::LruCache; use lru::LruCache;
use parking_lot::Mutex; use parking_lot::Mutex;
...@@ -14,7 +14,6 @@ use serde_json::Value; ...@@ -14,7 +14,6 @@ use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::Debug; use std::fmt::Debug;
use std::io; use std::io;
use std::io::Write;
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use std::time::Duration; use std::time::Duration;
...@@ -148,7 +147,7 @@ impl Channel { ...@@ -148,7 +147,7 @@ impl Channel {
executor executor
.spawn(async move { .spawn(async move {
let mut len_bytes = Vec::new(); let mut len_bytes = [0u8; 4];
let mut bytes = Vec::new(); let mut bytes = Vec::new();
let mut reader = BufReader::new(reader); let mut reader = BufReader::new(reader);
// This this contain cache of targets that are known to not have buffering, so // This this contain cache of targets that are known to not have buffering, so
...@@ -157,14 +156,8 @@ impl Channel { ...@@ -157,14 +156,8 @@ impl Channel {
LruCache::<SubscriptionTarget, ()>::new(1000); LruCache::<SubscriptionTarget, ()>::new(1000);
loop { loop {
let read_bytes = reader.read_until(b':', &mut len_bytes).await?; reader.read_exact(&mut len_bytes).await?;
if read_bytes == 0 { let length = u32::from_ne_bytes(len_bytes) as usize;
// EOF
break;
}
let length = String::from_utf8_lossy(&len_bytes[..(read_bytes - 1)])
.parse::<usize>()
.unwrap();
if length > NS_PAYLOAD_MAX_LEN { if length > NS_PAYLOAD_MAX_LEN {
warn!( warn!(
...@@ -173,13 +166,11 @@ impl Channel { ...@@ -173,13 +166,11 @@ impl Channel {
); );
} }
len_bytes.clear(); if bytes.len() < length {
if bytes.len() < length + 1 {
// Increase bytes size if/when needed // Increase bytes size if/when needed
bytes.resize(length + 1, 0); bytes.resize(length, 0);
} }
// +1 because of netstring `,` at the very end reader.read_exact(&mut bytes[..length]).await?;
reader.read_exact(&mut bytes[..=length]).await?;
trace!( trace!(
"received raw message: {}", "received raw message: {}",
...@@ -273,13 +264,11 @@ impl Channel { ...@@ -273,13 +264,11 @@ impl Channel {
executor executor
.spawn(async move { .spawn(async move {
let mut len = Vec::new();
while let Ok(message) = receiver.recv().await { while let Ok(message) = receiver.recv().await {
len.clear(); writer
write!(&mut len, "{}:", message.len()).unwrap(); .write_all(&(message.len() as u32).to_ne_bytes())
writer.write_all(&len).await?; .await?;
writer.write_all(&message).await?; writer.write_all(&message).await?;
writer.write_all(&[b',']).await?;
} }
io::Result::Ok(()) io::Result::Ok(())
......
...@@ -5,7 +5,7 @@ use async_executor::Executor; ...@@ -5,7 +5,7 @@ use async_executor::Executor;
use async_fs::File; use async_fs::File;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use futures_lite::io::BufReader; use futures_lite::io::BufReader;
use futures_lite::{future, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt}; use futures_lite::{future, AsyncReadExt, AsyncWriteExt};
use log::{debug, error, trace, warn}; use log::{debug, error, trace, warn};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
...@@ -13,7 +13,6 @@ use serde_json::Value; ...@@ -13,7 +13,6 @@ use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::Debug; use std::fmt::Debug;
use std::io; use std::io;
use std::io::Write;
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use std::time::Duration; use std::time::Duration;
use thiserror::Error; use thiserror::Error;
...@@ -122,19 +121,13 @@ impl PayloadChannel { ...@@ -122,19 +121,13 @@ impl PayloadChannel {
executor executor
.spawn(async move { .spawn(async move {
let mut len_bytes = Vec::new(); let mut len_bytes = [0u8; 4];
let mut bytes = Vec::new(); let mut bytes = Vec::new();
let mut reader = BufReader::new(reader); let mut reader = BufReader::new(reader);
loop { loop {
let read_bytes = reader.read_until(b':', &mut len_bytes).await?; reader.read_exact(&mut len_bytes).await?;
if read_bytes == 0 { let length = u32::from_ne_bytes(len_bytes) as usize;
// EOF
break;
}
let length = String::from_utf8_lossy(&len_bytes[..(read_bytes - 1)])
.parse::<usize>()
.unwrap();
if length > NS_PAYLOAD_MAX_LEN { if length > NS_PAYLOAD_MAX_LEN {
warn!( warn!(
...@@ -143,13 +136,11 @@ impl PayloadChannel { ...@@ -143,13 +136,11 @@ impl PayloadChannel {
); );
} }
len_bytes.clear(); if bytes.len() < length {
if bytes.len() < length + 1 {
// Increase bytes size if/when needed // Increase bytes size if/when needed
bytes.resize(length + 1, 0); bytes.resize(length, 0);
} }
// +1 because of netstring `,` at the very end reader.read_exact(&mut bytes[..length]).await?;
reader.read_exact(&mut bytes[..=length]).await?;
trace!( trace!(
"received raw message: {}", "received raw message: {}",
...@@ -197,15 +188,8 @@ impl PayloadChannel { ...@@ -197,15 +188,8 @@ impl PayloadChannel {
}) })
}); });
let read_bytes = reader.read_until(b':', &mut len_bytes).await?; reader.read_exact(&mut len_bytes).await?;
if read_bytes == 0 { let length = u32::from_ne_bytes(len_bytes) as usize;
// EOF
break;
}
let length =
String::from_utf8_lossy(&len_bytes[..(read_bytes - 1)])
.parse::<usize>()
.unwrap();
if length > NS_PAYLOAD_MAX_LEN { if length > NS_PAYLOAD_MAX_LEN {
warn!( warn!(
...@@ -214,9 +198,11 @@ impl PayloadChannel { ...@@ -214,9 +198,11 @@ impl PayloadChannel {
); );
} }
len_bytes.clear(); if bytes.len() < length {
// +1 because of netstring `,` at the very end // Increase bytes size if/when needed
reader.read_exact(&mut bytes[..=length]).await?; bytes.resize(length, 0);
}
reader.read_exact(&mut bytes[..length]).await?;
trace!("received notification payload of {} bytes", length); trace!("received notification payload of {} bytes", length);
...@@ -259,19 +245,16 @@ impl PayloadChannel { ...@@ -259,19 +245,16 @@ impl PayloadChannel {
executor executor
.spawn(async move { .spawn(async move {
let mut len = Vec::new();
while let Ok(message) = receiver.recv().await { while let Ok(message) = receiver.recv().await {
len.clear(); writer
write!(&mut len, "{}:", message.message.len()).unwrap(); .write_all(&(message.message.len() as u32).to_ne_bytes())
writer.write_all(&len).await?; .await?;
writer.write_all(&message.message).await?; writer.write_all(&message.message).await?;
writer.write_all(&[b',']).await?;
len.clear(); writer
write!(&mut len, "{}:", message.payload.len()).unwrap(); .write_all(&(message.payload.len() as u32).to_ne_bytes())
writer.write_all(&len).await?; .await?;
writer.write_all(&message.payload).await?; writer.write_all(&message.payload).await?;
writer.write_all(&[b',']).await?;
} }
io::Result::Ok(()) io::Result::Ok(())
......
...@@ -150,6 +150,8 @@ fn get_stats_succeeds() { ...@@ -150,6 +150,8 @@ fn get_stats_succeeds() {
assert_eq!(stats[0].rtx_send_bitrate, 0); assert_eq!(stats[0].rtx_send_bitrate, 0);
assert_eq!(stats[0].probation_bytes_sent, 0); assert_eq!(stats[0].probation_bytes_sent, 0);
assert_eq!(stats[0].probation_send_bitrate, 0); assert_eq!(stats[0].probation_send_bitrate, 0);
assert_eq!(stats[0].rtp_packet_loss_received, None);
assert_eq!(stats[0].rtp_packet_loss_sent, None);
}); });
} }
......
...@@ -4,6 +4,7 @@ mod consumer; ...@@ -4,6 +4,7 @@ mod consumer;
mod data_consumer; mod data_consumer;
mod data_producer; mod data_producer;
mod direct_transport; mod direct_transport;
mod multiopus;
mod pipe_transport; mod pipe_transport;
mod plain_transport; mod plain_transport;
mod producer; mod producer;
......
差异被折叠。
...@@ -411,6 +411,8 @@ fn get_stats_succeeds() { ...@@ -411,6 +411,8 @@ fn get_stats_succeeds() {
assert_eq!(stats[0].rtx_send_bitrate, 0); assert_eq!(stats[0].rtx_send_bitrate, 0);
assert_eq!(stats[0].probation_bytes_sent, 0); assert_eq!(stats[0].probation_bytes_sent, 0);
assert_eq!(stats[0].probation_send_bitrate, 0); assert_eq!(stats[0].probation_send_bitrate, 0);
assert_eq!(stats[0].rtp_packet_loss_received, None);
assert_eq!(stats[0].rtp_packet_loss_sent, None);
assert!(matches!( assert!(matches!(
stats[0].tuple, stats[0].tuple,
Some(TransportTuple::LocalOnly { .. }), Some(TransportTuple::LocalOnly { .. }),
......
...@@ -360,6 +360,8 @@ fn get_stats_succeeds() { ...@@ -360,6 +360,8 @@ fn get_stats_succeeds() {
assert_eq!(stats[0].probation_send_bitrate, 0); assert_eq!(stats[0].probation_send_bitrate, 0);
assert_eq!(stats[0].ice_selected_tuple, None); assert_eq!(stats[0].ice_selected_tuple, None);
assert_eq!(stats[0].max_incoming_bitrate, None); assert_eq!(stats[0].max_incoming_bitrate, None);
assert_eq!(stats[0].rtp_packet_loss_received, None);
assert_eq!(stats[0].rtp_packet_loss_sent, None);
}); });
} }
......
import * as os from 'os';
import { Duplex } from 'stream'; import { Duplex } from 'stream';
// @ts-ignore
import * as netstring from 'netstring';
import { Logger } from './Logger'; import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { InvalidStateError } from './errors'; import { InvalidStateError } from './errors';
const littleEndian = os.endianness() == 'LE';
const logger = new Logger('Channel'); const logger = new Logger('Channel');
type Sent = type Sent =
...@@ -17,9 +17,9 @@ type Sent = ...@@ -17,9 +17,9 @@ type Sent =
close: () => void; close: () => void;
} }
// netstring length for a 4194304 bytes payload. // Binary length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313; const MESSAGE_MAX_LEN = 4194308;
const NS_PAYLOAD_MAX_LEN = 4194304; const PAYLOAD_MAX_LEN = 4194304;
export class Channel extends EnhancedEventEmitter export class Channel extends EnhancedEventEmitter
{ {
...@@ -39,7 +39,7 @@ export class Channel extends EnhancedEventEmitter ...@@ -39,7 +39,7 @@ export class Channel extends EnhancedEventEmitter
private readonly _sents: Map<number, Sent> = new Map(); private readonly _sents: Map<number, Sent> = new Map();
// Buffer for reading messages from the worker. // Buffer for reading messages from the worker.
private _recvBuffer?: Buffer; private _recvBuffer = Buffer.alloc(0);
/** /**
* @private * @private
...@@ -66,7 +66,7 @@ export class Channel extends EnhancedEventEmitter ...@@ -66,7 +66,7 @@ export class Channel extends EnhancedEventEmitter
// Read Channel responses/notifications from the worker. // Read Channel responses/notifications from the worker.
this._consumerSocket.on('data', (buffer: Buffer) => this._consumerSocket.on('data', (buffer: Buffer) =>
{ {
if (!this._recvBuffer) if (!this._recvBuffer.length)
{ {
this._recvBuffer = buffer; this._recvBuffer = buffer;
} }
...@@ -77,76 +77,79 @@ export class Channel extends EnhancedEventEmitter ...@@ -77,76 +77,79 @@ export class Channel extends EnhancedEventEmitter
this._recvBuffer.length + buffer.length); this._recvBuffer.length + buffer.length);
} }
if (this._recvBuffer!.length > NS_PAYLOAD_MAX_LEN) if (this._recvBuffer.length > PAYLOAD_MAX_LEN)
{ {
logger.error('receiving buffer is full, discarding all data into it'); logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit. // Reset the buffer and exit.
this._recvBuffer = undefined; this._recvBuffer = Buffer.alloc(0);
return; return;
} }
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition while (true) // eslint-disable-line no-constant-condition
{ {
let nsPayload; const readLen = this._recvBuffer.length - msgStart;
try if (readLen < 4)
{ {
nsPayload = netstring.nsPayload(this._recvBuffer); // Incomplete data.
break;
} }
catch (error)
{
logger.error(
'invalid netstring data received from the worker process: %s',
String(error));
// Reset the buffer and exit. const dataView = new DataView(
this._recvBuffer = undefined; this._recvBuffer.buffer,
this._recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
return; if (readLen < 4 + msgLen)
{
// Incomplete data.
break;
} }
// Incomplete netstring message. const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
if (nsPayload === -1)
return; msgStart += 4 + msgLen;
try try
{ {
// We can receive JSON messages (Channel messages) or log strings. // We can receive JSON messages (Channel messages) or log strings.
switch (nsPayload[0]) switch (payload[0])
{ {
// 123 = '{' (a Channel JSON messsage). // 123 = '{' (a Channel JSON message).
case 123: case 123:
this._processMessage(JSON.parse(nsPayload.toString('utf8'))); this._processMessage(JSON.parse(payload.toString('utf8')));
break; break;
// 68 = 'D' (a debug log). // 68 = 'D' (a debug log).
case 68: case 68:
logger.debug(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`); logger.debug(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break; break;
// 87 = 'W' (a warn log). // 87 = 'W' (a warn log).
case 87: case 87:
logger.warn(`[pid:${pid}] ${nsPayload.toString('utf8', 1)}`); logger.warn(`[pid:${pid}] ${payload.toString('utf8', 1)}`);
break; break;
// 69 = 'E' (an error log). // 69 = 'E' (an error log).
case 69: case 69:
logger.error(`[pid:${pid} ${nsPayload.toString('utf8', 1)}`); logger.error(`[pid:${pid} ${payload.toString('utf8', 1)}`);
break; break;
// 88 = 'X' (a dump log). // 88 = 'X' (a dump log).
case 88: case 88:
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(nsPayload.toString('utf8', 1)); console.log(payload.toString('utf8', 1));
break; break;
default: default:
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.warn( console.warn(
`worker[pid:${pid}] unexpected data: %s`, `worker[pid:${pid}] unexpected data: %s`,
nsPayload.toString('utf8', 1)); payload.toString('utf8', 1));
} }
} }
catch (error) catch (error)
...@@ -155,17 +158,11 @@ export class Channel extends EnhancedEventEmitter ...@@ -155,17 +158,11 @@ export class Channel extends EnhancedEventEmitter
'received invalid message from the worker process: %s', 'received invalid message from the worker process: %s',
String(error)); String(error));
} }
}
// Remove the read payload from the buffer. if (msgStart != 0)
this._recvBuffer =
this._recvBuffer!.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length)
{ {
this._recvBuffer = undefined; this._recvBuffer = this._recvBuffer.slice(msgStart);
return;
}
} }
}); });
...@@ -239,13 +236,15 @@ export class Channel extends EnhancedEventEmitter ...@@ -239,13 +236,15 @@ export class Channel extends EnhancedEventEmitter
throw new InvalidStateError('Channel closed'); throw new InvalidStateError('Channel closed');
const request = { id, method, internal, data }; const request = { id, method, internal, data };
const ns = netstring.nsWrite(JSON.stringify(request)); const payload = JSON.stringify(request);
if (Buffer.byteLength(ns) > NS_MESSAGE_MAX_LEN) if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big'); throw new Error('Channel request too big');
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns); this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
return new Promise((pResolve, pReject) => return new Promise((pResolve, pReject) =>
{ {
......
import * as os from 'os';
import { Duplex } from 'stream'; import { Duplex } from 'stream';
// @ts-ignore
import * as netstring from 'netstring';
import { Logger } from './Logger'; import { Logger } from './Logger';
import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { InvalidStateError } from './errors'; import { InvalidStateError } from './errors';
const littleEndian = os.endianness() == 'LE';
const logger = new Logger('PayloadChannel'); const logger = new Logger('PayloadChannel');
type Sent = type Sent =
...@@ -17,9 +17,9 @@ type Sent = ...@@ -17,9 +17,9 @@ type Sent =
close: () => void; close: () => void;
} }
// netstring length for a 4194304 bytes payload. // Binary length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313; const MESSAGE_MAX_LEN = 4194308;
const NS_PAYLOAD_MAX_LEN = 4194304; const PAYLOAD_MAX_LEN = 4194304;
export class PayloadChannel extends EnhancedEventEmitter export class PayloadChannel extends EnhancedEventEmitter
{ {
...@@ -39,7 +39,7 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -39,7 +39,7 @@ export class PayloadChannel extends EnhancedEventEmitter
private readonly _sents: Map<number, Sent> = new Map(); private readonly _sents: Map<number, Sent> = new Map();
// Buffer for reading messages from the worker. // Buffer for reading messages from the worker.
private _recvBuffer?: Buffer; private _recvBuffer = Buffer.alloc(0);
// Ongoing notification (waiting for its payload). // Ongoing notification (waiting for its payload).
private _ongoingNotification?: { targetId: string; event: string; data?: any }; private _ongoingNotification?: { targetId: string; event: string; data?: any };
...@@ -67,7 +67,7 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -67,7 +67,7 @@ export class PayloadChannel extends EnhancedEventEmitter
// Read PayloadChannel notifications from the worker. // Read PayloadChannel notifications from the worker.
this._consumerSocket.on('data', (buffer: Buffer) => this._consumerSocket.on('data', (buffer: Buffer) =>
{ {
if (!this._recvBuffer) if (!this._recvBuffer.length)
{ {
this._recvBuffer = buffer; this._recvBuffer = buffer;
} }
...@@ -78,52 +78,49 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -78,52 +78,49 @@ export class PayloadChannel extends EnhancedEventEmitter
this._recvBuffer.length + buffer.length); this._recvBuffer.length + buffer.length);
} }
if (this._recvBuffer!.length > NS_PAYLOAD_MAX_LEN) if (this._recvBuffer.length > PAYLOAD_MAX_LEN)
{ {
logger.error('receiving buffer is full, discarding all data into it'); logger.error('receiving buffer is full, discarding all data in it');
// Reset the buffer and exit. // Reset the buffer and exit.
this._recvBuffer = undefined; this._recvBuffer = Buffer.alloc(0);
return; return;
} }
let msgStart = 0;
while (true) // eslint-disable-line no-constant-condition while (true) // eslint-disable-line no-constant-condition
{ {
let nsPayload; const readLen = this._recvBuffer.length - msgStart;
try if (readLen < 4)
{ {
nsPayload = netstring.nsPayload(this._recvBuffer); // Incomplete data.
break;
} }
catch (error)
{
logger.error(
'invalid netstring data received from the worker process: %s',
String(error));
// Reset the buffer and exit. const dataView = new DataView(
this._recvBuffer = undefined; this._recvBuffer.buffer,
this._recvBuffer.byteOffset + msgStart);
const msgLen = dataView.getUint32(0, littleEndian);
return; if (readLen < 4 + msgLen)
{
// Incomplete data.
break;
} }
// Incomplete netstring message. const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
if (nsPayload === -1)
return;
this._processData(nsPayload); msgStart += 4 + msgLen;
// Remove the read payload from the buffer. this._processData(payload);
this._recvBuffer = }
this._recvBuffer!.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length) if (msgStart != 0)
{ {
this._recvBuffer = undefined; this._recvBuffer = this._recvBuffer.slice(msgStart);
return;
}
} }
}); });
...@@ -191,19 +188,19 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -191,19 +188,19 @@ export class PayloadChannel extends EnhancedEventEmitter
if (this._closed) if (this._closed)
throw new InvalidStateError('PayloadChannel closed'); throw new InvalidStateError('PayloadChannel closed');
const notification = { event, internal, data }; const notification = JSON.stringify({ event, internal, data });
const ns1 = netstring.nsWrite(JSON.stringify(notification));
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN) if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big'); throw new Error('PayloadChannel notification too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN) else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big'); throw new Error('PayloadChannel payload too big');
try try
{ {
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns1); this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(notification)).buffer));
this._producerSocket.write(notification);
} }
catch (error) catch (error)
{ {
...@@ -215,7 +212,9 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -215,7 +212,9 @@ export class PayloadChannel extends EnhancedEventEmitter
try try
{ {
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns2); this._producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this._producerSocket.write(payload);
} }
catch (error) catch (error)
{ {
...@@ -243,18 +242,20 @@ export class PayloadChannel extends EnhancedEventEmitter ...@@ -243,18 +242,20 @@ export class PayloadChannel extends EnhancedEventEmitter
if (this._closed) if (this._closed)
throw new InvalidStateError('Channel closed'); throw new InvalidStateError('Channel closed');
const request = { id, method, internal, data }; const request = JSON.stringify({ id, method, internal, data });
const ns1 = netstring.nsWrite(JSON.stringify(request));
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN) if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big'); throw new Error('Channel request too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN) else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big'); throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended. // This may throw if closed or remote side ended.
this._producerSocket.write(ns1); this._producerSocket.write(
this._producerSocket.write(ns2); 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) => return new Promise((pResolve, pReject) =>
{ {
......
...@@ -291,7 +291,7 @@ export class Worker extends EnhancedEventEmitter ...@@ -291,7 +291,7 @@ export class Worker extends EnhancedEventEmitter
windowsHide : true windowsHide : true
}); });
this._pid = this._child.pid; this._pid = this._child.pid!;
this._channel = new Channel( this._channel = new Channel(
{ {
......
...@@ -1205,6 +1205,23 @@ function matchCodecs( ...@@ -1205,6 +1205,23 @@ function matchCodecs(
// Per codec special checks. // Per codec special checks.
switch (aMimeType) 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':
{ {
const aPacketizationMode = aCodec.parameters['packetization-mode'] || 0; const aPacketizationMode = aCodec.parameters['packetization-mode'] || 0;
......
...@@ -14,6 +14,57 @@ const supportedRtpCapabilities: RtpCapabilities = ...@@ -14,6 +14,57 @@ const supportedRtpCapabilities: RtpCapabilities =
{ type: 'transport-cc' } { 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', kind : 'audio',
mimeType : 'audio/PCMU', mimeType : 'audio/PCMU',
......
const { toBeType } = require('jest-tobetype');
const mediasoup = require('../');
const { UnsupportedError } = require('../lib/errors');
const { createWorker } = mediasoup;
expect.extend({ toBeType });
let worker;
let router;
let transport;
const mediaCodecs = [
{
kind : 'audio',
mimeType : 'audio/multiopus',
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
];
const audioProducerOptions = {
kind : 'audio',
rtpParameters :
{
mid : 'AUDIO',
codecs :
[
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
],
headerExtensions :
[
{
uri : 'urn:ietf:params:rtp-hdrext:sdes:mid',
id : 10
},
{
uri : 'urn:ietf:params:rtp-hdrext:ssrc-audio-level',
id : 12
}
]
}
};
const consumerDeviceCapabilities = {
codecs :
[
{
mimeType : 'audio/multiopus',
kind : 'audio',
preferredPayloadType : 100,
clockRate : 48000,
channels : 6,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
],
headerExtensions :
[
{
kind : 'audio',
uri : 'urn:ietf:params:rtp-hdrext:sdes:mid',
preferredId : 1,
preferredEncrypt : false
},
{
kind : 'audio',
uri : 'http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time', // eslint-disable-line max-len
preferredId : 4,
preferredEncrypt : false
},
{
kind : 'audio',
uri : 'urn:ietf:params:rtp-hdrext:ssrc-audio-level',
preferredId : 10,
preferredEncrypt : false
}
]
};
beforeAll(async () =>
{
worker = await createWorker();
router = await worker.createRouter({ mediaCodecs });
transport = await router.createWebRtcTransport(
{
listenIps : [ '127.0.0.1' ]
});
});
afterAll(() => worker.close());
test('produce/consume succeeds', async () =>
{
const audioProducer = await transport.produce(audioProducerOptions);
expect(audioProducer.rtpParameters.codecs).toEqual([
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
},
rtcpFeedback : []
}
]);
expect(router.canConsume({
producerId : audioProducer.id,
rtpCapabilities : consumerDeviceCapabilities
}))
.toBe(true);
const audioConsumer = await transport.consume({
producerId : audioProducer.id,
rtpCapabilities : consumerDeviceCapabilities
});
expect(audioConsumer.rtpParameters.codecs).toEqual([
{
mimeType : 'audio/multiopus',
payloadType : 100,
clockRate : 48000,
channels : 6,
parameters :
{
useinbandfec : 1,
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
},
rtcpFeedback : []
}
]);
audioProducer.close();
audioConsumer.close();
}, 2000);
test('fails to produce wrong parameters', async () =>
{
await expect(transport.produce({
kind : 'audio',
rtpParameters :
{
mid : 'AUDIO',
codecs :
[
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 2,
'coupled_streams' : 2
}
}
]
}
}))
.rejects
.toThrow(UnsupportedError);
await expect(transport.produce({
kind : 'audio',
rtpParameters :
{
mid : 'AUDIO',
codecs :
[
{
mimeType : 'audio/multiopus',
payloadType : 0,
clockRate : 48000,
channels : 6,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 1
}
}
]
}
}))
.rejects
.toThrow(UnsupportedError);
}, 2000);
test('fails to consume wrong channels', async () =>
{
const audioProducer = await transport.produce(audioProducerOptions);
const localConsumerDeviceCapabilities = {
codecs :
[
{
mimeType : 'audio/multiopus',
kind : 'audio',
preferredPayloadType : 100,
clockRate : 48000,
channels : 8,
parameters :
{
'channel_mapping' : '0,4,1,2,3,5',
'num_streams' : 4,
'coupled_streams' : 2
}
}
]
};
expect(!router.canConsume({
producerId : audioProducer.id,
rtpCapabilities : localConsumerDeviceCapabilities
}))
.toBe(true);
await expect(transport.consume({
producerId : audioProducer.id,
rtpCapabilities : localConsumerDeviceCapabilities
}))
.rejects
.toThrow(Error);
audioProducer.close();
}, 2000);
...@@ -54,7 +54,7 @@ IncludeCategories: ...@@ -54,7 +54,7 @@ IncludeCategories:
Priority: 3 Priority: 3
- Regex: '"*"' - Regex: '"*"'
Priority: 2 Priority: 2
- Regex: '^<(json|netstring|uv|openssl|srtp|usrsctp|libwebrtc)(.|/)' - Regex: '^<(json|uv|openssl|srtp|usrsctp|libwebrtc)(.|/)'
Priority: 4 Priority: 4
- Regex: '<*>' - Regex: '<*>'
Priority: 5 Priority: 5
......
[package] [package]
name = "mediasoup-sys" name = "mediasoup-sys"
version = "0.2.4" version = "0.2.5"
description = "FFI bindings to C++ libmediasoup-worker" description = "FFI bindings to C++ libmediasoup-worker"
authors = ["Nazar Mokrynskyi <nazar@mokrynskyi.com>"] authors = ["Nazar Mokrynskyi <nazar@mokrynskyi.com>"]
edition = "2018" edition = "2018"
......
...@@ -49,56 +49,21 @@ fn main() { ...@@ -49,56 +49,21 @@ fn main() {
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
let clang_llvm_version = "clang+llvm-12.0.0-x86_64-apple-darwin"; let path = Command::new("xcrun")
let status = Command::new("curl") .args(&["--show-sdk-path"])
.args(&[ .output()
"-L", .expect("Failed to start")
"-s", .stdout;
"-O",
&format!("https://github.com/llvm/llvm-project/releases/download/llvmorg-12.0.0/{}.tar.xz", clang_llvm_version),
])
.current_dir(&out_dir)
.status()
.expect("Failed to start");
if !status.success() {
panic!("Failed to download libc++");
}
let status = Command::new("tar")
.args(&[
"-xf",
&format!("{}.tar.xz", clang_llvm_version),
&format!("{}/lib/libc++.a", clang_llvm_version),
&format!("{}/lib/libc++abi.a", clang_llvm_version),
])
.current_dir(&out_dir)
.status()
.expect("Failed to start");
if !status.success() {
panic!("Failed to download libc++");
}
for file in &["libc++.a", "libc++abi.a"] {
std::fs::copy(
format!("{}/{}/lib/{}", out_dir, clang_llvm_version, file),
format!("{}/{}", out_dir, file),
)
.unwrap_or_else(|_| {
panic!(
"Failed to copy static library from {}/{}/lib/{} to {}/{}",
out_dir, clang_llvm_version, file, out_dir, file
)
});
}
std::fs::remove_file(format!("{}/{}.tar.xz", out_dir, clang_llvm_version))
.expect("Failed to remove downloaded clang+llvm archive");
std::fs::remove_dir_all(format!("{}/{}", out_dir, clang_llvm_version))
.expect("Failed to remove extracted clang+llvm files");
println!("cargo:rustc-link-lib=static=c++"); let libpath = format!(
println!("cargo:rustc-link-lib=static=c++abi"); "{}/usr/lib",
String::from_utf8(path)
.expect("Failed to decode path")
.trim()
);
println!("cargo:rustc-link-search={}", libpath);
println!("cargo:rustc-link-lib=dylib=c++");
println!("cargo:rustc-link-lib=dylib=c++abi");
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
...@@ -111,6 +76,7 @@ fn main() { ...@@ -111,6 +76,7 @@ fn main() {
// number of files. So instead we build in place, copy files to out directory and then clean // number of files. So instead we build in place, copy files to out directory and then clean
// after ourselves // after ourselves
{ {
// Build
if !Command::new("make") if !Command::new("make")
.arg("libmediasoup-worker") .arg("libmediasoup-worker")
.env("PYTHONDONTWRITEBYTECODE", "1") .env("PYTHONDONTWRITEBYTECODE", "1")
......
Netstring parsing
=================
A [netstring](http://en.wikipedia.org/wiki/Netstring) is a way of encoding a sequence of bytes for transmission over a network, or for serialization. They're very easy to work with. They encode the data's length, and can be concatenated trivially. The format was [defined by D. J. Bernstein](http://cr.yp.to/proto/netstrings.txt) and is used in various software. Examples of netstrings:
"12:hello, world!,"
"3:foo,"
"0:,"
To specify a list of strings, just concatenate the netstrings. The list ["hey", "everyone"] can be encoded as
"3:hey,8:everyone,"
This is some code in C for netstring serialization and deserialization. It checks netstrings for validity when parsing them, and guards against malicious input. It's also fast.
Basic API
---------
All the code is in `netstring.c` and `netstring.h`, and these have no external dependencies. To use them, just include them in your application. Include `netstring.h` and link with the C code.
**Parsing netstrings**
To parse a netstring, use `netstring_read()`.
int netstring_read(char *buffer, size_t buffer_length,
char **netstring_start, size_t *netstring_length);
Reads a netstring from a `buffer` of length `buffer_length`. Writes to
`netstring_start` a pointer to the beginning of the string in the
buffer, and to `netstring_length` the length of the string. Does not
allocate any memory. If it reads successfully, then it returns 0. If
there is an error, then the return value will be negative. The error
values are:
NETSTRING_ERROR_TOO_LONG More than 999999999 bytes in a field
NETSTRING_ERROR_NO_COLON No colon was found after the number
NETSTRING_ERROR_TOO_SHORT Number of bytes greater than buffer length
NETSTRING_ERROR_NO_COMMA No comma was found at the end
NETSTRING_ERROR_LEADING_ZERO Leading zeros are not allowed
NETSTRING_ERROR_NO_LENGTH Length not given at start of netstring
If you're sending messages with more than 999999999 bytes -- about 2
GB -- then you probably should not be doing so in the form of a single
netstring. This restriction is in place partially to protect from
malicious or erroneous input, and partly to be compatible with
D. J. Bernstein's reference implementation.
**Creating netstrings**
To create a netstring, there are a few ways to do it. You could do something really simple like this example from [the spec](http://cr.yp.to/proto/netstrings.txt):
if (printf("%lu:", len) < 0) barf();
if (fwrite(buf, 1, len, stdout) < len) barf();
if (putchar(',') < 0) barf();
This code provides a convenience function for creating a new netstring:
size_t netstring_encode_new(char **netstring, char *data, size_t len);
This allocates and creates a netstring containing the first `len` bytes of `data`. This must be manually freed by the client. If `len` is 0 then no data will be read from `data`, and it may be null.
Contributing
------------
All this code is Public Domain. If you want to contribute, you can send bug reports, or fork the project on GitHub. Contributions are welcomed with open arms.
\ No newline at end of file
CFLAGS = -O2 -Wall
LDFLAGS= -lm
.PHONY: test clean
all: testsuite
testsuite: testsuite.c netstring.o
test: testsuite
./testsuite
clean:
rm -f *.o testsuite
/* Streaming API for netstrings. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include "netstring.h"
/* Reads a netstring from a `buffer` of length `buffer_length`. Writes
to `netstring_start` a pointer to the beginning of the string in
the buffer, and to `netstring_length` the length of the
string. Does not allocate any memory. If it reads successfully,
then it returns 0. If there is an error, then the return value will
be negative. The error values are:
NETSTRING_ERROR_TOO_LONG More than 999999999 bytes in a field
NETSTRING_ERROR_NO_COLON No colon was found after the number
NETSTRING_ERROR_TOO_SHORT Number of bytes greater than buffer length
NETSTRING_ERROR_NO_COMMA No comma was found at the end
NETSTRING_ERROR_LEADING_ZERO Leading zeros are not allowed
NETSTRING_ERROR_NO_LENGTH Length not given at start of netstring
If you're sending messages with more than 999999999 bytes -- about
2 GB -- then you probably should not be doing so in the form of a
single netstring. This restriction is in place partially to protect
from malicious or erroneous input, and partly to be compatible with
D. J. Bernstein's reference implementation.
Example:
if (netstring_read("3:foo,", 6, &str, &len) < 0) explode_and_die();
*/
int netstring_read(char *buffer, size_t buffer_length,
char **netstring_start, size_t *netstring_length) {
int i;
size_t len = 0;
/* Write default values for outputs */
*netstring_start = NULL; *netstring_length = 0;
/* Make sure buffer is big enough. Minimum size is 3. */
if (buffer_length < 3) return NETSTRING_ERROR_TOO_SHORT;
/* No leading zeros allowed! */
if (buffer[0] == '0' && isdigit(buffer[1]))
return NETSTRING_ERROR_LEADING_ZERO;
/* The netstring must start with a number */
if (!isdigit(buffer[0])) return NETSTRING_ERROR_NO_LENGTH;
/* Read the number of bytes */
for (i = 0; i < buffer_length && isdigit(buffer[i]); i++) {
/* Error if more than 9 digits */
if (i >= 9) return NETSTRING_ERROR_TOO_LONG;
/* Accumulate each digit, assuming ASCII. */
len = len*10 + (buffer[i] - '0');
}
/* Check buffer length once and for all. Specifically, we make sure
that the buffer is longer than the number we've read, the length
of the string itself, and the colon and comma. */
if (i + len + 1 >= buffer_length) return NETSTRING_ERROR_TOO_SHORT;
/* Read the colon */
if (buffer[i++] != ':') return NETSTRING_ERROR_NO_COLON;
/* Test for the trailing comma, and set the return values */
if (buffer[i + len] != ',') return NETSTRING_ERROR_NO_COMMA;
*netstring_start = &buffer[i]; *netstring_length = len;
return 0;
}
/* Return the length, in ASCII characters, of a netstring containing
`data_length` bytes. */
size_t netstring_buffer_size(size_t data_length) {
if (data_length == 0) return 3;
return (size_t)ceil(log10((double)data_length + 1)) + data_length + 2;
}
/* Allocate and create a netstring containing the first `len` bytes of
`data`. This must be manually freed by the client. If `len` is 0
then no data will be read from `data`, and it may be NULL. */
size_t netstring_encode_new(char **netstring, char *data, size_t len) {
char *ns;
size_t num_len = 1;
if (len == 0) {
ns = malloc(3);
ns[0] = '0';
ns[1] = ':';
ns[2] = ',';
} else {
num_len = (size_t)ceil(log10((double)len + 1));
ns = malloc(num_len + len + 2);
sprintf(ns, "%lu:", (unsigned long)len);
memcpy(ns + num_len + 1, data, len);
ns[num_len + len + 1] = ',';
}
*netstring = ns;
return num_len + len + 2;
}
#ifndef __NETSTRING_STREAM_H
#define __NETSTRING_STREAM_H
#include <string.h>
int netstring_read(char *buffer, size_t buffer_length,
char **netstring_start, size_t *netstring_length);
size_t netstring_buffer_size(size_t data_length);
size_t netstring_encode_new(char **netstring, char *data, size_t len);
/* Errors that can occur during netstring parsing */
#define NETSTRING_ERROR_TOO_LONG -1
#define NETSTRING_ERROR_NO_COLON -2
#define NETSTRING_ERROR_TOO_SHORT -3
#define NETSTRING_ERROR_NO_COMMA -4
#define NETSTRING_ERROR_LEADING_ZERO -5
#define NETSTRING_ERROR_NO_LENGTH -6
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "netstring.h"
/* Good examples */
char ex1[] = "12:hello world!,";
char ex2[] = "3:foo,0:,3:bar,";
/* Bad examples */
char ex3[] = "12:hello world! "; /* No comma */
char ex4[] = "15:hello world!,"; /* Too short */
char ex5[] = "03:foo,"; /* Leading zeros are forbidden */
char ex6[] = "999999999999999:haha lol,"; /* Too long */
char ex7[] = "3fool,"; /* No colon */
char ex8[] = "what's up"; /* No number or colon */
char ex9[] = ":what's up"; /* No number */
void test_netstring_read(void) {
char *netstring;
size_t netstring_len;
int retval;
/* ex1: hello world */
retval = netstring_read(ex1, strlen(ex1), &netstring, &netstring_len);
assert(netstring_len == 12); assert(strncmp(netstring, "hello world!", 12) == 0);
assert(retval == 0);
/* ex2: three netstrings, concatenated. */
retval = netstring_read(ex2, strlen(ex2), &netstring, &netstring_len);
assert(netstring_len == 3); assert(strncmp(netstring, "foo", 3) == 0);
assert(retval == 0);
retval = netstring_read(netstring+netstring_len+1, 9, &netstring, &netstring_len);
assert(netstring_len == 0); assert(retval == 0);
retval = netstring_read(netstring+netstring_len+1, 6, &netstring, &netstring_len);
assert(netstring_len == 3); assert(strncmp(netstring, "bar", 3) == 0);
assert(retval == 0);
/* ex3: no comma */
retval = netstring_read(ex3, strlen(ex3), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_COMMA);
/* ex4: too short */
retval = netstring_read(ex4, strlen(ex4), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_TOO_SHORT);
/* ex5: leading zero */
retval = netstring_read(ex5, strlen(ex5), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_LEADING_ZERO);
/* ex6: too long */
retval = netstring_read(ex6, strlen(ex6), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_TOO_LONG);
/* ex7: no colon */
retval = netstring_read(ex7, strlen(ex7), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_COLON);
/* ex8: no number or colon */
retval = netstring_read(ex8, strlen(ex8), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_LENGTH);
/* ex9: no number */
retval = netstring_read(ex9, strlen(ex9), &netstring, &netstring_len);
assert(netstring_len == 0); assert(netstring == NULL);
assert(retval == NETSTRING_ERROR_NO_LENGTH);
}
void test_netstring_buffer_size(void) {
assert(netstring_buffer_size(0) == 3);
assert(netstring_buffer_size(1) == 4);
assert(netstring_buffer_size(2) == 5);
assert(netstring_buffer_size(9) == 12);
assert(netstring_buffer_size(10) == 14);
assert(netstring_buffer_size(12345) == 12345 + 5 + 2);
}
void test_netstring_encode_new(void) {
char *ns; size_t bytes;
bytes = netstring_encode_new(&ns, "foo", 3);
assert(ns != NULL); assert(strncmp(ns, "3:foo,", 6) == 0); assert(bytes == 6);
free(ns);
bytes = netstring_encode_new(&ns, NULL, 0);
assert(ns != NULL); assert(strncmp(ns, "0:,", 3) == 0); assert(bytes == 3);
free(ns);
bytes = netstring_encode_new(&ns, "hello world!", 12); assert(bytes == 16);
assert(ns != NULL); assert(strncmp(ns, "12:hello world!,", 16) == 0);
free(ns);
}
int main(void) {
printf("Running test suite...\n");
test_netstring_read();
test_netstring_buffer_size();
test_netstring_encode_new();
printf("All tests passed!\n");
return 0;
}
{
'targets':
[
{
'target_name': 'netstring',
'type': 'static_library',
'sources':
[
'netstring-c/netstring.c',
'netstring-c/netstring.h'
],
'direct_dependent_settings':
{
'include_dirs':
[
'netstring-c'
]
},
'conditions':
[
[ 'OS != "win"', {
'cflags': [ '-Wall', '-Wno-sign-compare' ]
}],
[ 'OS == "mac"', {
'xcode_settings':
{
'WARNING_CFLAGS': [ '-Wall', '-Wno-sign-compare' ]
}
}]
]
}
]
}
...@@ -31,8 +31,6 @@ namespace Channel ...@@ -31,8 +31,6 @@ namespace Channel
private: private:
// Passed by argument. // Passed by argument.
Listener* listener{ nullptr }; Listener* listener{ nullptr };
// Others.
size_t msgStart{ 0u }; // Where the latest message starts.
}; };
class ProducerSocket : public ::UnixStreamSocket class ProducerSocket : public ::UnixStreamSocket
...@@ -72,10 +70,10 @@ namespace Channel ...@@ -72,10 +70,10 @@ namespace Channel
void Close(); void Close();
void SetListener(Listener* listener); void SetListener(Listener* listener);
void Send(json& jsonMessage); void Send(json& jsonMessage);
void SendLog(char* message, size_t messageLen); void SendLog(char* message, uint32_t messageLen);
private: private:
void SendImpl(const void* nsPayload, size_t nsPayloadLen); void SendImpl(const void* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */ /* Pure virtual methods inherited from ConsumerSocket::Listener. */
public: public:
......
...@@ -160,7 +160,7 @@ public: ...@@ -160,7 +160,7 @@ public:
if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG) \ if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG) \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D(trace) " _MS_LOG_STR, _MS_LOG_ARG); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D(trace) " _MS_LOG_STR, _MS_LOG_ARG); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
} \ } \
while (false) while (false)
...@@ -192,7 +192,7 @@ public: ...@@ -192,7 +192,7 @@ public:
if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG && _MS_TAG_ENABLED(tag)) \ if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG && _MS_TAG_ENABLED(tag)) \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
} \ } \
while (false) while (false)
...@@ -214,7 +214,7 @@ public: ...@@ -214,7 +214,7 @@ public:
if (Settings::configuration.logLevel >= LogLevel::LOG_WARN && _MS_TAG_ENABLED(tag)) \ if (Settings::configuration.logLevel >= LogLevel::LOG_WARN && _MS_TAG_ENABLED(tag)) \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
} \ } \
while (false) while (false)
...@@ -236,7 +236,7 @@ public: ...@@ -236,7 +236,7 @@ public:
if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG && _MS_TAG_ENABLED_2(tag1, tag2)) \ if (Settings::configuration.logLevel == LogLevel::LOG_DEBUG && _MS_TAG_ENABLED_2(tag1, tag2)) \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
} \ } \
while (false) while (false)
...@@ -258,7 +258,7 @@ public: ...@@ -258,7 +258,7 @@ public:
if (Settings::configuration.logLevel >= LogLevel::LOG_WARN && _MS_TAG_ENABLED_2(tag1, tag2)) \ if (Settings::configuration.logLevel >= LogLevel::LOG_WARN && _MS_TAG_ENABLED_2(tag1, tag2)) \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
} \ } \
while (false) while (false)
...@@ -279,7 +279,7 @@ public: ...@@ -279,7 +279,7 @@ public:
do \ do \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "D" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
while (false) while (false)
...@@ -301,7 +301,7 @@ public: ...@@ -301,7 +301,7 @@ public:
do \ do \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "W" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
while (false) while (false)
...@@ -321,7 +321,7 @@ public: ...@@ -321,7 +321,7 @@ public:
do \ do \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
while (false) while (false)
...@@ -337,7 +337,7 @@ public: ...@@ -337,7 +337,7 @@ public:
do \ do \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X(data) " _MS_LOG_STR, _MS_LOG_ARG); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "X(data) " _MS_LOG_STR, _MS_LOG_ARG); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
size_t bufferDataLen{ 0 }; \ size_t bufferDataLen{ 0 }; \
for (size_t i{0}; i < len; ++i) \ for (size_t i{0}; i < len; ++i) \
{ \ { \
...@@ -345,7 +345,7 @@ public: ...@@ -345,7 +345,7 @@ public:
{ \ { \
if (bufferDataLen != 0) \ if (bufferDataLen != 0) \
{ \ { \
Logger::channel->SendLog(Logger::buffer, bufferDataLen); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(bufferDataLen)); \
bufferDataLen = 0; \ bufferDataLen = 0; \
} \ } \
int loggerWritten = std::snprintf(Logger::buffer + bufferDataLen, Logger::bufferSize, "X%06X ", static_cast<unsigned int>(i)); \ int loggerWritten = std::snprintf(Logger::buffer + bufferDataLen, Logger::bufferSize, "X%06X ", static_cast<unsigned int>(i)); \
...@@ -355,7 +355,7 @@ public: ...@@ -355,7 +355,7 @@ public:
bufferDataLen += loggerWritten; \ bufferDataLen += loggerWritten; \
} \ } \
if (bufferDataLen != 0) \ if (bufferDataLen != 0) \
Logger::channel->SendLog(Logger::buffer, bufferDataLen); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(bufferDataLen)); \
} \ } \
while (false) while (false)
...@@ -395,7 +395,7 @@ public: ...@@ -395,7 +395,7 @@ public:
if (Settings::configuration.logLevel >= LogLevel::LOG_ERROR || MS_LOG_DEV_LEVEL >= 1) \ if (Settings::configuration.logLevel >= LogLevel::LOG_ERROR || MS_LOG_DEV_LEVEL >= 1) \
{ \ { \
int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "E" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \ int loggerWritten = std::snprintf(Logger::buffer, Logger::bufferSize, "E" _MS_LOG_STR_DESC desc, _MS_LOG_ARG, ##__VA_ARGS__); \
Logger::channel->SendLog(Logger::buffer, loggerWritten); \ Logger::channel->SendLog(Logger::buffer, static_cast<uint32_t>(loggerWritten)); \
} \ } \
} \ } \
while (false) while (false)
......
...@@ -34,10 +34,6 @@ namespace PayloadChannel ...@@ -34,10 +34,6 @@ namespace PayloadChannel
private: private:
// Passed by argument. // Passed by argument.
Listener* listener{ nullptr }; Listener* listener{ nullptr };
// Allocated by this.
uint8_t* readBuffer{ nullptr };
// Others.
size_t msgStart{ 0u }; // Where the latest message starts.
}; };
class ProducerSocket : public ::UnixStreamSocket class ProducerSocket : public ::UnixStreamSocket
...@@ -84,7 +80,7 @@ namespace PayloadChannel ...@@ -84,7 +80,7 @@ namespace PayloadChannel
void Send(json& jsonMessage); void Send(json& jsonMessage);
private: private:
void SendImpl(const void* nsPayload, size_t nsPayloadLen); void SendImpl(const void* payload, uint32_t payloadLen);
/* Pure virtual methods inherited from ConsumerSocket::Listener. */ /* Pure virtual methods inherited from ConsumerSocket::Listener. */
public: public:
......
...@@ -25,8 +25,8 @@ namespace RTC ...@@ -25,8 +25,8 @@ namespace RTC
Speaker(); Speaker();
void EvalActivityScores(); void EvalActivityScores();
double GetActivityScore(int32_t interval); double GetActivityScore(int32_t interval);
void LevelChanged(uint32_t level, uint64_t time); void LevelChanged(uint32_t level, uint64_t now);
void LevelTimedOut(); void LevelTimedOut(uint64_t now);
private: private:
bool ComputeImmediates(); bool ComputeImmediates();
...@@ -52,6 +52,7 @@ namespace RTC ...@@ -52,6 +52,7 @@ namespace RTC
std::vector<uint8_t> mediums; std::vector<uint8_t> mediums;
std::vector<uint8_t> longs; std::vector<uint8_t> longs;
std::vector<uint8_t> levels; std::vector<uint8_t> levels;
size_t nextLevelIndex;
}; };
struct ProducerSpeaker struct ProducerSpeaker
......
...@@ -58,7 +58,7 @@ namespace RTC ...@@ -58,7 +58,7 @@ namespace RTC
} }
size_t GetSize() const override size_t GetSize() const override
{ {
size_t size = sizeof(Packet::CommonHeader); size_t size = Packet::CommonHeaderSize;
size += ssrcs.size() * 4u; size += ssrcs.size() * 4u;
......
...@@ -21,6 +21,7 @@ namespace RTC ...@@ -21,6 +21,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 8 };
static RTCP::Type rtcpType; static RTCP::Type rtcpType;
static FeedbackPacket<T>* Parse(const uint8_t* data, size_t len); static FeedbackPacket<T>* Parse(const uint8_t* data, size_t len);
static const std::string& MessageType2String(typename T::MessageType type); static const std::string& MessageType2String(typename T::MessageType type);
...@@ -60,7 +61,7 @@ namespace RTC ...@@ -60,7 +61,7 @@ namespace RTC
} }
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(CommonHeader) + sizeof(Header); return Packet::CommonHeaderSize + HeaderSize;
} }
protected: protected:
......
...@@ -14,7 +14,7 @@ namespace RTC ...@@ -14,7 +14,7 @@ namespace RTC
static Item* Parse(const uint8_t* data, size_t len) static Item* Parse(const uint8_t* data, size_t len)
{ {
// data size must be >= header. // data size must be >= header.
if (sizeof(typename Item::Header) > len) if (Item::HeaderSize > len)
return nullptr; return nullptr;
auto* header = auto* header =
......
...@@ -27,9 +27,9 @@ namespace RTC ...@@ -27,9 +27,9 @@ namespace RTC
: FeedbackPsPacket(commonHeader) : FeedbackPsPacket(commonHeader)
{ {
this->size = ((static_cast<size_t>(ntohs(commonHeader->length)) + 1) * 4) - this->size = ((static_cast<size_t>(ntohs(commonHeader->length)) + 1) * 4) -
(sizeof(CommonHeader) + sizeof(FeedbackPacket::Header)); (Packet::CommonHeaderSize + FeedbackPacket::HeaderSize);
this->data = (uint8_t*)commonHeader + sizeof(CommonHeader) + sizeof(FeedbackPacket::Header); this->data = (uint8_t*)commonHeader + Packet::CommonHeaderSize + FeedbackPacket::HeaderSize;
this->application = application; this->application = application;
} }
......
...@@ -35,6 +35,7 @@ namespace RTC ...@@ -35,6 +35,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize = 8;
static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::FIR }; static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::FIR };
public: public:
...@@ -62,7 +63,7 @@ namespace RTC ...@@ -62,7 +63,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackPsFirItem::HeaderSize;
} }
private: private:
......
...@@ -26,6 +26,7 @@ namespace RTC ...@@ -26,6 +26,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 4 };
static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::PSLEI }; static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::PSLEI };
public: public:
...@@ -49,7 +50,7 @@ namespace RTC ...@@ -49,7 +50,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackPsLeiItem::HeaderSize;
} }
private: private:
......
...@@ -33,7 +33,8 @@ namespace RTC ...@@ -33,7 +33,8 @@ namespace RTC
{ {
public: public:
// 'R' 'E' 'M' 'B'. // 'R' 'E' 'M' 'B'.
static uint32_t uniqueIdentifier; static const uint32_t UniqueIdentifier{ 0x52454D42 };
static const size_t UniqueIdentifierSize{ 4 };
public: public:
static FeedbackPsRembPacket* Parse(const uint8_t* data, size_t len); static FeedbackPsRembPacket* Parse(const uint8_t* data, size_t len);
......
...@@ -29,12 +29,18 @@ namespace RTC ...@@ -29,12 +29,18 @@ namespace RTC
struct Header struct Header
{ {
uint8_t paddingBits; uint8_t paddingBits;
#if defined(MS_LITTLE_ENDIAN)
uint8_t payloadType : 7;
uint8_t zero : 1;
#elif defined(MS_BIG_ENDIAN)
uint8_t zero : 1; uint8_t zero : 1;
uint8_t payloadType : 7; uint8_t payloadType : 7;
#endif
uint8_t bitString[maxBitStringSize]; uint8_t bitString[maxBitStringSize];
}; };
public: public:
static const size_t HeaderSize = 8;
static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::RPSI }; static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::RPSI };
public: public:
...@@ -68,7 +74,7 @@ namespace RTC ...@@ -68,7 +74,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackPsRpsiItem::HeaderSize;
} }
private: private:
......
...@@ -26,6 +26,7 @@ namespace RTC ...@@ -26,6 +26,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 4 };
static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::SLI }; static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::SLI };
public: public:
...@@ -65,7 +66,7 @@ namespace RTC ...@@ -65,7 +66,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackPsSliItem::HeaderSize;
} }
private: private:
......
...@@ -12,8 +12,7 @@ ...@@ -12,8 +12,7 @@
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SSRC | | SSRC |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Seq nr. | | Seq nr. | Reserved | Index |
| Reserved | Index |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/ */
...@@ -28,12 +27,19 @@ namespace RTC ...@@ -28,12 +27,19 @@ namespace RTC
struct Header struct Header
{ {
uint32_t ssrc; uint32_t ssrc;
uint32_t sequenceNumber : 8; uint8_t sequenceNumber;
uint32_t reserved : 19; uint16_t reserved1;
uint32_t index : 5; #if defined(MS_LITTLE_ENDIAN)
uint8_t index : 5;
uint8_t reserved2 : 3;
#elif defined(MS_BIG_ENDIAN)
uint8_t reserved2 : 3;
uint8_t index : 5;
#endif
}; };
public: public:
static const size_t HeaderSize{ 8 };
static const FeedbackPs::MessageType messageType; static const FeedbackPs::MessageType messageType;
public: public:
...@@ -52,11 +58,11 @@ namespace RTC ...@@ -52,11 +58,11 @@ namespace RTC
} }
uint8_t GetSequenceNumber() const uint8_t GetSequenceNumber() const
{ {
return static_cast<uint8_t>(this->header->sequenceNumber); return this->header->sequenceNumber;
} }
uint8_t GetIndex() const uint8_t GetIndex() const
{ {
return static_cast<uint8_t>(this->header->index); return this->header->index;
} }
/* Virtual methods inherited from FeedbackItem. */ /* Virtual methods inherited from FeedbackItem. */
...@@ -65,7 +71,7 @@ namespace RTC ...@@ -65,7 +71,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackPsTstItem::HeaderSize;
} }
private: private:
......
...@@ -30,13 +30,19 @@ namespace RTC ...@@ -30,13 +30,19 @@ namespace RTC
{ {
uint32_t ssrc; uint32_t ssrc;
uint8_t sequenceNumber; uint8_t sequenceNumber;
#if defined(MS_LITTLE_ENDIAN)
uint8_t payloadType : 7;
uint8_t zero : 1;
#elif defined(MS_BIG_ENDIAN)
uint8_t zero : 1; uint8_t zero : 1;
uint8_t payloadType : 7; uint8_t payloadType : 7;
#endif
uint16_t length; uint16_t length;
uint8_t value[]; uint8_t value[];
}; };
public: public:
static const size_t HeaderSize{ 8 };
static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::FIR }; static const FeedbackPs::MessageType messageType{ FeedbackPs::MessageType::FIR };
public: public:
...@@ -77,7 +83,7 @@ namespace RTC ...@@ -77,7 +83,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
size_t size = 8 + static_cast<size_t>(GetLength()); size_t size = FeedbackPsVbcmItem::HeaderSize + static_cast<size_t>(GetLength());
// Consider pading to 32 bits (4 bytes) boundary. // Consider pading to 32 bits (4 bytes) boundary.
return (size + 3) & ~3; return (size + 3) & ~3;
......
...@@ -42,6 +42,7 @@ namespace RTC ...@@ -42,6 +42,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 20 };
static const FeedbackRtp::MessageType messageType{ FeedbackRtp::MessageType::ECN }; static const FeedbackRtp::MessageType messageType{ FeedbackRtp::MessageType::ECN };
public: public:
...@@ -88,7 +89,7 @@ namespace RTC ...@@ -88,7 +89,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackRtpEcnItem::HeaderSize;
} }
private: private:
......
...@@ -28,6 +28,7 @@ namespace RTC ...@@ -28,6 +28,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 4 };
static const FeedbackRtp::MessageType messageType{ FeedbackRtp::MessageType::NACK }; static const FeedbackRtp::MessageType messageType{ FeedbackRtp::MessageType::NACK };
public: public:
...@@ -59,7 +60,7 @@ namespace RTC ...@@ -59,7 +60,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackRtpNackItem::HeaderSize;
} }
private: private:
......
...@@ -27,6 +27,7 @@ namespace RTC ...@@ -27,6 +27,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 4 };
static const FeedbackRtp::MessageType messageType{ FeedbackRtp::MessageType::TLLEI }; static const FeedbackRtp::MessageType messageType{ FeedbackRtp::MessageType::TLLEI };
public: public:
...@@ -54,7 +55,7 @@ namespace RTC ...@@ -54,7 +55,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackRtpTlleiItem::HeaderSize;
} }
private: private:
......
...@@ -31,6 +31,7 @@ namespace RTC ...@@ -31,6 +31,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 8 };
static const FeedbackRtp::MessageType messageType; static const FeedbackRtp::MessageType messageType;
public: public:
...@@ -70,7 +71,7 @@ namespace RTC ...@@ -70,7 +71,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer) override; size_t Serialize(uint8_t* buffer) override;
size_t GetSize() const override size_t GetSize() const override
{ {
return sizeof(Header); return FeedbackRtpTmmbItem::HeaderSize;
} }
private: private:
......
...@@ -44,18 +44,19 @@ namespace RTC ...@@ -44,18 +44,19 @@ namespace RTC
uint8_t padding : 1; uint8_t padding : 1;
uint8_t count : 5; uint8_t count : 5;
#endif #endif
uint8_t packetType : 8; uint8_t packetType;
uint16_t length : 16; uint16_t length;
}; };
public: public:
static const size_t CommonHeaderSize{ 4 };
static bool IsRtcp(const uint8_t* data, size_t len) static bool IsRtcp(const uint8_t* data, size_t len)
{ {
auto header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data)); auto header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
// clang-format off // clang-format off
return ( return (
(len >= sizeof(CommonHeader)) && (len >= CommonHeaderSize) &&
// DOC: https://tools.ietf.org/html/draft-ietf-avtcore-rfc5764-mux-fixes // DOC: https://tools.ietf.org/html/draft-ietf-avtcore-rfc5764-mux-fixes
(data[0] > 127 && data[0] < 192) && (data[0] > 127 && data[0] < 192) &&
// RTP Version must be 2. // RTP Version must be 2.
......
...@@ -26,6 +26,7 @@ namespace RTC ...@@ -26,6 +26,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 24 };
static ReceiverReport* Parse(const uint8_t* data, size_t len); static ReceiverReport* Parse(const uint8_t* data, size_t len);
public: public:
...@@ -46,7 +47,7 @@ namespace RTC ...@@ -46,7 +47,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer); size_t Serialize(uint8_t* buffer);
size_t GetSize() const size_t GetSize() const
{ {
return sizeof(Header); return HeaderSize;
} }
uint32_t GetSsrc() const uint32_t GetSsrc() const
{ {
...@@ -123,7 +124,7 @@ namespace RTC ...@@ -123,7 +124,7 @@ namespace RTC
private: private:
Header* header{ nullptr }; Header* header{ nullptr };
uint8_t raw[sizeof(Header)]{ 0u }; uint8_t raw[HeaderSize]{ 0u };
}; };
class ReceiverReportPacket : public Packet class ReceiverReportPacket : public Packet
...@@ -188,7 +189,7 @@ namespace RTC ...@@ -188,7 +189,7 @@ namespace RTC
} }
size_t GetSize() const override size_t GetSize() const override
{ {
size_t size = sizeof(Packet::CommonHeader) + 4u /* this->ssrc */; size_t size = Packet::CommonHeaderSize + 4u /* this->ssrc */;
for (auto* report : reports) for (auto* report : reports)
{ {
......
...@@ -37,6 +37,7 @@ namespace RTC ...@@ -37,6 +37,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize = 2;
static SdesItem* Parse(const uint8_t* data, size_t len); static SdesItem* Parse(const uint8_t* data, size_t len);
static const std::string& Type2String(SdesItem::Type type); static const std::string& Type2String(SdesItem::Type type);
...@@ -197,7 +198,7 @@ namespace RTC ...@@ -197,7 +198,7 @@ namespace RTC
} }
size_t GetSize() const override size_t GetSize() const override
{ {
size_t size = sizeof(Packet::CommonHeader); size_t size = Packet::CommonHeaderSize;
for (auto* chunk : this->chunks) for (auto* chunk : this->chunks)
{ {
......
...@@ -24,6 +24,7 @@ namespace RTC ...@@ -24,6 +24,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 24 };
static SenderReport* Parse(const uint8_t* data, size_t len); static SenderReport* Parse(const uint8_t* data, size_t len);
public: public:
...@@ -44,7 +45,7 @@ namespace RTC ...@@ -44,7 +45,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer); size_t Serialize(uint8_t* buffer);
size_t GetSize() const size_t GetSize() const
{ {
return sizeof(Header); return HeaderSize;
} }
uint32_t GetSsrc() const uint32_t GetSsrc() const
{ {
...@@ -97,7 +98,7 @@ namespace RTC ...@@ -97,7 +98,7 @@ namespace RTC
private: private:
Header* header{ nullptr }; Header* header{ nullptr };
uint8_t raw[sizeof(Header)]{ 0 }; uint8_t raw[HeaderSize]{ 0 };
}; };
class SenderReportPacket : public Packet class SenderReportPacket : public Packet
...@@ -146,7 +147,7 @@ namespace RTC ...@@ -146,7 +147,7 @@ namespace RTC
} }
size_t GetSize() const override size_t GetSize() const override
{ {
size_t size = sizeof(Packet::CommonHeader); size_t size = Packet::CommonHeaderSize;
for (auto* report : this->reports) for (auto* report : this->reports)
{ {
......
...@@ -46,6 +46,7 @@ namespace RTC ...@@ -46,6 +46,7 @@ namespace RTC
}; };
public: public:
static const size_t CommonHeaderSize{ 4 };
static ExtendedReportBlock* Parse(const uint8_t* data, size_t len); static ExtendedReportBlock* Parse(const uint8_t* data, size_t len);
public: public:
...@@ -71,7 +72,7 @@ namespace RTC ...@@ -71,7 +72,7 @@ namespace RTC
CommonHeader* header{ nullptr }; CommonHeader* header{ nullptr };
private: private:
uint8_t raw[sizeof(CommonHeader)] = { 0 }; uint8_t raw[Packet::CommonHeaderSize] = { 0 };
}; };
class ExtendedReportPacket : public Packet class ExtendedReportPacket : public Packet
...@@ -128,7 +129,7 @@ namespace RTC ...@@ -128,7 +129,7 @@ namespace RTC
} }
size_t GetSize() const override size_t GetSize() const override
{ {
size_t size = sizeof(Packet::CommonHeader) + 4u /*ssrc*/; size_t size = Packet::CommonHeaderSize + 4u /*ssrc*/;
for (auto* report : this->reports) for (auto* report : this->reports)
{ {
......
...@@ -36,6 +36,7 @@ namespace RTC ...@@ -36,6 +36,7 @@ namespace RTC
class SsrcInfo class SsrcInfo
{ {
public: public:
static const size_t BodySize{ 12 };
static SsrcInfo* Parse(const uint8_t* data, size_t len); static SsrcInfo* Parse(const uint8_t* data, size_t len);
public: public:
...@@ -61,7 +62,7 @@ namespace RTC ...@@ -61,7 +62,7 @@ namespace RTC
size_t Serialize(uint8_t* buffer); size_t Serialize(uint8_t* buffer);
size_t GetSize() const size_t GetSize() const
{ {
return sizeof(Body); return BodySize;
} }
uint32_t GetSsrc() const uint32_t GetSsrc() const
{ {
...@@ -90,7 +91,7 @@ namespace RTC ...@@ -90,7 +91,7 @@ namespace RTC
private: private:
Body* body{ nullptr }; Body* body{ nullptr };
uint8_t raw[sizeof(Body)] = { 0 }; uint8_t raw[BodySize] = { 0 };
}; };
public: public:
......
...@@ -31,6 +31,7 @@ namespace RTC ...@@ -31,6 +31,7 @@ namespace RTC
}; };
public: public:
static const size_t BodySize{ 8 };
static ReceiverReferenceTime* Parse(const uint8_t* data, size_t len); static ReceiverReferenceTime* Parse(const uint8_t* data, size_t len);
public: public:
...@@ -73,14 +74,14 @@ namespace RTC ...@@ -73,14 +74,14 @@ namespace RTC
{ {
size_t size{ 4 }; // Common header. size_t size{ 4 }; // Common header.
size += sizeof(Body); size += BodySize;
return size; return size;
} }
private: private:
Body* body{ nullptr }; Body* body{ nullptr };
uint8_t raw[sizeof(Body)] = { 0 }; uint8_t raw[BodySize] = { 0 };
}; };
} // namespace RTCP } // namespace RTCP
} // namespace RTC } // namespace RTC
......
...@@ -49,6 +49,8 @@ namespace RTC ...@@ -49,6 +49,8 @@ namespace RTC
UNSET = 0, UNSET = 0,
// Audio codecs: // Audio codecs:
OPUS = 100, OPUS = 100,
// Multi-channel Opus.
MULTIOPUS,
PCMA, PCMA,
PCMU, PCMU,
ISAC, ISAC,
......
...@@ -74,8 +74,8 @@ namespace RTC ...@@ -74,8 +74,8 @@ namespace RTC
/* Struct for Two-Bytes extension. */ /* Struct for Two-Bytes extension. */
struct TwoBytesExtension struct TwoBytesExtension
{ {
uint8_t id : 8; uint8_t id;
uint8_t len : 8; uint8_t len;
uint8_t value[1]; uint8_t value[1];
}; };
...@@ -85,8 +85,8 @@ namespace RTC ...@@ -85,8 +85,8 @@ namespace RTC
{ {
GenericExtension(uint8_t id, uint8_t len, uint8_t* value) : id(id), len(len), value(value){}; GenericExtension(uint8_t id, uint8_t len, uint8_t* value) : id(id), len(len), value(value){};
uint8_t id : 8; uint8_t id;
uint8_t len : 8; uint8_t len;
uint8_t* value; uint8_t* value;
}; };
...@@ -114,6 +114,7 @@ namespace RTC ...@@ -114,6 +114,7 @@ namespace RTC
}; };
public: public:
static const size_t HeaderSize{ 12 };
static bool IsRtp(const uint8_t* data, size_t len) static bool IsRtp(const uint8_t* data, size_t len)
{ {
// NOTE: RtcpPacket::IsRtcp() must always be called before this method. // NOTE: RtcpPacket::IsRtcp() must always be called before this method.
...@@ -122,7 +123,7 @@ namespace RTC ...@@ -122,7 +123,7 @@ namespace RTC
// clang-format off // clang-format off
return ( return (
(len >= sizeof(Header)) && (len >= HeaderSize) &&
// DOC: https://tools.ietf.org/html/draft-ietf-avtcore-rfc5764-mux-fixes // DOC: https://tools.ietf.org/html/draft-ietf-avtcore-rfc5764-mux-fixes
(data[0] > 127 && data[0] < 192) && (data[0] > 127 && data[0] < 192) &&
// RTP Version must be 2. // RTP Version must be 2.
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
#include <libwebrtc/api/transport/network_types.h> #include <libwebrtc/api/transport/network_types.h>
#include <libwebrtc/call/rtp_transport_controller_send.h> #include <libwebrtc/call/rtp_transport_controller_send.h>
#include <libwebrtc/modules/pacing/packet_router.h> #include <libwebrtc/modules/pacing/packet_router.h>
#include <deque>
namespace RTC namespace RTC
{ {
...@@ -76,10 +77,12 @@ namespace RTC ...@@ -76,10 +77,12 @@ namespace RTC
return this->bitrates; return this->bitrates;
} }
uint32_t GetAvailableBitrate() const; uint32_t GetAvailableBitrate() const;
double GetPacketLoss() const;
void RescheduleNextAvailableBitrateEvent(); void RescheduleNextAvailableBitrateEvent();
private: private:
void MayEmitAvailableBitrateEvent(uint32_t previousAvailableBitrate); void MayEmitAvailableBitrateEvent(uint32_t previousAvailableBitrate);
void UpdatePacketLoss(double packetLoss);
// jmillan: missing. // jmillan: missing.
// void OnRemoteNetworkEstimate(NetworkStateEstimate estimate) override; // void OnRemoteNetworkEstimate(NetworkStateEstimate estimate) override;
...@@ -113,6 +116,8 @@ namespace RTC ...@@ -113,6 +116,8 @@ namespace RTC
bool availableBitrateEventCalled{ false }; bool availableBitrateEventCalled{ false };
uint64_t lastAvailableBitrateEventAtMs{ 0u }; uint64_t lastAvailableBitrateEventAtMs{ 0u };
RTC::TrendCalculator desiredBitrateTrend; RTC::TrendCalculator desiredBitrateTrend;
std::deque<double> packetLossHistory;
double packetLoss{ 0 };
}; };
} // namespace RTC } // namespace RTC
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
#include "RTC/RtpPacket.hpp" #include "RTC/RtpPacket.hpp"
#include "handles/Timer.hpp" #include "handles/Timer.hpp"
#include <libwebrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_abs_send_time.h> #include <libwebrtc/modules/remote_bitrate_estimator/remote_bitrate_estimator_abs_send_time.h>
#include <deque>
namespace RTC namespace RTC
{ {
...@@ -50,12 +51,14 @@ namespace RTC ...@@ -50,12 +51,14 @@ namespace RTC
return 0u; return 0u;
} }
} }
double GetPacketLoss() const;
void IncomingPacket(uint64_t nowMs, const RTC::RtpPacket* packet); void IncomingPacket(uint64_t nowMs, const RTC::RtpPacket* packet);
void SetMaxIncomingBitrate(uint32_t bitrate); void SetMaxIncomingBitrate(uint32_t bitrate);
private: private:
void SendTransportCcFeedback(); void SendTransportCcFeedback();
void MaySendLimitationRembFeedback(); void MaySendLimitationRembFeedback();
void UpdatePacketLoss(double packetLoss);
/* Pure virtual methods inherited from webrtc::RemoteBitrateEstimator::Listener. */ /* Pure virtual methods inherited from webrtc::RemoteBitrateEstimator::Listener. */
public: public:
...@@ -84,6 +87,8 @@ namespace RTC ...@@ -84,6 +87,8 @@ namespace RTC
uint32_t maxIncomingBitrate{ 0u }; uint32_t maxIncomingBitrate{ 0u };
uint64_t limitationRembSentAtMs{ 0u }; uint64_t limitationRembSentAtMs{ 0u };
uint8_t unlimitedRembCounter{ 0u }; uint8_t unlimitedRembCounter{ 0u };
std::deque<double> packetLossHistory;
double packetLoss{ 0 };
}; };
} // namespace RTC } // namespace RTC
......
...@@ -68,15 +68,6 @@ function get_json() ...@@ -68,15 +68,6 @@ function get_json()
${DEST}/third_party/ ${DEST}/third_party/
} }
function get_netstring()
{
GIT_REPO="https://github.com/PeterScott/netstring-c.git"
GIT_TAG="master"
DEST="deps/netstring/netstring-c"
get_dep "${GIT_REPO}" "${GIT_TAG}" "${DEST}"
}
function get_libuv() function get_libuv()
{ {
GIT_REPO="https://github.com/libuv/libuv.git" GIT_REPO="https://github.com/libuv/libuv.git"
...@@ -183,7 +174,7 @@ function get_win_getopt() ...@@ -183,7 +174,7 @@ function get_win_getopt()
case "${DEP}" in case "${DEP}" in
'-h') '-h')
echo "Usage:" echo "Usage:"
echo " ./scripts/$(basename $0) [gyp|json|netstring|libuv|openssl|libsrtp|usrsctp|abseil-cpp|catch|lcov|clang-fuzzer|fuzzer-corpora|win-getopt]" echo " ./scripts/$(basename $0) [gyp|json|libuv|openssl|libsrtp|usrsctp|abseil-cpp|catch|lcov|clang-fuzzer|fuzzer-corpora|win-getopt]"
echo echo
;; ;;
gyp) gyp)
...@@ -192,9 +183,6 @@ case "${DEP}" in ...@@ -192,9 +183,6 @@ case "${DEP}" in
json) json)
get_json get_json
;; ;;
netstring)
get_netstring
;;
libuv) libuv)
get_libuv get_libuv
;; ;;
......
...@@ -7,26 +7,22 @@ ...@@ -7,26 +7,22 @@
#include <cmath> // std::ceil() #include <cmath> // std::ceil()
#include <cstdio> // sprintf() #include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove() #include <cstring> // std::memcpy(), std::memmove()
extern "C"
{
#include <netstring.h>
}
namespace Channel namespace Channel
{ {
/* Static. */ /* Static. */
// netstring length for a 4194304 bytes payload. // Binary length for a 4194304 bytes payload.
static constexpr size_t NsMessageMaxLen{ 4194313 }; static constexpr size_t MessageMaxLen{ 4194308 };
static constexpr size_t NsPayloadMaxLen{ 4194304 }; static constexpr size_t PayloadMaxLen{ 4194304 };
/* Instance methods. */ /* Instance methods. */
ChannelSocket::ChannelSocket(int consumerFd, int producerFd) ChannelSocket::ChannelSocket(int consumerFd, int producerFd)
: consumerSocket(consumerFd, NsMessageMaxLen, this), producerSocket(producerFd, NsMessageMaxLen) : consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(NsMessageMaxLen)); this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
} }
ChannelSocket::~ChannelSocket() ChannelSocket::~ChannelSocket()
...@@ -68,26 +64,26 @@ namespace Channel ...@@ -68,26 +64,26 @@ namespace Channel
std::string message = jsonMessage.dump(); std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen) if (message.length() > PayloadMaxLen)
{ {
MS_ERROR_STD("mesage too big"); MS_ERROR_STD("message too big");
return; return;
} }
SendImpl(message.c_str(), message.length()); SendImpl(message.c_str(), static_cast<uint32_t>(message.length()));
} }
void ChannelSocket::SendLog(char* message, size_t messageLen) void ChannelSocket::SendLog(char* message, uint32_t messageLen)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
if (this->closed) if (this->closed)
return; return;
if (messageLen > NsPayloadMaxLen) if (messageLen > PayloadMaxLen)
{ {
MS_ERROR_STD("mesage too big"); MS_ERROR_STD("message too big");
return; return;
} }
...@@ -95,30 +91,20 @@ namespace Channel ...@@ -95,30 +91,20 @@ namespace Channel
SendImpl(message, messageLen); SendImpl(message, messageLen);
} }
inline void ChannelSocket::SendImpl(const void* nsPayload, size_t nsPayloadLen) inline void ChannelSocket::SendImpl(const void* payload, uint32_t payloadLen)
{ {
MS_TRACE_STD(); MS_TRACE_STD();
size_t nsNumLen; std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (nsPayloadLen == 0) if (payloadLen != 0)
{
nsNumLen = 1;
this->writeBuffer[0] = '0';
this->writeBuffer[1] = ':';
this->writeBuffer[2] = ',';
}
else
{ {
nsNumLen = static_cast<size_t>(std::ceil(std::log10(static_cast<double>(nsPayloadLen) + 1))); std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen);
std::sprintf(reinterpret_cast<char*>(this->writeBuffer), "%zu:", nsPayloadLen);
std::memcpy(this->writeBuffer + nsNumLen + 1, nsPayload, nsPayloadLen);
this->writeBuffer[nsNumLen + nsPayloadLen + 1] = ',';
} }
size_t nsLen = nsNumLen + nsPayloadLen + 2; size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket.Write(this->writeBuffer, nsLen); this->producerSocket.Write(this->writeBuffer, len);
} }
void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen) void ChannelSocket::OnConsumerSocketMessage(ConsumerSocket* /*consumerSocket*/, char* msg, size_t msgLen)
...@@ -174,124 +160,48 @@ namespace Channel ...@@ -174,124 +160,48 @@ namespace Channel
{ {
MS_TRACE_STD(); MS_TRACE_STD();
size_t msgStart{ 0 };
// Be ready to parse more than a single message in a single chunk. // Be ready to parse more than a single message in a single chunk.
while (true) while (true)
{ {
if (IsClosed()) if (IsClosed())
return; return;
size_t readLen = this->bufferDataLen - this->msgStart; size_t readLen = this->bufferDataLen - msgStart;
char* msgStart = nullptr;
size_t msgLen;
int nsRet = netstring_read(
reinterpret_cast<char*>(this->buffer + this->msgStart), readLen, &msgStart, &msgLen);
if (nsRet != 0)
{
switch (nsRet)
{
case NETSTRING_ERROR_TOO_SHORT:
{
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize)
{
// First case: the incomplete message does not begin at position 0 of
// the buffer, so move the incomplete message to the position 0.
if (this->msgStart != 0)
{
std::memmove(this->buffer, this->buffer + this->msgStart, readLen);
this->msgStart = 0;
this->bufferDataLen = readLen;
}
// Second case: the incomplete message begins at position 0 of the buffer.
// The message is too big, so discard it.
else
{
MS_ERROR_STD(
"no more space in the buffer for the unfinished message being parsed, "
"discarding it");
this->msgStart = 0;
this->bufferDataLen = 0;
}
}
// Otherwise the buffer is not full, just wait. if (readLen < sizeof(uint32_t))
return;
}
case NETSTRING_ERROR_TOO_LONG:
{ {
MS_ERROR_STD("NETSTRING_ERROR_TOO_LONG"); // Incomplete data.
break; break;
} }
case NETSTRING_ERROR_NO_COLON: uint32_t msgLen;
{ // Read message length.
MS_ERROR_STD("NETSTRING_ERROR_NO_COLON"); std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
break; if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
}
case NETSTRING_ERROR_NO_COMMA:
{ {
MS_ERROR_STD("NETSTRING_ERROR_NO_COMMA"); // Incomplete data.
break; break;
} }
case NETSTRING_ERROR_LEADING_ZERO: this->listener->OnConsumerSocketMessage(
{ this,
MS_ERROR_STD("NETSTRING_ERROR_LEADING_ZERO"); reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
break; msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
} }
case NETSTRING_ERROR_NO_LENGTH: if (msgStart != 0)
{ {
MS_ERROR_STD("NETSTRING_ERROR_NO_LENGTH"); this->bufferDataLen = this->bufferDataLen - msgStart;
break; if (this->bufferDataLen != 0)
}
}
// Error, so reset and exit the parsing loop.
this->msgStart = 0;
this->bufferDataLen = 0;
return;
}
// If here it means that msgStart points to the beginning of a message
// with msgLen bytes length, so recalculate readLen.
readLen =
reinterpret_cast<const uint8_t*>(msgStart) - (this->buffer + this->msgStart) + msgLen + 1;
this->listener->OnConsumerSocketMessage(this, msgStart, msgLen);
// If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + readLen) == this->bufferSize)
{
this->msgStart = 0;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else
{ {
this->msgStart += readLen; std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
} }
// If there is more data in the buffer after the parsed message
// then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart)
{
continue;
}
break;
} }
} }
......
...@@ -8,26 +8,22 @@ ...@@ -8,26 +8,22 @@
#include <cmath> // std::ceil() #include <cmath> // std::ceil()
#include <cstdio> // sprintf() #include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove() #include <cstring> // std::memcpy(), std::memmove()
extern "C"
{
#include <netstring.h>
}
namespace PayloadChannel namespace PayloadChannel
{ {
/* Static. */ /* Static. */
// netstring length for a 4194304 bytes payload. // Binary length for a 4194304 bytes payload.
static constexpr size_t NsMessageMaxLen{ 4194313 }; static constexpr size_t MessageMaxLen{ 4194308 };
static constexpr size_t NsPayloadMaxLen{ 4194304 }; static constexpr size_t PayloadMaxLen{ 4194304 };
/* Instance methods. */ /* Instance methods. */
PayloadChannelSocket::PayloadChannelSocket(int consumerFd, int producerFd) PayloadChannelSocket::PayloadChannelSocket(int consumerFd, int producerFd)
: consumerSocket(consumerFd, NsMessageMaxLen, this), producerSocket(producerFd, NsMessageMaxLen) : consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen)
{ {
MS_TRACE(); MS_TRACE();
this->writeBuffer = (uint8_t*)std::malloc(NsMessageMaxLen); this->writeBuffer = (uint8_t*)std::malloc(MessageMaxLen);
} }
PayloadChannelSocket::~PayloadChannelSocket() PayloadChannelSocket::~PayloadChannelSocket()
...@@ -70,21 +66,21 @@ namespace PayloadChannel ...@@ -70,21 +66,21 @@ namespace PayloadChannel
std::string message = jsonMessage.dump(); std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen) if (message.length() > PayloadMaxLen)
{ {
MS_ERROR("mesage too big"); MS_ERROR("message too big");
return; return;
} }
else if (payloadLen > NsPayloadMaxLen) else if (payloadLen > PayloadMaxLen)
{ {
MS_ERROR("payload too big"); MS_ERROR("payload too big");
return; return;
} }
SendImpl(message.c_str(), message.length()); SendImpl(message.c_str(), static_cast<uint32_t>(message.length()));
SendImpl(payload, payloadLen); SendImpl(payload, static_cast<uint32_t>(payloadLen));
} }
void PayloadChannelSocket::Send(json& jsonMessage) void PayloadChannelSocket::Send(json& jsonMessage)
...@@ -96,40 +92,30 @@ namespace PayloadChannel ...@@ -96,40 +92,30 @@ namespace PayloadChannel
std::string message = jsonMessage.dump(); std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen) if (message.length() > PayloadMaxLen)
{ {
MS_ERROR_STD("mesage too big"); MS_ERROR_STD("message too big");
return; return;
} }
SendImpl(message.c_str(), message.length()); SendImpl(message.c_str(), static_cast<uint32_t>(message.length()));
} }
inline void PayloadChannelSocket::SendImpl(const void* nsPayload, size_t nsPayloadLen) inline void PayloadChannelSocket::SendImpl(const void* payload, uint32_t payloadLen)
{ {
MS_TRACE(); MS_TRACE();
size_t nsNumLen; std::memcpy(this->writeBuffer, &payloadLen, sizeof(uint32_t));
if (nsPayloadLen == 0) if (payloadLen != 0)
{
nsNumLen = 1;
this->writeBuffer[0] = '0';
this->writeBuffer[1] = ':';
this->writeBuffer[2] = ',';
}
else
{ {
nsNumLen = static_cast<size_t>(std::ceil(std::log10(static_cast<double>(nsPayloadLen) + 1))); std::memcpy(this->writeBuffer + sizeof(uint32_t), payload, payloadLen);
std::sprintf(reinterpret_cast<char*>(this->writeBuffer), "%zu:", nsPayloadLen);
std::memcpy(this->writeBuffer + nsNumLen + 1, nsPayload, nsPayloadLen);
this->writeBuffer[nsNumLen + nsPayloadLen + 1] = ',';
} }
size_t nsLen = nsNumLen + nsPayloadLen + 2; size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket.Write(this->writeBuffer, nsLen); this->producerSocket.Write(this->writeBuffer, len);
} }
void PayloadChannelSocket::OnConsumerSocketMessage( void PayloadChannelSocket::OnConsumerSocketMessage(
...@@ -232,140 +218,59 @@ namespace PayloadChannel ...@@ -232,140 +218,59 @@ namespace PayloadChannel
: ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener) : ::UnixStreamSocket(fd, bufferSize, ::UnixStreamSocket::Role::CONSUMER), listener(listener)
{ {
MS_TRACE(); MS_TRACE();
this->readBuffer = static_cast<uint8_t*>(std::malloc(NsMessageMaxLen));
} }
ConsumerSocket::~ConsumerSocket() ConsumerSocket::~ConsumerSocket()
{ {
MS_TRACE(); MS_TRACE();
std::free(this->readBuffer);
} }
void ConsumerSocket::UserOnUnixStreamRead() void ConsumerSocket::UserOnUnixStreamRead()
{ {
MS_TRACE(); MS_TRACE();
size_t msgStart{ 0 };
// Be ready to parse more than a single message in a single chunk. // Be ready to parse more than a single message in a single chunk.
while (true) while (true)
{ {
if (IsClosed()) if (IsClosed())
return; return;
size_t readLen = this->bufferDataLen - this->msgStart; size_t readLen = this->bufferDataLen - msgStart;
char* msgStart = nullptr;
size_t msgLen;
int nsRet = netstring_read(
reinterpret_cast<char*>(this->buffer + this->msgStart), readLen, &msgStart, &msgLen);
if (nsRet != 0)
{
switch (nsRet)
{
case NETSTRING_ERROR_TOO_SHORT:
{
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize)
{
// First case: the incomplete message does not begin at position 0 of
// the buffer, so move the incomplete message to the position 0.
if (this->msgStart != 0)
{
std::memmove(this->buffer, this->buffer + this->msgStart, readLen);
this->msgStart = 0;
this->bufferDataLen = readLen;
}
// Second case: the incomplete message begins at position 0 of the buffer.
// The message is too big, so discard it.
else
{
MS_ERROR(
"no more space in the buffer for the unfinished message being parsed, "
"discarding it");
this->msgStart = 0;
this->bufferDataLen = 0;
}
}
// Otherwise the buffer is not full, just wait.
return;
}
case NETSTRING_ERROR_TOO_LONG:
{
MS_ERROR("NETSTRING_ERROR_TOO_LONG");
break;
}
case NETSTRING_ERROR_NO_COLON:
{
MS_ERROR("NETSTRING_ERROR_NO_COLON");
break;
}
case NETSTRING_ERROR_NO_COMMA: if (readLen < sizeof(uint32_t))
{ {
MS_ERROR("NETSTRING_ERROR_NO_COMMA"); // Incomplete data.
break; break;
} }
case NETSTRING_ERROR_LEADING_ZERO: uint32_t msgLen;
{ // Read message length.
MS_ERROR("NETSTRING_ERROR_LEADING_ZERO"); std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
break;
}
case NETSTRING_ERROR_NO_LENGTH: if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
{ {
MS_ERROR("NETSTRING_ERROR_NO_LENGTH"); // Incomplete data.
break; break;
} }
}
// Error, so reset and exit the parsing loop. this->listener->OnConsumerSocketMessage(
this->msgStart = 0; this,
this->bufferDataLen = 0; reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
return; msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
} }
// If here it means that msgStart points to the beginning of a message if (msgStart != 0)
// with msgLen bytes length, so recalculate readLen.
readLen =
reinterpret_cast<const uint8_t*>(msgStart) - (this->buffer + this->msgStart) + msgLen + 1;
std::memcpy(this->readBuffer, msgStart, msgLen);
this->listener->OnConsumerSocketMessage(this, reinterpret_cast<char*>(this->readBuffer), msgLen);
// If there is no more space available in the buffer and that is because
// the latest parsed message filled it, then empty the full buffer.
if ((this->msgStart + readLen) == this->bufferSize)
{ {
this->msgStart = 0; this->bufferDataLen = this->bufferDataLen - msgStart;
this->bufferDataLen = 0;
}
// If there is still space in the buffer, set the beginning of the next
// parsing to the next position after the parsed message.
else
{
this->msgStart += readLen;
}
// If there is more data in the buffer after the parsed message if (this->bufferDataLen != 0)
// then parse again. Otherwise break here and wait for more data.
if (this->bufferDataLen > this->msgStart)
{ {
continue; std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
} }
break;
} }
} }
......
...@@ -196,11 +196,12 @@ namespace RTC ...@@ -196,11 +196,12 @@ namespace RTC
if (IsPaused()) if (IsPaused())
return; return;
uint8_t volume; uint8_t level;
bool voice; bool voice;
if (!packet->ReadSsrcAudioLevel(volume, voice)) if (!packet->ReadSsrcAudioLevel(level, voice))
return; return;
uint8_t volume = 127 - level;
auto it = this->mapProducerSpeaker.find(producer->id); auto it = this->mapProducerSpeaker.find(producer->id);
...@@ -239,9 +240,8 @@ namespace RTC ...@@ -239,9 +240,8 @@ namespace RTC
MS_TRACE(); MS_TRACE();
uint64_t now = DepLibUV::GetTimeMs(); uint64_t now = DepLibUV::GetTimeMs();
int64_t levelIdleTimeout = LevelIdleTimeout - (now - this->lastLevelIdleTime);
if (levelIdleTimeout <= 0) if (now - this->lastLevelIdleTime >= LevelIdleTimeout)
{ {
if (this->lastLevelIdleTime != 0) if (this->lastLevelIdleTime != 0)
{ {
...@@ -310,13 +310,12 @@ namespace RTC ...@@ -310,13 +310,12 @@ namespace RTC
for (int interval = 0; interval < this->relativeSpeachActivitiesLen; ++interval) for (int interval = 0; interval < this->relativeSpeachActivitiesLen; ++interval)
{ {
this->relativeSpeachActivities[interval] = std::log( this->relativeSpeachActivities[interval] = std::log(
dominantSpeaker->GetActivityScore(interval) / speaker->GetActivityScore(interval)); speaker->GetActivityScore(interval) / dominantSpeaker->GetActivityScore(interval));
} }
double c1 = this->relativeSpeachActivities[0]; double c1 = this->relativeSpeachActivities[0];
double c2 = this->relativeSpeachActivities[1]; double c2 = this->relativeSpeachActivities[1];
double c3 = this->relativeSpeachActivities[2]; double c3 = this->relativeSpeachActivities[2];
if ((c1 > C1) && (c2 > C2) && (c3 > C3) && (c2 > newDominantC2)) if ((c1 > C1) && (c2 > C2) && (c3 > C3) && (c2 > newDominantC2))
{ {
newDominantC2 = c2; newDominantC2 = c2;
...@@ -351,27 +350,18 @@ namespace RTC ...@@ -351,27 +350,18 @@ namespace RTC
} }
else if (LevelIdleTimeout < idle) else if (LevelIdleTimeout < idle)
{ {
speaker->LevelTimedOut(); speaker->LevelTimedOut(now);
} }
} }
} }
ActiveSpeakerObserver::Speaker::Speaker() ActiveSpeakerObserver::Speaker::Speaker()
: immediateActivityScore(MinActivityScore), mediumActivityScore(MinActivityScore),
longActivityScore(MinActivityScore), lastLevelChangeTime(DepLibUV::GetTimeMs()),
minLevel(MinLevel), nextMinLevel(MinLevel), immediates(ImmediateBuffLen, 0),
mediums(MediumsBuffLen, 0), longs(LongsBuffLen, 0), levels(LevelsBuffLen, 0), nextLevelIndex(0)
{ {
MS_TRACE(); MS_TRACE();
this->minLevel = MinLevel;
this->nextMinLevel = MinLevel;
this->immediateActivityScore = MinActivityScore;
this->mediumActivityScore = MinActivityScore;
this->longActivityScore = MinActivityScore;
this->immediates.resize(ImmediateBuffLen);
this->mediums.resize(MediumsBuffLen);
this->longs.resize(LongsBuffLen);
this->levels.resize(LevelsBuffLen);
this->lastLevelChangeTime = DepLibUV::GetTimeMs();
} }
void ActiveSpeakerObserver::Speaker::EvalActivityScores() void ActiveSpeakerObserver::Speaker::EvalActivityScores()
...@@ -413,11 +403,13 @@ namespace RTC ...@@ -413,11 +403,13 @@ namespace RTC
return 0; return 0;
} }
void ActiveSpeakerObserver::Speaker::LevelChanged(uint32_t level, uint64_t time) void ActiveSpeakerObserver::Speaker::LevelChanged(uint32_t level, uint64_t now)
{ {
if (this->lastLevelChangeTime <= time) if (this->lastLevelChangeTime <= now)
{ {
this->lastLevelChangeTime = time; uint64_t elapsed = now - this->lastLevelChangeTime;
this->lastLevelChangeTime = now;
int8_t b = 0; int8_t b = 0;
...@@ -434,19 +426,26 @@ namespace RTC ...@@ -434,19 +426,26 @@ namespace RTC
b = level; b = level;
} }
std::copy(this->levels.begin(), this->levels.end() - 1, this->levels.begin() + 1); // The algorithm expect to have an update every 20 milliseconds. If the producer is paused,
// using a different packetization time or using DTX we need to update more than one sample
// when receiving an audio packet.
uint32_t intervalsUpdated =
std::min(std::max(static_cast<uint32_t>(elapsed / 20), 1U), LevelsBuffLen);
for (uint32_t i = 0; i < intervalsUpdated; i++)
{
this->levels[this->nextLevelIndex] = b;
this->nextLevelIndex = (this->nextLevelIndex + 1) % LevelsBuffLen;
}
this->levels[0] = b;
UpdateMinLevel(b); UpdateMinLevel(b);
this->paused = false;
} }
} }
void ActiveSpeakerObserver::Speaker::LevelTimedOut() void ActiveSpeakerObserver::Speaker::LevelTimedOut(uint64_t now)
{ {
MS_TRACE(); MS_TRACE();
LevelChanged(MinLevel, this->lastLevelChangeTime); LevelChanged(MinLevel, now);
} }
bool ActiveSpeakerObserver::Speaker::ComputeImmediates() bool ActiveSpeakerObserver::Speaker::ComputeImmediates()
...@@ -458,7 +457,13 @@ namespace RTC ...@@ -458,7 +457,13 @@ namespace RTC
for (uint32_t i = 0; i < ImmediateBuffLen; ++i) for (uint32_t i = 0; i < ImmediateBuffLen; ++i)
{ {
uint8_t level = this->levels[i]; // this->levels is a circular buffer where new samples are written in the
// next vector index. this->immediates is a buffer where the most recent
// value is always in index 0.
size_t levelIndex = this->nextLevelIndex >= (i + 1)
? this->nextLevelIndex - i - 1
: this->nextLevelIndex + LevelsBuffLen - i - 1;
uint8_t level = this->levels[levelIndex];
if (level < minLevel) if (level < minLevel)
{ {
......
...@@ -429,7 +429,7 @@ namespace RTC ...@@ -429,7 +429,7 @@ namespace RTC
uv_close(reinterpret_cast<uv_handle_t*>(uvHandle), static_cast<uv_close_cb>(onClose)); uv_close(reinterpret_cast<uv_handle_t*>(uvHandle), static_cast<uv_close_cb>(onClose));
MS_THROW_ERROR( MS_THROW_ERROR(
"uv_udp_bind() failed [transport:%s, ip:'%s', port:%" PRIu16 ": %s", "uv_udp_bind() failed [transport:%s, ip:'%s', port:%" PRIu16 "]: %s",
transportStr.c_str(), transportStr.c_str(),
ip.c_str(), ip.c_str(),
port, port,
......
...@@ -19,7 +19,7 @@ namespace RTC ...@@ -19,7 +19,7 @@ namespace RTC
// Get the header. // Get the header.
auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data)); auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
std::unique_ptr<ByePacket> packet(new ByePacket(header)); std::unique_ptr<ByePacket> packet(new ByePacket(header));
size_t offset = sizeof(Packet::CommonHeader); size_t offset = Packet::CommonHeaderSize;
uint8_t count = header->count; uint8_t count = header->count;
while (((count--) != 0u) && (len > offset)) while (((count--) != 0u) && (len > offset))
......
...@@ -23,7 +23,7 @@ namespace RTC ...@@ -23,7 +23,7 @@ namespace RTC
if (this->receiverReportPacket.GetCount() != 0u) if (this->receiverReportPacket.GetCount() != 0u)
{ {
this->size += sizeof(ReceiverReport::Header) * this->receiverReportPacket.GetCount(); this->size += ReceiverReport::HeaderSize * this->receiverReportPacket.GetCount();
} }
} }
// If no sender nor receiver reports are present send an empty Receiver Report // If no sender nor receiver reports are present send an empty Receiver Report
...@@ -56,8 +56,8 @@ namespace RTC ...@@ -56,8 +56,8 @@ namespace RTC
{ {
// Fix header length field. // Fix header length field.
size_t length = size_t length =
((sizeof(SenderReport::Header) + ((SenderReport::HeaderSize +
(sizeof(ReceiverReport::Header) * this->receiverReportPacket.GetCount())) / (ReceiverReport::HeaderSize * this->receiverReportPacket.GetCount())) /
4); 4);
header->length = uint16_t{ htons(length) }; header->length = uint16_t{ htons(length) };
...@@ -72,7 +72,7 @@ namespace RTC ...@@ -72,7 +72,7 @@ namespace RTC
ReceiverReport* report = (*it); ReceiverReport* report = (*it);
report->Serialize(this->header + offset); report->Serialize(this->header + offset);
offset += sizeof(ReceiverReport::Header); offset += ReceiverReport::HeaderSize;
} }
} }
} }
......
...@@ -45,8 +45,8 @@ namespace RTC ...@@ -45,8 +45,8 @@ namespace RTC
FeedbackPacket<T>::FeedbackPacket(CommonHeader* commonHeader) FeedbackPacket<T>::FeedbackPacket(CommonHeader* commonHeader)
: Packet(commonHeader), messageType(typename T::MessageType(commonHeader->count)) : Packet(commonHeader), messageType(typename T::MessageType(commonHeader->count))
{ {
this->header = this->header = reinterpret_cast<Header*>(
reinterpret_cast<Header*>(reinterpret_cast<uint8_t*>(commonHeader) + sizeof(CommonHeader)); reinterpret_cast<uint8_t*>(commonHeader) + Packet::CommonHeaderSize);
} }
template<typename T> template<typename T>
...@@ -54,7 +54,7 @@ namespace RTC ...@@ -54,7 +54,7 @@ namespace RTC
typename T::MessageType messageType, uint32_t senderSsrc, uint32_t mediaSsrc) typename T::MessageType messageType, uint32_t senderSsrc, uint32_t mediaSsrc)
: Packet(rtcpType), messageType(messageType) : Packet(rtcpType), messageType(messageType)
{ {
this->raw = new uint8_t[sizeof(Header)]; this->raw = new uint8_t[HeaderSize];
this->header = reinterpret_cast<Header*>(this->raw); this->header = reinterpret_cast<Header*>(this->raw);
this->header->senderSsrc = uint32_t{ htonl(senderSsrc) }; this->header->senderSsrc = uint32_t{ htonl(senderSsrc) };
this->header->mediaSsrc = uint32_t{ htonl(mediaSsrc) }; this->header->mediaSsrc = uint32_t{ htonl(mediaSsrc) };
...@@ -76,9 +76,9 @@ namespace RTC ...@@ -76,9 +76,9 @@ namespace RTC
size_t offset = Packet::Serialize(buffer); size_t offset = Packet::Serialize(buffer);
// Copy the header. // Copy the header.
std::memcpy(buffer + offset, this->header, sizeof(Header)); std::memcpy(buffer + offset, this->header, HeaderSize);
return offset + sizeof(Header); return offset + HeaderSize;
} }
template<typename T> template<typename T>
...@@ -119,7 +119,7 @@ namespace RTC ...@@ -119,7 +119,7 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (len < sizeof(CommonHeader) + sizeof(FeedbackPacket::Header)) if (len < Packet::CommonHeaderSize + FeedbackPacket::HeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded"); MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
...@@ -210,7 +210,7 @@ namespace RTC ...@@ -210,7 +210,7 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (len < sizeof(CommonHeader) + sizeof(FeedbackPacket::Header)) if (len < Packet::CommonHeaderSize + FeedbackPacket::HeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded"); MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
......
...@@ -22,7 +22,7 @@ namespace RTC ...@@ -22,7 +22,7 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (len < sizeof(CommonHeader) + sizeof(FeedbackPacket::Header)) if (len < Packet::CommonHeaderSize + FeedbackPacket::HeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded"); MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
...@@ -35,7 +35,7 @@ namespace RTC ...@@ -35,7 +35,7 @@ namespace RTC
std::unique_ptr<FeedbackPsItemsPacket<Item>> packet( std::unique_ptr<FeedbackPsItemsPacket<Item>> packet(
new FeedbackPsItemsPacket<Item>(commonHeader)); new FeedbackPsItemsPacket<Item>(commonHeader));
size_t offset = sizeof(CommonHeader) + sizeof(FeedbackPacket::Header); size_t offset = Packet::CommonHeaderSize + FeedbackPacket::HeaderSize;
while (len > offset) while (len > offset)
{ {
......
...@@ -17,7 +17,7 @@ namespace RTC ...@@ -17,7 +17,7 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (len < sizeof(CommonHeader) + sizeof(FeedbackPacket::Header)) if (len < Packet::CommonHeaderSize + FeedbackPacket::HeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded"); MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
...@@ -29,12 +29,12 @@ namespace RTC ...@@ -29,12 +29,12 @@ namespace RTC
std::unique_ptr<FeedbackPsAfbPacket> packet; std::unique_ptr<FeedbackPsAfbPacket> packet;
constexpr size_t Offset = sizeof(CommonHeader) + sizeof(FeedbackPacket::Header); constexpr size_t Offset = Packet::CommonHeaderSize + FeedbackPacket::HeaderSize;
// clang-format off // clang-format off
if ( if (
len >= sizeof(CommonHeader) + sizeof(FeedbackPacket::Header) + 4 && len >= Packet::CommonHeaderSize + FeedbackPacket::HeaderSize + 4 &&
Utils::Byte::Get4Bytes(data, Offset) == FeedbackPsRembPacket::uniqueIdentifier Utils::Byte::Get4Bytes(data, Offset) == FeedbackPsRembPacket::UniqueIdentifier
) )
// clang-format on // clang-format on
{ {
......
...@@ -18,11 +18,11 @@ namespace RTC ...@@ -18,11 +18,11 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
this->raw = new uint8_t[sizeof(Header)]; this->raw = new uint8_t[HeaderSize];
this->header = reinterpret_cast<Header*>(this->raw); this->header = reinterpret_cast<Header*>(this->raw);
// Set reserved bits to zero. // Set reserved bits to zero.
std::memset(this->header, 0, sizeof(Header)); std::memset(this->header, 0, HeaderSize);
this->header->ssrc = uint32_t{ htonl(ssrc) }; this->header->ssrc = uint32_t{ htonl(ssrc) };
this->header->sequenceNumber = sequenceNumber; this->header->sequenceNumber = sequenceNumber;
...@@ -32,9 +32,9 @@ namespace RTC ...@@ -32,9 +32,9 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
void FeedbackPsFirItem::Dump() const void FeedbackPsFirItem::Dump() const
......
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论