提交 6a4f52d8 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Add room.createRtpStreamer()

上级 fb1385f8
# TODO in mediasoup v2 (server-side) # TODO in mediasoup v2 (server-side)
* `RtpStreamer` should have its own RTP capabilities rather than using the ones from the room.
* Instead of using `static_cast<size_t>(number)` use `size_t{ number }`. NOTE: Investigate it. * Instead of using `static_cast<size_t>(number)` use `size_t{ number }`. NOTE: Investigate it.
* Set a proper value for `Producer::FullFrameRequestBlockTimeout` (currently 1 second). * Set a proper value for `Producer::FullFrameRequestBlockTimeout` (currently 1 second).
......
...@@ -28,7 +28,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -28,7 +28,7 @@ class Consumer extends EnhancedEventEmitter
// Consumer data. // Consumer data.
// - .kind // - .kind
// - .peer // - .peer (just if this Consumer belongs to a Peer)
// - .transport // - .transport
// - .rtpParameters // - .rtpParameters
// - .source // - .source
...@@ -189,15 +189,19 @@ class Consumer extends EnhancedEventEmitter ...@@ -189,15 +189,19 @@ class Consumer extends EnhancedEventEmitter
this._closed = true; this._closed = true;
// Notify if it has a Peer.
if (this.hasPeer())
{
const data = const data =
{ {
id : this.id, id : this.id,
peerName : this.peer.name peerName : this.peer.name
}; };
// Don't notify `consumerClosed` if the Peer is already closed. // Don't notify 'consumerClosed' if the Peer is already closed.
if (!this.peer.closed) if (!this.peer.closed)
this.emit('@notify', 'consumerClosed', data); this.emit('@notify', 'consumerClosed', data);
}
this.emit('@close'); this.emit('@close');
this.safeEmit('close'); this.safeEmit('close');
...@@ -248,16 +252,31 @@ class Consumer extends EnhancedEventEmitter ...@@ -248,16 +252,31 @@ class Consumer extends EnhancedEventEmitter
toJson() toJson()
{ {
return { const json =
{
id : this.id, id : this.id,
kind : this.kind, kind : this.kind,
peerName : this.peer.name,
rtpParameters : this.rtpParameters, rtpParameters : this.rtpParameters,
paused : this.paused, paused : this.paused,
preferredProfile : this.preferredProfile, preferredProfile : this.preferredProfile,
effectiveProfile : this.effectiveProfile, effectiveProfile : this.effectiveProfile,
appData : this.appData appData : this.appData
}; };
if (this.hasPeer())
json.peerName = this.peer.name;
return json;
}
/**
* Whether this Consumer belongs to a Peer.
*
* @return {Boolean}
*/
hasPeer()
{
return Boolean(this.peer);
} }
/** /**
...@@ -340,6 +359,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -340,6 +359,9 @@ class Consumer extends EnhancedEventEmitter
this._locallyPaused = true; this._locallyPaused = true;
// Notify if it has a Peer.
if (this.hasPeer())
{
if (this.enabled && !this._sourcePaused) if (this.enabled && !this._sourcePaused)
{ {
const data = const data =
...@@ -351,6 +373,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -351,6 +373,7 @@ class Consumer extends EnhancedEventEmitter
this.emit('@notify', 'consumerPaused', data); this.emit('@notify', 'consumerPaused', data);
} }
}
this._channel.request('consumer.pause', this._internal) this._channel.request('consumer.pause', this._internal)
.then(() => .then(() =>
...@@ -422,6 +445,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -422,6 +445,9 @@ class Consumer extends EnhancedEventEmitter
this._locallyPaused = false; this._locallyPaused = false;
// Notify if it has a Peer.
if (this.hasPeer())
{
if (this.enabled && !this._sourcePaused) if (this.enabled && !this._sourcePaused)
{ {
const data = const data =
...@@ -433,6 +459,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -433,6 +459,7 @@ class Consumer extends EnhancedEventEmitter
this.emit('@notify', 'consumerResumed', data); this.emit('@notify', 'consumerResumed', data);
} }
}
if (!this._remotelyPaused) if (!this._remotelyPaused)
{ {
...@@ -522,6 +549,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -522,6 +549,9 @@ class Consumer extends EnhancedEventEmitter
this._preferredProfile = profile; this._preferredProfile = profile;
// Notify if it has a Peer.
if (this.hasPeer())
{
const data = const data =
{ {
id : this.id, id : this.id,
...@@ -530,6 +560,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -530,6 +560,7 @@ class Consumer extends EnhancedEventEmitter
}; };
this.emit('@notify', 'consumerPreferredProfileSet', data); this.emit('@notify', 'consumerPreferredProfileSet', data);
}
}) })
.catch((error) => .catch((error) =>
{ {
...@@ -588,6 +619,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -588,6 +619,9 @@ class Consumer extends EnhancedEventEmitter
this._sourcePaused = true; this._sourcePaused = true;
// Notify if it has a Peer.
if (this.hasPeer())
{
if (this.enabled && !this._locallyPaused) if (this.enabled && !this._locallyPaused)
{ {
const data2 = const data2 =
...@@ -598,6 +632,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -598,6 +632,7 @@ class Consumer extends EnhancedEventEmitter
this.emit('@notify', 'consumerPaused', data2); this.emit('@notify', 'consumerPaused', data2);
} }
}
this.safeEmit('pause', 'source'); this.safeEmit('pause', 'source');
...@@ -611,6 +646,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -611,6 +646,9 @@ class Consumer extends EnhancedEventEmitter
this._sourcePaused = false; this._sourcePaused = false;
// Notify if it has a Peer.
if (this.hasPeer())
{
if (this.enabled && !this._locallyPaused) if (this.enabled && !this._locallyPaused)
{ {
const data2 = const data2 =
...@@ -621,6 +659,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -621,6 +659,7 @@ class Consumer extends EnhancedEventEmitter
this.emit('@notify', 'consumerResumed', data2); this.emit('@notify', 'consumerResumed', data2);
} }
}
this.safeEmit('resume', 'source'); this.safeEmit('resume', 'source');
...@@ -636,6 +675,9 @@ class Consumer extends EnhancedEventEmitter ...@@ -636,6 +675,9 @@ class Consumer extends EnhancedEventEmitter
this._effectiveProfile = profile; this._effectiveProfile = profile;
// Notify if it has a Peer.
if (this.hasPeer())
{
if (this.enabled) if (this.enabled)
{ {
const data2 = const data2 =
...@@ -647,6 +689,7 @@ class Consumer extends EnhancedEventEmitter ...@@ -647,6 +689,7 @@ class Consumer extends EnhancedEventEmitter
this.emit('@notify', 'consumerEffectiveProfileChanged', data2); this.emit('@notify', 'consumerEffectiveProfileChanged', data2);
} }
}
this.safeEmit('effectiveprofilechange', this._effectiveProfile); this.safeEmit('effectiveprofilechange', this._effectiveProfile);
......
...@@ -334,7 +334,7 @@ class Peer extends EnhancedEventEmitter ...@@ -334,7 +334,7 @@ class Peer extends EnhancedEventEmitter
appData appData
} = request; } = request;
return this._createTransport(id, direction, options, appData) return this._createWebRtcTransport(id, direction, options, appData)
.then((transport) => .then((transport) =>
{ {
// If no client's DTLS parameters are given, we are done. // If no client's DTLS parameters are given, we are done.
...@@ -690,9 +690,9 @@ class Peer extends EnhancedEventEmitter ...@@ -690,9 +690,9 @@ class Peer extends EnhancedEventEmitter
this.safeEmit('notify', notification); this.safeEmit('notify', notification);
} }
_createTransport(id, direction, options, appData) _createWebRtcTransport(id, direction, options, appData)
{ {
logger.debug('_createTransport() [id:%s, direction:%s]', id, direction); logger.debug('_createWebRtcTransport() [id:%s, direction:%s]', id, direction);
const internal = const internal =
{ {
......
'use strict';
const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const errors = require('./errors');
const logger = new Logger('PlainRtpTransport');
class PlainRtpTransport extends EnhancedEventEmitter
{
constructor(internal, data, channel)
{
super(logger);
logger.debug('constructor()');
// Closed flag.
this._closed = false;
// Internal data.
// - .routerId
// - .transportId
this._internal = internal;
// PlainRtpTransport data provided by the worker.
// - .tuple
// - .local
// - .ip
// - .port
// - .protocol
// - .remote
// - .ip
// - .port
// - .protocol
this._data = data;
// Channel instance.
this._channel = channel;
this._handleWorkerNotifications();
}
get id()
{
return this._internal.transportId;
}
get closed()
{
return this._closed;
}
get tuple()
{
return this._data.tuple;
}
/**
* Close the PlainRtpTransport.
*
* @param {Boolean} [notifyChannel=true] - Private.
*/
close(notifyChannel = true)
{
logger.debug('close()');
if (this._closed)
return;
this._closed = true;
this.emit('@close');
// Remove notification subscriptions.
this._channel.removeAllListeners(this._internal.transportId);
if (notifyChannel)
{
this._channel.request('transport.close', this._internal)
.then(() =>
{
logger.debug('"transport.close" request succeeded');
})
.catch((error) =>
{
logger.error('"transport.close" request failed: %s', String(error));
});
}
}
/**
* Dump the PlainRtpTransport.
*
* @return {Promise}
*/
dump()
{
logger.debug('dump()');
if (this._closed)
return Promise.reject(new errors.InvalidStateError('PlainRtpTransport closed'));
return this._channel.request('transport.dump', this._internal)
.then((data) =>
{
logger.debug('"transport.dump" request succeeded');
return data;
})
.catch((error) =>
{
logger.error('"transport.dump" request failed: %s', String(error));
throw error;
});
}
_handleWorkerNotifications()
{
// Subscribe to notifications.
this._channel.on(this._internal.transportId, (event) =>
{
switch (event)
{
case 'close':
{
this.close(false);
break;
}
default:
logger.error('ignoring unknown event "%s"', event);
}
});
}
}
module.exports = PlainRtpTransport;
...@@ -2,9 +2,13 @@ ...@@ -2,9 +2,13 @@
const Logger = require('./Logger'); const Logger = require('./Logger');
const EnhancedEventEmitter = require('./EnhancedEventEmitter'); const EnhancedEventEmitter = require('./EnhancedEventEmitter');
const utils = require('./utils');
const errors = require('./errors'); const errors = require('./errors');
const ortc = require('./ortc'); const ortc = require('./ortc');
const Peer = require('./Peer'); const Peer = require('./Peer');
const Consumer = require('./Consumer');
const PlainRtpTransport = require('./PlainRtpTransport');
const plugins = require('./plugins');
const logger = new Logger('Room'); const logger = new Logger('Room');
...@@ -212,6 +216,89 @@ class Room extends EnhancedEventEmitter ...@@ -212,6 +216,89 @@ class Room extends EnhancedEventEmitter
}); });
} }
createActiveSpeakerDetector()
{
logger.debug('createActiveSpeakerDetector()');
const activeSpeakerDetector = new plugins.ActiveSpeakerDetector(this);
return activeSpeakerDetector;
}
createRtpStreamer(producer, options)
{
logger.debug('createRtpStreamer()');
if (!this._producers.has(producer.id))
return Promise.reject(new Error('Producer not found'));
let plainRtpTransport;
let consumer;
return Promise.resolve()
// Create a PlainRtpTransport in the worker.
.then(() =>
{
return this._createPlainRtpTransport(options)
.then((transport) =>
{
plainRtpTransport = transport;
});
})
// Create a Consumer.
.then(() =>
{
const internal =
{
routerId : this._internal.routerId,
consumerId : utils.randomNumber(),
producerId : producer.id,
transportId : undefined
};
// TODO: The app should provide his own RTP capabilities.
const consumerRtpParameters =
ortc.getConsumerRtpParameters(
producer.consumableRtpParameters, this.rtpCapabilities);
const data =
{
kind : producer.kind,
transport : undefined,
rtpParameters : consumerRtpParameters,
source : producer
};
// Create a Consumer instance.
consumer = new Consumer(internal, data, this._channel);
return this._channel.request('router.createConsumer', internal,
{
kind : consumer.kind
})
.then(() =>
{
logger.debug('"router.createConsumer" request succeeded');
})
.catch((error) =>
{
logger.error('"router.createConsumer" request failed: %s', String(error));
throw error;
});
})
.then(() =>
{
return consumer.enable(plainRtpTransport);
})
.then(() =>
{
const rtpStreamer = new plugins.RtpStreamer(consumer, plainRtpTransport);
return rtpStreamer;
});
}
_createPeer(peerName, rtpCapabilities, appData) _createPeer(peerName, rtpCapabilities, appData)
{ {
logger.debug('_createPeer() [peerName:"%s]', peerName); logger.debug('_createPeer() [peerName:"%s]', peerName);
...@@ -322,6 +409,35 @@ class Room extends EnhancedEventEmitter ...@@ -322,6 +409,35 @@ class Room extends EnhancedEventEmitter
} }
} }
_createPlainRtpTransport(options)
{
logger.debug('_createPlainRtpTransport()');
const internal =
{
routerId : this._internal.routerId,
transportId : utils.randomNumber()
};
return this._channel.request('router.createPlainRtpTransport', internal, options)
.then((data) =>
{
logger.debug('"router.createPlainRtpTransport" request succeeded');
// Create a PlainRtpTransport.
const transport = new PlainRtpTransport(internal, data, this._channel);
return transport;
})
.catch((error) =>
{
logger.error(
'"router.createPlainRtpTransport" request failed: %s', String(error));
throw error;
});
}
_handleWorkerNotifications() _handleWorkerNotifications()
{ {
// Subscribe to notifications. // Subscribe to notifications.
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
const Logger = require('./Logger'); const Logger = require('./Logger');
const Server = require('./Server'); const Server = require('./Server');
const errors = require('./errors'); const errors = require('./errors');
const plugins = require('./plugins');
const PKG = require('../package.json'); const PKG = require('../package.json');
const logger = new Logger(); const logger = new Logger();
...@@ -54,11 +53,6 @@ exports.Server = function(options) ...@@ -54,11 +53,6 @@ exports.Server = function(options)
*/ */
exports.errors = errors; exports.errors = errors;
/**
* Export plugins.
*/
exports.plugins = plugins;
// On process exit close all the Servers. // On process exit close all the Servers.
process.on('exit', () => process.on('exit', () =>
{ {
......
'use strict';
const Logger = require('../Logger');
const EnhancedEventEmitter = require('../EnhancedEventEmitter');
const logger = new Logger('RtpStreamer');
class RtpStreamer extends EnhancedEventEmitter
{
constructor(consumer, transport)
{
super(logger);
logger.debug('constructor()');
// Closed flag.
// @type {Boolean}
this._closed = false;
// Associated Consumer.
// @type {Consumer}
this._consumer = consumer;
// Associated PlainRtpTransport.
// @type {PlainRtpTransport}
this._transport = transport;
this._handleConsumer();
this._handleTransport();
}
get consumer()
{
return this._consumer;
}
get transport()
{
return this._transport;
}
close()
{
logger.debug('close()');
if (this._closed)
return;
this._closed = true;
if (!this._consumer.closed)
this._consumer.close();
if (!this._transport.closed)
this._transport.close();
this.emit('close');
}
_handleConsumer()
{
this._consumer.on('@close', () =>
{
if (!this._closed)
this.close();
});
}
_handleTransport()
{
this._transport.on('@close', () =>
{
if (!this._closed)
this.close();
});
}
}
module.exports = RtpStreamer;
const ActiveSpeakerDetector = require('./ActiveSpeakerDetector'); const ActiveSpeakerDetector = require('./ActiveSpeakerDetector');
const RtpStreamer = require('./RtpStreamer');
exports.ActiveSpeakerDetector = ActiveSpeakerDetector; exports.ActiveSpeakerDetector = ActiveSpeakerDetector;
exports.RtpStreamer = RtpStreamer;
...@@ -69,6 +69,11 @@ ...@@ -69,6 +69,11 @@
"directory": "PATH/worker/out", "directory": "PATH/worker/out",
"file": "PATH/worker/src/RTC/NackGenerator.cpp" "file": "PATH/worker/src/RTC/NackGenerator.cpp"
}, },
{
"command": "c++ -c -DMS_LITTLE_ENDIAN -D_POSIX_C_SOURCE=200112 -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_INT16_T -DHAVE_INT32_T -DHAVE_INT8_T -DHAVE_UINT16_T -DHAVE_UINT32_T -DHAVE_UINT64_T -DHAVE_UINT8_T -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -DCPU_CISC -I../include -I../deps/jsoncpp/jsoncpp/bundled -I../deps/netstring/netstring-c -I../deps/libuv/include -I../deps/openssl/openssl/include -I../deps/libsrtp/srtp/include -std=c++11 -Wall -Wextra -Wno-unused-parameter -m64 -g -o PATH/worker/out/Release/obj.target/mediasoup-worker/src/RTC/PlainRtpTransport.o ../src/RTC/PlainRtpTransport.cpp",
"directory": "PATH/worker/out",
"file": "PATH/worker/src/RTC/PlainRtpTransport.cpp"
},
{ {
"command": "c++ -c -DMS_LITTLE_ENDIAN -D_POSIX_C_SOURCE=200112 -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_INT16_T -DHAVE_INT32_T -DHAVE_INT8_T -DHAVE_UINT16_T -DHAVE_UINT32_T -DHAVE_UINT64_T -DHAVE_UINT8_T -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -DCPU_CISC -I../include -I../deps/jsoncpp/jsoncpp/bundled -I../deps/netstring/netstring-c -I../deps/libuv/include -I../deps/openssl/openssl/include -I../deps/libsrtp/srtp/include -std=c++11 -Wall -Wextra -Wno-unused-parameter -m64 -g -o PATH/worker/out/Release/obj.target/mediasoup-worker/src/RTC/Producer.o ../src/RTC/Producer.cpp", "command": "c++ -c -DMS_LITTLE_ENDIAN -D_POSIX_C_SOURCE=200112 -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_INT16_T -DHAVE_INT32_T -DHAVE_INT8_T -DHAVE_UINT16_T -DHAVE_UINT32_T -DHAVE_UINT64_T -DHAVE_UINT8_T -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -DCPU_CISC -I../include -I../deps/jsoncpp/jsoncpp/bundled -I../deps/netstring/netstring-c -I../deps/libuv/include -I../deps/openssl/openssl/include -I../deps/libsrtp/srtp/include -std=c++11 -Wall -Wextra -Wno-unused-parameter -m64 -g -o PATH/worker/out/Release/obj.target/mediasoup-worker/src/RTC/Producer.o ../src/RTC/Producer.cpp",
"directory": "PATH/worker/out", "directory": "PATH/worker/out",
...@@ -144,6 +149,11 @@ ...@@ -144,6 +149,11 @@
"directory": "PATH/worker/out", "directory": "PATH/worker/out",
"file": "PATH/worker/src/RTC/UdpSocket.cpp" "file": "PATH/worker/src/RTC/UdpSocket.cpp"
}, },
{
"command": "c++ -c -DMS_LITTLE_ENDIAN -D_POSIX_C_SOURCE=200112 -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_INT16_T -DHAVE_INT32_T -DHAVE_INT8_T -DHAVE_UINT16_T -DHAVE_UINT32_T -DHAVE_UINT64_T -DHAVE_UINT8_T -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -DCPU_CISC -I../include -I../deps/jsoncpp/jsoncpp/bundled -I../deps/netstring/netstring-c -I../deps/libuv/include -I../deps/openssl/openssl/include -I../deps/libsrtp/srtp/include -std=c++11 -Wall -Wextra -Wno-unused-parameter -m64 -g -o PATH/worker/out/Release/obj.target/mediasoup-worker/src/RTC/WebRtcTransport.o ../src/RTC/WebRtcTransport.cpp",
"directory": "PATH/worker/out",
"file": "PATH/worker/src/RTC/WebRtcTransport.cpp"
},
{ {
"command": "c++ -c -DMS_LITTLE_ENDIAN -D_POSIX_C_SOURCE=200112 -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_INT16_T -DHAVE_INT32_T -DHAVE_INT8_T -DHAVE_UINT16_T -DHAVE_UINT32_T -DHAVE_UINT64_T -DHAVE_UINT8_T -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -DCPU_CISC -I../include -I../deps/jsoncpp/jsoncpp/bundled -I../deps/netstring/netstring-c -I../deps/libuv/include -I../deps/openssl/openssl/include -I../deps/libsrtp/srtp/include -std=c++11 -Wall -Wextra -Wno-unused-parameter -m64 -g -o PATH/worker/out/Release/obj.target/mediasoup-worker/src/RTC/RtpDictionaries/Media.o ../src/RTC/RtpDictionaries/Media.cpp", "command": "c++ -c -DMS_LITTLE_ENDIAN -D_POSIX_C_SOURCE=200112 -D_GNU_SOURCE -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_INT16_T -DHAVE_INT32_T -DHAVE_INT8_T -DHAVE_UINT16_T -DHAVE_UINT32_T -DHAVE_UINT64_T -DHAVE_UINT8_T -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -DCPU_CISC -I../include -I../deps/jsoncpp/jsoncpp/bundled -I../deps/netstring/netstring-c -I../deps/libuv/include -I../deps/openssl/openssl/include -I../deps/libsrtp/srtp/include -std=c++11 -Wall -Wextra -Wno-unused-parameter -m64 -g -o PATH/worker/out/Release/obj.target/mediasoup-worker/src/RTC/RtpDictionaries/Media.o ../src/RTC/RtpDictionaries/Media.cpp",
"directory": "PATH/worker/out", "directory": "PATH/worker/out",
......
...@@ -23,6 +23,7 @@ namespace Channel ...@@ -23,6 +23,7 @@ namespace Channel
ROUTER_CLOSE, ROUTER_CLOSE,
ROUTER_DUMP, ROUTER_DUMP,
ROUTER_CREATE_WEBRTC_TRANSPORT, ROUTER_CREATE_WEBRTC_TRANSPORT,
ROUTER_CREATE_PLAIN_RTP_TRANSPORT,
ROUTER_CREATE_PRODUCER, ROUTER_CREATE_PRODUCER,
ROUTER_CREATE_CONSUMER, ROUTER_CREATE_CONSUMER,
ROUTER_SET_AUDIO_LEVELS_EVENT, ROUTER_SET_AUDIO_LEVELS_EVENT,
......
#ifndef MS_RTC_PLAIN_RTPWEBRTC_TRANSPORT_HPP
#define MS_RTC_PLAIN_RTPWEBRTC_TRANSPORT_HPP
#include "common.hpp"
#include "Channel/Notifier.hpp"
#include "RTC/Transport.hpp"
#include "RTC/TransportTuple.hpp"
#include "RTC/UdpSocket.hpp"
#include <json/json.h>
#include <string>
namespace RTC
{
class PlainRtpTransport : public RTC::Transport, public RTC::UdpSocket::Listener
{
public:
struct TransportOptions
{
std::string remoteIP;
uint16_t remotePort;
};
public:
PlainRtpTransport(
RTC::Transport::Listener* listener,
Channel::Notifier* notifier,
uint32_t transportId,
TransportOptions& options);
private:
~PlainRtpTransport();
public:
Json::Value ToJson() const override;
void SendRtpPacket(RTC::RtpPacket* packet) override;
void SendRtcpPacket(RTC::RTCP::Packet* packet) override;
private:
bool IsConnected() const override;
void SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet) override;
/* Private methods to unify UDP and TCP behavior. */
private:
void OnPacketRecv(RTC::TransportTuple* tuple, const uint8_t* data, size_t len);
void OnRtpDataRecv(RTC::TransportTuple* tuple, const uint8_t* data, size_t len);
void OnRtcpDataRecv(RTC::TransportTuple* tuple, const uint8_t* data, size_t len);
/* Pure virtual methods inherited from RTC::UdpSocket::Listener. */
public:
void OnPacketRecv(
RTC::UdpSocket* socket, const uint8_t* data, size_t len, const struct sockaddr* remoteAddr) override;
private:
// Allocated by this.
RTC::UdpSocket* udpSocket{ nullptr };
RTC::TransportTuple* tuple{ nullptr };
// Others.
struct sockaddr_storage remoteAddrStorage;
};
} // namespace RTC
#endif
...@@ -35,9 +35,9 @@ namespace RTC ...@@ -35,9 +35,9 @@ namespace RTC
// Passed by argument. // Passed by argument.
RTC::UdpSocket* udpSocket{ nullptr }; RTC::UdpSocket* udpSocket{ nullptr };
struct sockaddr* udpRemoteAddr{ nullptr }; struct sockaddr* udpRemoteAddr{ nullptr };
sockaddr_storage udpRemoteAddrStorage;
RTC::TcpConnection* tcpConnection{ nullptr }; RTC::TcpConnection* tcpConnection{ nullptr };
// Others. // Others.
struct sockaddr_storage udpRemoteAddrStorage;
Protocol protocol; Protocol protocol;
}; };
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
'src/RTC/IceCandidate.cpp', 'src/RTC/IceCandidate.cpp',
'src/RTC/IceServer.cpp', 'src/RTC/IceServer.cpp',
'src/RTC/NackGenerator.cpp', 'src/RTC/NackGenerator.cpp',
'src/RTC/PlainRtpTransport.cpp',
'src/RTC/Producer.cpp', 'src/RTC/Producer.cpp',
'src/RTC/Router.cpp', 'src/RTC/Router.cpp',
'src/RTC/RtpListener.cpp', 'src/RTC/RtpListener.cpp',
...@@ -115,6 +116,7 @@ ...@@ -115,6 +116,7 @@
'include/RTC/IceServer.hpp', 'include/RTC/IceServer.hpp',
'include/RTC/NackGenerator.hpp', 'include/RTC/NackGenerator.hpp',
'include/RTC/Parameters.hpp', 'include/RTC/Parameters.hpp',
'include/RTC/PlainRtpTransport.hpp',
'include/RTC/Producer.hpp', 'include/RTC/Producer.hpp',
'include/RTC/ProducerListener.hpp', 'include/RTC/ProducerListener.hpp',
'include/RTC/Router.hpp', 'include/RTC/Router.hpp',
......
...@@ -18,6 +18,7 @@ namespace Channel ...@@ -18,6 +18,7 @@ namespace Channel
{ "router.close", Request::MethodId::ROUTER_CLOSE }, { "router.close", Request::MethodId::ROUTER_CLOSE },
{ "router.dump", Request::MethodId::ROUTER_DUMP }, { "router.dump", Request::MethodId::ROUTER_DUMP },
{ "router.createWebRtcTransport", Request::MethodId::ROUTER_CREATE_WEBRTC_TRANSPORT }, { "router.createWebRtcTransport", Request::MethodId::ROUTER_CREATE_WEBRTC_TRANSPORT },
{ "router.createPlainRtpTransport", Request::MethodId::ROUTER_CREATE_PLAIN_RTP_TRANSPORT },
{ "router.createProducer", Request::MethodId::ROUTER_CREATE_PRODUCER }, { "router.createProducer", Request::MethodId::ROUTER_CREATE_PRODUCER },
{ "router.createConsumer", Request::MethodId::ROUTER_CREATE_CONSUMER }, { "router.createConsumer", Request::MethodId::ROUTER_CREATE_CONSUMER },
{ "router.setAudioLevelsEvent", Request::MethodId::ROUTER_SET_AUDIO_LEVELS_EVENT }, { "router.setAudioLevelsEvent", Request::MethodId::ROUTER_SET_AUDIO_LEVELS_EVENT },
......
#define MS_CLASS "RTC::PlainRtpTransport"
// #define MS_LOG_DEV
#include "RTC/PlainRtpTransport.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupError.hpp"
#include "Settings.hpp"
#include "Utils.hpp"
#include "RTC/Consumer.hpp"
#include "RTC/Producer.hpp"
namespace RTC
{
/* Instance methods. */
PlainRtpTransport::PlainRtpTransport(
RTC::Transport::Listener* listener,
Channel::Notifier* notifier,
uint32_t transportId,
TransportOptions& options)
: RTC::Transport::Transport(listener, notifier, transportId)
{
MS_TRACE();
int err;
switch (Utils::IP::GetFamily(options.remoteIP))
{
case AF_INET:
{
if (!Settings::configuration.hasIPv4)
MS_THROW_ERROR("IPv4 disabled");
err = uv_ip4_addr(
options.remoteIP.c_str(),
static_cast<int>(options.remotePort),
reinterpret_cast<struct sockaddr_in*>(&this->remoteAddrStorage));
if (err != 0)
MS_ABORT("uv_ipv4_addr() failed: %s", uv_strerror(err));
this->udpSocket = new RTC::UdpSocket(this, AF_INET);
break;
}
case AF_INET6:
{
if (!Settings::configuration.hasIPv6)
MS_THROW_ERROR("IPv6 disabled");
err = uv_ip6_addr(
options.remoteIP.c_str(),
static_cast<int>(options.remotePort),
reinterpret_cast<struct sockaddr_in6*>(&this->remoteAddrStorage));
if (err != 0)
MS_ABORT("uv_ipv6_addr() failed: %s", uv_strerror(err));
this->udpSocket = new RTC::UdpSocket(this, AF_INET6);
break;
}
default:
{
MS_THROW_ERROR("invalid destination IP '%s'", options.remoteIP.c_str());
break;
}
}
this->tuple = new RTC::TransportTuple(
this->udpSocket, reinterpret_cast<struct sockaddr*>(&this->remoteAddrStorage));
}
PlainRtpTransport::~PlainRtpTransport()
{
MS_TRACE();
delete this->tuple;
if (this->udpSocket)
this->udpSocket->Destroy();
}
Json::Value PlainRtpTransport::ToJson() const
{
MS_TRACE();
static const Json::StaticString JsonStringTransportId{ "transportId" };
static const Json::StaticString JsonStringTuple{ "tuple" };
static const Json::StaticString JsonStringRtpListener{ "rtpListener" };
Json::Value json(Json::objectValue);
// Add transportId.
json[JsonStringTransportId] = Json::UInt{ this->transportId };
// Add tuple.
if (this->tuple != nullptr)
json[JsonStringTuple] = this->tuple->ToJson();
// Add rtpListener.
json[JsonStringRtpListener] = this->rtpListener.ToJson();
return json;
}
void PlainRtpTransport::SendRtpPacket(RTC::RtpPacket* packet)
{
MS_TRACE();
if (!IsConnected())
return;
const uint8_t* data = packet->GetData();
size_t len = packet->GetSize();
this->tuple->Send(data, len);
}
void PlainRtpTransport::SendRtcpPacket(RTC::RTCP::Packet* packet)
{
MS_TRACE();
if (!IsConnected())
return;
const uint8_t* data = packet->GetData();
size_t len = packet->GetSize();
this->tuple->Send(data, len);
}
bool PlainRtpTransport::IsConnected() const
{
return true;
}
void PlainRtpTransport::SendRtcpCompoundPacket(RTC::RTCP::CompoundPacket* packet)
{
MS_TRACE();
if (!IsConnected())
return;
const uint8_t* data = packet->GetData();
size_t len = packet->GetSize();
this->tuple->Send(data, len);
}
inline void PlainRtpTransport::OnPacketRecv(RTC::TransportTuple* tuple, const uint8_t* data, size_t len)
{
MS_TRACE();
// Check if it's RTCP.
if (RTCP::Packet::IsRtcp(data, len))
{
OnRtcpDataRecv(tuple, data, len);
}
// Check if it's RTP.
else if (RtpPacket::IsRtp(data, len))
{
OnRtpDataRecv(tuple, data, len);
}
else
{
MS_WARN_DEV("ignoring received packet of unknown type");
}
}
inline void PlainRtpTransport::OnRtpDataRecv(RTC::TransportTuple* tuple, const uint8_t* data, size_t len)
{
MS_TRACE();
RTC::RtpPacket* packet = RTC::RtpPacket::Parse(data, len);
if (packet == nullptr)
{
MS_WARN_TAG(rtp, "received data is not a valid RTP packet");
return;
}
// Apply the Transport RTP header extension ids so the RTP listener can use them.
if (this->headerExtensionIds.rid != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::RTP_STREAM_ID, this->headerExtensionIds.rid);
}
// Get the associated Producer.
RTC::Producer* producer = this->rtpListener.GetProducer(packet);
if (producer == nullptr)
{
MS_WARN_TAG(
rtp,
"no suitable Producer for received RTP packet [ssrc:%" PRIu32 ", payloadType:%" PRIu8 "]",
packet->GetSsrc(),
packet->GetPayloadType());
delete packet;
return;
}
MS_DEBUG_DEV(
"RTP packet received [ssrc:%" PRIu32 ", payloadType:%" PRIu8 ", producer:%" PRIu32 "]",
packet->GetSsrc(),
packet->GetPayloadType(),
producer->producerId);
// Pass the RTP packet to the corresponding Producer.
producer->ReceiveRtpPacket(packet);
delete packet;
}
inline void PlainRtpTransport::OnRtcpDataRecv(
RTC::TransportTuple* tuple, const uint8_t* data, size_t len)
{
MS_TRACE();
RTC::RTCP::Packet* packet = RTC::RTCP::Packet::Parse(data, len);
if (packet == nullptr)
{
MS_WARN_TAG(rtcp, "received data is not a valid RTCP compound or single packet");
return;
}
// Handle each RTCP packet.
while (packet != nullptr)
{
HandleRtcpPacket(packet);
RTC::RTCP::Packet* previousPacket = packet;
packet = packet->GetNext();
delete previousPacket;
}
}
void PlainRtpTransport::OnPacketRecv(
RTC::UdpSocket* socket, const uint8_t* data, size_t len, const struct sockaddr* remoteAddr)
{
MS_TRACE();
RTC::TransportTuple tuple(socket, remoteAddr);
OnPacketRecv(&tuple, data, len);
}
} // namespace RTC
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
#include "Logger.hpp" #include "Logger.hpp"
#include "MediaSoupError.hpp" #include "MediaSoupError.hpp"
#include "Utils.hpp" #include "Utils.hpp"
#include "RTC/PlainRtpTransport.hpp"
#include "RTC/RtpDictionaries.hpp" #include "RTC/RtpDictionaries.hpp"
#include "RTC/WebRtcTransport.hpp" #include "RTC/WebRtcTransport.hpp"
#include <cmath> // std::lround() #include <cmath> // std::lround()
...@@ -235,6 +236,61 @@ namespace RTC ...@@ -235,6 +236,61 @@ namespace RTC
break; break;
} }
case Channel::Request::MethodId::ROUTER_CREATE_PLAIN_RTP_TRANSPORT:
{
static const Json::StaticString JsonStringRemoteIP{ "remoteIP" };
static const Json::StaticString JsonStringRemotePort{ "remotePort" };
uint32_t transportId;
try
{
transportId = GetNewTransportIdFromRequest(request);
}
catch (const MediaSoupError& error)
{
request->Reject(error.what());
return;
}
RTC::PlainRtpTransport::TransportOptions options;
if (!request->data[JsonStringRemoteIP].isString())
MS_THROW_ERROR("missing remoteIP");
options.remoteIP = request->data[JsonStringRemoteIP].asString();
if (!request->data[JsonStringRemotePort].isUInt())
MS_THROW_ERROR("missing remotePort");
options.remotePort = request->data[JsonStringRemotePort].asUInt();
RTC::PlainRtpTransport* plainRtpTransport;
try
{
// NOTE: This may throw.
plainRtpTransport = new RTC::PlainRtpTransport(this, this->notifier, transportId, options);
}
catch (const MediaSoupError& error)
{
request->Reject(error.what());
return;
}
// Insert into the map.
this->transports[transportId] = plainRtpTransport;
MS_DEBUG_DEV("PlainRtpTransport created [transportId:%" PRIu32 "]", transportId);
auto data = plainRtpTransport->ToJson();
request->Accept(data);
break;
}
case Channel::Request::MethodId::ROUTER_CREATE_PRODUCER: case Channel::Request::MethodId::ROUTER_CREATE_PRODUCER:
{ {
static const Json::StaticString JsonStringKind{ "kind" }; static const Json::StaticString JsonStringKind{ "kind" };
......
...@@ -15,33 +15,28 @@ ...@@ -15,33 +15,28 @@
#include <iterator> // std::ostream_iterator #include <iterator> // std::ostream_iterator
#include <sstream> // std::ostringstream #include <sstream> // std::ostringstream
/* Consts. */
static constexpr uint16_t IceCandidateDefaultLocalPriority{ 20000 };
static constexpr uint16_t IceCandidateLocalPriorityPreferFamilyIncrement{ 10000 };
static constexpr uint16_t IceCandidateLocalPriorityPreferProtocolIncrement{ 5000 };
// We just provide "host" candidates so type preference is fixed.
static constexpr uint16_t IceTypePreference{ 64 };
// We do not support non rtcp-mux so component is always 1.
static constexpr uint16_t IceComponent{ 1 };
/* Static helpers. */
static inline uint32_t generateIceCandidatePriority(uint16_t localPreference)
{
MS_TRACE();
return std::pow(2, 24) * IceTypePreference + std::pow(2, 8) * localPreference +
std::pow(2, 0) * (256 - IceComponent);
}
namespace RTC namespace RTC
{ {
/* Static. */ /* Static. */
static constexpr uint16_t IceCandidateDefaultLocalPriority{ 20000 };
static constexpr uint16_t IceCandidateLocalPriorityPreferFamilyIncrement{ 10000 };
static constexpr uint16_t IceCandidateLocalPriorityPreferProtocolIncrement{ 5000 };
// We just provide "host" candidates so type preference is fixed.
static constexpr uint16_t IceTypePreference{ 64 };
// We do not support non rtcp-mux so component is always 1.
static constexpr uint16_t IceComponent{ 1 };
static constexpr uint64_t EffectiveMaxBitrateCheckInterval{ 2000 }; // In ms. static constexpr uint64_t EffectiveMaxBitrateCheckInterval{ 2000 }; // In ms.
static constexpr double EffectiveMaxBitrateThresholdBeforeKeyFrame{ 0.6 }; // 0.0 - 1.0. static constexpr double EffectiveMaxBitrateThresholdBeforeKeyFrame{ 0.6 }; // 0.0 - 1.0.
static inline uint32_t generateIceCandidatePriority(uint16_t localPreference)
{
MS_TRACE();
return std::pow(2, 24) * IceTypePreference + std::pow(2, 8) * localPreference +
std::pow(2, 0) * (256 - IceComponent);
}
/* Instance methods. */ /* Instance methods. */
WebRtcTransport::WebRtcTransport( WebRtcTransport::WebRtcTransport(
...@@ -76,7 +71,7 @@ namespace RTC ...@@ -76,7 +71,7 @@ namespace RTC
try try
{ {
auto udpSocket = new RTC::UdpSocket(this, AF_INET); auto* udpSocket = new RTC::UdpSocket(this, AF_INET);
RTC::IceCandidate iceCandidate(udpSocket, priority); RTC::IceCandidate iceCandidate(udpSocket, priority);
this->udpSockets.push_back(udpSocket); this->udpSockets.push_back(udpSocket);
...@@ -102,7 +97,7 @@ namespace RTC ...@@ -102,7 +97,7 @@ namespace RTC
try try
{ {
auto udpSocket = new RTC::UdpSocket(this, AF_INET6); auto* udpSocket = new RTC::UdpSocket(this, AF_INET6);
RTC::IceCandidate iceCandidate(udpSocket, priority); RTC::IceCandidate iceCandidate(udpSocket, priority);
this->udpSockets.push_back(udpSocket); this->udpSockets.push_back(udpSocket);
...@@ -128,7 +123,7 @@ namespace RTC ...@@ -128,7 +123,7 @@ namespace RTC
try try
{ {
auto tcpServer = new RTC::TcpServer(this, this, AF_INET); auto* tcpServer = new RTC::TcpServer(this, this, AF_INET);
RTC::IceCandidate iceCandidate(tcpServer, priority); RTC::IceCandidate iceCandidate(tcpServer, priority);
this->tcpServers.push_back(tcpServer); this->tcpServers.push_back(tcpServer);
...@@ -154,7 +149,7 @@ namespace RTC ...@@ -154,7 +149,7 @@ namespace RTC
try try
{ {
auto tcpServer = new RTC::TcpServer(this, this, AF_INET6); auto* tcpServer = new RTC::TcpServer(this, this, AF_INET6);
RTC::IceCandidate iceCandidate(tcpServer, priority); RTC::IceCandidate iceCandidate(tcpServer, priority);
this->tcpServers.push_back(tcpServer); this->tcpServers.push_back(tcpServer);
...@@ -200,13 +195,13 @@ namespace RTC ...@@ -200,13 +195,13 @@ namespace RTC
if (this->iceServer != nullptr) if (this->iceServer != nullptr)
this->iceServer->Destroy(); this->iceServer->Destroy();
for (auto socket : this->udpSockets) for (auto* socket : this->udpSockets)
{ {
socket->Destroy(); socket->Destroy();
} }
this->udpSockets.clear(); this->udpSockets.clear();
for (auto server : this->tcpServers) for (auto* server : this->tcpServers)
{ {
server->Destroy(); server->Destroy();
} }
......
...@@ -239,6 +239,7 @@ void Worker::OnChannelRequest(Channel::UnixStreamSocket* /*channel*/, Channel::R ...@@ -239,6 +239,7 @@ void Worker::OnChannelRequest(Channel::UnixStreamSocket* /*channel*/, Channel::R
case Channel::Request::MethodId::ROUTER_DUMP: case Channel::Request::MethodId::ROUTER_DUMP:
case Channel::Request::MethodId::ROUTER_CREATE_WEBRTC_TRANSPORT: case Channel::Request::MethodId::ROUTER_CREATE_WEBRTC_TRANSPORT:
case Channel::Request::MethodId::ROUTER_CREATE_PLAIN_RTP_TRANSPORT:
case Channel::Request::MethodId::ROUTER_CREATE_PRODUCER: case Channel::Request::MethodId::ROUTER_CREATE_PRODUCER:
case Channel::Request::MethodId::ROUTER_CREATE_CONSUMER: case Channel::Request::MethodId::ROUTER_CREATE_CONSUMER:
case Channel::Request::MethodId::ROUTER_SET_AUDIO_LEVELS_EVENT: case Channel::Request::MethodId::ROUTER_SET_AUDIO_LEVELS_EVENT:
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论