Browse Source

Merge pull request #314 from stazio/rtcp_lock

Added a mutex for RtcpHandler
Paul-Louis Ageneau 4 years ago
parent
commit
61d0cd064f
2 changed files with 20 additions and 9 deletions
  1. 3 0
      include/rtc/track.hpp
  2. 17 9
      src/track.cpp

+ 3 - 0
include/rtc/track.hpp

@@ -28,6 +28,7 @@
 
 #include <atomic>
 #include <variant>
+#include <shared_mutex>
 
 namespace rtc {
 
@@ -77,6 +78,8 @@ private:
 	std::atomic<bool> mIsClosed = false;
 
 	Queue<message_ptr> mRecvQueue;
+
+	std::shared_mutex mRtcpHandlerMutex;
 	std::shared_ptr<RtcpHandler> mRtcpHandler;
 
 	friend class PeerConnection;

+ 17 - 9
src/track.cpp

@@ -65,8 +65,8 @@ bool Track::send(message_variant data) {
 
 	auto message = make_message(std::move(data));
 
-	if (mRtcpHandler) {
-		message = mRtcpHandler->outgoing(message);
+	if (auto handler = getRtcpHandler()) {
+		message = handler->outgoing(message);
 		if (!message)
 			return false;
 	}
@@ -125,8 +125,8 @@ void Track::incoming(message_ptr message) {
 		return;
 	}
 
-	if (mRtcpHandler) {
-		message = mRtcpHandler->incoming(message);
+	if (auto handler = getRtcpHandler()) {
+		message = handler->incoming(message);
 		if (!message)
 			return;
 	}
@@ -162,17 +162,25 @@ bool Track::outgoing([[maybe_unused]] message_ptr message) {
 }
 
 void Track::setRtcpHandler(std::shared_ptr<RtcpHandler> handler) {
+	std::unique_lock lock(mRtcpHandlerMutex);
 	mRtcpHandler = std::move(handler);
-	if (mRtcpHandler)
-		mRtcpHandler->onOutgoing(std::bind(&Track::outgoing, this, std::placeholders::_1));
+	if (mRtcpHandler) {
+		auto copy = mRtcpHandler;
+		lock.unlock();
+		copy->onOutgoing(std::bind(&Track::outgoing, this, std::placeholders::_1));
+	}
 }
 
 bool Track::requestKeyframe() {
-	if (mRtcpHandler)
-		return mRtcpHandler->requestKeyframe();
+	if (auto handler = getRtcpHandler()) {
+		return handler->requestKeyframe();
+	}
 	return false;
 }
 
-std::shared_ptr<RtcpHandler> Track::getRtcpHandler() { return mRtcpHandler; }
+std::shared_ptr<RtcpHandler> Track::getRtcpHandler() {
+	std::shared_lock lock(mRtcpHandlerMutex);
+	return mRtcpHandler;
+}
 
 } // namespace rtc