Unverified 提交 b555e54d authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi 提交者: GitHub

Merge pull request #881 from nazar-pc/refactor-message-handling

Refactor message handling
......@@ -289,7 +289,7 @@ impl Default for DtlsRole {
/// The hash function algorithm (as defined in the "Hash function Textual Names" registry initially
/// specified in [RFC 4572](https://tools.ietf.org/html/rfc4572#section-8) Section 8) and its
/// corresponding certificate fingerprint value.
#[derive(Copy, Clone, PartialOrd, PartialEq)]
#[derive(Copy, Clone, PartialOrd, Eq, PartialEq)]
pub enum DtlsFingerprint {
/// sha-1
Sha1 {
......@@ -748,7 +748,7 @@ impl DtlsFingerprint {
}
/// DTLS parameters.
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
pub struct DtlsParameters {
/// DTLS role.
pub role: DtlsRole,
......
......@@ -356,6 +356,7 @@ impl WeakPipeTransportPair {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_transport: Bag<Arc<dyn Fn(NewTransport<'_>) + Send + Sync>>,
new_rtp_observer: Bag<Arc<dyn Fn(NewRtpObserver<'_>) + Send + Sync>>,
......
......@@ -49,6 +49,7 @@ pub struct ActiveSpeakerObserverDominantSpeaker {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
dominant_speaker: Bag<
Arc<dyn Fn(&ActiveSpeakerObserverDominantSpeaker) + Send + Sync>,
......
......@@ -60,6 +60,7 @@ pub struct AudioLevelObserverVolume {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
volumes: Bag<Arc<dyn Fn(&[AudioLevelObserverVolume]) + Send + Sync>>,
silence: Bag<Arc<dyn Fn() + Send + Sync>>,
......
......@@ -104,7 +104,7 @@ impl ConsumerOptions {
}
}
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
pub struct RtpStreamParams {
......@@ -125,7 +125,7 @@ pub struct RtpStreamParams {
pub rtc_payload_type: Option<u8>,
}
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
pub struct RtpStream {
......@@ -133,7 +133,7 @@ pub struct RtpStream {
pub score: u8,
}
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
pub struct RtpRtxParameters {
......@@ -347,6 +347,7 @@ enum PayloadNotification {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
rtp: Bag<Arc<dyn Fn(&[u8]) + Send + Sync>>,
pause: Bag<Arc<dyn Fn() + Send + Sync>>,
......
......@@ -125,7 +125,7 @@ impl DataConsumerOptions {
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -140,7 +140,7 @@ pub struct DataConsumerDump {
}
/// RTC statistics of the data consumer.
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
#[allow(missing_docs)]
......@@ -182,6 +182,7 @@ enum PayloadNotification {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
message: Bag<Arc<dyn Fn(&WebRtcMessage<'_>) + Send + Sync>>,
sctp_send_buffer_full: Bag<Arc<dyn Fn() + Send + Sync>>,
......
......@@ -95,7 +95,7 @@ pub enum DataProducerType {
Direct,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -108,7 +108,7 @@ pub struct DataProducerDump {
}
/// RTC statistics of the data producer.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
#[allow(missing_docs)]
......@@ -122,6 +122,7 @@ pub struct DataProducerStat {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
transport_close: BagOnce<Box<dyn FnOnce() + Send>>,
close: BagOnce<Box<dyn FnOnce() + Send>>,
......
......@@ -49,7 +49,7 @@ impl Default for DirectTransportOptions {
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -110,6 +110,7 @@ pub struct DirectTransportStat {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
rtcp: Bag<Arc<dyn Fn(&[u8]) + Send + Sync>>,
new_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
......
......@@ -82,7 +82,7 @@ impl PipeTransportOptions {
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -161,6 +161,7 @@ pub struct PipeTransportRemoteParameters {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
new_consumer: Bag<Arc<dyn Fn(&Consumer) + Send + Sync>, Consumer>,
......
......@@ -98,7 +98,7 @@ impl PlainTransportOptions {
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -190,6 +190,7 @@ pub struct PlainTransportRemoteParameters {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
new_consumer: Bag<Arc<dyn Fn(&Consumer) + Send + Sync>, Consumer>,
......
......@@ -24,12 +24,10 @@ async fn init() -> Router {
.await
.expect("Failed to create worker");
let router = worker
worker
.create_router(RouterOptions::default())
.await
.expect("Failed to create router");
router
.expect("Failed to create router")
}
#[test]
......
......@@ -89,7 +89,7 @@ impl ProducerOptions {
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
pub struct RtpStreamRecv {
......@@ -278,6 +278,7 @@ enum Notification {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
score: Bag<Arc<dyn Fn(&[ProducerScore]) + Send + Sync>>,
video_orientation_change: Bag<Arc<dyn Fn(ProducerVideoOrientation) + Send + Sync>>,
......
......@@ -78,7 +78,7 @@ pub enum TransportTraceEventType {
Bwe,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
pub struct RtpListener {
......@@ -101,7 +101,7 @@ pub struct RecvRtpHeaderExtensions {
transport_wide_cc01: Option<u8>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
pub struct SctpListener {
......
......@@ -183,7 +183,7 @@ impl WebRtcTransportOptions {
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -258,7 +258,7 @@ pub struct WebRtcTransportStat {
}
/// Remote parameters for [`WebRtcTransport`].
#[derive(Debug, Clone, PartialOrd, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, PartialOrd, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WebRtcTransportRemoteParameters {
/// Remote DTLS parameters.
......@@ -266,6 +266,7 @@ pub struct WebRtcTransportRemoteParameters {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_producer: Bag<Arc<dyn Fn(&Producer) + Send + Sync>, Producer>,
new_consumer: Bag<Arc<dyn Fn(&Consumer) + Send + Sync>, Consumer>,
......
......@@ -59,7 +59,7 @@ pub struct WebRtcServerTupleHash {
pub webrtc_transport_id: TransportId,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
#[non_exhaustive]
......@@ -151,6 +151,7 @@ impl WebRtcServerOptions {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_webrtc_transport: BagOnce<Box<dyn Fn(&WebRtcTransport) + Send>>,
worker_close: BagOnce<Box<dyn FnOnce() + Send>>,
......
......@@ -274,6 +274,7 @@ pub enum CreateRouterError {
}
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_router: Bag<Arc<dyn Fn(&Router) + Send + Sync>, Router>,
new_webrtc_server: Bag<Arc<dyn Fn(&WebRtcServer) + Send + Sync>, WebRtcServer>,
......
......@@ -37,6 +37,7 @@ pub(super) enum InternalMessage {
Unexpected(Vec<u8>),
}
#[allow(clippy::type_complexity)]
pub(crate) struct BufferMessagesGuard {
target_id: SubscriptionTarget,
buffered_notifications_for: Arc<Mutex<HashedMap<SubscriptionTarget, Vec<Vec<u8>>>>>,
......@@ -158,6 +159,7 @@ struct OutgoingMessageBuffer {
messages: VecDeque<Arc<AtomicTake<Vec<u8>>>>,
}
#[allow(clippy::type_complexity)]
struct Inner {
outgoing_message_buffer: Arc<Mutex<OutgoingMessageBuffer>>,
internal_message_receiver: async_channel::Receiver<InternalMessage>,
......
......@@ -4,6 +4,7 @@ pub(super) use mediasoup_sys::{
use std::os::raw::c_void;
use std::slice;
#[allow(clippy::type_complexity)]
pub(super) struct ChannelReadCallback(Box<dyn FnMut(&[u8]) + Send + 'static>);
pub(crate) struct PreparedChannelWrite {
......@@ -59,6 +60,7 @@ where
}
}
#[allow(clippy::type_complexity)]
pub(super) struct PayloadChannelReadCallback(Box<dyn FnMut(&[u8], &[u8]) + Send + 'static>);
pub(crate) struct PreparedPayloadChannelWrite {
......
......@@ -17,6 +17,7 @@ use std::sync::Arc;
use std::{fmt, io, mem};
#[derive(Default)]
#[allow(clippy::type_complexity)]
struct Handlers {
new_worker: Bag<Arc<dyn Fn(&Worker) + Send + Sync>, Worker>,
}
......
......@@ -62,7 +62,7 @@ namespace RTC
};
public:
ActiveSpeakerObserver(const std::string& id, json& data);
ActiveSpeakerObserver(const std::string& id, RTC::RtpObserver::Listener* listener, json& data);
~ActiveSpeakerObserver() override;
public:
......
......@@ -20,7 +20,7 @@ namespace RTC
};
public:
AudioLevelObserver(const std::string& id, json& data);
AudioLevelObserver(const std::string& id, RTC::RtpObserver::Listener* listener, json& data);
~AudioLevelObserver() override;
public:
......
......@@ -12,6 +12,10 @@
namespace RTC
{
// Define class here such that we can use it even though we don't know what it looks like yet
// (this is to avoid circular dependencies).
class SctpAssociation;
class DataConsumer : public Channel::ChannelSocket::RequestHandler,
public PayloadChannel::PayloadChannelSocket::RequestHandler
{
......@@ -45,6 +49,7 @@ namespace RTC
DataConsumer(
const std::string& id,
const std::string& dataProducerId,
RTC::SctpAssociation* sctpAssociation,
RTC::DataConsumer::Listener* listener,
json& data,
size_t maxMessageSize);
......@@ -94,6 +99,7 @@ namespace RTC
private:
// Passed by argument.
RTC::SctpAssociation* sctpAssociation{ nullptr };
RTC::DataConsumer::Listener* listener{ nullptr };
size_t maxMessageSize{ 0u };
// Others.
......
......@@ -4,13 +4,16 @@
#include "common.hpp"
#include "Channel/ChannelRequest.hpp"
#include "Channel/ChannelSocket.hpp"
#include "PayloadChannel/PayloadChannelSocket.hpp"
#include "RTC/RTCP/Packet.hpp"
#include "RTC/SctpDictionaries.hpp"
#include <nlohmann/json.hpp>
#include <string>
namespace RTC
{
class DataProducer : public Channel::ChannelSocket::RequestHandler
class DataProducer : public Channel::ChannelSocket::RequestHandler,
public PayloadChannel::PayloadChannelSocket::NotificationHandler
{
public:
class Listener
......@@ -19,6 +22,7 @@ namespace RTC
virtual ~Listener() = default;
public:
virtual void OnDataProducerReceiveData(RTC::DataProducer* producer, size_t len) = 0;
virtual void OnDataProducerMessageReceived(
RTC::DataProducer* dataProducer, uint32_t ppid, const uint8_t* msg, size_t len) = 0;
};
......@@ -31,7 +35,8 @@ namespace RTC
};
public:
DataProducer(const std::string& id, RTC::DataProducer::Listener* listener, json& data);
DataProducer(
const std::string& id, size_t maxMessageSize, RTC::DataProducer::Listener* listener, json& data);
virtual ~DataProducer();
public:
......@@ -51,12 +56,17 @@ namespace RTC
public:
void HandleRequest(Channel::ChannelRequest* request) override;
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
public:
// Passed by argument.
const std::string id;
private:
// Passed by argument.
size_t maxMessageSize{ 0u };
RTC::DataProducer::Listener* listener{ nullptr };
// Others.
Type type;
......
......@@ -40,10 +40,6 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
private:
// Allocated by this.
uint8_t* buffer{ nullptr };
};
} // namespace RTC
......
......@@ -4,6 +4,7 @@
#include "common.hpp"
#include "Channel/ChannelRequest.hpp"
#include "Channel/ChannelSocket.hpp"
#include "PayloadChannel/PayloadChannelSocket.hpp"
#include "RTC/KeyFrameRequestManager.hpp"
#include "RTC/RTCP/CompoundPacket.hpp"
#include "RTC/RTCP/Packet.hpp"
......@@ -23,7 +24,8 @@ namespace RTC
{
class Producer : public RTC::RtpStreamRecv::Listener,
public RTC::KeyFrameRequestManager::Listener,
public Channel::ChannelSocket::RequestHandler
public Channel::ChannelSocket::RequestHandler,
public PayloadChannel::PayloadChannelSocket::NotificationHandler
{
public:
class Listener
......@@ -32,8 +34,10 @@ namespace RTC
virtual ~Listener() = default;
public:
virtual void OnProducerPaused(RTC::Producer* producer) = 0;
virtual void OnProducerResumed(RTC::Producer* producer) = 0;
virtual void OnProducerReceiveData(RTC::Producer* producer, size_t len) = 0;
virtual void OnProducerReceiveRtpPacket(RTC::Producer* producer, RTC::RtpPacket* packet) = 0;
virtual void OnProducerPaused(RTC::Producer* producer) = 0;
virtual void OnProducerResumed(RTC::Producer* producer) = 0;
virtual void OnProducerNewRtpStream(
RTC::Producer* producer, RTC::RtpStream* rtpStream, uint32_t mappedSsrc) = 0;
virtual void OnProducerRtpStreamScore(
......@@ -132,6 +136,10 @@ namespace RTC
public:
void HandleRequest(Channel::ChannelRequest* request) override;
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
private:
RTC::RtpStreamRecv* GetRtpStream(RTC::RtpPacket* packet);
RTC::RtpStreamRecv* CreateRtpStream(
......@@ -188,6 +196,8 @@ namespace RTC
bool videoOrientationDetected{ false };
struct VideoOrientation videoOrientation;
struct TraceEventTypes traceEventTypes;
// Static buffer.
thread_local static uint8_t* buffer;
};
} // namespace RTC
......
......@@ -24,6 +24,7 @@ using json = nlohmann::json;
namespace RTC
{
class Router : public RTC::Transport::Listener,
public RTC::RtpObserver::Listener,
public Channel::ChannelSocket::RequestHandler,
public PayloadChannel::PayloadChannelSocket::RequestHandler,
public PayloadChannel::PayloadChannelSocket::NotificationHandler
......@@ -112,6 +113,12 @@ namespace RTC
RTC::Transport* transport, RTC::DataConsumer* dataConsumer) override;
void OnTransportListenServerClosed(RTC::Transport* transport) override;
/* Pure virtual methods inherited from RTC::RtpObserver::Listener. */
public:
RTC::Producer* RtpObserverGetProducer(RTC::RtpObserver*, const std::string& id) override;
void OnRtpObserverAddProducer(RTC::RtpObserver* rtpObserver, RTC::Producer* producer) override;
void OnRtpObserverRemoveProducer(RTC::RtpObserver* rtpObserver, RTC::Producer* producer) override;
public:
// Passed by argument.
const std::string id;
......
......@@ -8,10 +8,24 @@
namespace RTC
{
class RtpObserver
class RtpObserver : public Channel::ChannelSocket::RequestHandler
{
public:
RtpObserver(const std::string& id);
class Listener
{
public:
virtual ~Listener() = default;
public:
virtual RTC::Producer* RtpObserverGetProducer(
RTC::RtpObserver* rtpObserver, const std::string& id) = 0;
virtual void OnRtpObserverAddProducer(RTC::RtpObserver* rtpObserver, RTC::Producer* producer) = 0;
virtual void OnRtpObserverRemoveProducer(
RTC::RtpObserver* rtpObserver, RTC::Producer* producer) = 0;
};
public:
RtpObserver(const std::string& id, RTC::RtpObserver::Listener* listener);
virtual ~RtpObserver();
public:
......@@ -27,13 +41,21 @@ namespace RTC
virtual void ProducerPaused(RTC::Producer* producer) = 0;
virtual void ProducerResumed(RTC::Producer* producer) = 0;
/* Methods inherited from Channel::ChannelSocket::RequestHandler. */
public:
void HandleRequest(Channel::ChannelRequest* request) override;
protected:
virtual void Paused() = 0;
virtual void Resumed() = 0;
private:
std::string GetProducerIdFromData(json& data) const;
public:
// Passed by argument.
const std::string id;
RTC::RtpObserver::Listener* listener{ nullptr };
private:
// Others.
......
......@@ -191,6 +191,14 @@ namespace RTC
/* Pure virtual methods inherited from RTC::Producer::Listener. */
public:
void OnProducerReceiveData(RTC::Producer* /*producer*/, size_t len) override
{
this->DataReceived(len);
}
void OnProducerReceiveRtpPacket(RTC::Producer* /*producer*/, RTC::RtpPacket* packet) override
{
this->ReceiveRtpPacket(packet);
}
void OnProducerPaused(RTC::Producer* producer) override;
void OnProducerResumed(RTC::Producer* producer) override;
void OnProducerNewRtpStream(
......@@ -215,6 +223,10 @@ namespace RTC
/* Pure virtual methods inherited from RTC::DataProducer::Listener. */
public:
void OnDataProducerReceiveData(RTC::DataProducer* /*dataProducer*/, size_t len) override
{
this->DataReceived(len);
}
void OnDataProducerMessageReceived(
RTC::DataProducer* dataProducer, uint32_t ppid, const uint8_t* msg, size_t len) override;
......
......@@ -92,8 +92,9 @@ namespace RTC
return changed;
}
ActiveSpeakerObserver::ActiveSpeakerObserver(const std::string& id, json& data)
: RTC::RtpObserver(id)
ActiveSpeakerObserver::ActiveSpeakerObserver(
const std::string& id, RTC::RtpObserver::Listener* listener, json& data)
: RTC::RtpObserver(id, listener)
{
MS_TRACE();
......
......@@ -14,7 +14,9 @@ namespace RTC
{
/* Instance methods. */
AudioLevelObserver::AudioLevelObserver(const std::string& id, json& data) : RTC::RtpObserver(id)
AudioLevelObserver::AudioLevelObserver(
const std::string& id, RTC::RtpObserver::Listener* listener, json& data)
: RTC::RtpObserver(id, listener)
{
MS_TRACE();
......
......@@ -7,6 +7,7 @@
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include "Channel/ChannelNotifier.hpp"
#include "RTC/SctpAssociation.hpp"
namespace RTC
{
......@@ -15,10 +16,12 @@ namespace RTC
DataConsumer::DataConsumer(
const std::string& id,
const std::string& dataProducerId,
RTC::SctpAssociation* sctpAssociation,
RTC::DataConsumer::Listener* listener,
json& data,
size_t maxMessageSize)
: id(id), dataProducerId(dataProducerId), listener(listener), maxMessageSize(maxMessageSize)
: id(id), dataProducerId(dataProducerId), sctpAssociation(sctpAssociation), listener(listener),
maxMessageSize(maxMessageSize)
{
MS_TRACE();
......@@ -153,8 +156,35 @@ namespace RTC
break;
}
case Channel::ChannelRequest::MethodId::DATA_CONSUMER_GET_BUFFERED_AMOUNT:
{
if (this->GetType() != RTC::DataConsumer::Type::SCTP)
{
MS_THROW_TYPE_ERROR("invalid DataConsumer type");
}
if (!this->sctpAssociation)
{
MS_THROW_ERROR("no SCTP association present");
}
// Create status response.
json data = json::object();
data["bufferedAmount"] = this->sctpAssociation->GetSctpBufferedAmount();
request->Accept(data);
break;
}
case Channel::ChannelRequest::MethodId::DATA_CONSUMER_SET_BUFFERED_AMOUNT_LOW_THRESHOLD:
{
if (this->GetType() != DataConsumer::Type::SCTP)
{
MS_THROW_TYPE_ERROR("invalid DataConsumer type");
}
auto jsonThresholdIt = request->data.find("threshold");
if (jsonThresholdIt == request->data.end() || !jsonThresholdIt->is_number_unsigned())
......@@ -200,6 +230,16 @@ namespace RTC
{
case PayloadChannel::PayloadChannelRequest::MethodId::DATA_CONSUMER_SEND:
{
if (this->GetType() != RTC::DataConsumer::Type::SCTP)
{
MS_THROW_TYPE_ERROR("invalid DataConsumer type");
}
if (!this->sctpAssociation)
{
MS_THROW_ERROR("no SCTP association present");
}
auto jsonPpidIt = request->data.find("ppid");
if (jsonPpidIt == request->data.end() || !Utils::Json::IsPositiveInteger(*jsonPpidIt))
......
......@@ -11,8 +11,9 @@ namespace RTC
{
/* Instance methods. */
DataProducer::DataProducer(const std::string& id, RTC::DataProducer::Listener* listener, json& data)
: id(id), listener(listener)
DataProducer::DataProducer(
const std::string& id, size_t maxMessageSize, RTC::DataProducer::Listener* listener, json& data)
: id(id), maxMessageSize(maxMessageSize), listener(listener)
{
MS_TRACE();
......@@ -145,6 +146,51 @@ namespace RTC
}
}
void DataProducer::HandleNotification(PayloadChannel::Notification* notification)
{
MS_TRACE();
switch (notification->eventId)
{
case PayloadChannel::Notification::EventId::DATA_PRODUCER_SEND:
{
auto jsonPpidIt = notification->data.find("ppid");
if (jsonPpidIt == notification->data.end() || !Utils::Json::IsPositiveInteger(*jsonPpidIt))
{
MS_THROW_TYPE_ERROR("invalid ppid");
}
auto ppid = jsonPpidIt->get<uint32_t>();
const auto* msg = notification->payload;
auto len = notification->payloadLen;
if (len > this->maxMessageSize)
{
MS_WARN_TAG(
message,
"given message exceeds maxMessageSize value [maxMessageSize:%zu, len:%zu]",
len,
this->maxMessageSize);
break;
}
this->ReceiveMessage(ppid, msg, len);
// Increase receive transmission.
this->listener->OnDataProducerReceiveData(this, len);
break;
}
default:
{
MS_ERROR("unknown event '%s'", notification->event.c_str());
}
}
}
void DataProducer::ReceiveMessage(uint32_t ppid, const uint8_t* msg, size_t len)
{
MS_TRACE();
......
......@@ -20,8 +20,6 @@ namespace RTC
DirectTransport::~DirectTransport()
{
MS_TRACE();
delete[] this->buffer;
}
void DirectTransport::FillJson(json& jsonObject) const
......@@ -91,37 +89,10 @@ namespace RTC
case PayloadChannel::Notification::EventId::PRODUCER_SEND:
{
const auto* data = notification->payload;
auto len = notification->payloadLen;
// Increase receive transmission.
RTC::Transport::DataReceived(len);
if (len > RTC::MtuSize + 100)
{
MS_WARN_TAG(rtp, "given RTP packet exceeds maximum size [len:%zu]", len);
return;
}
// If this is the first time to reveive a RTP packet then allocate the receiving buffer now.
if (!this->buffer)
this->buffer = new uint8_t[RTC::MtuSize + 100];
// Copy the received packet into this buffer so it can be expanded later.
std::memcpy(this->buffer, data, static_cast<size_t>(len));
RTC::RtpPacket* packet = RTC::RtpPacket::Parse(this->buffer, len);
if (!packet)
{
MS_WARN_TAG(rtp, "received data is not a valid RTP packet");
return;
}
// This may throw.
RTC::Producer* producer = GetProducerFromInternal(notification->internal);
// Pass the packet to the parent transport.
RTC::Transport::ReceiveRtpPacket(packet);
producer->HandleNotification(notification);
break;
}
......@@ -131,32 +102,7 @@ namespace RTC
// This may throw.
RTC::DataProducer* dataProducer = GetDataProducerFromInternal(notification->internal);
auto jsonPpidIt = notification->data.find("ppid");
if (jsonPpidIt == notification->data.end() || !Utils::Json::IsPositiveInteger(*jsonPpidIt))
{
MS_THROW_TYPE_ERROR("invalid ppid");
}
auto ppid = jsonPpidIt->get<uint32_t>();
const auto* msg = notification->payload;
auto len = notification->payloadLen;
if (len > this->maxMessageSize)
{
MS_WARN_TAG(
message,
"given message exceeds maxMessageSize value [maxMessageSize:%zu, len:%zu]",
len,
this->maxMessageSize);
return;
}
dataProducer->ReceiveMessage(ppid, msg, len);
// Increase receive transmission.
RTC::Transport::DataReceived(len);
dataProducer->HandleNotification(notification);
break;
}
......
......@@ -18,6 +18,10 @@
namespace RTC
{
/* Static variables. */
thread_local uint8_t* Producer::buffer{ nullptr };
/* Static. */
static constexpr unsigned int SendNackDelay{ 10u }; // In ms.
......@@ -605,6 +609,56 @@ namespace RTC
}
}
void Producer::HandleNotification(PayloadChannel::Notification* notification)
{
MS_TRACE();
switch (notification->eventId)
{
case PayloadChannel::Notification::EventId::PRODUCER_SEND:
{
const auto* data = notification->payload;
auto len = notification->payloadLen;
// Increase receive transmission.
this->listener->OnProducerReceiveData(this, len);
if (len > RTC::MtuSize + 100)
{
MS_WARN_TAG(rtp, "given RTP packet exceeds maximum size [len:%zu]", len);
break;
}
// If this is the first time to receive a RTP packet then allocate the receiving buffer now.
if (!Producer::buffer)
Producer::buffer = new uint8_t[RTC::MtuSize + 100];
// Copy the received packet into this buffer so it can be expanded later.
std::memcpy(Producer::buffer, data, static_cast<size_t>(len));
RTC::RtpPacket* packet = RTC::RtpPacket::Parse(Producer::buffer, len);
if (!packet)
{
MS_WARN_TAG(rtp, "received data is not a valid RTP packet");
break;
}
// Pass the packet to the parent transport.
this->listener->OnProducerReceiveRtpPacket(this, packet);
break;
}
default:
{
MS_ERROR("unknown event '%s'", notification->event.c_str());
}
}
}
Producer::ReceiveRtpPacketResult Producer::ReceiveRtpPacket(RTC::RtpPacket* packet)
{
MS_TRACE();
......
......@@ -365,7 +365,8 @@ namespace RTC
// This may throw.
SetNewRtpObserverIdFromInternal(request->internal, rtpObserverId);
auto* activeSpeakerObserver = new RTC::ActiveSpeakerObserver(rtpObserverId, request->data);
auto* activeSpeakerObserver =
new RTC::ActiveSpeakerObserver(rtpObserverId, this, request->data);
// Insert into the map.
this->mapRtpObservers[rtpObserverId] = activeSpeakerObserver;
......@@ -384,7 +385,7 @@ namespace RTC
// This may throw
SetNewRtpObserverIdFromInternal(request->internal, rtpObserverId);
auto* audioLevelObserver = new RTC::AudioLevelObserver(rtpObserverId, request->data);
auto* audioLevelObserver = new RTC::AudioLevelObserver(rtpObserverId, this, request->data);
// Insert into the map.
this->mapRtpObservers[rtpObserverId] = audioLevelObserver;
......@@ -445,57 +446,14 @@ namespace RTC
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_PAUSE:
{
// This may throw.
RTC::RtpObserver* rtpObserver = GetRtpObserverFromInternal(request->internal);
rtpObserver->Pause();
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_RESUME:
{
// This may throw.
RTC::RtpObserver* rtpObserver = GetRtpObserverFromInternal(request->internal);
rtpObserver->Resume();
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_ADD_PRODUCER:
{
// This may throw.
RTC::RtpObserver* rtpObserver = GetRtpObserverFromInternal(request->internal);
RTC::Producer* producer = GetProducerFromData(request->data);
rtpObserver->AddProducer(producer);
// Add to the map.
this->mapProducerRtpObservers[producer].insert(rtpObserver);
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_REMOVE_PRODUCER:
{
// This may throw.
RTC::RtpObserver* rtpObserver = GetRtpObserverFromInternal(request->internal);
RTC::Producer* producer = GetProducerFromData(request->data);
rtpObserver->RemoveProducer(producer);
// Remove from the map.
this->mapProducerRtpObservers[producer].erase(rtpObserver);
request->Accept();
rtpObserver->HandleRequest(request);
break;
}
......@@ -1121,4 +1079,29 @@ namespace RTC
// Delete it.
delete transport;
}
void Router::OnRtpObserverAddProducer(RTC::RtpObserver* rtpObserver, RTC::Producer* producer)
{
// Add to the map.
this->mapProducerRtpObservers[producer].insert(rtpObserver);
}
void Router::OnRtpObserverRemoveProducer(RTC::RtpObserver* rtpObserver, RTC::Producer* producer)
{
// Remove from the map.
this->mapProducerRtpObservers[producer].erase(rtpObserver);
}
RTC::Producer* Router::RtpObserverGetProducer(
RTC::RtpObserver* /* rtpObserver */, const std::string& id)
{
auto it = this->mapProducers.find(id);
if (it == this->mapProducers.end())
MS_THROW_ERROR("Producer not found");
RTC::Producer* producer = it->second;
return producer;
}
} // namespace RTC
......@@ -3,12 +3,14 @@
#include "RTC/RtpObserver.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
namespace RTC
{
/* Instance methods. */
RtpObserver::RtpObserver(const std::string& id) : id(id)
RtpObserver::RtpObserver(const std::string& id, RTC::RtpObserver::Listener* listener)
: id(id), listener(listener)
{
MS_TRACE();
}
......@@ -18,6 +20,68 @@ namespace RTC
MS_TRACE();
}
void RtpObserver::HandleRequest(Channel::ChannelRequest* request)
{
MS_TRACE();
switch (request->methodId)
{
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_PAUSE:
{
this->Pause();
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_RESUME:
{
this->Resume();
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_ADD_PRODUCER:
{
// This may throw.
auto producerId = GetProducerIdFromData(request->data);
RTC::Producer* producer = this->listener->RtpObserverGetProducer(this, producerId);
this->AddProducer(producer);
this->listener->OnRtpObserverAddProducer(this, producer);
request->Accept();
break;
}
case Channel::ChannelRequest::MethodId::RTP_OBSERVER_REMOVE_PRODUCER:
{
// This may throw.
auto producerId = GetProducerIdFromData(request->data);
RTC::Producer* producer = this->listener->RtpObserverGetProducer(this, producerId);
this->RemoveProducer(producer);
// Remove from the map.
this->listener->OnRtpObserverRemoveProducer(this, producer);
request->Accept();
break;
}
default:
{
MS_THROW_ERROR("unknown method '%s'", request->method.c_str());
}
}
}
void RtpObserver::Pause()
{
MS_TRACE();
......@@ -41,4 +105,16 @@ namespace RTC
Resumed();
}
std::string RtpObserver::GetProducerIdFromData(json& data) const
{
MS_TRACE();
auto jsonRouterIdIt = data.find("producerId");
if (jsonRouterIdIt == data.end() || !jsonRouterIdIt->is_string())
MS_THROW_ERROR("missing data.producerId");
return jsonRouterIdIt->get<std::string>();
}
} // namespace RTC
......@@ -1092,7 +1092,8 @@ namespace RTC
SetNewDataProducerIdFromInternal(request->internal, dataProducerId);
// This may throw.
auto* dataProducer = new RTC::DataProducer(dataProducerId, this, request->data);
auto* dataProducer =
new RTC::DataProducer(dataProducerId, this->maxMessageSize, this, request->data);
// Verify the type of the DataProducer.
switch (dataProducer->GetType())
......@@ -1197,7 +1198,7 @@ namespace RTC
// This may throw.
auto* dataConsumer = new RTC::DataConsumer(
dataConsumerId, dataProducerId, this, request->data, this->maxMessageSize);
dataConsumerId, dataProducerId, this->sctpAssociation, this, request->data, this->maxMessageSize);
// Verify the type of the DataConsumer.
switch (dataConsumer->GetType())
......@@ -1486,50 +1487,12 @@ namespace RTC
case Channel::ChannelRequest::MethodId::DATA_CONSUMER_DUMP:
case Channel::ChannelRequest::MethodId::DATA_CONSUMER_GET_STATS:
{
// This may throw.
RTC::DataConsumer* dataConsumer = GetDataConsumerFromInternal(request->internal);
dataConsumer->HandleRequest(request);
break;
}
case Channel::ChannelRequest::MethodId::DATA_CONSUMER_GET_BUFFERED_AMOUNT:
{
// This may throw.
RTC::DataConsumer* dataConsumer = GetDataConsumerFromInternal(request->internal);
if (dataConsumer->GetType() != RTC::DataConsumer::Type::SCTP)
{
MS_THROW_TYPE_ERROR("invalid DataConsumer type");
}
if (!this->sctpAssociation)
{
MS_THROW_ERROR("no SCTP association present");
}
// Create status response.
json data = json::object();
data["bufferedAmount"] = this->sctpAssociation->GetSctpBufferedAmount();
request->Accept(data);
break;
}
case Channel::ChannelRequest::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_TYPE_ERROR("invalid DataConsumer type");
}
dataConsumer->HandleRequest(request);
break;
......@@ -1553,16 +1516,6 @@ namespace RTC
// This may throw.
RTC::DataConsumer* dataConsumer = GetDataConsumerFromInternal(request->internal);
if (dataConsumer->GetType() != RTC::DataConsumer::Type::SCTP)
{
MS_THROW_TYPE_ERROR("invalid DataConsumer type");
}
if (!this->sctpAssociation)
{
MS_THROW_ERROR("no SCTP association present");
}
dataConsumer->HandleRequest(request);
break;
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论