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

Add Room.on('audiolevels') event

上级 93922141
......@@ -93,7 +93,10 @@ class Channel extends EventEmitter
{
// 123 = '{' (a Channel JSON messsage).
case 123:
this._processMessage(JSON.parse(nsPayload));
process.nextTick(() =>
{
this._processMessage(JSON.parse(nsPayload));
});
break;
// 68 = 'D' (a debug log).
......@@ -128,8 +131,12 @@ class Channel extends EventEmitter
// Reset.
this._lastBinaryNotification = null;
// Emit.
this.emit(msg.targetId, msg.event, msg.data, nsPayload);
process.nextTick(() =>
{
this.emit(msg.targetId, msg.event, msg.data, nsPayload);
});
}
// Remove the read payload from the recvBuffer.
......
......@@ -37,7 +37,7 @@ class Room extends EventEmitter
this._closed = false;
// Subscribe to notifications.
this._channel.on(this._internal.roomId, (event) =>
this._channel.on(this._internal.roomId, (event, data) =>
{
switch (event)
{
......@@ -47,11 +47,102 @@ class Room extends EventEmitter
break;
}
case 'audiolevels':
{
let entries = data.entries;
let data2 = [];
for (let entry of entries)
{
let rtpReceiverId = entry[0];
let audioLevel = entry[1];
let rtpReceiver = this._rtpReceivers.get(rtpReceiverId);
if (!rtpReceiver)
continue;
let peer = rtpReceiver.peer;
if (!peer)
continue;
data2.push({ peer, rtpReceiver, audioLevel });
}
let orderedEntries = data2.sort((a, b) =>
{
if (a.audioLevel > b.audioLevel)
return -1;
else if (a.audioLevel < b.audioLevel)
return 1;
else
return 0;
});
this.emit('audiolevels', orderedEntries);
break;
}
default:
logger.error('ignoring unknown event "%s"', event);
}
});
// Subscribe to new events.
this.on('newListener', (event) =>
{
switch (event)
{
case 'audiolevels':
{
// Ignore if there are listeners already.
if (this.listenerCount('audiolevels'))
return;
// Send Channel request.
this._channel.request('room.setAudioLevelsEvent', this._internal, { enabled: true })
.then(() =>
{
logger.debug('"room.setAudioLevelsEvent" request succeeded');
})
.catch((error) =>
{
logger.error('"room.setAudioLevelsEvent" request failed: %s', error);
});
break;
}
}
});
// Subscribe to events removal.
this.on('removeListener', (event) =>
{
switch (event)
{
case 'audiolevels':
{
// Ignore if there are other remaining listeners.
if (this.listenerCount('audiolevels'))
return;
// Send Channel request.
this._channel.request('room.setAudioLevelsEvent', this._internal, { enabled: false })
.then(() =>
{
logger.debug('"room.setAudioLevelsEvent" request succeeded');
})
.catch((error) =>
{
logger.error('"room.setAudioLevelsEvent" request failed: %s', error);
});
break;
}
}
});
// Set room's capabilities.
this._setCapabilities(data.capabilities);
}
......
......@@ -64,7 +64,7 @@ class RtpReceiver extends EventEmitter
}
});
// Subscribe to new events so we can handle 'rtpraw' and 'rtpobject'.
// Subscribe to new events.
this.on('newListener', (event) =>
{
switch (event)
......@@ -111,7 +111,7 @@ class RtpReceiver extends EventEmitter
}
});
// Subscribe to events removal so we can handle 'rtpraw' and 'rtpobject'.
// Subscribe to events removal.
this.on('removeListener', (event) =>
{
switch (event)
......
......@@ -218,10 +218,10 @@ class RTCPeerConnectionCommon extends EventEmitter
// Just for the initial SDP O/A.
if (!this._initialNegotiationDone && options)
{
if (Object.prototype.hasOwnProperty.call(options, 'offerToReceiveAudio'))
if ({}.hasOwnProperty.call(options, 'offerToReceiveAudio'))
this._initialCreateOfferOptions.offerToReceiveAudio = options.offerToReceiveAudio;
if (Object.prototype.hasOwnProperty.call(options, 'offerToReceiveVideo'))
if ({}.hasOwnProperty.call(options, 'offerToReceiveVideo'))
this._initialCreateOfferOptions.offerToReceiveVideo = options.offerToReceiveVideo;
}
......
......@@ -23,6 +23,7 @@ namespace Channel
ROOM_CLOSE,
ROOM_DUMP,
ROOM_CREATE_PEER,
ROOM_SET_AUDIO_LEVELS_EVENT,
PEER_CLOSE,
PEER_DUMP,
PEER_SET_CAPABILITIES,
......
......@@ -65,7 +65,7 @@ namespace RTC
Header* header{ nullptr };
};
// Vbcm packet declaration
// Vbcm packet declaration.
using FeedbackPsVbcmPacket = FeedbackPsItemsPacket<FeedbackPsVbcmItem>;
/* Inline instance methods. */
......
......@@ -13,6 +13,7 @@
#include "RTC/RtpPacket.hpp"
#include "RTC/RtpReceiver.hpp"
#include "RTC/RtpSender.hpp"
#include "handles/Timer.hpp"
#include <json/json.h>
#include <unordered_map>
#include <unordered_set>
......@@ -20,7 +21,7 @@
namespace RTC
{
class Room : public RTC::Peer::Listener
class Room : public RTC::Peer::Listener, public Timer::Listener
{
public:
class Listener
......@@ -72,6 +73,10 @@ namespace RTC
const RTC::Peer* peer, RTC::RtpReceiver* rtpReceiver, RTC::RTCP::SenderReport* report) override;
void OnFullFrameRequired(RTC::Peer* peer, RTC::RtpSender* rtpSender) override;
/* Pure virtual methods inherited from Timer::Listener. */
public:
void OnTimer(Timer* timer) override;
public:
// Passed by argument.
uint32_t roomId{ 0 };
......@@ -80,11 +85,15 @@ namespace RTC
// Passed by argument.
Listener* listener{ nullptr };
Channel::Notifier* notifier{ nullptr };
// Allocated by this.
Timer* audioLevelsTimer{ nullptr };
// Others.
RTC::RtpCapabilities capabilities;
std::unordered_map<uint32_t, RTC::Peer*> peers;
std::unordered_map<const RTC::RtpReceiver*, std::unordered_set<RTC::RtpSender*>> mapRtpReceiverRtpSenders;
std::unordered_map<const RTC::RtpSender*, const RTC::RtpReceiver*> mapRtpSenderRtpReceiver;
std::unordered_map<RTC::RtpReceiver*, std::vector<int8_t>> mapRtpReceiverAudioLevels;
bool audioLevelsEventEnabled{ false };
};
/* Inline static methods. */
......
......@@ -21,7 +21,8 @@ namespace RTC
uint32_t clockRate{ 0 };
bool useNack{ false };
bool usePli{ false };
uint8_t absSendTimeId{ 0 }; // 0 means no abs-send-time id.
uint8_t ssrcAudioLevelId{ 0 }; // 0 means no ssrc-audio-level id.
uint8_t absSendTimeId{ 0 }; // 0 means no abs-send-time id.
};
public:
......
......@@ -26,8 +26,9 @@ private:
public:
void Destroy();
void Start(uint64_t timeout);
void Start(uint64_t timeout, uint64_t repeat = 0);
void Stop();
bool IsActive() const;
/* Callbacks fired by UV events. */
public:
......@@ -40,4 +41,11 @@ private:
uv_timer_t* uvHandle{ nullptr };
};
/* Inline methods. */
inline bool Timer::IsActive() const
{
return uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0;
}
#endif
......@@ -18,6 +18,7 @@ namespace Channel
{ "room.close", Request::MethodId::ROOM_CLOSE },
{ "room.dump", Request::MethodId::ROOM_DUMP },
{ "room.createPeer", Request::MethodId::ROOM_CREATE_PEER },
{ "room.setAudioLevelsEvent", Request::MethodId::ROOM_SET_AUDIO_LEVELS_EVENT },
{ "peer.close", Request::MethodId::PEER_CLOSE },
{ "peer.dump", Request::MethodId::PEER_DUMP },
{ "peer.setCapabilities", Request::MethodId::PEER_SET_CAPABILITIES },
......
......@@ -217,6 +217,7 @@ void Loop::OnChannelRequest(Channel::UnixStreamSocket* /*channel*/, Channel::Req
case Channel::Request::MethodId::ROOM_CLOSE:
case Channel::Request::MethodId::ROOM_DUMP:
case Channel::Request::MethodId::ROOM_CREATE_PEER:
case Channel::Request::MethodId::ROOM_SET_AUDIO_LEVELS_EVENT:
case Channel::Request::MethodId::PEER_CLOSE:
case Channel::Request::MethodId::PEER_DUMP:
case Channel::Request::MethodId::PEER_SET_CAPABILITIES:
......
......@@ -94,7 +94,7 @@ namespace RTC
/* Specialization for Ps class. */
template<>
Type FeedbackPacket<FeedbackPs>::rtcpType = RTCP::Type::PSFB;
RTCP::Type FeedbackPacket<FeedbackPs>::rtcpType = RTCP::Type::PSFB;
// clang-format off
template<>
......
......@@ -5,12 +5,17 @@
#include "Logger.hpp"
#include "MediaSoupError.hpp"
#include "Utils.hpp"
#include <cmath> // std::lround()
#include <set>
#include <string>
#include <vector>
namespace RTC
{
/* Static. */
static constexpr uint64_t AudioLevelsInterval{ 500 }; // In ms.
/* Class variables. */
RTC::RtpCapabilities Room::supportedRtpCapabilities;
......@@ -106,6 +111,9 @@ namespace RTC
// NOTE: This may throw.
SetCapabilities(mediaCodecs);
}
// Set the audio levels timer.
this->audioLevelsTimer = new Timer(this);
}
Room::~Room()
......@@ -133,6 +141,9 @@ namespace RTC
peer->Destroy();
}
// Close the audio level timer.
this->audioLevelsTimer->Destroy();
// Notify.
eventData[JsonStringClass] = "Room";
this->notifier->Emit(this->roomId, "close", eventData);
......@@ -152,6 +163,7 @@ namespace RTC
static const Json::StaticString JsonStringPeers{ "peers" };
static const Json::StaticString JsonStringMapRtpReceiverRtpSenders{ "mapRtpReceiverRtpSenders" };
static const Json::StaticString JsonStringMapRtpSenderRtpReceiver{ "mapRtpSenderRtpReceiver" };
static const Json::StaticString JsonStringAudioLevelsEventEnabled{ "audioLevelsEventEnabled" };
Json::Value json(Json::objectValue);
Json::Value jsonPeers(Json::arrayValue);
......@@ -200,6 +212,8 @@ namespace RTC
}
json[JsonStringMapRtpSenderRtpReceiver] = jsonMapRtpSenderRtpReceiver;
json[JsonStringAudioLevelsEventEnabled] = this->audioLevelsEventEnabled;
return json;
}
......@@ -289,6 +303,38 @@ namespace RTC
break;
}
case Channel::Request::MethodId::ROOM_SET_AUDIO_LEVELS_EVENT:
{
static const Json::StaticString JsonStringEnabled{ "enabled" };
if (!request->data[JsonStringEnabled].isBool())
{
request->Reject("Request has invalid data.enabled");
return;
}
bool audioLevelsEventEnabled = request->data[JsonStringEnabled].asBool();
if (audioLevelsEventEnabled == this->audioLevelsEventEnabled)
return;
// Clear map of audio levels.
this->mapRtpReceiverAudioLevels.clear();
// Start or stop audio levels periodic timer.
if (audioLevelsEventEnabled)
this->audioLevelsTimer->Start(AudioLevelsInterval, AudioLevelsInterval);
else
this->audioLevelsTimer->Stop();
this->audioLevelsEventEnabled = audioLevelsEventEnabled;
request->Accept();
break;
}
case Channel::Request::MethodId::PEER_CLOSE:
case Channel::Request::MethodId::PEER_DUMP:
case Channel::Request::MethodId::PEER_SET_CAPABILITIES:
......@@ -630,6 +676,20 @@ namespace RTC
{
rtpSender->SendRtpPacket(packet);
}
// Update audio levels.
if (this->audioLevelsEventEnabled)
{
uint8_t volume;
bool voice;
if (packet->ReadAudioLevel(&volume, &voice))
{
int8_t dBov = volume * -1;
this->mapRtpReceiverAudioLevels[rtpReceiver].push_back(dBov);
}
}
}
void Room::OnPeerRtcpReceiverReport(
......@@ -697,4 +757,63 @@ namespace RTC
rtpReceiver->RequestFullFrame();
}
inline void Room::OnTimer(Timer* timer)
{
MS_TRACE();
static const Json::StaticString JsonStringClass{ "class" };
static const Json::StaticString JsonStringEntries{ "entries" };
// Audio levels timer.
if (timer == this->audioLevelsTimer)
{
std::unordered_map<RTC::RtpReceiver*, int8_t> mapRtpReceiverAudioLevel;
for (auto& kv : this->mapRtpReceiverAudioLevels)
{
auto rtpReceiver = kv.first;
auto& dBovs = kv.second;
int8_t avgdBov{ -127 };
if (!dBovs.empty())
{
int16_t sumdBovs{ 0 };
for (auto& dBov : dBovs)
{
sumdBovs += dBov;
}
avgdBov = static_cast<int8_t>(
std::lround(sumdBovs / static_cast<int16_t>(dBovs.size())));
}
mapRtpReceiverAudioLevel[rtpReceiver] = avgdBov;
}
// Clear map.
this->mapRtpReceiverAudioLevels.clear();
// Emit event.
Json::Value eventData(Json::objectValue);
eventData[JsonStringClass] = "Room";
eventData[JsonStringEntries] = Json::arrayValue;
for (auto& kv : mapRtpReceiverAudioLevel)
{
auto& rtpReceiverId = kv.first->rtpReceiverId;
auto& audioLevel = kv.second;
Json::Value entry(Json::arrayValue);
entry.append(Json::UInt{ rtpReceiverId });
entry.append(Json::Int{ audioLevel });
eventData[JsonStringEntries].append(entry);
}
this->notifier->Emit(this->roomId, "audiolevels", eventData);
}
}
} // namespace RTC
......@@ -378,6 +378,7 @@ namespace RTC
bool useNack{ false };
bool usePli{ false };
bool useRemb{ false };
uint8_t ssrcAudioLevelId{ 0 };
uint8_t absSendTimeId{ 0 };
for (auto& fb : codec.rtcpFeedback)
......@@ -404,6 +405,12 @@ namespace RTC
for (auto& exten : this->rtpParameters->headerExtensions)
{
if (this->kind == RTC::Media::Kind::AUDIO && (ssrcAudioLevelId == 0u) &&
exten.type == RTC::RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL)
{
ssrcAudioLevelId = exten.id;
}
if ((absSendTimeId == 0u) && exten.type == RTC::RtpHeaderExtensionUri::Type::ABS_SEND_TIME)
{
absSendTimeId = exten.id;
......@@ -413,13 +420,14 @@ namespace RTC
// Create stream params.
RTC::RtpStream::Params params;
params.ssrc = ssrc;
params.payloadType = codec.payloadType;
params.mime = codec.mime;
params.clockRate = codec.clockRate;
params.useNack = useNack;
params.usePli = usePli;
params.absSendTimeId = absSendTimeId;
params.ssrc = ssrc;
params.payloadType = codec.payloadType;
params.mime = codec.mime;
params.clockRate = codec.clockRate;
params.useNack = useNack;
params.usePli = usePli;
params.ssrcAudioLevelId = ssrcAudioLevelId;
params.absSendTimeId = absSendTimeId;
// Create a RtpStreamRecv for receiving a media stream.
this->rtpStreams[ssrc] = new RTC::RtpStreamRecv(this, params);
......
......@@ -405,7 +405,8 @@ namespace RTC
auto& codec = this->rtpParameters->GetCodecForEncoding(encoding);
bool useNack{ false };
bool usePli{ false };
uint8_t absSendTimeId{ 0 }; // 0 means no abs-send-time id.
uint8_t ssrcAudioLevelId{ 0 };
uint8_t absSendTimeId{ 0 };
for (auto& fb : codec.rtcpFeedback)
{
......@@ -425,6 +426,12 @@ namespace RTC
for (auto& exten : this->rtpParameters->headerExtensions)
{
if (this->kind == RTC::Media::Kind::AUDIO && (ssrcAudioLevelId == 0u) &&
exten.type == RTC::RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL)
{
ssrcAudioLevelId = exten.id;
}
if ((absSendTimeId == 0u) && exten.type == RTC::RtpHeaderExtensionUri::Type::ABS_SEND_TIME)
{
absSendTimeId = exten.id;
......@@ -434,13 +441,14 @@ namespace RTC
// Create stream params.
RTC::RtpStream::Params params;
params.ssrc = ssrc;
params.payloadType = codec.payloadType;
params.mime = codec.mime;
params.clockRate = codec.clockRate;
params.useNack = useNack;
params.usePli = usePli;
params.absSendTimeId = absSendTimeId;
params.ssrc = ssrc;
params.payloadType = codec.payloadType;
params.mime = codec.mime;
params.clockRate = codec.clockRate;
params.useNack = useNack;
params.usePli = usePli;
params.ssrcAudioLevelId = ssrcAudioLevelId;
params.absSendTimeId = absSendTimeId;
// Create a RtpStreamSend for sending a single media stream.
if (useNack)
......
......@@ -180,17 +180,19 @@ namespace RTC
static const Json::StaticString JsonStringClockRate{ "clockRate" };
static const Json::StaticString JsonStringUseNack{ "useNack" };
static const Json::StaticString JsonStringUsePli{ "usePli" };
static const Json::StaticString JsonStringSsrcAudioLevelId{ "ssrcAudioLevelId" };
static const Json::StaticString JsonStringAbsSendTimeId{ "absSendTimeId" };
Json::Value json(Json::objectValue);
json[JsonStringSsrc] = Json::UInt{ this->ssrc };
json[JsonStringPayloadType] = Json::UInt{ this->payloadType };
json[JsonStringMime] = this->mime.name;
json[JsonStringClockRate] = Json::UInt{ this->clockRate };
json[JsonStringUseNack] = this->useNack;
json[JsonStringUsePli] = this->usePli;
json[JsonStringAbsSendTimeId] = Json::UInt{ this->absSendTimeId };
json[JsonStringSsrc] = Json::UInt{ this->ssrc };
json[JsonStringPayloadType] = Json::UInt{ this->payloadType };
json[JsonStringMime] = this->mime.name;
json[JsonStringClockRate] = Json::UInt{ this->clockRate };
json[JsonStringUseNack] = this->useNack;
json[JsonStringUsePli] = this->usePli;
json[JsonStringSsrcAudioLevelId] = Json::UInt{ this->ssrcAudioLevelId };
json[JsonStringAbsSendTimeId] = Json::UInt{ this->absSendTimeId };
return json;
}
......
......@@ -53,6 +53,12 @@ namespace RTC
CalculateJitter(packet->GetTimestamp());
// Set RTP header extension ids.
if (this->params.ssrcAudioLevelId != 0u)
{
packet->AddExtensionMapping(
RtpHeaderExtensionUri::Type::SSRC_AUDIO_LEVEL, this->params.ssrcAudioLevelId);
}
if (this->params.absSendTimeId != 0u)
{
packet->AddExtensionMapping(
......
......@@ -49,7 +49,7 @@ void Timer::Destroy()
delete this;
}
void Timer::Start(uint64_t timeout)
void Timer::Start(uint64_t timeout, uint64_t repeat)
{
MS_TRACE();
......@@ -58,7 +58,7 @@ void Timer::Start(uint64_t timeout)
if (uv_is_active(reinterpret_cast<uv_handle_t*>(this->uvHandle)) != 0)
Stop();
err = uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), timeout, 0);
err = uv_timer_start(this->uvHandle, static_cast<uv_timer_cb>(onTimer), timeout, repeat);
if (err != 0)
MS_THROW_ERROR("uv_timer_start() failed: %s", uv_strerror(err));
}
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论