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

New API to send data from Node throught SCTP DataConsumer (#444)

* New API to send data from Node throught SCTP DataConsumer

* Update CHANGELOG.md

* DataConsumer: onQueuedCallback

* Place static methods above static members

* typo

* Enhance error message

* Enhance error message
上级 8d01ce0b
......@@ -5,6 +5,7 @@
* `SctpAssociation.cpp`: Fix `OnSctpAssociationBufferedAmount()` call.
* Update deps.
* New API to send data from Node throught SCTP DataConsumer.
### 3.6.15
......
......@@ -178,7 +178,7 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
});
}
_processMessage(msg) {
// If a response retrieve its associated request.
// If a response, retrieve its associated request.
if (msg.id) {
const sent = this._sents.get(msg.id);
if (!sent) {
......
/// <reference types="node" />
import { EnhancedEventEmitter } from './EnhancedEventEmitter';
import { Channel } from './Channel';
import { PayloadChannel } from './PayloadChannel';
......@@ -51,8 +52,6 @@ export declare class DataConsumer extends EnhancedEventEmitter {
private readonly _channel;
private readonly _payloadChannel;
private _closed;
private _bufferedAmountLowThreshold;
private _bufferedAmount;
private readonly _appData?;
private readonly _observer;
/**
......@@ -80,11 +79,6 @@ export declare class DataConsumer extends EnhancedEventEmitter {
* Associated DataProducer id.
*/
get dataProducerId(): string;
/**
* Buffered amount threshold.
*/
get bufferedAmountLowThreshold(): number;
set bufferedAmountLowThreshold(value: number);
/**
* Whether the DataConsumer is closed.
*/
......@@ -137,6 +131,14 @@ export declare class DataConsumer extends EnhancedEventEmitter {
* Get DataConsumer stats.
*/
getStats(): Promise<DataConsumerStat[]>;
/**
* Set buffered amount low threshold.
*/
setBufferedAmountLowThreshold(threshold: number): Promise<void>;
/**
* Send data.
*/
send(message: string | Buffer, ppid?: number): Promise<void>;
/**
* Get buffered amount size.
*/
......
{"version":3,"file":"DataConsumer.d.ts","sourceRoot":"","sources":["../src/DataConsumer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD,oBAAY,mBAAmB,GAC/B;IACC;;OAEG;IACH,cAAc,EAAE,MAAM,CAAC;IAEvB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;OAKG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;OAEG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;CACd,CAAA;AAED,oBAAY,gBAAgB,GAC5B;IACC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;CAClB,CAAA;AAED;;GAEG;AACH,oBAAY,gBAAgB,GAAG,MAAM,GAAG,QAAQ,CAAC;AAIjD,qBAAa,YAAa,SAAQ,oBAAoB;IAGrD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAMxB;IAGF,OAAO,CAAC,QAAQ,CAAC,KAAK,CAMpB;IAGF,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU;IAGnC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAiB;IAGjD,OAAO,CAAC,OAAO,CAAS;IAGxB,OAAO,CAAC,2BAA2B,CAAI;IAGvC,OAAO,CAAC,eAAe,CAAI;IAG3B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAM;IAGhC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA8B;IAExD;;;;;;;;;OASG;gBAEF,EACC,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,cAAc,EACd,OAAO,EACP,EACD;QACC,QAAQ,EAAE,GAAG,CAAC;QACd,IAAI,EAAE,GAAG,CAAC;QACV,OAAO,EAAE,OAAO,CAAC;QACjB,cAAc,EAAE,cAAc,CAAC;QAC/B,OAAO,EAAE,GAAG,CAAC;KACb;IAgBF;;OAEG;IACH,IAAI,EAAE,IAAI,MAAM,CAGf;IAED;;OAEG;IACH,IAAI,cAAc,IAAI,MAAM,CAG3B;IAED;;OAEG;IACH,IAAI,0BAA0B,IAAI,MAAM,CAGvC;IAED,IAAI,0BAA0B,CAAC,KAAK,EAAE,MAAM,EAG3C;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,OAAO,CAGpB;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,gBAAgB,CAG3B;IAED;;OAEG;IACH,IAAI,oBAAoB,IAAI,oBAAoB,GAAG,SAAS,CAG3D;IAED;;OAEG;IACH,IAAI,KAAK,IAAI,MAAM,CAGlB;IAED;;OAEG;IACH,IAAI,QAAQ,IAAI,MAAM,CAGrB;IAED;;OAEG;IACH,IAAI,OAAO,IAAI,GAAG,CAGjB;IAED;;OAEG;IACH,IAAI,OAAO,CAAC,OAAO,EAAE,GAAG,EAGvB;IAED;;;;OAIG;IACH,IAAI,QAAQ,IAAI,oBAAoB,CAGnC;IAED;;OAEG;IACH,KAAK,IAAI,IAAI;IAqBb;;;;OAIG;IACH,eAAe,IAAI,IAAI;IAkBvB;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC;IAO1B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAO7C;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC;IAU1C,OAAO,CAAC,0BAA0B;CAmFlC"}
\ No newline at end of file
{"version":3,"file":"DataConsumer.d.ts","sourceRoot":"","sources":["../src/DataConsumer.ts"],"names":[],"mappings":"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"}
\ No newline at end of file
......@@ -18,10 +18,6 @@ class DataConsumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
super();
// Closed flag.
this._closed = false;
// Buffered amount threshold.
this._bufferedAmountLowThreshold = 0;
// Buffered amount.
this._bufferedAmount = 0;
// Observer instance.
this._observer = new EnhancedEventEmitter_1.EnhancedEventEmitter();
logger.debug('constructor()');
......@@ -44,15 +40,6 @@ class DataConsumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
get dataProducerId() {
return this._internal.dataProducerId;
}
/**
* Buffered amount threshold.
*/
get bufferedAmountLowThreshold() {
return this._bufferedAmountLowThreshold;
}
set bufferedAmountLowThreshold(value) {
this._bufferedAmountLowThreshold = value;
}
/**
* Whether the DataConsumer is closed.
*/
......@@ -149,6 +136,49 @@ class DataConsumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('getStats()');
return this._channel.request('dataConsumer.getStats', this._internal);
}
/**
* Set buffered amount low threshold.
*/
async setBufferedAmountLowThreshold(threshold) {
logger.debug('setBufferedAmountLowThreshold() [threshold:%s]', threshold);
const reqData = { threshold };
await this._channel.request('dataConsumer.setBufferedAmountLowThreshold', this._internal, reqData);
}
/**
* Send data.
*/
async send(message, ppid) {
if (typeof message !== 'string' && !Buffer.isBuffer(message)) {
throw new TypeError('message must be a string or a Buffer');
}
/*
* +-------------------------------+----------+
* | Value | SCTP |
* | | PPID |
* +-------------------------------+----------+
* | WebRTC String | 51 |
* | WebRTC Binary Partial | 52 |
* | (Deprecated) | |
* | WebRTC Binary | 53 |
* | WebRTC String Partial | 54 |
* | (Deprecated) | |
* | WebRTC String Empty | 56 |
* | WebRTC Binary Empty | 57 |
* +-------------------------------+----------+
*/
if (typeof ppid !== 'number') {
ppid = (typeof message === 'string')
? message.length > 0 ? 51 : 56
: message.length > 0 ? 53 : 57;
}
// Ensure we honor PPIDs.
if (ppid === 56)
message = ' ';
else if (ppid === 57)
message = Buffer.alloc(1);
const requestData = { ppid };
await this._payloadChannel.request('dataConsumer.send', this._internal, requestData, message);
}
/**
* Get buffered amount size.
*/
......@@ -178,15 +208,10 @@ class DataConsumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
this.safeEmit('sctpsendbufferfull');
break;
}
case 'bufferedamount':
case 'bufferedamountlow':
{
const { bufferedAmount } = data;
const previousBufferedAmount = this._bufferedAmount;
this._bufferedAmount = bufferedAmount;
if (previousBufferedAmount > this._bufferedAmountLowThreshold &&
this._bufferedAmount <= this._bufferedAmountLowThreshold) {
this.safeEmit('bufferedamountlow', bufferedAmount);
}
this.safeEmit('bufferedamountlow', bufferedAmount);
break;
}
default:
......
......@@ -4,6 +4,8 @@ export declare class PayloadChannel extends EnhancedEventEmitter {
private _closed;
private readonly _producerSocket;
private readonly _consumerSocket;
private _nextId;
private readonly _sents;
private _recvBuffer?;
private _ongoingNotification?;
/**
......@@ -21,6 +23,10 @@ export declare class PayloadChannel extends EnhancedEventEmitter {
* @private
*/
notify(event: string, internal: object, data: any | undefined, payload: string | Buffer): void;
/**
* @private
*/
request(method: string, internal: object, data: any, payload: string | Buffer): Promise<any>;
private _processData;
}
//# sourceMappingURL=PayloadChannel.d.ts.map
\ No newline at end of file
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAS9D,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,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,OAAO,CAAC,YAAY;CAgDpB"}
\ No newline at end of file
{"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"}
\ No newline at end of file
......@@ -17,6 +17,10 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
super();
// Closed flag.
this._closed = false;
// Next id for messages sent to the worker process.
this._nextId = 0;
// Map of pending sent requests.
this._sents = new Map();
logger.debug('constructor()');
this._producerSocket = producerSocket;
this._consumerSocket = consumerSocket;
......@@ -123,6 +127,56 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
return;
}
}
/**
* @private
*/
async request(method, internal, data, payload) {
this._nextId < 4294967295 ? ++this._nextId : (this._nextId = 1);
const id = this._nextId;
logger.debug('request() [method:%s, id:%s]', method, id);
if (this._closed)
throw new errors_1.InvalidStateError('Channel closed');
const request = { id, method, internal, data };
const ns1 = netstring.nsWrite(JSON.stringify(request));
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended.
this._producerSocket.write(ns1);
this._producerSocket.write(ns2);
return new Promise((pResolve, pReject) => {
const timeout = 1000 * (15 + (0.1 * this._sents.size));
const sent = {
id: id,
method: method,
resolve: (data2) => {
if (!this._sents.delete(id))
return;
clearTimeout(sent.timer);
pResolve(data2);
},
reject: (error) => {
if (!this._sents.delete(id))
return;
clearTimeout(sent.timer);
pReject(error);
},
timer: setTimeout(() => {
if (!this._sents.delete(id))
return;
pReject(new Error('Channel request timeout'));
}, timeout),
close: () => {
clearTimeout(sent.timer);
pReject(new errors_1.InvalidStateError('Channel closed'));
}
};
// Add sent stuff to the map.
this._sents.set(id, sent);
});
}
_processData(data) {
if (!this._ongoingNotification) {
let msg;
......@@ -133,16 +187,44 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.error('received invalid data from the worker process: %s', String(error));
return;
}
if (!msg.targetId || !msg.event) {
logger.error('received message is not a notification');
// If a response, retrieve its associated request.
if (msg.id) {
const sent = this._sents.get(msg.id);
if (!sent) {
logger.error('received response does not match any sent request [id:%s]', msg.id);
return;
}
if (msg.accepted) {
logger.debug('request succeeded [method:%s, id:%s]', sent.method, sent.id);
sent.resolve(msg.data);
}
else if (msg.error) {
logger.warn('request failed [method:%s, id:%s]: %s', sent.method, sent.id, msg.reason);
switch (msg.error) {
case 'TypeError':
sent.reject(new TypeError(msg.reason));
break;
default:
sent.reject(new Error(msg.reason));
}
}
else {
logger.error('received response is not accepted nor rejected [method:%s, id:%s]', sent.method, sent.id);
}
}
// If a notification, create the ongoing notification instance.
else if (msg.targetId && msg.event) {
this._ongoingNotification =
{
targetId: msg.targetId,
event: msg.event,
data: msg.data
};
}
else {
logger.error('received data is not a notification nor a response');
return;
}
this._ongoingNotification =
{
targetId: msg.targetId,
event: msg.event,
data: msg.data
};
}
else {
const payload = data;
......
......@@ -67,7 +67,7 @@ class Worker extends EnhancedEventEmitter_1.EnhancedEventEmitter {
// options
{
env: {
MEDIASOUP_VERSION: '3.6.15'
MEDIASOUP_VERSION: '3.6.14'
},
detached: false,
// fd 0 (stdin) : Just ignore it.
......
......@@ -291,7 +291,7 @@ export class Channel extends EnhancedEventEmitter
private _processMessage(msg: any): void
{
// If a response retrieve its associated request.
// If a response, retrieve its associated request.
if (msg.id)
{
const sent = this._sents.get(msg.id);
......
......@@ -87,12 +87,6 @@ export class DataConsumer extends EnhancedEventEmitter
// Closed flag.
private _closed = false;
// Buffered amount threshold.
private _bufferedAmountLowThreshold = 0
// Buffered amount.
private _bufferedAmount = 0
// Custom app data.
private readonly _appData?: any;
......@@ -155,19 +149,6 @@ export class DataConsumer extends EnhancedEventEmitter
return this._internal.dataProducerId;
}
/**
* Buffered amount threshold.
*/
get bufferedAmountLowThreshold(): number
{
return this._bufferedAmountLowThreshold;
}
set bufferedAmountLowThreshold(value: number)
{
this._bufferedAmountLowThreshold = value;
}
/**
* Whether the DataConsumer is closed.
*/
......@@ -301,6 +282,64 @@ export class DataConsumer extends EnhancedEventEmitter
return this._channel.request('dataConsumer.getStats', this._internal);
}
/**
* Set buffered amount low threshold.
*/
async setBufferedAmountLowThreshold(threshold: number): Promise<void>
{
logger.debug('setBufferedAmountLowThreshold() [threshold:%s]', threshold);
const reqData = { threshold };
await this._channel.request(
'dataConsumer.setBufferedAmountLowThreshold', this._internal, reqData);
}
/**
* Send data.
*/
async send(message: string | Buffer, ppid?: number): Promise<void>
{
if (typeof message !== 'string' && !Buffer.isBuffer(message))
{
throw new TypeError('message must be a string or a Buffer');
}
/*
* +-------------------------------+----------+
* | Value | SCTP |
* | | PPID |
* +-------------------------------+----------+
* | WebRTC String | 51 |
* | WebRTC Binary Partial | 52 |
* | (Deprecated) | |
* | WebRTC Binary | 53 |
* | WebRTC String Partial | 54 |
* | (Deprecated) | |
* | WebRTC String Empty | 56 |
* | WebRTC Binary Empty | 57 |
* +-------------------------------+----------+
*/
if (typeof ppid !== 'number')
{
ppid = (typeof message === 'string')
? message.length > 0 ? 51 : 56
: message.length > 0 ? 53 : 57;
}
// Ensure we honor PPIDs.
if (ppid === 56)
message = ' ';
else if (ppid === 57)
message = Buffer.alloc(1);
const requestData = { ppid };
await this._payloadChannel.request(
'dataConsumer.send', this._internal, requestData, message);
}
/**
* Get buffered amount size.
*/
......@@ -346,20 +385,11 @@ export class DataConsumer extends EnhancedEventEmitter
break;
}
case 'bufferedamount':
case 'bufferedamountlow':
{
const { bufferedAmount } = data as { bufferedAmount: number };
const previousBufferedAmount = this._bufferedAmount;
this._bufferedAmount = bufferedAmount;
if (
previousBufferedAmount > this._bufferedAmountLowThreshold &&
this._bufferedAmount <= this._bufferedAmountLowThreshold
)
{
this.safeEmit('bufferedamountlow', bufferedAmount);
}
this.safeEmit('bufferedamountlow', bufferedAmount);
break;
}
......
......@@ -7,6 +7,16 @@ import { InvalidStateError } from './errors';
const logger = new Logger('PayloadChannel');
type Sent =
{
id: number;
method: string;
resolve: (data?: any) => void;
reject: (error: Error) => void;
timer: NodeJS.Timer;
close: () => void;
}
// netstring length for a 4194304 bytes payload.
const NS_MESSAGE_MAX_LEN = 4194313;
const NS_PAYLOAD_MAX_LEN = 4194304;
......@@ -22,6 +32,12 @@ export class PayloadChannel extends EnhancedEventEmitter
// Unix Socket instance for receiving messages to the worker process.
private readonly _consumerSocket: Duplex;
// Next id for messages sent to the worker process.
private _nextId = 0;
// Map of pending sent requests.
private readonly _sents: Map<number, Sent> = new Map();
// Buffer for reading messages from the worker.
private _recvBuffer?: Buffer;
......@@ -209,6 +225,79 @@ export class PayloadChannel extends EnhancedEventEmitter
}
}
/**
* @private
*/
async request(
method: string,
internal: object,
data: any,
payload: string | Buffer): Promise<any>
{
this._nextId < 4294967295 ? ++this._nextId : (this._nextId = 1);
const id = this._nextId;
logger.debug('request() [method:%s, id:%s]', method, id);
if (this._closed)
throw new InvalidStateError('Channel closed');
const request = { id, method, internal, data };
const ns1 = netstring.nsWrite(JSON.stringify(request));
const ns2 = netstring.nsWrite(payload);
if (Buffer.byteLength(ns1) > NS_MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
else if (Buffer.byteLength(ns2) > NS_MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended.
this._producerSocket.write(ns1);
this._producerSocket.write(ns2);
return new Promise((pResolve, pReject) =>
{
const timeout = 1000 * (15 + (0.1 * this._sents.size));
const sent: Sent =
{
id : id,
method : method,
resolve : (data2) =>
{
if (!this._sents.delete(id))
return;
clearTimeout(sent.timer);
pResolve(data2);
},
reject : (error) =>
{
if (!this._sents.delete(id))
return;
clearTimeout(sent.timer);
pReject(error);
},
timer : setTimeout(() =>
{
if (!this._sents.delete(id))
return;
pReject(new Error('Channel request timeout'));
}, timeout),
close : () =>
{
clearTimeout(sent.timer);
pReject(new InvalidStateError('Channel closed'));
}
};
// Add sent stuff to the map.
this._sents.set(id, sent);
});
}
private _processData(data: Buffer): void
{
if (!this._ongoingNotification)
......@@ -228,19 +317,65 @@ export class PayloadChannel extends EnhancedEventEmitter
return;
}
if (!msg.targetId || !msg.event)
// If a response, retrieve its associated request.
if (msg.id)
{
logger.error('received message is not a notification');
const sent = this._sents.get(msg.id);
return;
}
if (!sent)
{
logger.error(
'received response does not match any sent request [id:%s]', msg.id);
return;
}
if (msg.accepted)
{
logger.debug(
'request succeeded [method:%s, id:%s]', sent.method, sent.id);
this._ongoingNotification =
sent.resolve(msg.data);
}
else if (msg.error)
{
logger.warn(
'request failed [method:%s, id:%s]: %s',
sent.method, sent.id, msg.reason);
switch (msg.error)
{
case 'TypeError':
sent.reject(new TypeError(msg.reason));
break;
default:
sent.reject(new Error(msg.reason));
}
}
else
{
logger.error(
'received response is not accepted nor rejected [method:%s, id:%s]',
sent.method, sent.id);
}
}
// If a notification, create the ongoing notification instance.
else if (msg.targetId && msg.event)
{
targetId : msg.targetId,
event : msg.event,
data : msg.data
};
this._ongoingNotification =
{
targetId : msg.targetId,
event : msg.event,
data : msg.data
};
}
else
{
logger.error('received data is not a notification nor a response');
return;
}
}
else
{
......
......@@ -63,6 +63,7 @@ namespace Channel
DATA_CONSUMER_DUMP,
DATA_CONSUMER_GET_STATS,
DATA_CONSUMER_GET_BUFFERED_AMOUNT,
DATA_CONSUMER_SET_BUFFERED_AMOUNT_LOW_THRESHOLD,
RTP_OBSERVER_CLOSE,
RTP_OBSERVER_PAUSE,
RTP_OBSERVER_RESUME,
......
......@@ -20,6 +20,9 @@ namespace PayloadChannel
DATA_PRODUCER_SEND
};
public:
static bool IsNotification(json& jsonNotification);
private:
static std::unordered_map<std::string, EventId> string2EventId;
......
#ifndef MS_PAYLOAD_CHANNEL_REQUEST_HPP
#define MS_PAYLOAD_CHANNEL_REQUEST_HPP
#include "common.hpp"
#include <json.hpp>
#include <string>
#include <unordered_map>
using json = nlohmann::json;
namespace PayloadChannel
{
// Avoid cyclic #include problem by declaring classes instead of including
// the corresponding header files.
class UnixStreamSocket;
class Request
{
public:
enum class MethodId
{
DATA_CONSUMER_SEND
};
public:
static bool IsRequest(json& jsonRequest);
private:
static std::unordered_map<std::string, MethodId> string2MethodId;
public:
Request(PayloadChannel::UnixStreamSocket* channel, json& jsonRequest);
virtual ~Request();
public:
void Accept();
void Accept(json& data);
void Error(const char* reason = nullptr);
void TypeError(const char* reason = nullptr);
void SetPayload(const uint8_t* payload, size_t payloadLen);
public:
// Passed by argument.
PayloadChannel::UnixStreamSocket* channel{ nullptr };
uint32_t id{ 0u };
std::string method;
MethodId methodId;
json internal;
json data;
const uint8_t* payload{ nullptr };
size_t payloadLen{ 0u };
// Others.
bool replied{ false };
};
} // namespace PayloadChannel
#endif
......@@ -3,6 +3,7 @@
#include "common.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/Request.hpp"
#include "handles/UnixStreamSocket.hpp"
#include <json.hpp>
......@@ -56,7 +57,9 @@ namespace PayloadChannel
public:
virtual void OnPayloadChannelNotification(
PayloadChannel::UnixStreamSocket* payloadChannel,
PayloadChannel::Notification* notification) = 0;
PayloadChannel::Notification* notification) = 0;
virtual void OnPayloadChannelRequest(
PayloadChannel::UnixStreamSocket* payloadChannel, PayloadChannel::Request* request) = 0;
virtual void OnPayloadChannelClosed(PayloadChannel::UnixStreamSocket* payloadChannel) = 0;
};
......@@ -67,6 +70,7 @@ namespace PayloadChannel
public:
void SetListener(Listener* listener);
void Send(json& jsonMessage, const uint8_t* payload, size_t payloadLen);
void Send(json& jsonMessage);
private:
void SendImpl(const void* nsPayload, size_t nsPayloadLen);
......@@ -83,6 +87,7 @@ namespace PayloadChannel
ConsumerSocket consumerSocket;
ProducerSocket producerSocket;
PayloadChannel::Notification* ongoingNotification{ nullptr };
PayloadChannel::Request* ongoingRequest{ nullptr };
};
} // namespace PayloadChannel
......
......@@ -3,6 +3,7 @@
#include "common.hpp"
#include "Channel/Request.hpp"
#include "PayloadChannel/Request.hpp"
#include "RTC/SctpDictionaries.hpp"
#include <json.hpp>
#include <string>
......@@ -11,13 +12,20 @@ namespace RTC
{
class DataConsumer
{
protected:
using onQueuedCallback = const std::function<void(bool queued)>;
public:
class Listener
{
public:
virtual void OnDataConsumerSendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) = 0;
virtual void OnDataConsumerDataProducerClosed(RTC::DataConsumer* dataConsumer) = 0;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* cb) = 0;
virtual void OnDataConsumerDataProducerClosed(RTC::DataConsumer* dataConsumer) = 0;
};
public:
......@@ -40,6 +48,7 @@ namespace RTC
void FillJson(json& jsonObject) const;
void FillJsonStats(json& jsonArray) const;
void HandleRequest(Channel::Request* request);
void HandleRequest(PayloadChannel::Request* request);
Type GetType() const
{
return this->type;
......@@ -62,8 +71,9 @@ namespace RTC
void TransportDisconnected();
void SctpAssociationConnected();
void SctpAssociationClosed();
void SctpAssociationBufferedAmount(uint32_t bufferedAmount);
void DataProducerClosed();
void SendMessage(uint32_t ppid, const uint8_t* msg, size_t len);
void SendMessage(uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* = nullptr);
public:
// Passed by argument.
......@@ -85,6 +95,8 @@ namespace RTC
bool dataProducerClosed{ false };
size_t messagesSent{ 0u };
size_t bytesSent{ 0u };
uint32_t bufferedAmount{ 0u };
uint32_t bufferedAmountLowThreshold{ 0u };
};
} // namespace RTC
......
......@@ -26,7 +26,11 @@ namespace RTC
void SendRtcpPacket(RTC::RTCP::Packet* packet) override;
void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet) override;
void SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) override;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* cb = nullptr) override;
void SendSctpData(const uint8_t* data, size_t len) override;
void RecvStreamClosed(uint32_t ssrc) override;
void SendStreamClosed(uint32_t ssrc) override;
......
......@@ -42,7 +42,11 @@ namespace RTC
void SendRtcpPacket(RTC::RTCP::Packet* packet) override;
void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet) override;
void SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) override;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* cb = nullptr) override;
void SendSctpData(const uint8_t* data, size_t len) override;
void RecvStreamClosed(uint32_t ssrc) override;
void SendStreamClosed(uint32_t ssrc) override;
......
......@@ -44,7 +44,11 @@ namespace RTC
void SendRtcpPacket(RTC::RTCP::Packet* packet) override;
void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet) override;
void SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) override;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* cb = nullptr) override;
void SendSctpData(const uint8_t* data, size_t len) override;
void RecvStreamClosed(uint32_t ssrc) override;
void SendStreamClosed(uint32_t ssrc) override;
......
......@@ -4,6 +4,7 @@
#include "common.hpp"
#include "Channel/Request.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/Request.hpp"
#include "RTC/Consumer.hpp"
#include "RTC/DataConsumer.hpp"
#include "RTC/DataProducer.hpp"
......@@ -30,6 +31,7 @@ namespace RTC
public:
void FillJson(json& jsonObject) const;
void HandleRequest(Channel::Request* request);
void HandleRequest(PayloadChannel::Request* request);
void HandleNotification(PayloadChannel::Notification* notification);
private:
......
......@@ -31,6 +31,9 @@ namespace RTC
OUTGOING
};
protected:
using onQueuedCallback = const std::function<void(bool queued)>;
public:
class Listener
{
......@@ -86,7 +89,12 @@ namespace RTC
return this->sctpBufferedAmount;
}
void ProcessSctpData(const uint8_t* data, size_t len);
void SendSctpMessage(RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len);
void SendSctpMessage(
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* cb = nullptr);
void HandleDataConsumer(RTC::DataConsumer* dataConsumer);
void DataProducerClosed(RTC::DataProducer* dataProducer);
void DataConsumerClosed(RTC::DataConsumer* dataConsumer);
......
......@@ -6,6 +6,7 @@
#include "DepLibUV.hpp"
#include "Channel/Request.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/Request.hpp"
#include "RTC/Consumer.hpp"
#include "RTC/DataConsumer.hpp"
#include "RTC/DataProducer.hpp"
......@@ -46,7 +47,8 @@ namespace RTC
public Timer::Listener
{
protected:
using onSendCallback = const std::function<void(bool sent)>;
using onSendCallback = const std::function<void(bool sent)>;
using onQueuedCallback = const std::function<void(bool queued)>;
public:
class Listener
......@@ -120,6 +122,7 @@ namespace RTC
// Subclasses must implement these methods and call the parent's ones to
// handle common requests.
virtual void HandleRequest(Channel::Request* request);
virtual void HandleRequest(PayloadChannel::Request* request);
virtual void HandleNotification(PayloadChannel::Notification* notification);
protected:
......@@ -157,10 +160,14 @@ namespace RTC
virtual void SendRtcpPacket(RTC::RTCP::Packet* packet) = 0;
virtual void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet) = 0;
virtual void SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) = 0;
virtual void SendSctpData(const uint8_t* data, size_t len) = 0;
virtual void RecvStreamClosed(uint32_t ssrc) = 0;
virtual void SendStreamClosed(uint32_t ssrc) = 0;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* = nullptr) = 0;
virtual void SendSctpData(const uint8_t* data, size_t len) = 0;
virtual void RecvStreamClosed(uint32_t ssrc) = 0;
virtual void SendStreamClosed(uint32_t ssrc) = 0;
void DistributeAvailableOutgoingBitrate();
void ComputeOutgoingDesiredBitrate(bool forceBitrate = false);
void EmitTraceEventProbationType(RTC::RtpPacket* packet) const;
......@@ -198,7 +205,11 @@ namespace RTC
/* Pure virtual methods inherited from RTC::DataConsumer::Listener. */
public:
void OnDataConsumerSendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) override;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* = nullptr) override;
void OnDataConsumerDataProducerClosed(RTC::DataConsumer* dataConsumer) override;
/* Pure virtual methods inherited from RTC::SctpAssociation::Listener. */
......@@ -215,7 +226,8 @@ namespace RTC
uint32_t ppid,
const uint8_t* msg,
size_t len) override;
void OnSctpAssociationBufferedAmount(RTC::SctpAssociation* sctpAssociation, uint32_t len) override;
void OnSctpAssociationBufferedAmount(
RTC::SctpAssociation* sctpAssociation, uint32_t bufferedAmount) override;
/* Pure virtual methods inherited from RTC::TransportCongestionControlClient::Listener. */
public:
......
......@@ -49,7 +49,11 @@ namespace RTC
void SendRtcpPacket(RTC::RTCP::Packet* packet) override;
void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet) override;
void SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len) override;
RTC::DataConsumer* dataConsumer,
uint32_t ppid,
const uint8_t* msg,
size_t len,
onQueuedCallback* cb = nullptr) override;
void SendSctpData(const uint8_t* data, size_t len) override;
void RecvStreamClosed(uint32_t ssrc) override;
void SendStreamClosed(uint32_t ssrc) override;
......
......@@ -5,6 +5,7 @@
#include "Channel/Request.hpp"
#include "Channel/UnixStreamSocket.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/Request.hpp"
#include "PayloadChannel/UnixStreamSocket.hpp"
#include "RTC/Router.hpp"
#include "handles/SignalsHandler.hpp"
......@@ -39,6 +40,8 @@ public:
void OnPayloadChannelNotification(
PayloadChannel::UnixStreamSocket* payloadChannel,
PayloadChannel::Notification* notification) override;
void OnPayloadChannelRequest(
PayloadChannel::UnixStreamSocket* payloadChannel, PayloadChannel::Request* request) override;
void OnPayloadChannelClosed(PayloadChannel::UnixStreamSocket* payloadChannel) override;
/* Methods inherited from SignalsHandler::Listener. */
......
......@@ -39,6 +39,7 @@
'src/Channel/UnixStreamSocket.cpp',
'src/PayloadChannel/Notification.cpp',
'src/PayloadChannel/Notifier.cpp',
'src/PayloadChannel/Request.cpp',
'src/PayloadChannel/UnixStreamSocket.cpp',
'src/RTC/AudioLevelObserver.cpp',
'src/RTC/Consumer.cpp',
......@@ -149,6 +150,7 @@
'include/Channel/UnixStreamSocket.hpp',
'include/PayloadChannel/Notification.hpp',
'include/PayloadChannel/Notifier.hpp',
'include/PayloadChannel/Request.hpp',
'include/PayloadChannel/UnixStreamSocket.hpp',
'include/RTC/BweType.hpp',
'include/RTC/AudioLevelObserver.hpp',
......
......@@ -19,6 +19,27 @@ namespace PayloadChannel
};
// clang-format on
/* Class methods. */
bool Notification::IsNotification(json& jsonNotification)
{
MS_TRACE();
auto jsonEventIdIt = jsonNotification.find("event");
if (jsonEventIdIt == jsonNotification.end() || !jsonEventIdIt->is_string())
return false;
auto event = jsonEventIdIt->get<std::string>();
auto eventIdIt = Notification::string2EventId.find(event);
if (eventIdIt == Notification::string2EventId.end())
return false;
return true;
}
/* Instance methods. */
Notification::Notification(json& jsonNotification)
......
#define MS_CLASS "PayloadChannel::Request"
// #define MS_LOG_DEV_LEVEL 3
#include "PayloadChannel/Request.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include "PayloadChannel/UnixStreamSocket.hpp"
namespace PayloadChannel
{
/* Class variables. */
// clang-format off
std::unordered_map<std::string, Request::MethodId> Request::string2MethodId =
{
{ "dataConsumer.send", Request::MethodId::DATA_CONSUMER_SEND },
};
// clang-format on
/* Class methods. */
bool Request::IsRequest(json& jsonRequest)
{
MS_TRACE();
auto jsonIdIt = jsonRequest.find("id");
if (jsonIdIt == jsonRequest.end() || !Utils::Json::IsPositiveInteger(*jsonIdIt))
return false;
auto jsonMethodIt = jsonRequest.find("method");
if (jsonMethodIt == jsonRequest.end() || !jsonMethodIt->is_string())
return false;
return true;
}
/* Instance methods. */
Request::Request(PayloadChannel::UnixStreamSocket* channel, json& jsonRequest) : channel(channel)
{
MS_TRACE();
auto jsonIdIt = jsonRequest.find("id");
if (jsonIdIt == jsonRequest.end() || !Utils::Json::IsPositiveInteger(*jsonIdIt))
MS_THROW_ERROR("missing id");
this->id = jsonIdIt->get<uint32_t>();
auto jsonMethodIt = jsonRequest.find("method");
if (jsonMethodIt == jsonRequest.end() || !jsonMethodIt->is_string())
MS_THROW_ERROR("missing method");
this->method = jsonMethodIt->get<std::string>();
auto methodIdIt = Request::string2MethodId.find(this->method);
if (methodIdIt == Request::string2MethodId.end())
{
Error("unknown method");
MS_THROW_ERROR("unknown method '%s'", this->method.c_str());
}
this->methodId = methodIdIt->second;
auto jsonInternalIt = jsonRequest.find("internal");
if (jsonInternalIt != jsonRequest.end() && jsonInternalIt->is_object())
this->internal = *jsonInternalIt;
else
this->internal = json::object();
auto jsonDataIt = jsonRequest.find("data");
if (jsonDataIt != jsonRequest.end() && jsonDataIt->is_object())
this->data = *jsonDataIt;
else
this->data = json::object();
}
Request::~Request()
{
MS_TRACE();
}
void Request::Accept()
{
MS_TRACE();
MS_ASSERT(!this->replied, "request already replied");
this->replied = true;
json jsonResponse = json::object();
jsonResponse["id"] = this->id;
jsonResponse["accepted"] = true;
this->channel->Send(jsonResponse);
}
void Request::Accept(json& data)
{
MS_TRACE();
MS_ASSERT(!this->replied, "request already replied");
this->replied = true;
json jsonResponse = json::object();
jsonResponse["id"] = this->id;
jsonResponse["accepted"] = true;
if (data.is_structured())
jsonResponse["data"] = data;
this->channel->Send(jsonResponse);
}
void Request::Error(const char* reason)
{
MS_TRACE();
MS_ASSERT(!this->replied, "request already replied");
this->replied = true;
json jsonResponse = json::object();
jsonResponse["id"] = this->id;
jsonResponse["error"] = "Error";
if (reason != nullptr)
jsonResponse["reason"] = reason;
this->channel->Send(jsonResponse);
}
void Request::TypeError(const char* reason)
{
MS_TRACE();
MS_ASSERT(!this->replied, "request already replied");
this->replied = true;
json jsonResponse = json::object();
jsonResponse["id"] = this->id;
jsonResponse["error"] = "TypeError";
if (reason != nullptr)
jsonResponse["reason"] = reason;
this->channel->Send(jsonResponse);
}
void Request::SetPayload(const uint8_t* payload, size_t payloadLen)
{
MS_TRACE();
this->payload = payload;
this->payloadLen = payloadLen;
}
} // namespace PayloadChannel
......@@ -4,6 +4,7 @@
#include "PayloadChannel/UnixStreamSocket.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "PayloadChannel/Request.hpp"
#include <cmath> // std::ceil()
#include <cstdio> // sprintf()
#include <cstring> // std::memcpy(), std::memmove()
......@@ -68,6 +69,25 @@ namespace PayloadChannel
SendImpl(payload, payloadLen);
}
void UnixStreamSocket::Send(json& jsonMessage)
{
MS_TRACE_STD();
if (this->consumerSocket.IsClosed())
return;
std::string message = jsonMessage.dump();
if (message.length() > NsPayloadMaxLen)
{
MS_ERROR_STD("mesage too big");
return;
}
SendImpl(message.c_str(), message.length());
}
inline void UnixStreamSocket::SendImpl(const void* nsPayload, size_t nsPayloadLen)
{
MS_TRACE();
......@@ -99,23 +119,49 @@ namespace PayloadChannel
{
MS_TRACE();
if (!this->ongoingNotification)
if (!this->ongoingNotification && !this->ongoingRequest)
{
try
json jsonData = json::parse(msg, msg + msgLen);
if (Request::IsRequest(jsonData))
{
json jsonMessage = json::parse(msg, msg + msgLen);
this->ongoingNotification = new PayloadChannel::Notification(jsonMessage);
try
{
json jsonMessage = json::parse(msg, msg + msgLen);
this->ongoingRequest = new PayloadChannel::Request(this, jsonMessage);
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification");
}
}
catch (const json::parse_error& error)
else if (Notification::IsNotification(jsonData))
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
try
{
json jsonMessage = json::parse(msg, msg + msgLen);
this->ongoingNotification = new PayloadChannel::Notification(jsonMessage);
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification");
}
}
catch (const MediaSoupError& error)
else
{
MS_ERROR("discarding wrong Payload Channel notification");
MS_ERROR("discarding wrong Payload Channel data");
}
}
else
else if (this->ongoingNotification)
{
this->ongoingNotification->SetPayload(reinterpret_cast<const uint8_t*>(msg), msgLen);
......@@ -133,6 +179,28 @@ namespace PayloadChannel
delete this->ongoingNotification;
this->ongoingNotification = nullptr;
}
else if (this->ongoingRequest)
{
this->ongoingRequest->SetPayload(reinterpret_cast<const uint8_t*>(msg), msgLen);
// Notify the listener.
try
{
this->listener->OnPayloadChannelRequest(this, this->ongoingRequest);
}
catch (const MediaSoupTypeError& error)
{
this->ongoingRequest->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
this->ongoingRequest->Error(error.what());
}
// Delete the Request.
delete this->ongoingRequest;
this->ongoingRequest = nullptr;
}
}
void UnixStreamSocket::OnConsumerSocketClosed(ConsumerSocket* /*consumerSocket*/)
......
......@@ -5,6 +5,7 @@
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include "Channel/Notifier.hpp"
namespace RTC
......@@ -90,6 +91,12 @@ namespace RTC
// Add protocol.
jsonObject["protocol"] = this->protocol;
// Add bufferedAmount.
jsonObject["bufferedAmount"] = this->bufferedAmount;
// Add bufferedAmountLowThreshold.
jsonObject["bufferedAmountLowThreshold"] = this->bufferedAmountLowThreshold;
}
void DataConsumer::FillJsonStats(json& jsonArray) const
......@@ -146,6 +153,69 @@ namespace RTC
break;
}
case Channel::Request::MethodId::DATA_CONSUMER_SET_BUFFERED_AMOUNT_LOW_THRESHOLD:
{
auto jsonThresholdIt = request->data.find("threshold");
if (jsonThresholdIt == request->data.end() || !jsonThresholdIt->is_number_unsigned())
MS_THROW_TYPE_ERROR("wrong bufferedAmountThreshold (not an unsigned number)");
this->bufferedAmountLowThreshold = jsonThresholdIt->get<uint32_t>();
request->Accept();
break;
}
default:
{
MS_THROW_ERROR("unknown method '%s'", request->method.c_str());
}
}
}
void DataConsumer::HandleRequest(PayloadChannel::Request* request)
{
MS_TRACE();
switch (request->methodId)
{
case PayloadChannel::Request::MethodId::DATA_CONSUMER_SEND:
{
auto jsonPpidIt = request->data.find("ppid");
if (jsonPpidIt == request->data.end() || !Utils::Json::IsPositiveInteger(*jsonPpidIt))
{
MS_THROW_TYPE_ERROR("invalid ppid");
}
auto ppid = jsonPpidIt->get<uint32_t>();
const auto* msg = request->payload;
auto len = request->payloadLen;
if (len > this->maxMessageSize)
{
MS_WARN_TAG(
message,
"given message exceeds maxMessageSize value [maxMessageSize:%zu, len:%zu]",
len,
this->maxMessageSize);
return;
}
const auto* cb = new onQueuedCallback([&request](bool queued) {
if (queued)
request->Accept();
else
request->Error("message send failed");
});
SendMessage(ppid, msg, len, cb);
break;
}
default:
{
MS_THROW_ERROR("unknown method '%s'", request->method.c_str());
......@@ -189,6 +259,30 @@ namespace RTC
MS_DEBUG_DEV("SctpAssociation closed [dataConsumerId:%s]", this->id.c_str());
}
void DataConsumer::SctpAssociationBufferedAmount(uint32_t bufferedAmount)
{
MS_TRACE();
auto previousBufferedAmount = this->bufferedAmount;
this->bufferedAmount = bufferedAmount;
// clang-format off
if (
previousBufferedAmount > this->bufferedAmountLowThreshold &&
this->bufferedAmount <= this->bufferedAmountLowThreshold
)
// clang-format on
{
// Notify the Node DataConsumer.
json data = json::object();
data["bufferedAmount"] = this->bufferedAmount;
Channel::Notifier::Emit(this->id, "bufferedamountlow", data);
}
}
// The caller (Router) is supposed to proceed with the deletion of this DataConsumer
// right after calling this method. Otherwise ugly things may happen.
void DataConsumer::DataProducerClosed()
......@@ -204,7 +298,7 @@ namespace RTC
this->listener->OnDataConsumerDataProducerClosed(this);
}
void DataConsumer::SendMessage(uint32_t ppid, const uint8_t* msg, size_t len)
void DataConsumer::SendMessage(uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
......@@ -225,6 +319,6 @@ namespace RTC
this->messagesSent++;
this->bytesSent += len;
this->listener->OnDataConsumerSendMessage(this, ppid, msg, len);
this->listener->OnDataConsumerSendMessage(this, ppid, msg, len, cb);
}
} // namespace RTC
......@@ -144,7 +144,6 @@ namespace RTC
return;
}
// Pass the message to the DataProducer.
dataProducer->ReceiveMessage(ppid, msg, len);
// Increase receive transmission.
......@@ -224,7 +223,7 @@ namespace RTC
}
void DirectTransport::SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len)
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
......
......@@ -495,11 +495,11 @@ namespace RTC
}
void PipeTransport::SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len)
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
this->sctpAssociation->SendSctpMessage(dataConsumer, ppid, msg, len);
this->sctpAssociation->SendSctpMessage(dataConsumer, ppid, msg, len, cb);
}
void PipeTransport::SendSctpData(const uint8_t* data, size_t len)
......
......@@ -685,11 +685,11 @@ namespace RTC
}
void PlainTransport::SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len)
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
this->sctpAssociation->SendSctpMessage(dataConsumer, ppid, msg, len);
this->sctpAssociation->SendSctpMessage(dataConsumer, ppid, msg, len, cb);
}
void PlainTransport::SendSctpData(const uint8_t* data, size_t len)
......
......@@ -406,6 +406,16 @@ namespace RTC
}
}
void Router::HandleRequest(PayloadChannel::Request* request)
{
MS_TRACE();
// This may throw.
RTC::Transport* transport = GetTransportFromInternal(request->internal);
transport->HandleRequest(request);
}
void Router::HandleNotification(PayloadChannel::Notification* notification)
{
MS_TRACE();
......
......@@ -379,7 +379,7 @@ namespace RTC
}
void SctpAssociation::SendSctpMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len)
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
......@@ -428,10 +428,13 @@ namespace RTC
int ret = usrsctp_sendv(
this->socket, msg, len, nullptr, 0, &spa, static_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
if (ret == 0)
if (ret > 0)
{
// NOTE: 'usrsctp_sendv' returns the number of bytes sent.
// Don't decrese such value to sctpBufferedAmount since nothing is sent
// at this point.
this->sctpBufferedAmount += len;
this->listener->OnSctpAssociationBufferedAmount(this, this->sctpSendBufferSize);
this->listener->OnSctpAssociationBufferedAmount(this, this->sctpBufferedAmount);
}
if (ret < 0)
......@@ -443,9 +446,22 @@ namespace RTC
ppid,
len,
std::strerror(errno));
if (cb)
{
(*cb)(false);
delete cb;
}
}
else if (cb)
{
(*cb)(true);
delete cb;
}
if (ret == EWOULDBLOCK || ret == EAGAIN)
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
Channel::Notifier::Emit(dataConsumer->id, "sctpsendbufferfull");
}
......
......@@ -1459,6 +1459,54 @@ namespace RTC
break;
}
case Channel::Request::MethodId::DATA_CONSUMER_SET_BUFFERED_AMOUNT_LOW_THRESHOLD:
{
// This may throw.
RTC::DataConsumer* dataConsumer = GetDataConsumerFromInternal(request->internal);
if (dataConsumer->GetType() != RTC::DataConsumer::Type::SCTP)
{
MS_THROW_ERROR("invalid DataConsumer type");
}
dataConsumer->HandleRequest(request);
break;
}
default:
{
MS_THROW_ERROR("unknown method '%s'", request->method.c_str());
}
}
}
void Transport::HandleRequest(PayloadChannel::Request* request)
{
MS_TRACE();
switch (request->methodId)
{
case PayloadChannel::Request::MethodId::DATA_CONSUMER_SEND:
{
// This may throw.
RTC::DataConsumer* dataConsumer = GetDataConsumerFromInternal(request->internal);
if (dataConsumer->GetType() != RTC::DataConsumer::Type::SCTP)
{
MS_THROW_ERROR("invalid DataConsumer type");
}
if (!this->sctpAssociation)
{
MS_THROW_ERROR("no SCTP association present");
}
dataConsumer->HandleRequest(request);
break;
}
default:
{
MS_THROW_ERROR("unknown method '%s'", request->method.c_str());
......@@ -2666,11 +2714,11 @@ namespace RTC
}
inline void Transport::OnDataConsumerSendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len)
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
SendMessage(dataConsumer, ppid, msg, len);
SendMessage(dataConsumer, ppid, msg, len, cb);
}
inline void Transport::OnDataConsumerDataProducerClosed(RTC::DataConsumer* dataConsumer)
......@@ -2810,25 +2858,27 @@ namespace RTC
}
// Pass the SCTP message to the corresponding DataProducer.
dataProducer->ReceiveMessage(ppid, msg, len);
try
{
dataProducer->ReceiveMessage(ppid, msg, len);
}
catch (std::exception& error)
{
// Nothing to do.
}
}
inline void Transport::OnSctpAssociationBufferedAmount(
RTC::SctpAssociation* /*sctpAssociation*/, uint32_t len)
RTC::SctpAssociation* /*sctpAssociation*/, uint32_t bufferedAmount)
{
MS_TRACE();
// Notify the Node DataConsumers.
json data = json::object();
data["bufferedAmount"] = len;
for (const auto& kv : this->mapDataConsumers)
{
const auto* dataConsumer = kv.second;
auto* dataConsumer = kv.second;
if (dataConsumer->GetType() == RTC::DataConsumer::Type::SCTP)
Channel::Notifier::Emit(dataConsumer->id, "bufferedamount", data);
dataConsumer->SctpAssociationBufferedAmount(bufferedAmount);
}
}
......
......@@ -801,11 +801,11 @@ namespace RTC
}
void WebRtcTransport::SendMessage(
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len)
RTC::DataConsumer* dataConsumer, uint32_t ppid, const uint8_t* msg, size_t len, onQueuedCallback* cb)
{
MS_TRACE();
this->sctpAssociation->SendSctpMessage(dataConsumer, ppid, msg, len);
this->sctpAssociation->SendSctpMessage(dataConsumer, ppid, msg, len, cb);
}
void WebRtcTransport::SendSctpData(const uint8_t* data, size_t len)
......
......@@ -8,9 +8,6 @@
#include "Settings.hpp"
#include "Channel/Notifier.hpp"
// TODO: REMOVE
#include "PayloadChannel/Notifier.hpp"
/* Instance methods. */
Worker::Worker(::Channel::UnixStreamSocket* channel, PayloadChannel::UnixStreamSocket* payloadChannel)
......@@ -300,6 +297,22 @@ inline void Worker::OnPayloadChannelNotification(
router->HandleNotification(notification);
}
inline void Worker::OnPayloadChannelRequest(
PayloadChannel::UnixStreamSocket* /*payloadChannel*/, PayloadChannel::Request* request)
{
MS_TRACE();
MS_DEBUG_DEV(
"PayloadChannel request received [method:%s, id:%" PRIu32 "]",
request->method.c_str(),
request->id);
// This may throw.
RTC::Router* router = GetRouterFromInternal(request->internal);
router->HandleRequest(request);
}
inline void Worker::OnPayloadChannelClosed(PayloadChannel::UnixStreamSocket* /*payloadChannel*/)
{
MS_TRACE();
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论