提交 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 = if (msgStart != 0) {
this._recvBuffer.slice(netstring.nsLength(this._recvBuffer)); this._recvBuffer = this._recvBuffer.slice(msgStart);
if (!this._recvBuffer.length) {
this._recvBuffer = undefined;
return;
}
} }
}); });
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.
if (nsPayload === -1)
return;
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;
} }
const payload = this._recvBuffer.subarray(msgStart + 4, msgStart + 4 + msgLen);
msgStart += 4 + msgLen;
this._processData(payload);
}
if (msgStart != 0) {
this._recvBuffer = this._recvBuffer.slice(msgStart);
} }
}); });
this._consumerSocket.on('end', () => (logger.debug('Consumer PayloadChannel ended by the worker process'))); this._consumerSocket.on('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);
{ receivePreview.srcObject = receiveMediaStream;
receiveMediaStream.addTrack(consumer.track);
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
......
use actix::prelude::*;
use actix_web::web::{Data, Payload};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
use mediasoup::prelude::*;
use mediasoup::rtp_parameters::{RtpCodecParameters, RtpEncodingParameters};
use mediasoup::worker::{WorkerLogLevel, WorkerLogTag};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::num::{NonZeroU32, NonZeroU8};
/// List of codecs that SFU will accept from clients
fn media_codecs() -> Vec<RtpCodecCapability> {
vec![RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1_u32.into()),
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![RtcpFeedback::TransportCc],
}]
}
/// Data structure containing all the necessary information about transport options required from
/// the server to establish transport connection on the client
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct TransportOptions {
id: TransportId,
dtls_parameters: DtlsParameters,
ice_candidates: Vec<IceCandidate>,
ice_parameters: IceParameters,
}
/// Server messages sent to the client
#[derive(Serialize, Message)]
#[serde(tag = "action")]
#[rtype(result = "()")]
enum ServerMessage {
/// Initialization message with consumer transport options and Router's RTP
/// capabilities necessary to establish WebRTC transport connection client-side
#[serde(rename_all = "camelCase")]
Init {
consumer_transport_options: TransportOptions,
router_rtp_capabilities: RtpCapabilitiesFinalized,
rtp_producer_id: ProducerId,
},
/// Notification that consumer transport was connected successfully (in case of error connection
/// is just dropped, in real-world application you probably want to handle it better)
ConnectedConsumerTransport,
/// Notification that consumer was successfully created server-side, client can resume the
/// consumer after this
#[serde(rename_all = "camelCase")]
Consumed {
id: ConsumerId,
producer_id: ProducerId,
kind: MediaKind,
rtp_parameters: RtpParameters,
},
}
/// Client messages sent to the server
#[derive(Deserialize, Message)]
#[serde(tag = "action")]
#[rtype(result = "()")]
enum ClientMessage {
/// Client-side initialization with its RTP capabilities, in this simple case we expect those to
/// match server Router's RTP capabilities
#[serde(rename_all = "camelCase")]
Init { rtp_capabilities: RtpCapabilities },
/// Request to connect consumer transport with client-side DTLS parameters
#[serde(rename_all = "camelCase")]
ConnectConsumerTransport { dtls_parameters: DtlsParameters },
/// Request to consume specified producer
#[serde(rename_all = "camelCase")]
Consume { producer_id: ProducerId },
}
/// Internal actor messages for convenience
#[derive(Message)]
#[rtype(result = "()")]
enum InternalMessage {
/// Save consumer in connection-specific hashmap to prevent it from being destroyed
SaveConsumer(Consumer),
/// Stop/close the WebSocket connection
Stop,
}
/// Actor that will represent WebSocket connection from the client, it will handle inbound and
/// outbound WebSocket messages in JSON.
///
/// See https://actix.rs/docs/websockets/ for official `actix-web` documentation.
struct EchoConnection {
/// RTP capabilities received from the client
client_rtp_capabilities: Option<RtpCapabilities>,
/// Consumers associated with this client, preventing them from being destroyed
consumers: HashMap<ConsumerId, Consumer>,
/// RTP producer associated with this client, preventing it from being destroyed and useful to
/// get its ID later
rtp_producer: Producer,
/// Router associated with this client, useful to get its RTP capabilities later
router: Router,
/// Consumer transport associated with this client
consumer_transport: WebRtcTransport,
}
impl EchoConnection {
/// Create a new instance representing WebSocket connection
async fn new(worker_manager: &WorkerManager) -> Result<Self, String> {
let worker = worker_manager
.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
.map_err(|error| format!("Failed to create worker: {}", error))?;
let router = worker
.create_router(RouterOptions::new(media_codecs()))
.await
.map_err(|error| format!("Failed to create router: {}", error))?;
// For simplicity we will create plain transport for audio producer right away
let plain_transport = router
.create_plain_transport({
let mut options = PlainTransportOptions::new(TransportListenIp {
ip: "127.0.0.1".parse().unwrap(),
announced_ip: None,
});
options.comedia = true;
options.rtcp_mux = false;
options
})
.await
.map_err(|error| format!("Failed to create plain transport: {}", error))?;
// And creating audio producer that will be consumed over WebRTC later
let rtp_producer = plain_transport
.produce(ProducerOptions::new(
MediaKind::Audio,
RtpParameters {
mid: Some("AUDIO".to_string()),
codecs: vec![RtpCodecParameters::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
payload_type: 100,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1_u32.into()),
("channel_mapping", "0,1,4,5,2,3".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![],
}],
encodings: vec![RtpEncodingParameters {
ssrc: Some(1111),
..RtpEncodingParameters::default()
}],
..RtpParameters::default()
},
))
.await
.map_err(|error| format!("Failed to create audio producer: {}", error))?;
println!(
"Plain transport created:\n \
RTP listening on {}:{}\n \
RTCP listening on {}:{}\n \
PT=100\n \
SSRC=1111",
plain_transport.tuple().local_ip(),
plain_transport.tuple().local_port(),
plain_transport.rtcp_tuple().unwrap().local_ip(),
plain_transport.rtcp_tuple().unwrap().local_port(),
);
println!(
"Use following command with GStreamer (1.20+) to play a sample audio:\n\
gst-launch-1.0 \\\n \
rtpbin name=rtpbin \\\n \
souphttpsrc location=https://www2.iis.fraunhofer.de/AAC/ChID-BLITS-EBU-Narration.mp4 ! \\\n \
queue ! \\\n \
decodebin ! \\\n \
audioresample ! \\\n \
audioconvert ! \\\n \
opusenc inband-fec=true ! \\\n \
queue ! \\\n \
clocksync ! \\\n \
rtpopuspay pt=100 ssrc=1111 ! \\\n \
rtpbin.send_rtp_sink_0 \\\n \
rtpbin.send_rtp_src_0 ! udpsink host={} port={} sync=false async=false \\\n \
rtpbin.send_rtcp_src_0 ! udpsink host={} port={} sync=false async=false",
plain_transport.tuple().local_ip(),
plain_transport.tuple().local_port(),
plain_transport.rtcp_tuple().unwrap().local_ip(),
plain_transport.rtcp_tuple().unwrap().local_port(),
);
// We know that for multiopus example we'll need just consumer transport, so we can create
// it right away. This may not be the case for real-world applications or you may create
// this at a different time and/or in different order.
let consumer_transport = router
.create_webrtc_transport(WebRtcTransportOptions::new(TransportListenIps::new(
TransportListenIp {
ip: "127.0.0.1".parse().unwrap(),
announced_ip: None,
},
)))
.await
.map_err(|error| format!("Failed to create consumer transport: {}", error))?;
Ok(Self {
client_rtp_capabilities: None,
consumers: HashMap::new(),
rtp_producer,
router,
consumer_transport,
})
}
}
impl Actor for EchoConnection {
type Context = ws::WebsocketContext<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
println!("WebSocket connection created");
// We know that only consumer transport will be used, so we sent server information about it
// in an initialization message alongside with router capabilities to the client right after
// WebSocket connection is established
let server_init_message = ServerMessage::Init {
consumer_transport_options: TransportOptions {
id: self.consumer_transport.id(),
dtls_parameters: self.consumer_transport.dtls_parameters(),
ice_candidates: self.consumer_transport.ice_candidates().clone(),
ice_parameters: self.consumer_transport.ice_parameters().clone(),
},
router_rtp_capabilities: self.router.rtp_capabilities().clone(),
rtp_producer_id: self.rtp_producer.id(),
};
ctx.address().do_send(server_init_message);
}
fn stopped(&mut self, _ctx: &mut Self::Context) {
println!("WebSocket connection closed");
}
}
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for EchoConnection {
fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
// Here we handle incoming WebSocket messages, intentionally not handling continuation
// messages since we know all messages will fit into a single frame, but in real-world apps
// you need to handle continuation frames too (`ws::Message::Continuation`)
match msg {
Ok(ws::Message::Ping(msg)) => {
ctx.pong(&msg);
}
Ok(ws::Message::Pong(_)) => {}
Ok(ws::Message::Text(text)) => match serde_json::from_str::<ClientMessage>(&text) {
Ok(message) => {
// Parse JSON into an enum and just send it back to the actor to be processed
// by another handler below, it is much more convenient to just parse it in one
// place and have typed data structure everywhere else
ctx.address().do_send(message);
}
Err(error) => {
eprintln!("Failed to parse client message: {}\n{}", error, text);
}
},
Ok(ws::Message::Binary(bin)) => {
eprintln!("Unexpected binary message: {:?}", bin);
}
Ok(ws::Message::Close(reason)) => {
ctx.close(reason);
ctx.stop();
}
_ => ctx.stop(),
}
}
}
impl Handler<ClientMessage> for EchoConnection {
type Result = ();
fn handle(&mut self, message: ClientMessage, ctx: &mut Self::Context) {
match message {
ClientMessage::Init { rtp_capabilities } => {
// We need to know client's RTP capabilities, those are sent using initialization
// message and are stored in connection struct for future use
self.client_rtp_capabilities.replace(rtp_capabilities);
}
ClientMessage::ConnectConsumerTransport { dtls_parameters } => {
let address = ctx.address();
let transport = self.consumer_transport.clone();
// The same as producer transport, but for consumer transport
actix::spawn(async move {
match transport
.connect(WebRtcTransportRemoteParameters { dtls_parameters })
.await
{
Ok(_) => {
address.do_send(ServerMessage::ConnectedConsumerTransport);
println!("Consumer transport connected");
}
Err(error) => {
eprintln!("Failed to connect consumer transport: {}", error);
address.do_send(InternalMessage::Stop);
}
}
});
}
ClientMessage::Consume { producer_id } => {
let address = ctx.address();
let transport = self.consumer_transport.clone();
let rtp_capabilities = match self.client_rtp_capabilities.clone() {
Some(rtp_capabilities) => rtp_capabilities,
None => {
eprintln!("Client should send RTP capabilities before consuming");
return;
}
};
// Create consumer for given producer ID, while first making sure that RTP
// capabilities were sent by the client prior to that
actix::spawn(async move {
match transport
.consume(ConsumerOptions::new(producer_id, rtp_capabilities))
.await
{
Ok(consumer) => {
let id = consumer.id();
let kind = consumer.kind();
let rtp_parameters = consumer.rtp_parameters().clone();
address.do_send(ServerMessage::Consumed {
id,
producer_id,
kind,
rtp_parameters,
});
// Consumer is stored in a hashmap since if we don't do it, it will get
// destroyed as soon as its instance goes out out scope
address.do_send(InternalMessage::SaveConsumer(consumer));
println!("{:?} consumer created: {}", kind, id);
}
Err(error) => {
eprintln!("Failed to create consumer: {}", error);
address.do_send(InternalMessage::Stop);
}
}
});
}
}
}
}
/// Simple handler that will transform typed server messages into JSON and send them over to the
/// client over WebSocket connection
impl Handler<ServerMessage> for EchoConnection {
type Result = ();
fn handle(&mut self, message: ServerMessage, ctx: &mut Self::Context) {
ctx.text(serde_json::to_string(&message).unwrap());
}
}
/// Convenience handler for internal messages, these actions require mutable access to the
/// connection struct and having such message handler makes it easy to use from background tasks
/// where otherwise Mutex would have to be used instead
impl Handler<InternalMessage> for EchoConnection {
type Result = ();
fn handle(&mut self, message: InternalMessage, ctx: &mut Self::Context) {
match message {
InternalMessage::Stop => {
ctx.stop();
}
InternalMessage::SaveConsumer(consumer) => {
self.consumers.insert(consumer.id(), consumer);
}
}
}
}
/// Function that receives HTTP request on WebSocket route and upgrades it to WebSocket connection.
///
/// See https://actix.rs/docs/websockets/ for official `actix-web` documentation.
async fn ws_index(
request: HttpRequest,
worker_manager: Data<WorkerManager>,
stream: Payload,
) -> Result<HttpResponse, Error> {
match EchoConnection::new(&worker_manager).await {
Ok(echo_server) => ws::start(echo_server, &request, stream),
Err(error) => {
eprintln!("{}", error);
Ok(HttpResponse::InternalServerError().finish())
}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
// We will reuse the same worker manager across all connections, this is more than enough for
// this use case
let worker_manager = Data::new(WorkerManager::new());
HttpServer::new(move || {
App::new()
.app_data(worker_manager.clone())
.route("/ws", web::get().to(ws_index))
})
// 2 threads is plenty for this example, default is to have as many threads as CPU cores
.workers(2)
.bind("127.0.0.1:3000")?
.run()
.await
}
...@@ -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;
......
use futures_lite::future;
use mediasoup::data_structures::TransportListenIp;
use mediasoup::prelude::*;
use mediasoup::producer::ProducerOptions;
use mediasoup::router::{Router, RouterOptions};
use mediasoup::rtp_parameters::{
MediaKind, MimeTypeAudio, RtpCodecCapability, RtpCodecParameters, RtpCodecParametersParameters,
RtpHeaderExtension, RtpHeaderExtensionDirection, RtpHeaderExtensionParameters,
RtpHeaderExtensionUri, RtpParameters,
};
use mediasoup::webrtc_transport::{TransportListenIps, WebRtcTransport, WebRtcTransportOptions};
use mediasoup::worker::WorkerSettings;
use mediasoup::worker_manager::WorkerManager;
use std::env;
use std::num::{NonZeroU32, NonZeroU8};
fn media_codecs() -> Vec<RtpCodecCapability> {
vec![RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: None,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1_u32.into()),
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![],
}]
}
fn audio_producer_options() -> ProducerOptions {
ProducerOptions::new(
MediaKind::Audio,
RtpParameters {
mid: Some("AUDIO".to_string()),
codecs: vec![RtpCodecParameters::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
payload_type: 0,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1_u32.into()),
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![],
}],
header_extensions: vec![
RtpHeaderExtensionParameters {
uri: RtpHeaderExtensionUri::Mid,
id: 10,
encrypt: false,
},
RtpHeaderExtensionParameters {
uri: RtpHeaderExtensionUri::AudioLevel,
id: 12,
encrypt: false,
},
],
..RtpParameters::default()
},
)
}
fn consumer_device_capabilities() -> RtpCapabilities {
RtpCapabilities {
codecs: vec![RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: Some(100),
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
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![],
}],
header_extensions: vec![
RtpHeaderExtension {
kind: MediaKind::Audio,
uri: RtpHeaderExtensionUri::Mid,
preferred_id: 1,
preferred_encrypt: false,
direction: RtpHeaderExtensionDirection::default(),
},
RtpHeaderExtension {
kind: MediaKind::Audio,
uri: RtpHeaderExtensionUri::AbsSendTime,
preferred_id: 4,
preferred_encrypt: false,
direction: RtpHeaderExtensionDirection::default(),
},
RtpHeaderExtension {
kind: MediaKind::Audio,
uri: RtpHeaderExtensionUri::AudioLevel,
preferred_id: 10,
preferred_encrypt: false,
direction: RtpHeaderExtensionDirection::default(),
},
],
}
}
async fn init() -> (Router, WebRtcTransport) {
{
let mut builder = env_logger::builder();
if env::var(env_logger::DEFAULT_FILTER_ENV).is_err() {
builder.filter_level(log::LevelFilter::Off);
}
let _ = builder.is_test(true).try_init();
}
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await
.expect("Failed to create worker");
let router = worker
.create_router(RouterOptions::new(media_codecs()))
.await
.expect("Failed to create router");
let transport_options =
WebRtcTransportOptions::new(TransportListenIps::new(TransportListenIp {
ip: "127.0.0.1".parse().unwrap(),
announced_ip: None,
}));
let transport = router
.create_webrtc_transport(transport_options.clone())
.await
.expect("Failed to create transport");
(router, transport)
}
#[test]
fn produce_and_consume_succeeds() {
future::block_on(async move {
let (router, transport) = init().await;
let audio_producer = transport
.produce(audio_producer_options())
.await
.expect("Failed to produce audio");
assert_eq!(
audio_producer.rtp_parameters().codecs,
vec![RtpCodecParameters::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
payload_type: 0,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1_u32.into()),
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![],
}]
);
let consumer_device_capabilities = consumer_device_capabilities();
assert!(router.can_consume(&audio_producer.id(), &consumer_device_capabilities));
let audio_consumer = transport
.consume(ConsumerOptions::new(
audio_producer.id(),
consumer_device_capabilities.clone(),
))
.await
.expect("Failed to consume audio");
assert_eq!(
audio_consumer.rtp_parameters().codecs,
vec![RtpCodecParameters::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
payload_type: 100,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("useinbandfec", 1_u32.into()),
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![],
}]
);
});
}
#[test]
fn fails_to_consume_wrong_parameters() {
future::block_on(async move {
let (_router, transport) = init().await;
assert!(transport
.produce(ProducerOptions::new(
MediaKind::Audio,
RtpParameters {
mid: Some("AUDIO".to_string()),
codecs: vec![RtpCodecParameters::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
payload_type: 0,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 2_u32.into()),
("coupled_streams", 2_u32.into()),
]),
rtcp_feedback: vec![],
}],
..RtpParameters::default()
},
))
.await
.is_err());
assert!(transport
.produce(ProducerOptions::new(
MediaKind::Audio,
RtpParameters {
mid: Some("AUDIO".to_string()),
codecs: vec![RtpCodecParameters::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
payload_type: 0,
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(6).unwrap(),
parameters: RtpCodecParametersParameters::from([
("channel_mapping", "0,4,1,2,3,5".into()),
("num_streams", 4_u32.into()),
("coupled_streams", 1_u32.into()),
]),
rtcp_feedback: vec![],
}],
..RtpParameters::default()
},
))
.await
.is_err());
});
}
#[test]
fn fails_to_consume_wrong_channels() {
future::block_on(async move {
let (router, transport) = init().await;
let audio_producer = transport
.produce(audio_producer_options())
.await
.expect("Failed to produce audio");
let consumer_device_capabilities = RtpCapabilities {
codecs: vec![RtpCodecCapability::Audio {
mime_type: MimeTypeAudio::MultiChannelOpus,
preferred_payload_type: Some(100),
clock_rate: NonZeroU32::new(48000).unwrap(),
channels: NonZeroU8::new(8).unwrap(),
parameters: RtpCodecParametersParameters::default(),
rtcp_feedback: vec![],
}],
header_extensions: Vec::new(),
};
assert!(!router.can_consume(&audio_producer.id(), &consumer_device_capabilities));
let audio_consumer_result = transport
.consume(ConsumerOptions::new(
audio_producer.id(),
consumer_device_capabilities.clone(),
))
.await;
assert!(audio_consumer_result.is_err());
});
}
...@@ -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)); this._recvBuffer = this._recvBuffer.slice(msgStart);
if (!this._recvBuffer.length)
{
this._recvBuffer = undefined;
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);
// Remove the read payload from the buffer. msgStart += 4 + msgLen;
this._recvBuffer =
this._recvBuffer!.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length) this._processData(payload);
{ }
this._recvBuffer = undefined;
return; if (msgStart != 0)
} {
this._recvBuffer = this._recvBuffer.slice(msgStart);
} }
}); });
...@@ -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) if (readLen < sizeof(uint32_t))
{ {
switch (nsRet) // Incomplete data.
{ break;
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.
return;
}
case NETSTRING_ERROR_TOO_LONG:
{
MS_ERROR_STD("NETSTRING_ERROR_TOO_LONG");
break;
}
case NETSTRING_ERROR_NO_COLON:
{
MS_ERROR_STD("NETSTRING_ERROR_NO_COLON");
break;
}
case NETSTRING_ERROR_NO_COMMA:
{
MS_ERROR_STD("NETSTRING_ERROR_NO_COMMA");
break;
}
case NETSTRING_ERROR_LEADING_ZERO:
{
MS_ERROR_STD("NETSTRING_ERROR_LEADING_ZERO");
break;
}
case NETSTRING_ERROR_NO_LENGTH:
{
MS_ERROR_STD("NETSTRING_ERROR_NO_LENGTH");
break;
}
}
// 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 uint32_t msgLen;
// with msgLen bytes length, so recalculate readLen. // Read message length.
readLen = std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
reinterpret_cast<const uint8_t*>(msgStart) - (this->buffer + this->msgStart) + msgLen + 1;
this->listener->OnConsumerSocketMessage(this, msgStart, msgLen); if (readLen < sizeof(uint32_t) + static_cast<size_t>(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; // Incomplete data.
this->bufferDataLen = 0; break;
}
// 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 this->listener->OnConsumerSocketMessage(
// then parse again. Otherwise break here and wait for more data. this,
if (this->bufferDataLen > this->msgStart) reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
static_cast<size_t>(msgLen));
msgStart += sizeof(uint32_t) + static_cast<size_t>(msgLen);
}
if (msgStart != 0)
{
this->bufferDataLen = this->bufferDataLen - msgStart;
if (this->bufferDataLen != 0)
{ {
continue; std::memmove(this->buffer, this->buffer + msgStart, this->bufferDataLen);
} }
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) if (readLen < sizeof(uint32_t))
{ {
switch (nsRet) // Incomplete data.
{ break;
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:
{
MS_ERROR("NETSTRING_ERROR_NO_COMMA");
break;
}
case NETSTRING_ERROR_LEADING_ZERO:
{
MS_ERROR("NETSTRING_ERROR_LEADING_ZERO");
break;
}
case NETSTRING_ERROR_NO_LENGTH:
{
MS_ERROR("NETSTRING_ERROR_NO_LENGTH");
break;
}
}
// Error, so reset and exit the parsing loop. uint32_t msgLen;
this->msgStart = 0; // Read message length.
this->bufferDataLen = 0; std::memcpy(&msgLen, this->buffer + msgStart, sizeof(uint32_t));
return; if (readLen < sizeof(uint32_t) + static_cast<size_t>(msgLen))
{
// Incomplete data.
break;
} }
// If here it means that msgStart points to the beginning of a message this->listener->OnConsumerSocketMessage(
// with msgLen bytes length, so recalculate readLen. this,
readLen = reinterpret_cast<char*>(this->buffer + msgStart + sizeof(uint32_t)),
reinterpret_cast<const uint8_t*>(msgStart) - (this->buffer + this->msgStart) + msgLen + 1; static_cast<size_t>(msgLen));
std::memcpy(this->readBuffer, msgStart, msgLen); msgStart += sizeof(uint32_t) + static_cast<size_t>(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 if (msgStart != 0)
// the latest parsed message filled it, then empty the full buffer. {
if ((this->msgStart + readLen) == this->bufferSize) this->bufferDataLen = this->bufferDataLen - msgStart;
{
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;
}
// 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);
...@@ -238,10 +239,9 @@ namespace RTC ...@@ -238,10 +239,9 @@ 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
......
...@@ -14,7 +14,7 @@ namespace RTC ...@@ -14,7 +14,7 @@ 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);
this->header->ssrc = uint32_t{ htonl(ssrc) }; this->header->ssrc = uint32_t{ htonl(ssrc) };
} }
...@@ -24,9 +24,9 @@ namespace RTC ...@@ -24,9 +24,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Add minimum header. // Add minimum header.
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
void FeedbackPsLeiItem::Dump() const void FeedbackPsLeiItem::Dump() const
......
...@@ -14,7 +14,7 @@ namespace RTC ...@@ -14,7 +14,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");
......
...@@ -10,10 +10,6 @@ namespace RTC ...@@ -10,10 +10,6 @@ namespace RTC
{ {
namespace RTCP namespace RTCP
{ {
/* Class variables. */
uint32_t FeedbackPsRembPacket::uniqueIdentifier{ 0x52454D42 };
/* Class methods. */ /* Class methods. */
FeedbackPsRembPacket* FeedbackPsRembPacket::Parse(const uint8_t* data, size_t len) FeedbackPsRembPacket* FeedbackPsRembPacket::Parse(const uint8_t* data, size_t len)
...@@ -23,7 +19,7 @@ namespace RTC ...@@ -23,7 +19,7 @@ namespace RTC
// Check that there is space for the REMB unique identifier and basic fields. // Check that there is space for the REMB unique identifier and basic fields.
// NOTE: Feedback.cpp already checked that there is space for CommonHeader and // NOTE: Feedback.cpp already checked that there is space for CommonHeader and
// Feedback Header. // Feedback Header.
if (len < sizeof(CommonHeader) + sizeof(FeedbackPacket::Header) + 8u) if (len < Packet::CommonHeaderSize + FeedbackPacket::HeaderSize + 8u)
{ {
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded"); MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
...@@ -56,12 +52,12 @@ namespace RTC ...@@ -56,12 +52,12 @@ namespace RTC
} }
// Make data point to the 4 bytes that must containt the "REMB" identifier. // Make data point to the 4 bytes that must containt the "REMB" identifier.
auto* data = reinterpret_cast<uint8_t*>(commonHeader) + sizeof(CommonHeader) + auto* data = reinterpret_cast<uint8_t*>(commonHeader) + Packet::CommonHeaderSize +
sizeof(FeedbackPacket::Header); FeedbackPacket::HeaderSize;
size_t numSsrcs = data[4]; size_t numSsrcs = data[4];
// Ensure there is space for the the announced number of SSRC feedbacks. // Ensure there is space for the the announced number of SSRC feedbacks.
if (len != sizeof(CommonHeader) + sizeof(FeedbackPacket::Header) + 8u + (numSsrcs * 4u)) if (len != Packet::CommonHeaderSize + FeedbackPacket::HeaderSize + 8u + (numSsrcs * 4u))
{ {
MS_WARN_TAG( MS_WARN_TAG(
rtcp, "invalid payload size (%zu bytes) for the given number of ssrcs (%zu)", len, numSsrcs); rtcp, "invalid payload size (%zu bytes) for the given number of ssrcs (%zu)", len, numSsrcs);
...@@ -72,7 +68,7 @@ namespace RTC ...@@ -72,7 +68,7 @@ namespace RTC
} }
// Verify the "REMB" unique identifier. // Verify the "REMB" unique identifier.
if (Utils::Byte::Get4Bytes(data, 0) != FeedbackPsRembPacket::uniqueIdentifier) if (Utils::Byte::Get4Bytes(data, 0) != FeedbackPsRembPacket::UniqueIdentifier)
{ {
MS_WARN_TAG(rtcp, "invalid unique indentifier in REMB packet"); MS_WARN_TAG(rtcp, "invalid unique indentifier in REMB packet");
...@@ -122,8 +118,8 @@ namespace RTC ...@@ -122,8 +118,8 @@ namespace RTC
++exponent; ++exponent;
} }
Utils::Byte::Set4Bytes(buffer, offset, FeedbackPsRembPacket::uniqueIdentifier); Utils::Byte::Set4Bytes(buffer, offset, FeedbackPsRembPacket::UniqueIdentifier);
offset += sizeof(FeedbackPsRembPacket::uniqueIdentifier); offset += FeedbackPsRembPacket::UniqueIdentifierSize;
buffer[offset] = this->ssrcs.size(); buffer[offset] = this->ssrcs.size();
offset += 1; offset += 1;
......
...@@ -46,7 +46,7 @@ namespace RTC ...@@ -46,7 +46,7 @@ namespace RTC
length <= FeedbackPsRpsiItem::maxBitStringSize, length <= FeedbackPsRpsiItem::maxBitStringSize,
"rpsi bit string length exceeds the maximum value"); "rpsi bit string length exceeds the maximum value");
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);
// 32 bits padding. // 32 bits padding.
...@@ -59,7 +59,7 @@ namespace RTC ...@@ -59,7 +59,7 @@ namespace RTC
// Fill padding. // Fill padding.
for (size_t i{ 0 }; i < padding; ++i) for (size_t i{ 0 }; i < padding; ++i)
{ {
this->raw[sizeof(Header) + i - 1] = 0; this->raw[HeaderSize + i - 1] = 0;
} }
} }
...@@ -67,9 +67,9 @@ namespace RTC ...@@ -67,9 +67,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 FeedbackPsRpsiItem::Dump() const void FeedbackPsRpsiItem::Dump() const
......
...@@ -30,9 +30,9 @@ namespace RTC ...@@ -30,9 +30,9 @@ namespace RTC
auto* header = reinterpret_cast<Header*>(buffer); auto* header = reinterpret_cast<Header*>(buffer);
header->compact = uint32_t{ htonl(compact) }; header->compact = uint32_t{ htonl(compact) };
std::memcpy(buffer, header, sizeof(Header)); std::memcpy(buffer, header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
void FeedbackPsSliItem::Dump() const void FeedbackPsSliItem::Dump() const
......
...@@ -14,11 +14,11 @@ namespace RTC ...@@ -14,11 +14,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;
...@@ -30,9 +30,9 @@ namespace RTC ...@@ -30,9 +30,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;
} }
template<typename T> template<typename T>
......
...@@ -19,7 +19,7 @@ namespace RTC ...@@ -19,7 +19,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");
...@@ -32,7 +32,7 @@ namespace RTC ...@@ -32,7 +32,7 @@ namespace RTC
std::unique_ptr<FeedbackRtpItemsPacket<Item>> packet( std::unique_ptr<FeedbackRtpItemsPacket<Item>> packet(
new FeedbackRtpItemsPacket<Item>(commonHeader)); new FeedbackRtpItemsPacket<Item>(commonHeader));
size_t offset = sizeof(CommonHeader) + sizeof(FeedbackPacket::Header); size_t offset = Packet::CommonHeaderSize + FeedbackPacket::HeaderSize;
while (len > offset) while (len > offset)
{ {
......
...@@ -14,9 +14,9 @@ namespace RTC ...@@ -14,9 +14,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Add minimum header. // Add minimum header.
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
void FeedbackRtpEcnItem::Dump() const void FeedbackRtpEcnItem::Dump() const
......
...@@ -13,7 +13,7 @@ namespace RTC ...@@ -13,7 +13,7 @@ namespace RTC
/* Instance methods. */ /* Instance methods. */
FeedbackRtpNackItem::FeedbackRtpNackItem(uint16_t packetId, uint16_t lostPacketBitmask) FeedbackRtpNackItem::FeedbackRtpNackItem(uint16_t packetId, uint16_t lostPacketBitmask)
{ {
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->packetId = uint16_t{ htons(packetId) }; this->header->packetId = uint16_t{ htons(packetId) };
...@@ -25,9 +25,9 @@ namespace RTC ...@@ -25,9 +25,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Add minimum header. // Add minimum header.
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
void FeedbackRtpNackItem::Dump() const void FeedbackRtpNackItem::Dump() const
......
...@@ -14,7 +14,7 @@ namespace RTC ...@@ -14,7 +14,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");
......
...@@ -12,7 +12,7 @@ namespace RTC ...@@ -12,7 +12,7 @@ namespace RTC
/* Instance methods. */ /* Instance methods. */
FeedbackRtpTlleiItem::FeedbackRtpTlleiItem(uint16_t packetId, uint16_t lostPacketBitmask) FeedbackRtpTlleiItem::FeedbackRtpTlleiItem(uint16_t packetId, uint16_t lostPacketBitmask)
{ {
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->packetId = uint16_t{ htons(packetId) }; this->header->packetId = uint16_t{ htons(packetId) };
...@@ -24,9 +24,9 @@ namespace RTC ...@@ -24,9 +24,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Add minimum header. // Add minimum header.
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
void FeedbackRtpTlleiItem::Dump() const void FeedbackRtpTlleiItem::Dump() const
......
...@@ -60,7 +60,7 @@ namespace RTC ...@@ -60,7 +60,7 @@ namespace RTC
Utils::Byte::Set4Bytes(buffer, 4, compact); Utils::Byte::Set4Bytes(buffer, 4, compact);
return sizeof(Header); return HeaderSize;
} }
template<typename T> template<typename T>
......
...@@ -74,7 +74,7 @@ namespace RTC ...@@ -74,7 +74,7 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
if (len < sizeof(CommonHeader) + sizeof(FeedbackPacket::Header) + FeedbackRtpTransportPacket::fixedHeaderSize) if (len < Packet::CommonHeaderSize + FeedbackPacket::HeaderSize + FeedbackRtpTransportPacket::fixedHeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded"); MS_WARN_TAG(rtcp, "not enough space for Feedback packet, discarded");
...@@ -112,8 +112,8 @@ namespace RTC ...@@ -112,8 +112,8 @@ namespace RTC
} }
// Make data point to the packet specific info. // Make data point to the packet specific info.
auto* data = reinterpret_cast<uint8_t*>(commonHeader) + sizeof(CommonHeader) + auto* data = reinterpret_cast<uint8_t*>(commonHeader) + Packet::CommonHeaderSize +
sizeof(FeedbackPacket::Header); FeedbackPacket::HeaderSize;
this->baseSequenceNumber = Utils::Byte::Get2Bytes(data, 0); this->baseSequenceNumber = Utils::Byte::Get2Bytes(data, 0);
this->packetStatusCount = Utils::Byte::Get2Bytes(data, 2); this->packetStatusCount = Utils::Byte::Get2Bytes(data, 2);
...@@ -124,7 +124,7 @@ namespace RTC ...@@ -124,7 +124,7 @@ namespace RTC
// Make contentData point to the beginning of the chunks. // Make contentData point to the beginning of the chunks.
uint8_t* contentData = data + FeedbackRtpTransportPacket::fixedHeaderSize; uint8_t* contentData = data + FeedbackRtpTransportPacket::fixedHeaderSize;
// Make contentLen be the available length for chunks. // Make contentLen be the available length for chunks.
size_t contentLen = len - sizeof(CommonHeader) - sizeof(FeedbackPacket::Header) - size_t contentLen = len - Packet::CommonHeaderSize - FeedbackPacket::HeaderSize -
FeedbackRtpTransportPacket::fixedHeaderSize; FeedbackRtpTransportPacket::fixedHeaderSize;
size_t offset{ 0u }; size_t offset{ 0u };
uint16_t count{ 0u }; uint16_t count{ 0u };
......
...@@ -213,7 +213,7 @@ namespace RTC ...@@ -213,7 +213,7 @@ namespace RTC
this->header->packetType = static_cast<uint8_t>(GetType()); this->header->packetType = static_cast<uint8_t>(GetType());
this->header->length = uint16_t{ htons(length) }; this->header->length = uint16_t{ htons(length) };
return sizeof(CommonHeader); return CommonHeaderSize;
} }
} // namespace RTCP } // namespace RTCP
} // namespace RTC } // namespace RTC
...@@ -20,7 +20,7 @@ namespace RTC ...@@ -20,7 +20,7 @@ namespace RTC
auto* header = const_cast<Header*>(reinterpret_cast<const Header*>(data)); auto* header = const_cast<Header*>(reinterpret_cast<const Header*>(data));
// Packet size must be >= header size. // Packet size must be >= header size.
if (len < sizeof(Header)) if (len < HeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for receiver report, packet discarded"); MS_WARN_TAG(rtcp, "not enough space for receiver report, packet discarded");
...@@ -52,9 +52,9 @@ namespace RTC ...@@ -52,9 +52,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Copy the header. // Copy the header.
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
/* Class methods. */ /* Class methods. */
...@@ -73,7 +73,7 @@ namespace RTC ...@@ -73,7 +73,7 @@ namespace RTC
auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data)); auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
// Ensure there is space for the common header and the SSRC of packet sender. // Ensure there is space for the common header and the SSRC of packet sender.
if (len < sizeof(CommonHeader) + 4u /* ssrc */) if (len < Packet::CommonHeaderSize + 4u /* ssrc */)
{ {
MS_WARN_TAG(rtcp, "not enough space for receiver report packet, packet discarded"); MS_WARN_TAG(rtcp, "not enough space for receiver report packet, packet discarded");
...@@ -83,12 +83,12 @@ namespace RTC ...@@ -83,12 +83,12 @@ namespace RTC
std::unique_ptr<ReceiverReportPacket> packet(new ReceiverReportPacket(header)); std::unique_ptr<ReceiverReportPacket> packet(new ReceiverReportPacket(header));
uint32_t ssrc = uint32_t ssrc =
Utils::Byte::Get4Bytes(reinterpret_cast<uint8_t*>(header), sizeof(CommonHeader)); Utils::Byte::Get4Bytes(reinterpret_cast<uint8_t*>(header), Packet::CommonHeaderSize);
packet->SetSsrc(ssrc); packet->SetSsrc(ssrc);
if (offset == 0) if (offset == 0)
offset = sizeof(Packet::CommonHeader) + 4u /* ssrc */; offset = Packet::CommonHeaderSize + 4u /* ssrc */;
uint8_t count = header->count; uint8_t count = header->count;
...@@ -119,7 +119,7 @@ namespace RTC ...@@ -119,7 +119,7 @@ namespace RTC
size_t offset = Packet::Serialize(buffer); size_t offset = Packet::Serialize(buffer);
// Copy the SSRC. // Copy the SSRC.
Utils::Byte::Set4Bytes(buffer, sizeof(Packet::CommonHeader), this->ssrc); Utils::Byte::Set4Bytes(buffer, Packet::CommonHeaderSize, this->ssrc);
offset += 4u; offset += 4u;
// Serialize reports. // Serialize reports.
......
...@@ -37,7 +37,7 @@ namespace RTC ...@@ -37,7 +37,7 @@ namespace RTC
auto* header = const_cast<Header*>(reinterpret_cast<const Header*>(data)); auto* header = const_cast<Header*>(reinterpret_cast<const Header*>(data));
// data size must be >= header + length value. // data size must be >= header + length value.
if (len < sizeof(Header) || len < (1u * 2) + header->length) if (len < HeaderSize || len < (1u * 2) + header->length)
{ {
MS_WARN_TAG(rtcp, "not enough space for SDES item, discarded"); MS_WARN_TAG(rtcp, "not enough space for SDES item, discarded");
...@@ -188,7 +188,7 @@ namespace RTC ...@@ -188,7 +188,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<SdesPacket> packet(new SdesPacket(header)); std::unique_ptr<SdesPacket> packet(new SdesPacket(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))
......
...@@ -19,7 +19,7 @@ namespace RTC ...@@ -19,7 +19,7 @@ namespace RTC
auto* header = const_cast<Header*>(reinterpret_cast<const Header*>(data)); auto* header = const_cast<Header*>(reinterpret_cast<const Header*>(data));
// Packet size must be >= header size. // Packet size must be >= header size.
if (len < sizeof(Header)) if (len < HeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for sender report, packet discarded"); MS_WARN_TAG(rtcp, "not enough space for sender report, packet discarded");
...@@ -50,9 +50,9 @@ namespace RTC ...@@ -50,9 +50,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Copy the header. // Copy the header.
std::memcpy(buffer, this->header, sizeof(Header)); std::memcpy(buffer, this->header, HeaderSize);
return sizeof(Header); return HeaderSize;
} }
/* Class methods. */ /* Class methods. */
...@@ -65,7 +65,7 @@ namespace RTC ...@@ -65,7 +65,7 @@ namespace RTC
auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data)); auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
std::unique_ptr<SenderReportPacket> packet(new SenderReportPacket(header)); std::unique_ptr<SenderReportPacket> packet(new SenderReportPacket(header));
size_t offset = sizeof(Packet::CommonHeader); size_t offset = Packet::CommonHeaderSize;
SenderReport* report = SenderReport::Parse(data + offset, len - offset); SenderReport* report = SenderReport::Parse(data + offset, len - offset);
......
...@@ -20,7 +20,7 @@ namespace RTC ...@@ -20,7 +20,7 @@ namespace RTC
auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data)); auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
// Ensure there is space for the common header and the SSRC of packet sender. // Ensure there is space for the common header and the SSRC of packet sender.
if (len < sizeof(CommonHeader)) if (len < Packet::CommonHeaderSize)
{ {
MS_WARN_TAG(rtcp, "not enough space for a extended report block, report discarded"); MS_WARN_TAG(rtcp, "not enough space for a extended report block, report discarded");
...@@ -62,7 +62,7 @@ namespace RTC ...@@ -62,7 +62,7 @@ namespace RTC
auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data)); auto* header = const_cast<CommonHeader*>(reinterpret_cast<const CommonHeader*>(data));
// Ensure there is space for the common header and the SSRC of packet sender. // Ensure there is space for the common header and the SSRC of packet sender.
if (len < sizeof(CommonHeader) + 4u) if (len < Packet::CommonHeaderSize + 4u)
{ {
MS_WARN_TAG(rtcp, "not enough space for a extended report packet, packet discarded"); MS_WARN_TAG(rtcp, "not enough space for a extended report packet, packet discarded");
...@@ -72,11 +72,11 @@ namespace RTC ...@@ -72,11 +72,11 @@ namespace RTC
std::unique_ptr<ExtendedReportPacket> packet(new ExtendedReportPacket(header)); std::unique_ptr<ExtendedReportPacket> packet(new ExtendedReportPacket(header));
uint32_t ssrc = uint32_t ssrc =
Utils::Byte::Get4Bytes(reinterpret_cast<uint8_t*>(header), sizeof(CommonHeader)); Utils::Byte::Get4Bytes(reinterpret_cast<uint8_t*>(header), Packet::CommonHeaderSize);
packet->SetSsrc(ssrc); packet->SetSsrc(ssrc);
auto offset = sizeof(Packet::CommonHeader) + 4u /* ssrc */; auto offset = Packet::CommonHeaderSize + 4u /* ssrc */;
while (len > offset) while (len > offset)
{ {
...@@ -105,7 +105,7 @@ namespace RTC ...@@ -105,7 +105,7 @@ namespace RTC
size_t offset = Packet::Serialize(buffer); size_t offset = Packet::Serialize(buffer);
// Copy the SSRC. // Copy the SSRC.
Utils::Byte::Set4Bytes(buffer, sizeof(CommonHeader), this->ssrc); Utils::Byte::Set4Bytes(buffer, Packet::CommonHeaderSize, this->ssrc);
offset += 4u /*ssrc*/; offset += 4u /*ssrc*/;
// Serialize reports. // Serialize reports.
......
...@@ -16,7 +16,7 @@ namespace RTC ...@@ -16,7 +16,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Ensure there is space for the common header and the SSRC of packet sender. // Ensure there is space for the common header and the SSRC of packet sender.
if (len < sizeof(Body)) if (len < BodySize)
{ {
MS_WARN_TAG(rtcp, "not enough space for a extended DSLR sub-block, sub-block discarded"); MS_WARN_TAG(rtcp, "not enough space for a extended DSLR sub-block, sub-block discarded");
...@@ -49,9 +49,9 @@ namespace RTC ...@@ -49,9 +49,9 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Copy the body. // Copy the body.
std::memcpy(buffer, this->body, sizeof(DelaySinceLastRr::SsrcInfo::Body)); std::memcpy(buffer, this->body, DelaySinceLastRr::SsrcInfo::BodySize);
return sizeof(DelaySinceLastRr::SsrcInfo::Body); return DelaySinceLastRr::SsrcInfo::BodySize;
} }
/* Class methods. */ /* Class methods. */
...@@ -63,10 +63,10 @@ namespace RTC ...@@ -63,10 +63,10 @@ namespace RTC
auto* header = const_cast<ExtendedReportBlock::CommonHeader*>( auto* header = const_cast<ExtendedReportBlock::CommonHeader*>(
reinterpret_cast<const ExtendedReportBlock::CommonHeader*>(data)); reinterpret_cast<const ExtendedReportBlock::CommonHeader*>(data));
std::unique_ptr<DelaySinceLastRr> report(new DelaySinceLastRr(header)); std::unique_ptr<DelaySinceLastRr> report(new DelaySinceLastRr(header));
size_t offset{ sizeof(ExtendedReportBlock::CommonHeader) }; size_t offset{ ExtendedReportBlock::CommonHeaderSize };
uint16_t reportLength = ntohs(header->length) * 4; uint16_t reportLength = ntohs(header->length) * 4;
while (len > offset && reportLength >= sizeof(DelaySinceLastRr::SsrcInfo::Body)) while (len > offset && reportLength >= DelaySinceLastRr::SsrcInfo::BodySize)
{ {
DelaySinceLastRr::SsrcInfo* ssrcInfo = DelaySinceLastRr::SsrcInfo* ssrcInfo =
DelaySinceLastRr::SsrcInfo::Parse(data + offset, len - offset); DelaySinceLastRr::SsrcInfo::Parse(data + offset, len - offset);
...@@ -82,7 +82,7 @@ namespace RTC ...@@ -82,7 +82,7 @@ namespace RTC
} }
offset += ssrcInfo->GetSize(); offset += ssrcInfo->GetSize();
reportLength -= sizeof(DelaySinceLastRr::SsrcInfo::Body); reportLength -= DelaySinceLastRr::SsrcInfo::BodySize;
} }
return report.release(); return report.release();
...@@ -94,16 +94,16 @@ namespace RTC ...@@ -94,16 +94,16 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
size_t length = static_cast<uint16_t>((sizeof(SsrcInfo::Body) * this->ssrcInfos.size() / 4)); size_t length = static_cast<uint16_t>((SsrcInfo::BodySize * this->ssrcInfos.size() / 4));
// Fill the common header. // Fill the common header.
this->header->blockType = static_cast<uint8_t>(this->type); this->header->blockType = static_cast<uint8_t>(this->type);
this->header->reserved = 0; this->header->reserved = 0;
this->header->length = uint16_t{ htons(length) }; this->header->length = uint16_t{ htons(length) };
std::memcpy(buffer, this->header, sizeof(ExtendedReportBlock::CommonHeader)); std::memcpy(buffer, this->header, ExtendedReportBlock::CommonHeaderSize);
size_t offset{ sizeof(ExtendedReportBlock::CommonHeader) }; size_t offset{ ExtendedReportBlock::CommonHeaderSize };
// Serialize sub-blocks. // Serialize sub-blocks.
for (auto* ssrcInfo : this->ssrcInfos) for (auto* ssrcInfo : this->ssrcInfos)
...@@ -123,7 +123,7 @@ namespace RTC ...@@ -123,7 +123,7 @@ namespace RTC
MS_DUMP(" reserved : 0"); MS_DUMP(" reserved : 0");
MS_DUMP( MS_DUMP(
" length : %" PRIu16, " length : %" PRIu16,
static_cast<uint16_t>((sizeof(SsrcInfo::Body) * this->ssrcInfos.size() / 4))); static_cast<uint16_t>((SsrcInfo::BodySize * this->ssrcInfos.size() / 4)));
for (auto* ssrcInfo : this->ssrcInfos) for (auto* ssrcInfo : this->ssrcInfos)
{ {
ssrcInfo->Dump(); ssrcInfo->Dump();
......
...@@ -16,7 +16,7 @@ namespace RTC ...@@ -16,7 +16,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
// Ensure there is space for the common header and the body. // Ensure there is space for the common header and the body.
if (len < sizeof(ExtendedReportBlock::CommonHeader) + sizeof(ReceiverReferenceTime::Body)) if (len < ExtendedReportBlock::CommonHeaderSize + ReceiverReferenceTime::BodySize)
{ {
MS_WARN_TAG(rtcp, "not enough space for a extended RRT block, block discarded"); MS_WARN_TAG(rtcp, "not enough space for a extended RRT block, block discarded");
...@@ -52,14 +52,14 @@ namespace RTC ...@@ -52,14 +52,14 @@ namespace RTC
this->header->reserved = 0; this->header->reserved = 0;
this->header->length = htons(2); this->header->length = htons(2);
std::memcpy(buffer, this->header, sizeof(ExtendedReportBlock::CommonHeader)); std::memcpy(buffer, this->header, ExtendedReportBlock::CommonHeaderSize);
size_t offset{ sizeof(ExtendedReportBlock::CommonHeader) }; size_t offset{ ExtendedReportBlock::CommonHeaderSize };
// Copy the body. // Copy the body.
std::memcpy(buffer + offset, this->body, sizeof(ReceiverReferenceTime::Body)); std::memcpy(buffer + offset, this->body, ReceiverReferenceTime::BodySize);
offset += sizeof(ReceiverReferenceTime::Body); offset += ReceiverReferenceTime::BodySize;
return offset; return offset;
} }
......
...@@ -25,6 +25,7 @@ namespace RTC ...@@ -25,6 +25,7 @@ namespace RTC
{ {
// Audio codecs: // Audio codecs:
{ "opus", RtpCodecMimeType::Subtype::OPUS }, { "opus", RtpCodecMimeType::Subtype::OPUS },
{ "multiopus", RtpCodecMimeType::Subtype::MULTIOPUS },
{ "pcma", RtpCodecMimeType::Subtype::PCMA }, { "pcma", RtpCodecMimeType::Subtype::PCMA },
{ "pcmu", RtpCodecMimeType::Subtype::PCMU }, { "pcmu", RtpCodecMimeType::Subtype::PCMU },
{ "isac", RtpCodecMimeType::Subtype::ISAC }, { "isac", RtpCodecMimeType::Subtype::ISAC },
...@@ -51,6 +52,7 @@ namespace RTC ...@@ -51,6 +52,7 @@ namespace RTC
{ {
// Audio codecs: // Audio codecs:
{ RtpCodecMimeType::Subtype::OPUS, "opus" }, { RtpCodecMimeType::Subtype::OPUS, "opus" },
{ RtpCodecMimeType::Subtype::MULTIOPUS, "multiopus" },
{ RtpCodecMimeType::Subtype::PCMA, "PCMA" }, { RtpCodecMimeType::Subtype::PCMA, "PCMA" },
{ RtpCodecMimeType::Subtype::PCMU, "PCMU" }, { RtpCodecMimeType::Subtype::PCMU, "PCMU" },
{ RtpCodecMimeType::Subtype::ISAC, "ISAC" }, { RtpCodecMimeType::Subtype::ISAC, "ISAC" },
......
...@@ -24,7 +24,7 @@ namespace RTC ...@@ -24,7 +24,7 @@ namespace RTC
auto* header = reinterpret_cast<Header*>(ptr); auto* header = reinterpret_cast<Header*>(ptr);
// Inspect data after the minimum header size. // Inspect data after the minimum header size.
ptr += sizeof(Header); ptr += HeaderSize;
// Check CSRC list. // Check CSRC list.
size_t csrcListSize{ 0u }; size_t csrcListSize{ 0u };
...@@ -113,7 +113,7 @@ namespace RTC ...@@ -113,7 +113,7 @@ namespace RTC
} }
MS_ASSERT( MS_ASSERT(
len == sizeof(Header) + csrcListSize + (headerExtension ? 4 + extensionValueSize : 0) + len == HeaderSize + csrcListSize + (headerExtension ? 4 + extensionValueSize : 0) +
payloadLength + size_t{ payloadPadding }, payloadLength + size_t{ payloadPadding },
"packet's computed size does not match received size"); "packet's computed size does not match received size");
...@@ -138,7 +138,7 @@ namespace RTC ...@@ -138,7 +138,7 @@ namespace RTC
MS_TRACE(); MS_TRACE();
if (this->header->csrcCount != 0u) if (this->header->csrcCount != 0u)
this->csrcList = reinterpret_cast<uint8_t*>(header) + sizeof(Header); this->csrcList = reinterpret_cast<uint8_t*>(header) + HeaderSize;
// Parse RFC 5285 header extension. // Parse RFC 5285 header extension.
ParseExtensions(); ParseExtensions();
...@@ -640,7 +640,7 @@ namespace RTC ...@@ -640,7 +640,7 @@ namespace RTC
size_t numBytes{ 0 }; size_t numBytes{ 0 };
// Copy the minimum header. // Copy the minimum header.
numBytes = sizeof(Header); numBytes = HeaderSize;
std::memcpy(ptr, GetData(), numBytes); std::memcpy(ptr, GetData(), numBytes);
// Set header pointer. // Set header pointer.
......
...@@ -31,6 +31,7 @@ namespace RTC ...@@ -31,6 +31,7 @@ namespace RTC
}; };
// clang-format on // clang-format on
static constexpr size_t ProbationPacketHeaderSize{ 32 };
static constexpr size_t MaxProbationPacketSize{ 1400u }; static constexpr size_t MaxProbationPacketSize{ 1400u };
static const std::string MidValue{ "probator" }; // 8 bytes, same as RTC::MidMaxLength. static const std::string MidValue{ "probator" }; // 8 bytes, same as RTC::MidMaxLength.
...@@ -44,7 +45,7 @@ namespace RTC ...@@ -44,7 +45,7 @@ namespace RTC
this->probationPacketBuffer = new uint8_t[MaxProbationPacketSize]; this->probationPacketBuffer = new uint8_t[MaxProbationPacketSize];
// Copy the generic probation RTP packet header into the buffer. // Copy the generic probation RTP packet header into the buffer.
std::memcpy(this->probationPacketBuffer, ProbationPacketHeader, sizeof(ProbationPacketHeader)); std::memcpy(this->probationPacketBuffer, ProbationPacketHeader, ProbationPacketHeaderSize);
// Create the probation RTP packet. // Create the probation RTP packet.
this->probationPacket = this->probationPacket =
...@@ -139,8 +140,8 @@ namespace RTC ...@@ -139,8 +140,8 @@ namespace RTC
// Make the packet length fit into our available limits. // Make the packet length fit into our available limits.
if (size > MaxProbationPacketSize) if (size > MaxProbationPacketSize)
size = MaxProbationPacketSize; size = MaxProbationPacketSize;
else if (size < sizeof(ProbationPacketHeader)) else if (size < ProbationPacketHeaderSize)
size = sizeof(ProbationPacketHeader); size = ProbationPacketHeaderSize;
// Just send up to StepNumPackets per step. // Just send up to StepNumPackets per step.
// Increase RTP seq number and timestamp. // Increase RTP seq number and timestamp.
...@@ -154,7 +155,7 @@ namespace RTC ...@@ -154,7 +155,7 @@ namespace RTC
this->probationPacket->SetTimestamp(timestamp); this->probationPacket->SetTimestamp(timestamp);
// Set probation packet payload size. // Set probation packet payload size.
this->probationPacket->SetPayloadLength(size - sizeof(ProbationPacketHeader)); this->probationPacket->SetPayloadLength(size - ProbationPacketHeaderSize);
return this->probationPacket; return this->probationPacket;
} }
......
...@@ -552,6 +552,14 @@ namespace RTC ...@@ -552,6 +552,14 @@ namespace RTC
// Add maxIncomingBitrate. // Add maxIncomingBitrate.
if (this->maxIncomingBitrate != 0u) if (this->maxIncomingBitrate != 0u)
jsonObject["maxIncomingBitrate"] = this->maxIncomingBitrate; jsonObject["maxIncomingBitrate"] = this->maxIncomingBitrate;
// Add packetLossReceived.
if (this->tccServer)
jsonObject["rtpPacketLossReceived"] = this->tccServer->GetPacketLoss();
// Add packetLossSent.
if (this->tccClient)
jsonObject["rtpPacketLossSent"] = this->tccClient->GetPacketLoss();
} }
void Transport::HandleRequest(Channel::ChannelRequest* request) void Transport::HandleRequest(Channel::ChannelRequest* request)
......
...@@ -16,6 +16,7 @@ namespace RTC ...@@ -16,6 +16,7 @@ namespace RTC
static constexpr float MaxBitrateIncrementFactor{ 1.35f }; static constexpr float MaxBitrateIncrementFactor{ 1.35f };
static constexpr float MaxPaddingBitrateFactor{ 0.85f }; static constexpr float MaxPaddingBitrateFactor{ 0.85f };
static constexpr uint64_t AvailableBitrateEventInterval{ 2000u }; // In ms. static constexpr uint64_t AvailableBitrateEventInterval{ 2000u }; // In ms.
static constexpr size_t PacketLossHistogramLength{ 24 };
/* Instance methods. */ /* Instance methods. */
...@@ -163,9 +164,56 @@ namespace RTC ...@@ -163,9 +164,56 @@ namespace RTC
{ {
MS_TRACE(); MS_TRACE();
// Update packet loss history.
size_t expected_packets = feedback->GetPacketStatusCount();
size_t lost_packets = 0;
for (const auto& result : feedback->GetPacketResults())
{
if (!result.received)
lost_packets += 1;
}
this->UpdatePacketLoss(static_cast<double>(lost_packets) / expected_packets);
this->rtpTransportControllerSend->OnTransportFeedback(*feedback); this->rtpTransportControllerSend->OnTransportFeedback(*feedback);
} }
void TransportCongestionControlClient::UpdatePacketLoss(double packetLoss)
{
// Add the score into the histogram.
if (this->packetLossHistory.size() == PacketLossHistogramLength)
this->packetLossHistory.pop_front();
this->packetLossHistory.push_back(packetLoss);
/*
* Scoring mechanism is a weighted average.
*
* The more recent the score is, the more weight it has.
* The oldest score has a weight of 1 and subsequent scores weight is
* increased by one sequentially.
*
* Ie:
* - scores: [1,2,3,4]
* - this->scores = ((1) + (2+2) + (3+3+3) + (4+4+4+4)) / 10 = 2.8 => 3
*/
size_t weight{ 0 };
size_t samples{ 0 };
double totalPacketLoss{ 0 };
for (auto packetLossEntry : this->packetLossHistory)
{
weight++;
samples += weight;
totalPacketLoss += weight * packetLossEntry;
}
// clang-tidy "thinks" that this can lead to division by zero but we are
// smarter.
// NOLINTNEXTLINE(clang-analyzer-core.DivideZero)
this->packetLoss = totalPacketLoss / samples;
}
void TransportCongestionControlClient::SetMaxOutgoingBitrate(uint32_t maxBitrate) void TransportCongestionControlClient::SetMaxOutgoingBitrate(uint32_t maxBitrate)
{ {
if (maxBitrate < this->initialAvailableBitrate) if (maxBitrate < this->initialAvailableBitrate)
...@@ -245,6 +293,13 @@ namespace RTC ...@@ -245,6 +293,13 @@ namespace RTC
return this->bitrates.availableBitrate; return this->bitrates.availableBitrate;
} }
double TransportCongestionControlClient::GetPacketLoss() const
{
MS_TRACE();
return this->packetLoss;
}
void TransportCongestionControlClient::RescheduleNextAvailableBitrateEvent() void TransportCongestionControlClient::RescheduleNextAvailableBitrateEvent()
{ {
MS_TRACE(); MS_TRACE();
......
...@@ -15,6 +15,7 @@ namespace RTC ...@@ -15,6 +15,7 @@ namespace RTC
static constexpr uint64_t TransportCcFeedbackSendInterval{ 100u }; // In ms. static constexpr uint64_t TransportCcFeedbackSendInterval{ 100u }; // In ms.
static constexpr uint64_t LimitationRembInterval{ 1500u }; // In ms. static constexpr uint64_t LimitationRembInterval{ 1500u }; // In ms.
static constexpr uint8_t UnlimitedRembNumPackets{ 4u }; static constexpr uint8_t UnlimitedRembNumPackets{ 4u };
static constexpr size_t PacketLossHistogramLength{ 24 };
/* Instance methods. */ /* Instance methods. */
...@@ -101,6 +102,13 @@ namespace RTC ...@@ -101,6 +102,13 @@ namespace RTC
} }
} }
double TransportCongestionControlServer::GetPacketLoss() const
{
MS_TRACE();
return this->packetLoss;
}
void TransportCongestionControlServer::IncomingPacket(uint64_t nowMs, const RTC::RtpPacket* packet) void TransportCongestionControlServer::IncomingPacket(uint64_t nowMs, const RTC::RtpPacket* packet)
{ {
MS_TRACE(); MS_TRACE();
...@@ -119,7 +127,7 @@ namespace RTC ...@@ -119,7 +127,7 @@ namespace RTC
this->transportCcFeedbackMediaSsrc = packet->GetSsrc(); this->transportCcFeedbackMediaSsrc = packet->GetSsrc();
this->transportCcFeedbackPacket->SetSenderSsrc(0u); this->transportCcFeedbackPacket->SetSenderSsrc(0u);
this->transportCcFeedbackPacket->SetMediaSsrc(packet->GetSsrc()); this->transportCcFeedbackPacket->SetMediaSsrc(this->transportCcFeedbackMediaSsrc);
// Provide the feedback packet with the RTP packet info. If it fails, // Provide the feedback packet with the RTP packet info. If it fails,
// send current feedback and add the packet info to a new one. // send current feedback and add the packet info to a new one.
...@@ -223,6 +231,17 @@ namespace RTC ...@@ -223,6 +231,17 @@ namespace RTC
this->listener->OnTransportCongestionControlServerSendRtcpPacket( this->listener->OnTransportCongestionControlServerSendRtcpPacket(
this, this->transportCcFeedbackPacket.get()); this, this->transportCcFeedbackPacket.get());
// Update packet loss history.
size_t expected_packets = this->transportCcFeedbackPacket->GetPacketStatusCount();
size_t lost_packets = 0;
for (const auto& result : this->transportCcFeedbackPacket->GetPacketResults())
{
if (!result.received)
lost_packets += 1;
}
this->UpdatePacketLoss(static_cast<double>(lost_packets) / expected_packets);
// Create a new feedback packet. // Create a new feedback packet.
this->transportCcFeedbackPacket.reset(new RTC::RTCP::FeedbackRtpTransportPacket( this->transportCcFeedbackPacket.reset(new RTC::RTCP::FeedbackRtpTransportPacket(
this->transportCcFeedbackSenderSsrc, this->transportCcFeedbackMediaSsrc)); this->transportCcFeedbackSenderSsrc, this->transportCcFeedbackMediaSsrc));
...@@ -280,6 +299,32 @@ namespace RTC ...@@ -280,6 +299,32 @@ namespace RTC
} }
} }
void TransportCongestionControlServer::UpdatePacketLoss(double packetLoss)
{
// Add the score into the histogram.
if (this->packetLossHistory.size() == PacketLossHistogramLength)
this->packetLossHistory.pop_front();
this->packetLossHistory.push_back(packetLoss);
// Calculate a weighted average
size_t weight{ 0 };
size_t samples{ 0 };
double totalPacketLoss{ 0 };
for (auto packetLossEntry : this->packetLossHistory)
{
weight++;
samples += weight;
totalPacketLoss += weight * packetLossEntry;
}
// clang-tidy "thinks" that this can lead to division by zero but we are
// smarter.
// NOLINTNEXTLINE(clang-analyzer-core.DivideZero)
this->packetLoss = totalPacketLoss / samples;
}
inline void TransportCongestionControlServer::OnRembServerAvailableBitrate( inline void TransportCongestionControlServer::OnRembServerAvailableBitrate(
const webrtc::RemoteBitrateEstimator* /*rembServer*/, const webrtc::RemoteBitrateEstimator* /*rembServer*/,
const std::vector<uint32_t>& ssrcs, const std::vector<uint32_t>& ssrcs,
......
...@@ -25,7 +25,7 @@ namespace TestFeedbackPsRpsi ...@@ -25,7 +25,7 @@ namespace TestFeedbackPsRpsi
// RPSI values. // RPSI values.
uint32_t senderSsrc{ 0xfa17fa17 }; uint32_t senderSsrc{ 0xfa17fa17 };
uint32_t mediaSsrc{ 0 }; uint32_t mediaSsrc{ 0 };
uint8_t payloadType{ 1 }; uint8_t payloadType{ 2 };
uint8_t payloadMask{ 1 }; uint8_t payloadMask{ 1 };
size_t length{ 5 }; size_t length{ 5 };
......
...@@ -17,7 +17,7 @@ namespace TestFeedbackPsTstn ...@@ -17,7 +17,7 @@ namespace TestFeedbackPsTstn
0x00, 0x00, 0x00, 0x00, // Media source SSRC: 0x00000000 0x00, 0x00, 0x00, 0x00, // Media source SSRC: 0x00000000
0x02, 0xd0, 0x37, 0x02, // SSRC: 0x02d03702 0x02, 0xd0, 0x37, 0x02, // SSRC: 0x02d03702
0x08, // Seq: 8 0x08, // Seq: 8
0x00, 0x00, 0x08 // Reserved, Index: 1 0x00, 0x00, 0x01 // Reserved, Index: 1
}; };
// clang-format on // clang-format on
......
...@@ -29,7 +29,7 @@ namespace TestFeedbackPsVbcm ...@@ -29,7 +29,7 @@ namespace TestFeedbackPsVbcm
uint32_t mediaSsrc{ 0 }; uint32_t mediaSsrc{ 0 };
uint32_t ssrc{ 0x02d03702 }; uint32_t ssrc{ 0x02d03702 };
uint8_t seq{ 8 }; uint8_t seq{ 8 };
uint8_t payloadType{ 1 }; uint8_t payloadType{ 2 };
uint16_t length{ 1 }; uint16_t length{ 1 };
uint8_t valueMask{ 1 }; uint8_t valueMask{ 1 };
......
...@@ -25,7 +25,7 @@ namespace TestReceiverReport ...@@ -25,7 +25,7 @@ namespace TestReceiverReport
// clang-format on // clang-format on
// Receiver Report buffer start point. // Receiver Report buffer start point.
uint8_t* rrBuffer = buffer + sizeof(Packet::CommonHeader) + sizeof(uint32_t) /*Sender SSRC*/; uint8_t* rrBuffer = buffer + Packet::CommonHeaderSize + sizeof(uint32_t) /*Sender SSRC*/;
uint32_t ssrc{ 0x01932db4 }; uint32_t ssrc{ 0x01932db4 };
uint8_t fractionLost{ 0 }; uint8_t fractionLost{ 0 };
...@@ -76,7 +76,7 @@ SCENARIO("RTCP RR parsing", "[parser][rtcp][rr]") ...@@ -76,7 +76,7 @@ SCENARIO("RTCP RR parsing", "[parser][rtcp][rr]")
SECTION("parse RR") SECTION("parse RR")
{ {
ReceiverReport* report = ReceiverReport::Parse(rrBuffer, sizeof(ReceiverReport::Header)); ReceiverReport* report = ReceiverReport::Parse(rrBuffer, ReceiverReport::HeaderSize);
REQUIRE(report); REQUIRE(report);
......
...@@ -23,7 +23,7 @@ namespace TestSdes ...@@ -23,7 +23,7 @@ namespace TestSdes
}; };
// clang-format on // clang-format on
uint8_t* chunkBuffer = buffer + sizeof(Packet::CommonHeader); uint8_t* chunkBuffer = buffer + Packet::CommonHeaderSize;
// SDES values. // SDES values.
uint32_t ssrc{ 0x9f65e742 }; uint32_t ssrc{ 0x9f65e742 };
...@@ -58,14 +58,13 @@ SCENARIO("RTCP SDES parsing", "[parser][rtcp][sdes]") ...@@ -58,14 +58,13 @@ SCENARIO("RTCP SDES parsing", "[parser][rtcp][sdes]")
SECTION("serialize SdesChunk instance") SECTION("serialize SdesChunk instance")
{ {
uint8_t serialized[sizeof(buffer) - sizeof(Packet::CommonHeader)] = { 0 }; uint8_t serialized[sizeof(buffer) - Packet::CommonHeaderSize] = { 0 };
chunk->Serialize(serialized); chunk->Serialize(serialized);
SECTION("compare serialized SdesChunk with original buffer") SECTION("compare serialized SdesChunk with original buffer")
{ {
REQUIRE( REQUIRE(std::memcmp(chunkBuffer, serialized, sizeof(buffer) - Packet::CommonHeaderSize) == 0);
std::memcmp(chunkBuffer, serialized, sizeof(buffer) - sizeof(Packet::CommonHeader)) == 0);
} }
} }
delete packet; delete packet;
......
...@@ -23,7 +23,7 @@ namespace TestSenderReport ...@@ -23,7 +23,7 @@ namespace TestSenderReport
// clang-format on // clang-format on
// Sender Report buffer start point. // Sender Report buffer start point.
uint8_t* srBuffer = buffer + sizeof(Packet::CommonHeader); uint8_t* srBuffer = buffer + Packet::CommonHeaderSize;
// SR values. // SR values.
uint32_t ssrc{ 0x5d931534 }; uint32_t ssrc{ 0x5d931534 };
...@@ -73,7 +73,7 @@ SCENARIO("RTCP SR parsing", "[parser][rtcp][sr]") ...@@ -73,7 +73,7 @@ SCENARIO("RTCP SR parsing", "[parser][rtcp][sr]")
SECTION("parse SR") SECTION("parse SR")
{ {
SenderReport* report = SenderReport::Parse(srBuffer, sizeof(SenderReport::Header)); SenderReport* report = SenderReport::Parse(srBuffer, SenderReport::HeaderSize);
REQUIRE(report); REQUIRE(report);
...@@ -81,13 +81,13 @@ SCENARIO("RTCP SR parsing", "[parser][rtcp][sr]") ...@@ -81,13 +81,13 @@ SCENARIO("RTCP SR parsing", "[parser][rtcp][sr]")
SECTION("serialize SenderReport instance") SECTION("serialize SenderReport instance")
{ {
uint8_t serialized[sizeof(SenderReport::Header)] = { 0 }; uint8_t serialized[SenderReport::HeaderSize] = { 0 };
report->Serialize(serialized); report->Serialize(serialized);
SECTION("compare serialized SenderReport with original buffer") SECTION("compare serialized SenderReport with original buffer")
{ {
REQUIRE(std::memcmp(srBuffer, serialized, sizeof(SenderReport::Header)) == 0); REQUIRE(std::memcmp(srBuffer, serialized, SenderReport::HeaderSize) == 0);
} }
} }
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论