Browse Source

Merge pull request #9 from paullouisageneau/master

Sync
Erik Cota-Robles 4 years ago
parent
commit
ed89fe3e94

+ 1 - 1
.github/workflows/build-gnutls.yml

@@ -30,7 +30,7 @@ jobs:
     - name: submodules
     - name: submodules
       run: git submodule update --init --recursive
       run: git submodule update --init --recursive
     - name: cmake
     - name: cmake
-      run: cmake -B build -DUSE_GNUTLS=1 -DWARNINGS_AS_ERRORS=1
+      run: cmake -B build -DUSE_GNUTLS=1 -DWARNINGS_AS_ERRORS=1 -DENABLE_LOCAL_ADDRESS_TRANSLATION=1
     - name: make
     - name: make
       run: (cd build; make -j2)
       run: (cd build; make -j2)
     - name: test
     - name: test

+ 1 - 1
.github/workflows/build-openssl.yml

@@ -30,7 +30,7 @@ jobs:
     - name: submodules
     - name: submodules
       run: git submodule update --init --recursive
       run: git submodule update --init --recursive
     - name: cmake
     - name: cmake
-      run: cmake -B build -DUSE_GNUTLS=0 -WARNINGS_AS_ERRORS=1
+      run: cmake -B build -DUSE_GNUTLS=0 -WARNINGS_AS_ERRORS=1 -DENABLE_LOCAL_ADDRESS_TRANSLATION=1
       env:
       env:
         OPENSSL_ROOT_DIR: /usr/local/opt/openssl
         OPENSSL_ROOT_DIR: /usr/local/opt/openssl
         OPENSSL_LIBRARIES: /usr/local/opt/openssl/lib
         OPENSSL_LIBRARIES: /usr/local/opt/openssl/lib

+ 25 - 8
CMakeLists.txt

@@ -11,7 +11,11 @@ option(NO_WEBSOCKET "Disable WebSocket support" OFF)
 option(NO_EXAMPLES "Disable examples" OFF)
 option(NO_EXAMPLES "Disable examples" OFF)
 option(NO_TESTS "Disable tests build" OFF)
 option(NO_TESTS "Disable tests build" OFF)
 option(WARNINGS_AS_ERRORS "Treat warnings as errors" OFF)
 option(WARNINGS_AS_ERRORS "Treat warnings as errors" OFF)
+option(RSA_KEY_BITS_2048 "Use 2048-bit RSA key instead of 3072-bit" OFF)
 option(CAPI_STDCALL "Set calling convention of C API callbacks stdcall" OFF)
 option(CAPI_STDCALL "Set calling convention of C API callbacks stdcall" OFF)
+# Option USE_SRTP defaults to AUTO (enabled if libSRTP is found, else disabled)
+set(USE_SRTP AUTO CACHE STRING "Use libSRTP and enable media support")
+set_property(CACHE USE_SRTP PROPERTY STRINGS AUTO ON OFF)
 
 
 if(USE_NICE)
 if(USE_NICE)
 	option(USE_JUICE "Use libjuice" OFF)
 	option(USE_JUICE "Use libjuice" OFF)
@@ -20,9 +24,9 @@ else()
 endif()
 endif()
 
 
 if(USE_GNUTLS)
 if(USE_GNUTLS)
-	option(USE_NETTLE "Use Nettle instead of OpenSSL in libjuice" ON)
+	option(USE_NETTLE "Use Nettle in libjuice" ON)
 else()
 else()
-	option(USE_NETTLE "Use Nettle instead of OpenSSL in libjuice" OFF)
+	option(USE_NETTLE "Use Nettle in libjuice" OFF)
 endif()
 endif()
 
 
 set(CMAKE_POSITION_INDEPENDENT_CODE ON)
 set(CMAKE_POSITION_INDEPENDENT_CODE ON)
@@ -158,12 +162,22 @@ target_link_libraries(datachannel-static PUBLIC Threads::Threads plog::plog)
 target_link_libraries(datachannel-static PRIVATE Usrsctp::UsrsctpStatic)
 target_link_libraries(datachannel-static PRIVATE Usrsctp::UsrsctpStatic)
 
 
 if(WIN32)
 if(WIN32)
-	target_link_libraries(datachannel PRIVATE wsock32 ws2_32) # winsock2
-	target_link_libraries(datachannel-static PRIVATE wsock32 ws2_32) # winsock2
+	target_link_libraries(datachannel PRIVATE ws2_32) # winsock2
+	target_link_libraries(datachannel-static PRIVATE ws2_32) # winsock2
 endif()
 endif()
 
 
-find_package(SRTP)
-if(SRTP_FOUND)
+if(USE_SRTP STREQUAL "AUTO")
+	find_package(SRTP)
+	if(SRTP_FOUND)
+		message(STATUS "LibSRTP found, compiling with media transport")
+	else()
+		message(STATUS "LibSRTP NOT found, compiling WITHOUT media transport")
+	endif()
+elseif(USE_SRTP)
+	find_package(SRTP REQUIRED)
+endif()
+
+if(USE_SRTP AND SRTP_FOUND)
 	if(NOT TARGET SRTP::SRTP)
 	if(NOT TARGET SRTP::SRTP)
 		add_library(SRTP::SRTP UNKNOWN IMPORTED)
 		add_library(SRTP::SRTP UNKNOWN IMPORTED)
 		set_target_properties(SRTP::SRTP PROPERTIES
 		set_target_properties(SRTP::SRTP PROPERTIES
@@ -171,13 +185,11 @@ if(SRTP_FOUND)
 			IMPORTED_LINK_INTERFACE_LANGUAGES C
 			IMPORTED_LINK_INTERFACE_LANGUAGES C
 			IMPORTED_LOCATION ${SRTP_LIBRARIES})
 			IMPORTED_LOCATION ${SRTP_LIBRARIES})
 	endif()
 	endif()
-	message(STATUS "LibSRTP found, compiling with media transport")
 	target_compile_definitions(datachannel PUBLIC RTC_ENABLE_MEDIA=1)
 	target_compile_definitions(datachannel PUBLIC RTC_ENABLE_MEDIA=1)
 	target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_MEDIA=1)
 	target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_MEDIA=1)
 	target_link_libraries(datachannel PRIVATE SRTP::SRTP)
 	target_link_libraries(datachannel PRIVATE SRTP::SRTP)
 	target_link_libraries(datachannel-static PRIVATE SRTP::SRTP)
 	target_link_libraries(datachannel-static PRIVATE SRTP::SRTP)
 else()
 else()
-	message(STATUS "LibSRTP NOT found, compiling WITHOUT media transport")
 	target_compile_definitions(datachannel PUBLIC RTC_ENABLE_MEDIA=0)
 	target_compile_definitions(datachannel PUBLIC RTC_ENABLE_MEDIA=0)
 	target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_MEDIA=0)
 	target_compile_definitions(datachannel-static PUBLIC RTC_ENABLE_MEDIA=0)
 endif()
 endif()
@@ -218,6 +230,11 @@ else()
 	target_link_libraries(datachannel-static PRIVATE LibJuice::LibJuiceStatic)
 	target_link_libraries(datachannel-static PRIVATE LibJuice::LibJuiceStatic)
 endif()
 endif()
 
 
+if(RSA_KEY_BITS_2048)
+	target_compile_definitions(datachannel PUBLIC RSA_KEY_BITS_2048)
+	target_compile_definitions(datachannel-static PUBLIC RSA_KEY_BITS_2048)
+endif()
+
 if(CAPI_STDCALL)
 if(CAPI_STDCALL)
 	target_compile_definitions(datachannel PUBLIC CAPI_STDCALL)
 	target_compile_definitions(datachannel PUBLIC CAPI_STDCALL)
 	target_compile_definitions(datachannel-static PUBLIC CAPI_STDCALL)
 	target_compile_definitions(datachannel-static PUBLIC CAPI_STDCALL)

+ 1 - 1
deps/libjuice

@@ -1 +1 @@
-Subproject commit 5d3e8b36fe65b9a856e46f8da397a7ade74b2c44
+Subproject commit 0a44ac2d26959fcdda204fa6814b39624ebf84d1

+ 34 - 29
examples/client/main.cpp

@@ -30,6 +30,8 @@
 #include <memory>
 #include <memory>
 #include <random>
 #include <random>
 #include <thread>
 #include <thread>
+#include <future>
+#include <stdexcept>
 #include <unordered_map>
 #include <unordered_map>
 #include "parse_cl.h"
 #include "parse_cl.h"
 
 
@@ -49,25 +51,19 @@ bool echoDataChannelMessages = false;
 
 
 shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
 shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
                                                 weak_ptr<WebSocket> wws, string id);
                                                 weak_ptr<WebSocket> wws, string id);
-void confirmOnStdout(bool echoed, string id, string type, size_t length);
+void printReceived(bool echoed, string id, string type, size_t length);
 string randomId(size_t length);
 string randomId(size_t length);
 
 
-int main(int argc, char **argv) {
-	Cmdline *params = nullptr;
-	try {
-		params = new Cmdline(argc, argv);
-	} catch (const std::range_error&e) {
-		std::cout<< e.what() << '\n';
-		delete params;
-		return -1;
-	}
+
+int main(int argc, char **argv) try {
+	auto params = std::make_unique<Cmdline>(argc, argv);
 
 
 	rtc::InitLogger(LogLevel::Debug);
 	rtc::InitLogger(LogLevel::Debug);
 
 
 	Configuration config;
 	Configuration config;
 	string stunServer = "";
 	string stunServer = "";
 	if (params->noStun()) {
 	if (params->noStun()) {
-		cout << "No stun server is configured.  Only local hosts and public IP addresses suported." << endl;
+		cout << "No STUN server is configured. Only local hosts and public IP addresses supported." << endl;
 	} else {
 	} else {
 		if (params->stunServer().substr(0,5).compare("stun:") != 0) {
 		if (params->stunServer().substr(0,5).compare("stun:") != 0) {
 			stunServer = "stun:";
 			stunServer = "stun:";
@@ -86,12 +82,21 @@ int main(int argc, char **argv) {
 
 
 	auto ws = make_shared<WebSocket>();
 	auto ws = make_shared<WebSocket>();
 
 
-	ws->onOpen([]() { cout << "WebSocket connected, signaling ready" << endl; });
+	std::promise<void> wsPromise;
+	auto wsFuture = wsPromise.get_future();
+	
+	ws->onOpen([&wsPromise]() { 
+		cout << "WebSocket connected, signaling ready" << endl;
+		wsPromise.set_value();
+	});
 
 
+	ws->onError([&wsPromise](string s) { 
+		cout << "WebSocket error" << endl;
+		wsPromise.set_exception(std::make_exception_ptr(std::runtime_error(s)));
+	});
+	
 	ws->onClosed([]() { cout << "WebSocket closed" << endl; });
 	ws->onClosed([]() { cout << "WebSocket closed" << endl; });
-
-	ws->onError([](const string &error) { cout << "WebSocket failed: " << error << endl; });
-
+	
 	ws->onMessage([&](variant<binary, string> data) {
 	ws->onMessage([&](variant<binary, string> data) {
 		if (!holds_alternative<string>(data))
 		if (!holds_alternative<string>(data))
 			return;
 			return;
@@ -136,13 +141,9 @@ int main(int argc, char **argv) {
 		to_string(params->webSocketPort()) + "/" + localId;
 		to_string(params->webSocketPort()) + "/" + localId;
 	cout << "Url is " << url << endl;
 	cout << "Url is " << url << endl;
 	ws->open(url);
 	ws->open(url);
-
+	
 	cout << "Waiting for signaling to be connected..." << endl;
 	cout << "Waiting for signaling to be connected..." << endl;
-	while (!ws->isOpen()) {
-		if (ws->isClosed())
-			return 1;
-		this_thread::sleep_for(100ms);
-	}
+	wsFuture.get();
 
 
 	while (true) {
 	while (true) {
 		string id;
 		string id;
@@ -181,22 +182,25 @@ int main(int argc, char **argv) {
 					dc->send(message);
 					dc->send(message);
 					echoed = true;
 					echoed = true;
 				}
 				}
-				confirmOnStdout(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
-						get<string>(message).length());
+				printReceived(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
+				      get<string>(message).length());
 			}
 			}
 		});
 		});
 
 
 		dataChannelMap.emplace(id, dc);
 		dataChannelMap.emplace(id, dc);
-
-		this_thread::sleep_for(1s);
 	}
 	}
 
 
 	cout << "Cleaning up..." << endl;
 	cout << "Cleaning up..." << endl;
 
 
 	dataChannelMap.clear();
 	dataChannelMap.clear();
 	peerConnectionMap.clear();
 	peerConnectionMap.clear();
-	delete params;
 	return 0;
 	return 0;
+
+} catch (const std::exception &e) {
+	std::cout << "Error: " << e.what() << std::endl;
+	dataChannelMap.clear();
+	peerConnectionMap.clear();
+	return -1;
 }
 }
 
 
 // Create and setup a PeerConnection
 // Create and setup a PeerConnection
@@ -244,7 +248,7 @@ shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
 					dc->send(message);
 					dc->send(message);
 					echoed = true;
 					echoed = true;
 				}
 				}
-				confirmOnStdout(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
+				printReceived(echoed, id, (holds_alternative<string>(message) ? "text" : "binary"),
 						get<string>(message).length());
 						get<string>(message).length());
 			}
 			}
 		});
 		});
@@ -258,11 +262,12 @@ shared_ptr<PeerConnection> createPeerConnection(const Configuration &config,
 	return pc;
 	return pc;
 };
 };
 
 
-void confirmOnStdout(bool echoed, string id, string type, size_t length) {
+// Helper function to print received pings
+void printReceived(bool echoed, string id, string type, size_t length) {
 	static long count = 0;
 	static long count = 0;
 	static long freq = 100;
 	static long freq = 100;
 	if (!(++count%freq)) {
 	if (!(++count%freq)) {
-		cout << "Received " << count << " pings in total from host " << id << ", most recent of type "
+		cout << "Received " << count << " pings in total from " << id << ", most recent of type "
 		     << type << " and " << (echoed ? "" : "un") << "successfully echoed most recent ping of size "
 		     << type << " and " << (echoed ? "" : "un") << "successfully echoed most recent ping of size "
 		     << length << " back to " << id << endl;
 		     << length << " back to " << id << endl;
 		if (count >= (freq * 10) && freq < 1000000) {
 		if (count >= (freq * 10) && freq < 1000000) {

+ 3 - 5
examples/copy-paste/answerer.cpp

@@ -127,13 +127,11 @@ int main(int argc, char **argv) {
 				cout << "** Channel is not Open ** ";
 				cout << "** Channel is not Open ** ";
 				break;
 				break;
 			}
 			}
-			CandidateInfo local, remote;
+			Candidate local, remote;
 			std::optional<std::chrono::milliseconds> rtt = pc->rtt();
 			std::optional<std::chrono::milliseconds> rtt = pc->rtt();
 			if (pc->getSelectedCandidatePair(&local, &remote)) {
 			if (pc->getSelectedCandidatePair(&local, &remote)) {
-				cout << "Local: " << local.address << ":" << local.port << " " << local.type << " "
-				     << local.transportType << endl;
-				cout << "Remote: " << remote.address << ":" << remote.port << " " << remote.type
-				     << " " << remote.transportType << endl;
+				cout << "Local: " << local << endl;
+				cout << "Remote: " << remote << endl;
 				cout << "Bytes Sent:" << pc->bytesSent()
 				cout << "Bytes Sent:" << pc->bytesSent()
 				     << " / Bytes Received:" << pc->bytesReceived() << " / Round-Trip Time:";
 				     << " / Bytes Received:" << pc->bytesReceived() << " / Round-Trip Time:";
 				if (rtt.has_value())
 				if (rtt.has_value())

+ 3 - 5
examples/copy-paste/offerer.cpp

@@ -127,13 +127,11 @@ int main(int argc, char **argv) {
 				cout << "** Channel is not Open ** ";
 				cout << "** Channel is not Open ** ";
 				break;
 				break;
 			}
 			}
-			CandidateInfo local, remote;
+			Candidate local, remote;
 			std::optional<std::chrono::milliseconds> rtt = pc->rtt();
 			std::optional<std::chrono::milliseconds> rtt = pc->rtt();
 			if (pc->getSelectedCandidatePair(&local, &remote)) {
 			if (pc->getSelectedCandidatePair(&local, &remote)) {
-				cout << "Local: " << local.address << ":" << local.port << " " << local.type << " "
-				     << local.transportType << endl;
-				cout << "Remote: " << remote.address << ":" << remote.port << " " << remote.type
-				     << " " << remote.transportType << endl;
+				cout << "Local: " << local << endl;
+				cout << "Remote: " << remote << endl;
 				cout << "Bytes Sent:" << pc->bytesSent()
 				cout << "Bytes Sent:" << pc->bytesSent()
 				     << " / Bytes Received:" << pc->bytesReceived() << " / Round-Trip Time:";
 				     << " / Bytes Received:" << pc->bytesReceived() << " / Round-Trip Time:";
 				if (rtt.has_value())
 				if (rtt.has_value())

+ 23 - 14
include/rtc/candidate.hpp

@@ -25,38 +25,47 @@
 
 
 namespace rtc {
 namespace rtc {
 
 
-enum class CandidateType { Host = 0, ServerReflexive, PeerReflexive, Relayed };
-enum class CandidateTransportType { Udp = 0, TcpActive, TcpPassive, TcpSo };
-struct CandidateInfo {
-	string address;
-	int port;
-	CandidateType type;
-	CandidateTransportType transportType;
-};
-
 class Candidate {
 class Candidate {
 public:
 public:
-	Candidate(string candidate, string mid = "");
+	enum class Family { Unresolved, Ipv4, Ipv6 };
+	enum class Type { Unknown, Host, ServerReflexive, PeerReflexive, Relayed };
+	enum class TransportType { Unknown, Udp, TcpActive, TcpPassive, TcpSo, TcpUnknown };
+
+	Candidate(string candidate = "", string mid = "");
 
 
 	enum class ResolveMode { Simple, Lookup };
 	enum class ResolveMode { Simple, Lookup };
 	bool resolve(ResolveMode mode = ResolveMode::Simple);
 	bool resolve(ResolveMode mode = ResolveMode::Simple);
-	bool isResolved() const;
 
 
 	string candidate() const;
 	string candidate() const;
 	string mid() const;
 	string mid() const;
 	operator string() const;
 	operator string() const;
 
 
+	bool isResolved() const;
+	Family family() const;
+	Type type() const;
+	TransportType transportType() const;
+	std::optional<string> address() const;
+	std::optional<uint16_t> port() const;
+	std::optional<uint32_t> priority() const;
+
 private:
 private:
 	string mCandidate;
 	string mCandidate;
 	string mMid;
 	string mMid;
-	bool mIsResolved;
+
+	// Extracted on resolution
+	Family mFamily;
+	Type mType;
+	TransportType mTransportType;
+	string mAddress;
+	uint16_t mPort;
+	uint32_t mPriority;
 };
 };
 
 
 } // namespace rtc
 } // namespace rtc
 
 
 std::ostream &operator<<(std::ostream &out, const rtc::Candidate &candidate);
 std::ostream &operator<<(std::ostream &out, const rtc::Candidate &candidate);
-std::ostream &operator<<(std::ostream &out, const rtc::CandidateType &type);
-std::ostream &operator<<(std::ostream &out, const rtc::CandidateTransportType &transportType);
+std::ostream &operator<<(std::ostream &out, const rtc::Candidate::Type &type);
+std::ostream &operator<<(std::ostream &out, const rtc::Candidate::TransportType &transportType);
 
 
 #endif
 #endif
 
 

+ 16 - 15
include/rtc/description.hpp

@@ -34,8 +34,8 @@ namespace rtc {
 
 
 class Description {
 class Description {
 public:
 public:
-	enum class Type { Unspec = 0, Offer = 1, Answer = 2 };
-	enum class Role { ActPass = 0, Passive = 1, Active = 2 };
+	enum class Type { Unspec, Offer, Answer, Pranswer, Rollback };
+	enum class Role { ActPass, Passive, Active };
 	enum class Direction { SendOnly, RecvOnly, SendRecv, Inactive, Unknown };
 	enum class Direction { SendOnly, RecvOnly, SendRecv, Inactive, Unknown };
 
 
 	Description(const string &sdp, const string &typeString = "");
 	Description(const string &sdp, const string &typeString = "");
@@ -45,10 +45,9 @@ public:
 	Type type() const;
 	Type type() const;
 	string typeString() const;
 	string typeString() const;
 	Role role() const;
 	Role role() const;
-	string roleString() const;
 	string bundleMid() const;
 	string bundleMid() const;
-	string iceUfrag() const;
-	string icePwd() const;
+	std::optional<string> iceUfrag() const;
+	std::optional<string> icePwd() const;
 	std::optional<string> fingerprint() const;
 	std::optional<string> fingerprint() const;
 	bool ended() const;
 	bool ended() const;
 
 
@@ -56,6 +55,7 @@ public:
 	void setFingerprint(string fingerprint);
 	void setFingerprint(string fingerprint);
 
 
 	void addCandidate(Candidate candidate);
 	void addCandidate(Candidate candidate);
+	void addCandidates(std::vector<Candidate> candidates);
 	void endCandidates();
 	void endCandidates();
 	std::vector<Candidate> extractCandidates();
 	std::vector<Candidate> extractCandidates();
 
 
@@ -74,7 +74,7 @@ public:
 		void setDirection(Direction dir);
 		void setDirection(Direction dir);
 
 
 		operator string() const;
 		operator string() const;
-		string generateSdp(string_view eol) const;
+		string generateSdp(string_view eol, string_view addr, string_view port) const;
 
 
 		virtual void parseSdpLine(string_view line);
 		virtual void parseSdpLine(string_view line);
 
 
@@ -94,8 +94,7 @@ public:
 	struct Application : public Entry {
 	struct Application : public Entry {
 	public:
 	public:
 		Application(string mid = "data");
 		Application(string mid = "data");
-		Application(const Application &other) = default;
-		Application(Application &&other) = default;
+		virtual ~Application() = default;
 
 
 		string description() const override;
 		string description() const override;
 		Application reciprocate() const;
 		Application reciprocate() const;
@@ -121,8 +120,6 @@ public:
 	public:
 	public:
 		Media(const string &sdp);
 		Media(const string &sdp);
 		Media(const string &mline, string mid, Direction dir = Direction::SendOnly);
 		Media(const string &mline, string mid, Direction dir = Direction::SendOnly);
-		Media(const Media &other) = default;
-		Media(Media &&other) = default;
 		virtual ~Media() = default;
 		virtual ~Media() = default;
 
 
 		string description() const override;
 		string description() const override;
@@ -180,6 +177,7 @@ public:
 
 
 	bool hasApplication() const;
 	bool hasApplication() const;
 	bool hasAudioOrVideo() const;
 	bool hasAudioOrVideo() const;
+	bool hasMid(string_view mid) const;
 
 
 	int addMedia(Media media);
 	int addMedia(Media media);
 	int addMedia(Application application);
 	int addMedia(Application application);
@@ -193,7 +191,11 @@ public:
 
 
 	Application *application();
 	Application *application();
 
 
+	static Type stringToType(const string &typeString);
+	static string typeToString(Type type);
+
 private:
 private:
+	std::optional<Candidate> defaultCandidate() const;
 	std::shared_ptr<Entry> createEntry(string mline, string mid, Direction dir);
 	std::shared_ptr<Entry> createEntry(string mline, string mid, Direction dir);
 	void removeApplication();
 	void removeApplication();
 
 
@@ -201,8 +203,9 @@ private:
 
 
 	// Session-level attributes
 	// Session-level attributes
 	Role mRole;
 	Role mRole;
+	string mUsername;
 	string mSessionId;
 	string mSessionId;
-	string mIceUfrag, mIcePwd;
+	std::optional<string> mIceUfrag, mIcePwd;
 	std::optional<string> mFingerprint;
 	std::optional<string> mFingerprint;
 
 
 	// Entries
 	// Entries
@@ -212,14 +215,12 @@ private:
 	// Candidates
 	// Candidates
 	std::vector<Candidate> mCandidates;
 	std::vector<Candidate> mCandidates;
 	bool mEnded = false;
 	bool mEnded = false;
-
-	static Type stringToType(const string &typeString);
-	static string typeToString(Type type);
-	static string roleToString(Role role);
 };
 };
 
 
 } // namespace rtc
 } // namespace rtc
 
 
 std::ostream &operator<<(std::ostream &out, const rtc::Description &description);
 std::ostream &operator<<(std::ostream &out, const rtc::Description &description);
+std::ostream &operator<<(std::ostream &out, rtc::Description::Type type);
+std::ostream &operator<<(std::ostream &out, rtc::Description::Role role);
 
 
 #endif
 #endif

+ 21 - 4
include/rtc/include.hpp

@@ -29,7 +29,7 @@
 
 
 #ifdef _WIN32
 #ifdef _WIN32
 #ifndef _WIN32_WINNT
 #ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0602
+#define _WIN32_WINNT 0x0602 // Windows 8
 #endif
 #endif
 #endif
 #endif
 
 
@@ -62,7 +62,7 @@ using std::uint8_t;
 const size_t MAX_NUMERICNODE_LEN = 48; // Max IPv6 string representation length
 const size_t MAX_NUMERICNODE_LEN = 48; // Max IPv6 string representation length
 const size_t MAX_NUMERICSERV_LEN = 6;  // Max port string representation length
 const size_t MAX_NUMERICSERV_LEN = 6;  // Max port string representation length
 
 
-const uint16_t DEFAULT_SCTP_PORT = 5000; // SCTP port to use by default
+const uint16_t DEFAULT_SCTP_PORT = 5000;          // SCTP port to use by default
 const size_t DEFAULT_MAX_MESSAGE_SIZE = 65536;    // Remote max message size if not specified in SDP
 const size_t DEFAULT_MAX_MESSAGE_SIZE = 65536;    // Remote max message size if not specified in SDP
 const size_t LOCAL_MAX_MESSAGE_SIZE = 256 * 1024; // Local max message size
 const size_t LOCAL_MAX_MESSAGE_SIZE = 256 * 1024; // Local max message size
 
 
@@ -72,7 +72,7 @@ const int THREADPOOL_SIZE = 4; // Number of threads in the global thread pool
 
 
 // overloaded helper
 // overloaded helper
 template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
 template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
-template <class... Ts> overloaded(Ts...)->overloaded<Ts...>;
+template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
 
 
 // weak_ptr bind helper
 // weak_ptr bind helper
 template <typename F, typename T, typename... Args> auto weak_bind(F &&f, T *t, Args &&... _args) {
 template <typename F, typename T, typename... Args> auto weak_bind(F &&f, T *t, Args &&... _args) {
@@ -85,6 +85,23 @@ template <typename F, typename T, typename... Args> auto weak_bind(F &&f, T *t,
 	};
 	};
 }
 }
 
 
+// scope_guard helper
+class scope_guard {
+public:
+	scope_guard(std::function<void()> func) : function(std::move(func)) {}
+	scope_guard(scope_guard &&other) = delete;
+	scope_guard(const scope_guard &) = delete;
+	void operator=(const scope_guard &) = delete;
+
+	~scope_guard() {
+		if (function)
+			function();
+	}
+
+private:
+	std::function<void()> function;
+};
+
 template <typename... P> class synchronized_callback {
 template <typename... P> class synchronized_callback {
 public:
 public:
 	synchronized_callback() = default;
 	synchronized_callback() = default;
@@ -127,6 +144,6 @@ private:
 	std::function<void(P...)> callback;
 	std::function<void(P...)> callback;
 	mutable std::recursive_mutex mutex;
 	mutable std::recursive_mutex mutex;
 };
 };
-}
+} // namespace rtc
 
 
 #endif
 #endif

+ 23 - 6
include/rtc/peerconnection.hpp

@@ -67,6 +67,14 @@ public:
 		Complete = RTC_GATHERING_COMPLETE
 		Complete = RTC_GATHERING_COMPLETE
 	};
 	};
 
 
+	enum class SignalingState : int {
+		Stable = RTC_SIGNALING_STABLE,
+		HaveLocalOffer = RTC_SIGNALING_HAVE_LOCAL_OFFER,
+		HaveRemoteOffer = RTC_SIGNALING_HAVE_REMOTE_OFFER,
+		HaveLocalPranswer = RTC_SIGNALING_HAVE_LOCAL_PRANSWER,
+		HaveRemotePranswer = RTC_SIGNALING_HAVE_REMOTE_PRANSWER,
+	} rtcSignalingState;
+
 	PeerConnection(void);
 	PeerConnection(void);
 	PeerConnection(const Configuration &config);
 	PeerConnection(const Configuration &config);
 	~PeerConnection();
 	~PeerConnection();
@@ -76,6 +84,7 @@ public:
 	const Configuration *config() const;
 	const Configuration *config() const;
 	State state() const;
 	State state() const;
 	GatheringState gatheringState() const;
 	GatheringState gatheringState() const;
+	SignalingState signalingState() const;
 	bool hasLocalDescription() const;
 	bool hasLocalDescription() const;
 	bool hasRemoteDescription() const;
 	bool hasRemoteDescription() const;
 	bool hasMedia() const;
 	bool hasMedia() const;
@@ -83,8 +92,9 @@ public:
 	std::optional<Description> remoteDescription() const;
 	std::optional<Description> remoteDescription() const;
 	std::optional<string> localAddress() const;
 	std::optional<string> localAddress() const;
 	std::optional<string> remoteAddress() const;
 	std::optional<string> remoteAddress() const;
+	bool getSelectedCandidatePair(Candidate *local, Candidate *remote);
 
 
-	void setLocalDescription();
+	void setLocalDescription(Description::Type type = Description::Type::Unspec);
 	void setRemoteDescription(Description description);
 	void setRemoteDescription(Description description);
 	void addRemoteCandidate(Candidate candidate);
 	void addRemoteCandidate(Candidate candidate);
 
 
@@ -100,6 +110,7 @@ public:
 	void onLocalCandidate(std::function<void(Candidate candidate)> callback);
 	void onLocalCandidate(std::function<void(Candidate candidate)> callback);
 	void onStateChange(std::function<void(State state)> callback);
 	void onStateChange(std::function<void(State state)> callback);
 	void onGatheringStateChange(std::function<void(GatheringState state)> callback);
 	void onGatheringStateChange(std::function<void(GatheringState state)> callback);
+	void onSignalingStateChange(std::function<void(SignalingState state)> callback);
 
 
 	// Stats
 	// Stats
 	void clearStats();
 	void clearStats();
@@ -111,9 +122,6 @@ public:
 	std::shared_ptr<Track> addTrack(Description::Media description);
 	std::shared_ptr<Track> addTrack(Description::Media description);
 	void onTrack(std::function<void(std::shared_ptr<Track> track)> callback);
 	void onTrack(std::function<void(std::shared_ptr<Track> track)> callback);
 
 
-	// libnice only
-	bool getSelectedCandidatePair(CandidateInfo *local, CandidateInfo *remote);
-
 private:
 private:
 	std::shared_ptr<IceTransport> initIceTransport(Description::Role role);
 	std::shared_ptr<IceTransport> initIceTransport(Description::Role role);
 	std::shared_ptr<DtlsTransport> initDtlsTransport();
 	std::shared_ptr<DtlsTransport> initDtlsTransport();
@@ -137,12 +145,16 @@ private:
 	void incomingTrack(Description::Media description);
 	void incomingTrack(Description::Media description);
 	void openTracks();
 	void openTracks();
 
 
+	void validateRemoteDescription(const Description &description);
 	void processLocalDescription(Description description);
 	void processLocalDescription(Description description);
 	void processLocalCandidate(Candidate candidate);
 	void processLocalCandidate(Candidate candidate);
+	void processRemoteDescription(Description description);
+	void processRemoteCandidate(Candidate candidate);
 	void triggerDataChannel(std::weak_ptr<DataChannel> weakDataChannel);
 	void triggerDataChannel(std::weak_ptr<DataChannel> weakDataChannel);
 	void triggerTrack(std::shared_ptr<Track> track);
 	void triggerTrack(std::shared_ptr<Track> track);
 	bool changeState(State state);
 	bool changeState(State state);
 	bool changeGatheringState(GatheringState state);
 	bool changeGatheringState(GatheringState state);
+	bool changeSignalingState(SignalingState state);
 
 
 	void resetCallbacks();
 	void resetCallbacks();
 
 
@@ -154,6 +166,7 @@ private:
 	const std::unique_ptr<Processor> mProcessor;
 	const std::unique_ptr<Processor> mProcessor;
 
 
 	std::optional<Description> mLocalDescription, mRemoteDescription;
 	std::optional<Description> mLocalDescription, mRemoteDescription;
+	std::optional<Description> mCurrentLocalDescription;
 	mutable std::mutex mLocalDescriptionMutex, mRemoteDescriptionMutex;
 	mutable std::mutex mLocalDescriptionMutex, mRemoteDescriptionMutex;
 
 
 	std::shared_ptr<IceTransport> mIceTransport;
 	std::shared_ptr<IceTransport> mIceTransport;
@@ -168,18 +181,22 @@ private:
 
 
 	std::atomic<State> mState;
 	std::atomic<State> mState;
 	std::atomic<GatheringState> mGatheringState;
 	std::atomic<GatheringState> mGatheringState;
+	std::atomic<SignalingState> mSignalingState;
+	std::atomic<bool> mNegotiationNeeded;
 
 
 	synchronized_callback<std::shared_ptr<DataChannel>> mDataChannelCallback;
 	synchronized_callback<std::shared_ptr<DataChannel>> mDataChannelCallback;
 	synchronized_callback<Description> mLocalDescriptionCallback;
 	synchronized_callback<Description> mLocalDescriptionCallback;
 	synchronized_callback<Candidate> mLocalCandidateCallback;
 	synchronized_callback<Candidate> mLocalCandidateCallback;
 	synchronized_callback<State> mStateChangeCallback;
 	synchronized_callback<State> mStateChangeCallback;
 	synchronized_callback<GatheringState> mGatheringStateChangeCallback;
 	synchronized_callback<GatheringState> mGatheringStateChangeCallback;
+	synchronized_callback<SignalingState> mSignalingStateChangeCallback;
 	synchronized_callback<std::shared_ptr<Track>> mTrackCallback;
 	synchronized_callback<std::shared_ptr<Track>> mTrackCallback;
 };
 };
 
 
 } // namespace rtc
 } // namespace rtc
 
 
-std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::State &state);
-std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::GatheringState &state);
+std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::State state);
+std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::GatheringState state);
+std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::SignalingState state);
 
 
 #endif
 #endif

+ 13 - 1
include/rtc/rtc.h

@@ -59,6 +59,14 @@ typedef enum {
 	RTC_GATHERING_COMPLETE = 2
 	RTC_GATHERING_COMPLETE = 2
 } rtcGatheringState;
 } rtcGatheringState;
 
 
+typedef enum {
+	RTC_SIGNALING_STABLE = 0,
+	RTC_SIGNALING_HAVE_LOCAL_OFFER = 1,
+	RTC_SIGNALING_HAVE_REMOTE_OFFER = 2,
+	RTC_SIGNALING_HAVE_LOCAL_PRANSWER = 3,
+	RTC_SIGNALING_HAVE_REMOTE_PRANSWER = 4,
+} rtcSignalingState;
+
 typedef enum { // Don't change, it must match plog severity
 typedef enum { // Don't change, it must match plog severity
 	RTC_LOG_NONE = 0,
 	RTC_LOG_NONE = 0,
 	RTC_LOG_FATAL = 1,
 	RTC_LOG_FATAL = 1,
@@ -92,6 +100,7 @@ typedef void (RTC_API *rtcDescriptionCallbackFunc)(int pc, const char *sdp, cons
 typedef void (RTC_API *rtcCandidateCallbackFunc)(int pc, const char *cand, const char *mid, void *ptr);
 typedef void (RTC_API *rtcCandidateCallbackFunc)(int pc, const char *cand, const char *mid, void *ptr);
 typedef void (RTC_API *rtcStateChangeCallbackFunc)(int pc, rtcState state, void *ptr);
 typedef void (RTC_API *rtcStateChangeCallbackFunc)(int pc, rtcState state, void *ptr);
 typedef void (RTC_API *rtcGatheringStateCallbackFunc)(int pc, rtcGatheringState state, void *ptr);
 typedef void (RTC_API *rtcGatheringStateCallbackFunc)(int pc, rtcGatheringState state, void *ptr);
+typedef void (RTC_API *rtcSignalingStateCallbackFunc)(int pc, rtcSignalingState state, void *ptr);
 typedef void (RTC_API *rtcDataChannelCallbackFunc)(int pc, int dc, void *ptr);
 typedef void (RTC_API *rtcDataChannelCallbackFunc)(int pc, int dc, void *ptr);
 typedef void (RTC_API *rtcTrackCallbackFunc)(int pc, int tr, void *ptr);
 typedef void (RTC_API *rtcTrackCallbackFunc)(int pc, int tr, void *ptr);
 typedef void (RTC_API *rtcOpenCallbackFunc)(int id, void *ptr);
 typedef void (RTC_API *rtcOpenCallbackFunc)(int id, void *ptr);
@@ -116,8 +125,9 @@ RTC_EXPORT int rtcSetLocalDescriptionCallback(int pc, rtcDescriptionCallbackFunc
 RTC_EXPORT int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb);
 RTC_EXPORT int rtcSetLocalCandidateCallback(int pc, rtcCandidateCallbackFunc cb);
 RTC_EXPORT int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb);
 RTC_EXPORT int rtcSetStateChangeCallback(int pc, rtcStateChangeCallbackFunc cb);
 RTC_EXPORT int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb);
 RTC_EXPORT int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb);
+RTC_EXPORT int rtcSetSignalingStateChangeCallback(int pc, rtcSignalingStateCallbackFunc cb);
 
 
-RTC_EXPORT int rtcSetLocalDescription(int pc);
+RTC_EXPORT int rtcSetLocalDescription(int pc, const char *type);
 RTC_EXPORT int rtcSetRemoteDescription(int pc, const char *sdp, const char *type);
 RTC_EXPORT int rtcSetRemoteDescription(int pc, const char *sdp, const char *type);
 RTC_EXPORT int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid);
 RTC_EXPORT int rtcAddRemoteCandidate(int pc, const char *cand, const char *mid);
 
 
@@ -127,6 +137,8 @@ RTC_EXPORT int rtcGetRemoteDescription(int pc, char *buffer, int size);
 RTC_EXPORT int rtcGetLocalAddress(int pc, char *buffer, int size);
 RTC_EXPORT int rtcGetLocalAddress(int pc, char *buffer, int size);
 RTC_EXPORT int rtcGetRemoteAddress(int pc, char *buffer, int size);
 RTC_EXPORT int rtcGetRemoteAddress(int pc, char *buffer, int size);
 
 
+RTC_EXPORT int rtcGetSelectedCandidatePair(int pc, char *local, int localSize, char *remote, int remoteSize);
+
 // DataChannel
 // DataChannel
 RTC_EXPORT int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb);
 RTC_EXPORT int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb);
 RTC_EXPORT int rtcAddDataChannel(int pc, const char *label); // returns dc id
 RTC_EXPORT int rtcAddDataChannel(int pc, const char *label); // returns dc id

+ 2 - 0
include/rtc/track.hpp

@@ -43,6 +43,8 @@ public:
 	string mid() const;
 	string mid() const;
 	Description::Media description() const;
 	Description::Media description() const;
 
 
+	void setDescription(Description::Media description);
+
 	void close(void) override;
 	void close(void) override;
 	bool send(message_variant data) override;
 	bool send(message_variant data) override;
 	bool send(const byte *data, size_t size);
 	bool send(const byte *data, size_t size);

+ 102 - 33
src/candidate.cpp

@@ -21,6 +21,7 @@
 #include <algorithm>
 #include <algorithm>
 #include <array>
 #include <array>
 #include <sstream>
 #include <sstream>
+#include <unordered_map>
 
 
 #ifdef _WIN32
 #ifdef _WIN32
 #include <winsock2.h>
 #include <winsock2.h>
@@ -47,20 +48,40 @@ inline bool hasprefix(const string &str, const string &prefix) {
 
 
 namespace rtc {
 namespace rtc {
 
 
-Candidate::Candidate(string candidate, string mid) : mIsResolved(false) {
-	const std::array prefixes{"a=", "candidate:"};
-	for (const string &prefix : prefixes)
-		if (hasprefix(candidate, prefix))
-			candidate.erase(0, prefix.size());
+Candidate::Candidate(string candidate, string mid)
+    : mFamily(Family::Unresolved), mType(Type::Unknown), mTransportType(TransportType::Unknown),
+      mPort(0), mPriority(0) {
+
+	if (!candidate.empty()) {
+		const std::array prefixes{"a=", "candidate:"};
+		for (const string &prefix : prefixes)
+			if (hasprefix(candidate, prefix))
+				candidate.erase(0, prefix.size());
+	}
 
 
 	mCandidate = std::move(candidate);
 	mCandidate = std::move(candidate);
 	mMid = std::move(mid);
 	mMid = std::move(mid);
 }
 }
 
 
 bool Candidate::resolve(ResolveMode mode) {
 bool Candidate::resolve(ResolveMode mode) {
-	if (mIsResolved)
+	using TypeMap_t = std::unordered_map<string, Type>;	
+	using TcpTypeMap_t = std::unordered_map<string, TransportType>;
+
+	static const TypeMap_t TypeMap = {{"host", Type::Host},
+	                                  {"srflx", Type::ServerReflexive},
+	                                  {"prflx", Type::PeerReflexive},
+	                                  {"relay", Type::Relayed}};
+
+	static const TcpTypeMap_t TcpTypeMap = {{"active", TransportType::TcpActive},
+	                                        {"passive", TransportType::TcpPassive},
+	                                        {"so", TransportType::TcpSo}};
+
+	if (mFamily != Family::Unresolved)
 		return true;
 		return true;
 
 
+	if(mCandidate.empty())
+		throw std::logic_error("Candidate is empty");
+
 	PLOG_VERBOSE << "Resolving candidate (mode="
 	PLOG_VERBOSE << "Resolving candidate (mode="
 				 << (mode == ResolveMode::Simple ? "simple" : "lookup")
 				 << (mode == ResolveMode::Simple ? "simple" : "lookup")
 				 << "): " << mCandidate;
 				 << "): " << mCandidate;
@@ -75,16 +96,39 @@ bool Candidate::resolve(ResolveMode mode) {
 		string left;
 		string left;
 		std::getline(iss, left);
 		std::getline(iss, left);
 
 
+		if (auto it = TypeMap.find(type); it != TypeMap.end())
+			mType = it->second;
+		else
+			mType = Type::Unknown;
+		
+		if (transport == "UDP" || transport == "udp") {
+			mTransportType = TransportType::Udp;
+		}
+		else if (transport == "TCP" || transport == "tcp") {
+			std::istringstream iss(left);
+			string tcptype_, tcptype;
+			if(iss >> tcptype_ >> tcptype && tcptype_ == "tcptype") {
+				if (auto it = TcpTypeMap.find(tcptype); it != TcpTypeMap.end())
+					mTransportType = it->second;
+				else 
+					mTransportType = TransportType::TcpUnknown;
+
+			} else {
+				mTransportType = TransportType::TcpUnknown;
+			}
+		} else {
+			mTransportType = TransportType::Unknown;
+		}
+
 		// Try to resolve the node
 		// Try to resolve the node
 		struct addrinfo hints = {};
 		struct addrinfo hints = {};
 		hints.ai_family = AF_UNSPEC;
 		hints.ai_family = AF_UNSPEC;
 		hints.ai_flags = AI_ADDRCONFIG;
 		hints.ai_flags = AI_ADDRCONFIG;
-		if (transport == "UDP" || transport == "udp") {
+		if (mTransportType == TransportType::Udp) {
 			hints.ai_socktype = SOCK_DGRAM;
 			hints.ai_socktype = SOCK_DGRAM;
 			hints.ai_protocol = IPPROTO_UDP;
 			hints.ai_protocol = IPPROTO_UDP;
 		}
 		}
-
-		if (transport == "TCP" || transport == "tcp") {
+		else if (mTransportType != TransportType::Unknown) {
 			hints.ai_socktype = SOCK_STREAM;
 			hints.ai_socktype = SOCK_STREAM;
 			hints.ai_protocol = IPPROTO_TCP;
 			hints.ai_protocol = IPPROTO_TCP;
 		}
 		}
@@ -102,13 +146,18 @@ bool Candidate::resolve(ResolveMode mode) {
 					if (getnameinfo(p->ai_addr, socklen_t(p->ai_addrlen), nodebuffer,
 					if (getnameinfo(p->ai_addr, socklen_t(p->ai_addrlen), nodebuffer,
 					                MAX_NUMERICNODE_LEN, servbuffer, MAX_NUMERICSERV_LEN,
 					                MAX_NUMERICNODE_LEN, servbuffer, MAX_NUMERICSERV_LEN,
 					                NI_NUMERICHOST | NI_NUMERICSERV) == 0) {
 					                NI_NUMERICHOST | NI_NUMERICSERV) == 0) {
+						
+						mAddress = nodebuffer;
+						mPort = uint16_t(std::stoul(servbuffer));
+						mFamily = p->ai_family == AF_INET6 ? Family::Ipv6 : Family::Ipv4;
+						
 						const char sp{' '};
 						const char sp{' '};
 						std::ostringstream oss;
 						std::ostringstream oss;
 						oss << foundation << sp << component << sp << transport << sp << priority;
 						oss << foundation << sp << component << sp << transport << sp << priority;
 						oss << sp << nodebuffer << sp << servbuffer << sp << "typ" << sp << type;
 						oss << sp << nodebuffer << sp << servbuffer << sp << "typ" << sp << type;
 						oss << left;
 						oss << left;
 						mCandidate = oss.str();
 						mCandidate = oss.str();
-						mIsResolved = true;
+
 						PLOG_VERBOSE << "Resolved candidate: " << mCandidate;
 						PLOG_VERBOSE << "Resolved candidate: " << mCandidate;
 						break;
 						break;
 					}
 					}
@@ -119,11 +168,9 @@ bool Candidate::resolve(ResolveMode mode) {
 		}
 		}
 	}
 	}
 
 
-	return mIsResolved;
+	return mFamily != Family::Unresolved;
 }
 }
 
 
-bool Candidate::isResolved() const { return mIsResolved; }
-
 string Candidate::candidate() const { return "candidate:" + mCandidate; }
 string Candidate::candidate() const { return "candidate:" + mCandidate; }
 
 
 string Candidate::mid() const { return mMid; }
 string Candidate::mid() const { return mMid; }
@@ -134,38 +181,60 @@ Candidate::operator string() const {
 	return line.str();
 	return line.str();
 }
 }
 
 
+bool Candidate::isResolved() const { return mFamily != Family::Unresolved; }
+
+Candidate::Family Candidate::family() const { return mFamily; }
+
+Candidate::Type Candidate::type() const { return mType; }
+
+Candidate::TransportType Candidate::transportType() const { return mTransportType; }
+
+std::optional<string> Candidate::address() const {
+	return isResolved() ? std::make_optional(mAddress) : nullopt;
+}
+
+std::optional<uint16_t> Candidate::port() const {
+	return isResolved() ? std::make_optional(mPort) : nullopt;
+}
+
+std::optional<uint32_t> Candidate::priority() const {
+	return isResolved() ? std::make_optional(mPriority) : nullopt;
+}
+
 } // namespace rtc
 } // namespace rtc
 
 
 std::ostream &operator<<(std::ostream &out, const rtc::Candidate &candidate) {
 std::ostream &operator<<(std::ostream &out, const rtc::Candidate &candidate) {
 	return out << std::string(candidate);
 	return out << std::string(candidate);
 }
 }
 
 
-std::ostream &operator<<(std::ostream &out, const rtc::CandidateType &type) {
+std::ostream &operator<<(std::ostream &out, const rtc::Candidate::Type &type) {
 	switch (type) {
 	switch (type) {
-	case rtc::CandidateType::Host:
-		return out << "Host";
-	case rtc::CandidateType::PeerReflexive:
-		return out << "PeerReflexive";
-	case rtc::CandidateType::Relayed:
-		return out << "Relayed";
-	case rtc::CandidateType::ServerReflexive:
-		return out << "ServerReflexive";
+	case rtc::Candidate::Type::Host:
+		return out << "host";
+	case rtc::Candidate::Type::PeerReflexive:
+		return out << "peer_reflexive";
+	case rtc::Candidate::Type::ServerReflexive:
+		return out << "server_reflexive";
+	case rtc::Candidate::Type::Relayed:
+		return out << "relayed";
 	default:
 	default:
-		return out << "Unknown";
+		return out << "unknown";
 	}
 	}
 }
 }
 
 
-std::ostream &operator<<(std::ostream &out, const rtc::CandidateTransportType &transportType) {
+std::ostream &operator<<(std::ostream &out, const rtc::Candidate::TransportType &transportType) {
 	switch (transportType) {
 	switch (transportType) {
-	case rtc::CandidateTransportType::TcpActive:
-		return out << "TcpActive";
-	case rtc::CandidateTransportType::TcpPassive:
-		return out << "TcpPassive";
-	case rtc::CandidateTransportType::TcpSo:
-		return out << "TcpSo";
-	case rtc::CandidateTransportType::Udp:
-		return out << "Udp";
+	case rtc::Candidate::TransportType::Udp:
+		return out << "UDP";
+	case rtc::Candidate::TransportType::TcpActive:
+		return out << "TCP_active";
+	case rtc::Candidate::TransportType::TcpPassive:
+		return out << "TCP_passive";
+	case rtc::Candidate::TransportType::TcpSo:
+		return out << "TCP_so";
+	case rtc::Candidate::TransportType::TcpUnknown:
+		return out << "TCP_unknown";
 	default:
 	default:
-		return out << "Unknown";
+		return out << "unknown";
 	}
 	}
 }
 }

+ 48 - 3
src/capi.cpp

@@ -317,7 +317,7 @@ int rtcCreateDataChannel(int pc, const char *label) {
 int rtcCreateDataChannelExt(int pc, const char *label, const char *protocol,
 int rtcCreateDataChannelExt(int pc, const char *label, const char *protocol,
                             const rtcReliability *reliability) {
                             const rtcReliability *reliability) {
 	int dc = rtcAddDataChannelExt(pc, label, protocol, reliability);
 	int dc = rtcAddDataChannelExt(pc, label, protocol, reliability);
-	rtcSetLocalDescription(pc);
+	rtcSetLocalDescription(pc, NULL);
 	return dc;
 	return dc;
 }
 }
 
 
@@ -468,6 +468,19 @@ int rtcSetGatheringStateChangeCallback(int pc, rtcGatheringStateCallbackFunc cb)
 	});
 	});
 }
 }
 
 
+int rtcSetSignalingStateChangeCallback(int pc, rtcSignalingStateCallbackFunc cb) {
+	return WRAP({
+		auto peerConnection = getPeerConnection(pc);
+		if (cb)
+			peerConnection->onSignalingStateChange([pc, cb](PeerConnection::SignalingState state) {
+				if (auto ptr = getUserPointer(pc))
+					cb(pc, static_cast<rtcSignalingState>(state), *ptr);
+			});
+		else
+			peerConnection->onGatheringStateChange(nullptr);
+	});
+}
+
 int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb) {
 int rtcSetDataChannelCallback(int pc, rtcDataChannelCallbackFunc cb) {
 	return WRAP({
 	return WRAP({
 		auto peerConnection = getPeerConnection(pc);
 		auto peerConnection = getPeerConnection(pc);
@@ -500,10 +513,11 @@ int rtcSetTrackCallback(int pc, rtcTrackCallbackFunc cb) {
 	});
 	});
 }
 }
 
 
-int rtcSetLocalDescription(int pc) {
+int rtcSetLocalDescription(int pc, const char *type) {
 	return WRAP({
 	return WRAP({
 		auto peerConnection = getPeerConnection(pc);
 		auto peerConnection = getPeerConnection(pc);
-		peerConnection->setLocalDescription();
+		peerConnection->setLocalDescription(type ? Description::stringToType(type)
+		                                         : Description::Type::Unspec);
 	});
 	});
 }
 }
 
 
@@ -619,6 +633,37 @@ int rtcGetRemoteAddress(int pc, char *buffer, int size) {
 	});
 	});
 }
 }
 
 
+int rtcGetSelectedCandidatePair(int pc, char *local, int localSize, char *remote, int remoteSize) {
+	return WRAP({
+		auto peerConnection = getPeerConnection(pc);
+
+		if (!local)
+			localSize = 0;
+		if (!remote)
+			remoteSize = 0;
+
+		Candidate localCand;
+		Candidate remoteCand;
+		if (peerConnection->getSelectedCandidatePair(&localCand, &remoteCand)) {
+			if (localSize > 0) {
+				string localSdp = string(localCand);
+				localSize = std::min(localSize - 1, int(localSdp.size()));
+				std::copy(localSdp.begin(), localSdp.begin() + localSize, local);
+				local[localSize] = '\0';
+			}
+			if (remoteSize > 0) {
+				string remoteSdp = string(remoteCand);
+				remoteSize = std::min(remoteSize - 1, int(remoteSdp.size()));
+				std::copy(remoteSdp.begin(), remoteSdp.begin() + remoteSize, remote);
+				remote[remoteSize] = '\0';
+			}
+			return localSize + remoteSize;
+		}
+
+		return RTC_ERR_FAILURE;
+	});
+}
+
 int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
 int rtcGetDataChannelLabel(int dc, char *buffer, int size) {
 	return WRAP({
 	return WRAP({
 		auto dataChannel = getDataChannel(dc);
 		auto dataChannel = getDataChannel(dc);

+ 9 - 1
src/certificate.cpp

@@ -99,7 +99,11 @@ certificate_ptr make_certificate_impl(string commonName) {
 	unique_ptr<gnutls_x509_crt_t, decltype(&free_crt)> crt(new_crt(), free_crt);
 	unique_ptr<gnutls_x509_crt_t, decltype(&free_crt)> crt(new_crt(), free_crt);
 	unique_ptr<gnutls_x509_privkey_t, decltype(&free_privkey)> privkey(new_privkey(), free_privkey);
 	unique_ptr<gnutls_x509_privkey_t, decltype(&free_privkey)> privkey(new_privkey(), free_privkey);
 
 
+#ifdef RSA_KEY_BITS_2048
+	const unsigned int bits = 2048;
+#else
 	const unsigned int bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_HIGH);
 	const unsigned int bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_HIGH);
+#endif
 	gnutls::check(gnutls_x509_privkey_generate(*privkey, GNUTLS_PK_RSA, bits, 0),
 	gnutls::check(gnutls_x509_privkey_generate(*privkey, GNUTLS_PK_RSA, bits, 0),
 	              "Unable to generate key pair");
 	              "Unable to generate key pair");
 
 
@@ -190,7 +194,11 @@ certificate_ptr make_certificate_impl(string commonName) {
 	if (!x509 || !pkey || !rsa || !exponent || !serial_number || !name)
 	if (!x509 || !pkey || !rsa || !exponent || !serial_number || !name)
 		throw std::runtime_error("Unable allocate structures for certificate generation");
 		throw std::runtime_error("Unable allocate structures for certificate generation");
 
 
-	const int bits = 4096;
+#ifdef RSA_KEY_BITS_2048
+	const int bits = 2048;
+#else
+	const int bits = 3072;
+#endif
 	const unsigned int e = 65537; // 2^16 + 1
 	const unsigned int e = 65537; // 2^16 + 1
 
 
 	if (!pkey || !rsa || !exponent || !BN_set_word(exponent.get(), e) ||
 	if (!pkey || !rsa || !exponent || !BN_set_word(exponent.get(), e) ||

+ 117 - 56
src/description.cpp

@@ -26,6 +26,7 @@
 #include <iostream>
 #include <iostream>
 #include <random>
 #include <random>
 #include <sstream>
 #include <sstream>
+#include <unordered_map>
 
 
 using std::shared_ptr;
 using std::shared_ptr;
 using std::size_t;
 using std::size_t;
@@ -74,11 +75,6 @@ Description::Description(const string &sdp, Type type, Role role)
     : mType(Type::Unspec), mRole(role) {
     : mType(Type::Unspec), mRole(role) {
 	hintType(type);
 	hintType(type);
 
 
-	auto seed = static_cast<unsigned int>(system_clock::now().time_since_epoch().count());
-	std::default_random_engine generator(seed);
-	std::uniform_int_distribution<uint32_t> uniform;
-	mSessionId = std::to_string(uniform(generator));
-
 	int index = -1;
 	int index = -1;
 	std::shared_ptr<Entry> current;
 	std::shared_ptr<Entry> current;
 	std::istringstream ss(sdp);
 	std::istringstream ss(sdp);
@@ -89,14 +85,14 @@ Description::Description(const string &sdp, Type type, Role role)
 		if (line.empty())
 		if (line.empty())
 			continue;
 			continue;
 
 
-		// Media description line (aka m-line)
-		if (match_prefix(line, "m=")) {
-			++index;
-			string mline = line.substr(2);
-			current = createEntry(std::move(mline), std::to_string(index), Direction::Unknown);
+		if (match_prefix(line, "m=")) { // Media description line (aka m-line)
+			current = createEntry(line.substr(2), std::to_string(++index), Direction::Unknown);
+
+		} else if (match_prefix(line, "o=")) { // Origin line
+			std::istringstream origin(line.substr(2));
+			origin >> mUsername >> mSessionId;
 
 
-			// Attribute line
-		} else if (match_prefix(line, "a=")) {
+		} else if (match_prefix(line, "a=")) { // Attribute line
 			string attr = line.substr(2);
 			string attr = line.substr(2);
 			auto [key, value] = parse_pair(attr);
 			auto [key, value] = parse_pair(attr);
 
 
@@ -134,11 +130,15 @@ Description::Description(const string &sdp, Type type, Role role)
 		}
 		}
 	}
 	}
 
 
-	if (mIceUfrag.empty())
-		throw std::invalid_argument("Missing ice-ufrag parameter in SDP description");
+	if (mUsername.empty())
+		mUsername = "rtc";
 
 
-	if (mIcePwd.empty())
-		throw std::invalid_argument("Missing ice-pwd parameter in SDP description");
+	if (mSessionId.empty()) {
+		auto seed = static_cast<unsigned int>(system_clock::now().time_since_epoch().count());
+		std::default_random_engine generator(seed);
+		std::uniform_int_distribution<uint32_t> uniform;
+		mSessionId = std::to_string(uniform(generator));
+	}
 }
 }
 
 
 Description::Type Description::type() const { return mType; }
 Description::Type Description::type() const { return mType; }
@@ -147,16 +147,14 @@ string Description::typeString() const { return typeToString(mType); }
 
 
 Description::Role Description::role() const { return mRole; }
 Description::Role Description::role() const { return mRole; }
 
 
-string Description::roleString() const { return roleToString(mRole); }
-
 string Description::bundleMid() const {
 string Description::bundleMid() const {
 	// Get the mid of the first media
 	// Get the mid of the first media
 	return !mEntries.empty() ? mEntries[0]->mid() : "0";
 	return !mEntries.empty() ? mEntries[0]->mid() : "0";
 }
 }
 
 
-string Description::iceUfrag() const { return mIceUfrag; }
+std::optional<string> Description::iceUfrag() const { return mIceUfrag; }
 
 
-string Description::icePwd() const { return mIcePwd; }
+std::optional<string> Description::icePwd() const { return mIcePwd; }
 
 
 std::optional<string> Description::fingerprint() const { return mFingerprint; }
 std::optional<string> Description::fingerprint() const { return mFingerprint; }
 
 
@@ -178,6 +176,11 @@ void Description::addCandidate(Candidate candidate) {
 	mCandidates.emplace_back(std::move(candidate));
 	mCandidates.emplace_back(std::move(candidate));
 }
 }
 
 
+void Description::addCandidates(std::vector<Candidate> candidates) {
+	for(auto candidate : candidates)
+		mCandidates.emplace_back(std::move(candidate));
+}
+
 void Description::endCandidates() { mEnded = true; }
 void Description::endCandidates() { mEnded = true; }
 
 
 std::vector<Candidate> Description::extractCandidates() {
 std::vector<Candidate> Description::extractCandidates() {
@@ -194,7 +197,7 @@ string Description::generateSdp(string_view eol) const {
 
 
 	// Header
 	// Header
 	sdp << "v=0" << eol;
 	sdp << "v=0" << eol;
-	sdp << "o=- " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
+	sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
 	sdp << "s=-" << eol;
 	sdp << "s=-" << eol;
 	sdp << "t=0 0" << eol;
 	sdp << "t=0 0" << eol;
 
 
@@ -217,20 +220,29 @@ string Description::generateSdp(string_view eol) const {
 
 
 	// Session-level attributes
 	// Session-level attributes
 	sdp << "a=msid-semantic:WMS *" << eol;
 	sdp << "a=msid-semantic:WMS *" << eol;
-	sdp << "a=setup:" << roleToString(mRole) << eol;
-	sdp << "a=ice-ufrag:" << mIceUfrag << eol;
-	sdp << "a=ice-pwd:" << mIcePwd << eol;
+	sdp << "a=setup:" << mRole << eol;
 
 
+	if (mIceUfrag)
+		sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
+	if (mIcePwd)
+		sdp << "a=ice-pwd:" << *mIcePwd << eol;
 	if (!mEnded)
 	if (!mEnded)
 		sdp << "a=ice-options:trickle" << eol;
 		sdp << "a=ice-options:trickle" << eol;
-
 	if (mFingerprint)
 	if (mFingerprint)
 		sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
 		sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
 
 
+	auto cand = defaultCandidate();
+	const string addr = cand && cand->isResolved()
+	                        ? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
+	                           " " + *cand->address())
+	                        : "IP4 0.0.0.0";
+	const string port = std::to_string(
+	    cand && cand->isResolved() ? *cand->port() : 9); // Port 9 is the discard protocol
+
 	// Entries
 	// Entries
 	bool first = true;
 	bool first = true;
 	for (const auto &entry : mEntries) {
 	for (const auto &entry : mEntries) {
-		sdp << entry->generateSdp(eol);
+		sdp << entry->generateSdp(eol, addr, port);
 
 
 		if (std::exchange(first, false)) {
 		if (std::exchange(first, false)) {
 			// Candidates
 			// Candidates
@@ -250,23 +262,32 @@ string Description::generateApplicationSdp(string_view eol) const {
 
 
 	// Header
 	// Header
 	sdp << "v=0" << eol;
 	sdp << "v=0" << eol;
-	sdp << "o=- " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
+	sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
 	sdp << "s=-" << eol;
 	sdp << "s=-" << eol;
 	sdp << "t=0 0" << eol;
 	sdp << "t=0 0" << eol;
 
 
+	auto cand = defaultCandidate();
+	const string addr = cand && cand->isResolved()
+	                        ? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
+	                           " " + *cand->address())
+	                        : "IP4 0.0.0.0";
+	const string port = std::to_string(
+	    cand && cand->isResolved() ? *cand->port() : 9); // Port 9 is the discard protocol
+
 	// Application
 	// Application
 	auto app = mApplication ? mApplication : std::make_shared<Application>();
 	auto app = mApplication ? mApplication : std::make_shared<Application>();
-	sdp << app->generateSdp(eol);
+	sdp << app->generateSdp(eol, addr, port);
 
 
 	// Session-level attributes
 	// Session-level attributes
 	sdp << "a=msid-semantic:WMS *" << eol;
 	sdp << "a=msid-semantic:WMS *" << eol;
-	sdp << "a=setup:" << roleToString(mRole) << eol;
-	sdp << "a=ice-ufrag:" << mIceUfrag << eol;
-	sdp << "a=ice-pwd:" << mIcePwd << eol;
+	sdp << "a=setup:" << mRole << eol;
 
 
+	if (mIceUfrag)
+		sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
+	if (mIcePwd)
+		sdp << "a=ice-pwd:" << *mIcePwd << eol;
 	if (!mEnded)
 	if (!mEnded)
 		sdp << "a=ice-options:trickle" << eol;
 		sdp << "a=ice-options:trickle" << eol;
-
 	if (mFingerprint)
 	if (mFingerprint)
 		sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
 		sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
 
 
@@ -280,6 +301,21 @@ string Description::generateApplicationSdp(string_view eol) const {
 	return sdp.str();
 	return sdp.str();
 }
 }
 
 
+std::optional<Candidate> Description::defaultCandidate() const {
+	// Return the first host candidate with highest priority, favoring IPv4
+	std::optional<Candidate> result;
+	for (const auto &c : mCandidates) {
+		if (c.type() == Candidate::Type::Host) {
+			if (!result ||
+			    (result->family() == Candidate::Family::Ipv6 &&
+			     c.family() == Candidate::Family::Ipv4) ||
+			    (result->family() == c.family() && result->priority() < c.priority()))
+				result.emplace(c);
+		}
+	}
+	return result;
+}
+
 shared_ptr<Description::Entry> Description::createEntry(string mline, string mid, Direction dir) {
 shared_ptr<Description::Entry> Description::createEntry(string mline, string mid, Direction dir) {
 	string type = mline.substr(0, mline.find(' '));
 	string type = mline.substr(0, mline.find(' '));
 	if (type == "application") {
 	if (type == "application") {
@@ -315,6 +351,14 @@ bool Description::hasAudioOrVideo() const {
 	return false;
 	return false;
 }
 }
 
 
+bool Description::hasMid(string_view mid) const {
+	for (const auto &entry : mEntries)
+		if (entry->mid() == mid)
+			return true;
+
+	return false;
+}
+
 int Description::addMedia(Media media) {
 int Description::addMedia(Media media) {
 	mEntries.emplace_back(std::make_shared<Media>(std::move(media)));
 	mEntries.emplace_back(std::make_shared<Media>(std::move(media)));
 	return int(mEntries.size()) - 1;
 	return int(mEntries.size()) - 1;
@@ -390,13 +434,12 @@ Description::Entry::Entry(const string &mline, string mid, Direction dir)
 
 
 void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
 void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
 
 
-Description::Entry::operator string() const { return generateSdp("\r\n"); }
+Description::Entry::operator string() const { return generateSdp("\r\n", "IP4 0.0.0.0", "9"); }
 
 
-string Description::Entry::generateSdp(string_view eol) const {
+string Description::Entry::generateSdp(string_view eol, string_view addr, string_view port) const {
 	std::ostringstream sdp;
 	std::ostringstream sdp;
-	// Port 9 is the discard protocol
-	sdp << "m=" << type() << ' ' << 9 << ' ' << description() << eol;
-	sdp << "c=IN IP4 0.0.0.0" << eol;
+	sdp << "m=" << type() << ' ' << port << ' ' << description() << eol;
+	sdp << "c=IN " << addr << eol;
 	sdp << generateSdpLines(eol);
 	sdp << generateSdpLines(eol);
 
 
 	return sdp.str();
 	return sdp.str();
@@ -515,8 +558,7 @@ Description::Media::Media(const string &sdp) : Entry(sdp, "", Direction::Unknown
 }
 }
 
 
 Description::Media::Media(const string &mline, string mid, Direction dir)
 Description::Media::Media(const string &mline, string mid, Direction dir)
-    : Entry(mline, std::move(mid), dir) {
-}
+    : Entry(mline, std::move(mid), dir) {}
 
 
 string Description::Media::description() const {
 string Description::Media::description() const {
 	std::ostringstream desc;
 	std::ostringstream desc;
@@ -733,38 +775,57 @@ Description::Video::Video(string mid, Direction dir)
     : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
     : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
 
 
 Description::Type Description::stringToType(const string &typeString) {
 Description::Type Description::stringToType(const string &typeString) {
-	if (typeString == "offer")
-		return Type::Offer;
-	else if (typeString == "answer")
-		return Type::Answer;
-	else
-		return Type::Unspec;
+	using TypeMap_t = std::unordered_map<string, Type>;
+	static const TypeMap_t TypeMap = {{"unspec", Type::Unspec},
+	                                  {"offer", Type::Offer},
+	                                  {"answer", Type::Pranswer},
+	                                  {"pranswer", Type::Pranswer},
+	                                  {"rollback", Type::Rollback}};
+	auto it = TypeMap.find(typeString);
+	return it != TypeMap.end() ? it->second : Type::Unspec;
 }
 }
 
 
 string Description::typeToString(Type type) {
 string Description::typeToString(Type type) {
 	switch (type) {
 	switch (type) {
+	case Type::Unspec:
+		return "unspec";
 	case Type::Offer:
 	case Type::Offer:
 		return "offer";
 		return "offer";
 	case Type::Answer:
 	case Type::Answer:
 		return "answer";
 		return "answer";
+	case Type::Pranswer:
+		return "pranswer";
+	case Type::Rollback:
+		return "rollback";
 	default:
 	default:
-		return "";
+		return "unknown";
 	}
 	}
 }
 }
 
 
-string Description::roleToString(Role role) {
+} // namespace rtc
+
+std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
+	return out << std::string(description);
+}
+
+std::ostream &operator<<(std::ostream &out, rtc::Description::Type type) {
+	return out << rtc::Description::typeToString(type);
+}
+
+std::ostream &operator<<(std::ostream &out, rtc::Description::Role role) {
+	using Role = rtc::Description::Role;
+	const char *str;
+	// Used for SDP generation, do not change
 	switch (role) {
 	switch (role) {
 	case Role::Active:
 	case Role::Active:
-		return "active";
+		str = "active";
+		break;
 	case Role::Passive:
 	case Role::Passive:
-		return "passive";
+		str = "passive";
+		break;
 	default:
 	default:
-		return "actpass";
+		str = "actpass";
+		break;
 	}
 	}
-}
-
-} // namespace rtc
-
-std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
-	return out << std::string(description);
+	return out << str;
 }
 }

+ 32 - 46
src/icetransport.cpp

@@ -187,6 +187,24 @@ std::optional<string> IceTransport::getRemoteAddress() const {
 	return nullopt;
 	return nullopt;
 }
 }
 
 
+bool IceTransport::getSelectedCandidatePair(Candidate *local, Candidate *remote) {
+	char sdpLocal[JUICE_MAX_CANDIDATE_SDP_STRING_LEN];
+	char sdpRemote[JUICE_MAX_CANDIDATE_SDP_STRING_LEN];
+	if (juice_get_selected_candidates(mAgent.get(), sdpLocal, JUICE_MAX_CANDIDATE_SDP_STRING_LEN,
+	                                 sdpRemote, JUICE_MAX_CANDIDATE_SDP_STRING_LEN) == 0) {
+		if (local) {
+			*local = Candidate(sdpLocal, mMid);
+			local->resolve(Candidate::ResolveMode::Simple);
+		}
+		if (remote) {
+			*remote = Candidate(sdpRemote, mMid);
+			remote->resolve(Candidate::ResolveMode::Simple);
+		}
+		return true;
+	}
+	return false;
+}
+
 bool IceTransport::send(message_ptr message) {
 bool IceTransport::send(message_ptr message) {
 	auto s = state();
 	auto s = state();
 	if (!message || (s != State::Connected && s != State::Completed))
 	if (!message || (s != State::Connected && s != State::Completed))
@@ -716,56 +734,24 @@ void IceTransport::LogCallback(const gchar * /*logDomain*/, GLogLevelFlags logLe
 	PLOG(severity) << "nice: " << message;
 	PLOG(severity) << "nice: " << message;
 }
 }
 
 
-bool IceTransport::getSelectedCandidatePair(CandidateInfo *localInfo, CandidateInfo *remoteInfo) {
-	NiceCandidate *local, *remote;
-	gboolean result = nice_agent_get_selected_pair(mNiceAgent.get(), mStreamId, 1, &local, &remote);
-
-	if (!result)
+bool IceTransport::getSelectedCandidatePair(Candidate *local, Candidate *remote) {
+	NiceCandidate *niceLocal, *niceRemote;
+	if(!nice_agent_get_selected_pair(mNiceAgent.get(), mStreamId, 1, &niceLocal, &niceRemote))
 		return false;
 		return false;
 
 
-	char ipaddr[INET6_ADDRSTRLEN];
-	nice_address_to_string(&local->addr, ipaddr);
-	localInfo->address = std::string(ipaddr);
-	localInfo->port = nice_address_get_port(&local->addr);
-	localInfo->type = IceTransport::NiceTypeToCandidateType(local->type);
-	localInfo->transportType =
-	    IceTransport::NiceTransportTypeToCandidateTransportType(local->transport);
-
-	nice_address_to_string(&remote->addr, ipaddr);
-	remoteInfo->address = std::string(ipaddr);
-	remoteInfo->port = nice_address_get_port(&remote->addr);
-	remoteInfo->type = IceTransport::NiceTypeToCandidateType(remote->type);
-	remoteInfo->transportType =
-	    IceTransport::NiceTransportTypeToCandidateTransportType(remote->transport);
+	gchar *sdpLocal = nice_agent_generate_local_candidate_sdp(mNiceAgent.get(), niceLocal);
+	if(local) *local = Candidate(sdpLocal, mMid);
+	g_free(sdpLocal);
 
 
-	return true;
-}
+	gchar *sdpRemote = nice_agent_generate_local_candidate_sdp(mNiceAgent.get(), niceRemote);
+	if(remote) *remote = Candidate(sdpRemote, mMid);
+	g_free(sdpRemote);
 
 
-CandidateType IceTransport::NiceTypeToCandidateType(NiceCandidateType type) {
-	switch (type) {
-	case NiceCandidateType::NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
-		return CandidateType::PeerReflexive;
-	case NiceCandidateType::NICE_CANDIDATE_TYPE_RELAYED:
-		return CandidateType::Relayed;
-	case NiceCandidateType::NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
-		return CandidateType::ServerReflexive;
-	default:
-		return CandidateType::Host;
-	}
-}
-
-CandidateTransportType
-IceTransport::NiceTransportTypeToCandidateTransportType(NiceCandidateTransport type) {
-	switch (type) {
-	case NiceCandidateTransport::NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE:
-		return CandidateTransportType::TcpActive;
-	case NiceCandidateTransport::NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE:
-		return CandidateTransportType::TcpPassive;
-	case NiceCandidateTransport::NICE_CANDIDATE_TRANSPORT_TCP_SO:
-		return CandidateTransportType::TcpSo;
-	default:
-		return CandidateTransportType::Udp;
-	}
+	if (local)
+		local->resolve(Candidate::ResolveMode::Simple);
+	if (remote)
+		remote->resolve(Candidate::ResolveMode::Simple);
+	return true;
 }
 }
 
 
 } // namespace rtc
 } // namespace rtc

+ 1 - 6
src/icetransport.hpp

@@ -63,9 +63,7 @@ public:
 	bool stop() override;
 	bool stop() override;
 	bool send(message_ptr message) override; // false if dropped
 	bool send(message_ptr message) override; // false if dropped
 
 
-#if USE_NICE
-	bool getSelectedCandidatePair(CandidateInfo *local, CandidateInfo *remote);
-#endif
+	bool getSelectedCandidatePair(Candidate *local, Candidate *remote);
 
 
 private:
 private:
 	bool outgoing(message_ptr message) override;
 	bool outgoing(message_ptr message) override;
@@ -113,9 +111,6 @@ private:
 	static gboolean TimeoutCallback(gpointer userData);
 	static gboolean TimeoutCallback(gpointer userData);
 	static void LogCallback(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message,
 	static void LogCallback(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message,
 	                        gpointer user_data);
 	                        gpointer user_data);
-	static CandidateType NiceTypeToCandidateType(NiceCandidateType type);
-	static CandidateTransportType
-	NiceTransportTypeToCandidateTransportType(NiceCandidateTransport type);
 #endif
 #endif
 };
 };
 
 

+ 406 - 153
src/peerconnection.cpp

@@ -44,7 +44,8 @@ PeerConnection::PeerConnection() : PeerConnection(Configuration()) {}
 
 
 PeerConnection::PeerConnection(const Configuration &config)
 PeerConnection::PeerConnection(const Configuration &config)
     : mConfig(config), mCertificate(make_certificate()), mProcessor(std::make_unique<Processor>()),
     : mConfig(config), mCertificate(make_certificate()), mProcessor(std::make_unique<Processor>()),
-      mState(State::New), mGatheringState(GatheringState::New) {
+      mState(State::New), mGatheringState(GatheringState::New),
+      mSignalingState(SignalingState::Stable), mNegotiationNeeded(false) {
 	PLOG_VERBOSE << "Creating PeerConnection";
 	PLOG_VERBOSE << "Creating PeerConnection";
 
 
 	if (config.portRangeEnd && config.portRangeBegin > config.portRangeEnd)
 	if (config.portRangeEnd && config.portRangeBegin > config.portRangeEnd)
@@ -60,6 +61,8 @@ PeerConnection::~PeerConnection() {
 void PeerConnection::close() {
 void PeerConnection::close() {
 	PLOG_VERBOSE << "Closing PeerConnection";
 	PLOG_VERBOSE << "Closing PeerConnection";
 
 
+	mNegotiationNeeded = false;
+
 	// Close data channels asynchronously
 	// Close data channels asynchronously
 	mProcessor->enqueue(std::bind(&PeerConnection::closeDataChannels, this));
 	mProcessor->enqueue(std::bind(&PeerConnection::closeDataChannels, this));
 
 
@@ -72,6 +75,8 @@ PeerConnection::State PeerConnection::state() const { return mState; }
 
 
 PeerConnection::GatheringState PeerConnection::gatheringState() const { return mGatheringState; }
 PeerConnection::GatheringState PeerConnection::gatheringState() const { return mGatheringState; }
 
 
+PeerConnection::SignalingState PeerConnection::signalingState() const { return mSignalingState; }
+
 std::optional<Description> PeerConnection::localDescription() const {
 std::optional<Description> PeerConnection::localDescription() const {
 	std::lock_guard lock(mLocalDescriptionMutex);
 	std::lock_guard lock(mLocalDescriptionMutex);
 	return mLocalDescription;
 	return mLocalDescription;
@@ -97,88 +102,178 @@ bool PeerConnection::hasMedia() const {
 	return local && local->hasAudioOrVideo();
 	return local && local->hasAudioOrVideo();
 }
 }
 
 
-void PeerConnection::setLocalDescription() {
-	PLOG_VERBOSE << "Setting local description";
+void PeerConnection::setLocalDescription(Description::Type type) {
+	PLOG_VERBOSE << "Setting local description, type=" << Description::typeToString(type);
+
+	SignalingState signalingState = mSignalingState.load();
+	if (type == Description::Type::Rollback) {
+		if (signalingState == SignalingState::HaveLocalOffer ||
+		    signalingState == SignalingState::HaveLocalPranswer) {
+			PLOG_DEBUG << "Rolling back pending local description";
+
+			std::unique_lock lock(mLocalDescriptionMutex);
+			if (mCurrentLocalDescription) {
+				std::vector<Candidate> existingCandidates;
+				if (mLocalDescription)
+					existingCandidates = mLocalDescription->extractCandidates();
 
 
-	if (std::atomic_load(&mIceTransport)) {
-		PLOG_DEBUG << "Local description is already set, ignoring";
+				mLocalDescription.emplace(std::move(*mCurrentLocalDescription));
+				mLocalDescription->addCandidates(std::move(existingCandidates));
+				mCurrentLocalDescription.reset();
+			}
+			lock.unlock();
+
+			changeSignalingState(SignalingState::Stable);
+		}
 		return;
 		return;
 	}
 	}
 
 
-	// RFC 5763: The endpoint that is the offerer MUST use the setup attribute value of
-	// setup:actpass.
-	// See https://tools.ietf.org/html/rfc5763#section-5
-	auto iceTransport = initIceTransport(Description::Role::ActPass);
-	Description localDescription = iceTransport->getLocalDescription(Description::Type::Offer);
-	processLocalDescription(localDescription);
-	iceTransport->gatherLocalCandidates();
-}
+	// Guess the description type if unspecified
+	if (type == Description::Type::Unspec) {
+		if (mSignalingState == SignalingState::HaveRemoteOffer)
+			type = Description::Type::Answer;
+		else
+			type = Description::Type::Offer;
+	}
 
 
-void PeerConnection::setRemoteDescription(Description description) {
-	PLOG_VERBOSE << "Setting remote description: " << string(description);
+	// Only a local offer resets the negotiation needed flag
+	if (type == Description::Type::Offer && !mNegotiationNeeded.exchange(false)) {
+		PLOG_DEBUG << "No negotiation needed";
+		return;
+	}
 
 
-	if (hasRemoteDescription())
-		throw std::logic_error("Remote description is already set");
+	// Get the new signaling state
+	SignalingState newSignalingState;
+	switch (signalingState) {
+	case SignalingState::Stable:
+		if (type != Description::Type::Offer) {
+			std::ostringstream oss;
+			oss << "Unexpected local desciption type " << type << " in signaling state "
+			    << signalingState;
+			throw std::logic_error(oss.str());
+		}
+		newSignalingState = SignalingState::HaveLocalOffer;
+		break;
 
 
-	if (description.mediaCount() == 0)
-		throw std::invalid_argument("Remote description has no media line");
+	case SignalingState::HaveRemoteOffer:
+	case SignalingState::HaveLocalPranswer:
+		if (type != Description::Type::Answer && type != Description::Type::Pranswer) {
+			std::ostringstream oss;
+			oss << "Unexpected local description type " << type
+			    << " description in signaling state " << signalingState;
+			throw std::logic_error(oss.str());
+		}
+		newSignalingState = SignalingState::Stable;
+		break;
 
 
-	int activeMediaCount = 0;
-	for (int i = 0; i < description.mediaCount(); ++i)
-		std::visit( // reciprocate each media
-		    rtc::overloaded{[&](Description::Application *) { ++activeMediaCount; },
-		                    [&](Description::Media *media) {
-			                    if (media->direction() != Description::Direction::Inactive)
-				                    ++activeMediaCount;
-		                    }},
-		    description.media(i));
+	default: {
+		std::ostringstream oss;
+		oss << "Unexpected local description in signaling state " << signalingState << ", ignoring";
+		LOG_WARNING << oss.str();
+		return;
+	}
+	}
 
 
-	if (activeMediaCount == 0)
-		throw std::invalid_argument("Remote description has no active media");
+	auto iceTransport = std::atomic_load(&mIceTransport);
+	if (!iceTransport) {
+		// RFC 5763: The endpoint that is the offerer MUST use the setup attribute value of
+		// setup:actpass.
+		// See https://tools.ietf.org/html/rfc5763#section-5
+		iceTransport = initIceTransport(Description::Role::ActPass);
+	}
 
 
-	if (!description.fingerprint())
-		throw std::invalid_argument("Remote description has no fingerprint");
+	Description localDescription = iceTransport->getLocalDescription(type);
+	processLocalDescription(std::move(localDescription));
 
 
-	description.hintType(hasLocalDescription() ? Description::Type::Answer
-	                                           : Description::Type::Offer);
+	changeSignalingState(newSignalingState);
 
 
-	if (description.type() == Description::Type::Offer) {
-		if (hasLocalDescription()) {
-			PLOG_ERROR << "Got a remote offer description while an answer was expected";
-			throw std::logic_error("Got an unexpected remote offer description");
+	if (mGatheringState == GatheringState::New)
+		iceTransport->gatherLocalCandidates();
+}
+
+void PeerConnection::setRemoteDescription(Description description) {
+	PLOG_VERBOSE << "Setting remote description: " << string(description);
+
+	if (description.type() == Description::Type::Rollback) {
+		// This is mostly useless because we accept any offer
+		PLOG_VERBOSE << "Rolling back pending remote description";
+		changeSignalingState(SignalingState::Stable);
+		return;
+	}
+
+	validateRemoteDescription(description);
+
+	// Get the new signaling state
+	SignalingState signalingState = mSignalingState.load();
+	SignalingState newSignalingState;
+	switch (signalingState) {
+	case SignalingState::Stable:
+		description.hintType(Description::Type::Offer);
+		if (description.type() != Description::Type::Offer) {
+			std::ostringstream oss;
+			oss << "Unexpected remote " << description.type() << " description in signaling state "
+			    << signalingState;
+			throw std::logic_error(oss.str());
 		}
 		}
-	} else { // Answer
-		if (auto local = localDescription()) {
-			if (description.iceUfrag() == local->iceUfrag() &&
-			    description.icePwd() == local->icePwd())
-				throw std::logic_error("Got the local description as remote description");
-		} else {
-			PLOG_ERROR << "Got a remote answer description while an offer was expected";
-			throw std::logic_error("Got an unexpected remote answer description");
+		newSignalingState = SignalingState::HaveRemoteOffer;
+		break;
+
+	case SignalingState::HaveLocalOffer:
+		description.hintType(Description::Type::Answer);
+		if (description.type() == Description::Type::Offer) {
+			// The ICE agent will automatically initiate a rollback when a peer that had previously
+			// created an offer receives an offer from the remote peer
+			setLocalDescription(Description::Type::Rollback);
+			newSignalingState = SignalingState::HaveRemoteOffer;
+			break;
+		}
+		if (description.type() != Description::Type::Answer &&
+		    description.type() != Description::Type::Pranswer) {
+			std::ostringstream oss;
+			oss << "Unexpected remote " << description.type() << " description in signaling state "
+			    << signalingState;
+			throw std::logic_error(oss.str());
+		}
+		newSignalingState = SignalingState::Stable;
+		break;
+
+	case SignalingState::HaveRemotePranswer:
+		description.hintType(Description::Type::Answer);
+		if (description.type() != Description::Type::Answer &&
+		    description.type() != Description::Type::Pranswer) {
+			std::ostringstream oss;
+			oss << "Unexpected remote " << description.type() << " description in signaling state "
+			    << signalingState;
+			throw std::logic_error(oss.str());
 		}
 		}
+		newSignalingState = SignalingState::Stable;
+		break;
+
+	default: {
+		std::ostringstream oss;
+		oss << "Unexpected remote description in signaling state " << signalingState;
+		throw std::logic_error(oss.str());
+	}
 	}
 	}
 
 
 	// Candidates will be added at the end, extract them for now
 	// Candidates will be added at the end, extract them for now
 	auto remoteCandidates = description.extractCandidates();
 	auto remoteCandidates = description.extractCandidates();
+	auto type = description.type();
 
 
 	auto iceTransport = std::atomic_load(&mIceTransport);
 	auto iceTransport = std::atomic_load(&mIceTransport);
 	if (!iceTransport)
 	if (!iceTransport)
 		iceTransport = initIceTransport(Description::Role::ActPass);
 		iceTransport = initIceTransport(Description::Role::ActPass);
+
 	iceTransport->setRemoteDescription(description);
 	iceTransport->setRemoteDescription(description);
+	processRemoteDescription(std::move(description));
 
 
-	{
-		// Set as remote description
-		std::lock_guard lock(mRemoteDescriptionMutex);
-		mRemoteDescription.emplace(std::move(description));
-	}
+	changeSignalingState(newSignalingState);
 
 
-	if (description.type() == Description::Type::Offer) {
-		// This is an offer and we are the answerer.
-		Description localDescription = iceTransport->getLocalDescription(Description::Type::Answer);
-		processLocalDescription(localDescription);
-		iceTransport->gatherLocalCandidates();
+	if (type == Description::Type::Offer) {
+		// This is an offer, we need to answer
+		setLocalDescription(Description::Type::Answer);
 	} else {
 	} else {
-		// This is an answer and we are the offerer.
+		// This is an answer
 		auto sctpTransport = std::atomic_load(&mSctpTransport);
 		auto sctpTransport = std::atomic_load(&mSctpTransport);
 		if (!sctpTransport && iceTransport->role() == Description::Role::Active) {
 		if (!sctpTransport && iceTransport->role() == Description::Role::Active) {
 			// Since we assumed passive role during DataChannel creation, we need to shift the
 			// Since we assumed passive role during DataChannel creation, we need to shift the
@@ -203,27 +298,7 @@ void PeerConnection::setRemoteDescription(Description description) {
 
 
 void PeerConnection::addRemoteCandidate(Candidate candidate) {
 void PeerConnection::addRemoteCandidate(Candidate candidate) {
 	PLOG_VERBOSE << "Adding remote candidate: " << string(candidate);
 	PLOG_VERBOSE << "Adding remote candidate: " << string(candidate);
-
-	auto iceTransport = std::atomic_load(&mIceTransport);
-	if (!mRemoteDescription || !iceTransport)
-		throw std::logic_error("Remote candidate set without remote description");
-
-	if (candidate.resolve(Candidate::ResolveMode::Simple)) {
-		iceTransport->addRemoteCandidate(candidate);
-	} else {
-		// OK, we might need a lookup, do it asynchronously
-		// We don't use the thread pool because we have no control on the timeout
-		weak_ptr<IceTransport> weakIceTransport{iceTransport};
-		std::thread t([weakIceTransport, candidate]() mutable {
-			if (candidate.resolve(Candidate::ResolveMode::Lookup))
-				if (auto iceTransport = weakIceTransport.lock())
-					iceTransport->addRemoteCandidate(candidate);
-		});
-		t.detach();
-	}
-
-	std::lock_guard lock(mRemoteDescriptionMutex);
-	mRemoteDescription->addCandidate(candidate);
+	processRemoteCandidate(std::move(candidate));
 }
 }
 
 
 std::optional<string> PeerConnection::localAddress() const {
 std::optional<string> PeerConnection::localAddress() const {
@@ -238,11 +313,6 @@ std::optional<string> PeerConnection::remoteAddress() const {
 
 
 shared_ptr<DataChannel> PeerConnection::addDataChannel(string label, string protocol,
 shared_ptr<DataChannel> PeerConnection::addDataChannel(string label, string protocol,
                                                        Reliability reliability) {
                                                        Reliability reliability) {
-	if (auto local = localDescription(); local && !local->hasApplication()) {
-		PLOG_ERROR << "The PeerConnection was negociated without DataChannel support.";
-		throw std::runtime_error("No DataChannel support on the PeerConnection");
-	}
-
 	// RFC 5763: The answerer MUST use either a setup attribute value of setup:active or
 	// RFC 5763: The answerer MUST use either a setup attribute value of setup:active or
 	// setup:passive. [...] Thus, setup:active is RECOMMENDED.
 	// setup:passive. [...] Thus, setup:active is RECOMMENDED.
 	// See https://tools.ietf.org/html/rfc5763#section-5
 	// See https://tools.ietf.org/html/rfc5763#section-5
@@ -257,6 +327,11 @@ shared_ptr<DataChannel> PeerConnection::addDataChannel(string label, string prot
 		if (transport->state() == SctpTransport::State::Connected)
 		if (transport->state() == SctpTransport::State::Connected)
 			channel->open(transport);
 			channel->open(transport);
 
 
+	// Renegotiation is needed iff the current local description does not have application
+	std::lock_guard lock(mLocalDescriptionMutex);
+	if (!mLocalDescription || !mLocalDescription->hasApplication())
+		mNegotiationNeeded = true;
+
 	return channel;
 	return channel;
 }
 }
 
 
@@ -288,21 +363,30 @@ void PeerConnection::onGatheringStateChange(std::function<void(GatheringState st
 	mGatheringStateChangeCallback = callback;
 	mGatheringStateChangeCallback = callback;
 }
 }
 
 
-std::shared_ptr<Track> PeerConnection::addTrack(Description::Media description) {
-	if (hasLocalDescription())
-		throw std::logic_error("Tracks must be created before local description");
-
-	if (auto it = mTracks.find(description.mid()); it != mTracks.end())
-		if (auto track = it->second.lock())
-			return track;
+void PeerConnection::onSignalingStateChange(std::function<void(SignalingState state)> callback) {
+	mSignalingStateChangeCallback = callback;
+}
 
 
+std::shared_ptr<Track> PeerConnection::addTrack(Description::Media description) {
 #if !RTC_ENABLE_MEDIA
 #if !RTC_ENABLE_MEDIA
 	if (mTracks.empty()) {
 	if (mTracks.empty()) {
 		PLOG_WARNING << "Tracks will be inative (not compiled with SRTP support)";
 		PLOG_WARNING << "Tracks will be inative (not compiled with SRTP support)";
 	}
 	}
 #endif
 #endif
-	auto track = std::make_shared<Track>(std::move(description));
-	mTracks.emplace(std::make_pair(track->mid(), track));
+
+	std::shared_ptr<Track> track;
+	if (auto it = mTracks.find(description.mid()); it != mTracks.end())
+		if (track = it->second.lock(); track)
+			track->setDescription(std::move(description));
+
+	if (!track) {
+		track = std::make_shared<Track>(std::move(description));
+		mTracks.emplace(std::make_pair(track->mid(), track));
+	}
+
+	// Renegotiation is needed for the new or updated track
+	mNegotiationNeeded = true;
+
 	return track;
 	return track;
 }
 }
 
 
@@ -311,6 +395,7 @@ void PeerConnection::onTrack(std::function<void(std::shared_ptr<Track>)> callbac
 }
 }
 
 
 shared_ptr<IceTransport> PeerConnection::initIceTransport(Description::Role role) {
 shared_ptr<IceTransport> PeerConnection::initIceTransport(Description::Role role) {
+	PLOG_VERBOSE << "Starting ICE transport";
 	try {
 	try {
 		if (auto transport = std::atomic_load(&mIceTransport))
 		if (auto transport = std::atomic_load(&mIceTransport))
 			return transport;
 			return transport;
@@ -373,6 +458,7 @@ shared_ptr<IceTransport> PeerConnection::initIceTransport(Description::Role role
 }
 }
 
 
 shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
 shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
+	PLOG_VERBOSE << "Starting DTLS transport";
 	try {
 	try {
 		if (auto transport = std::atomic_load(&mDtlsTransport))
 		if (auto transport = std::atomic_load(&mDtlsTransport))
 			return transport;
 			return transport;
@@ -388,12 +474,12 @@ shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
 
 
 			switch (state) {
 			switch (state) {
 			case DtlsTransport::State::Connected:
 			case DtlsTransport::State::Connected:
-				if (auto local = localDescription(); local && local->hasApplication())
+				if (auto remote = remoteDescription(); remote && remote->hasApplication())
 					initSctpTransport();
 					initSctpTransport();
 				else
 				else
 					changeState(State::Connected);
 					changeState(State::Connected);
 
 
-				openTracks();
+				mProcessor->enqueue(std::bind(&PeerConnection::openTracks, this));
 				break;
 				break;
 			case DtlsTransport::State::Failed:
 			case DtlsTransport::State::Failed:
 				changeState(State::Failed);
 				changeState(State::Failed);
@@ -443,13 +529,14 @@ shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
 }
 }
 
 
 shared_ptr<SctpTransport> PeerConnection::initSctpTransport() {
 shared_ptr<SctpTransport> PeerConnection::initSctpTransport() {
+	PLOG_VERBOSE << "Starting SCTP transport";
 	try {
 	try {
 		if (auto transport = std::atomic_load(&mSctpTransport))
 		if (auto transport = std::atomic_load(&mSctpTransport))
 			return transport;
 			return transport;
 
 
 		auto remote = remoteDescription();
 		auto remote = remoteDescription();
 		if (!remote || !remote->application())
 		if (!remote || !remote->application())
-			throw std::logic_error("Initializing SCTP transport without application description");
+			throw std::logic_error("Starting SCTP transport without application description");
 
 
 		uint16_t sctpPort = remote->application()->sctpPort().value_or(DEFAULT_SCTP_PORT);
 		uint16_t sctpPort = remote->application()->sctpPort().value_or(DEFAULT_SCTP_PORT);
 		auto lower = std::atomic_load(&mDtlsTransport);
 		auto lower = std::atomic_load(&mDtlsTransport);
@@ -463,16 +550,16 @@ shared_ptr<SctpTransport> PeerConnection::initSctpTransport() {
 			    switch (state) {
 			    switch (state) {
 			    case SctpTransport::State::Connected:
 			    case SctpTransport::State::Connected:
 				    changeState(State::Connected);
 				    changeState(State::Connected);
-				    openDataChannels();
+				    mProcessor->enqueue(std::bind(&PeerConnection::openDataChannels, this));
 				    break;
 				    break;
 			    case SctpTransport::State::Failed:
 			    case SctpTransport::State::Failed:
 				    LOG_WARNING << "SCTP transport failed";
 				    LOG_WARNING << "SCTP transport failed";
-				    remoteCloseDataChannels();
 				    changeState(State::Failed);
 				    changeState(State::Failed);
+				    mProcessor->enqueue(std::bind(&PeerConnection::remoteCloseDataChannels, this));
 				    break;
 				    break;
 			    case SctpTransport::State::Disconnected:
 			    case SctpTransport::State::Disconnected:
-				    remoteCloseDataChannels();
 				    changeState(State::Disconnected);
 				    changeState(State::Disconnected);
+				    mProcessor->enqueue(std::bind(&PeerConnection::remoteCloseDataChannels, this));
 				    break;
 				    break;
 			    default:
 			    default:
 				    // Ignore
 				    // Ignore
@@ -499,7 +586,8 @@ void PeerConnection::closeTransports() {
 	PLOG_VERBOSE << "Closing transports";
 	PLOG_VERBOSE << "Closing transports";
 
 
 	// Change state to sink state Closed
 	// Change state to sink state Closed
-	changeState(State::Closed);
+	if (!changeState(State::Closed))
+		return; // already closed
 
 
 	// Reset callbacks now that state is changed
 	// Reset callbacks now that state is changed
 	resetCallbacks();
 	resetCallbacks();
@@ -723,40 +811,105 @@ void PeerConnection::openTracks() {
 		std::shared_lock lock(mTracksMutex); // read-only
 		std::shared_lock lock(mTracksMutex); // read-only
 		for (auto it = mTracks.begin(); it != mTracks.end(); ++it)
 		for (auto it = mTracks.begin(); it != mTracks.end(); ++it)
 			if (auto track = it->second.lock())
 			if (auto track = it->second.lock())
-				track->open(srtpTransport);
+				if (!track->isOpen())
+					track->open(srtpTransport);
 	}
 	}
 #endif
 #endif
 }
 }
 
 
+void PeerConnection::validateRemoteDescription(const Description &description) {
+	if (!description.iceUfrag())
+		throw std::invalid_argument("Remote description has no ICE user fragment");
+
+	if (!description.icePwd())
+		throw std::invalid_argument("Remote description has no ICE password");
+
+	if (!description.fingerprint())
+		throw std::invalid_argument("Remote description has no fingerprint");
+
+	if (description.mediaCount() == 0)
+		throw std::invalid_argument("Remote description has no media line");
 
 
-void PeerConnection::processLocalDescription(Description description) {
 	int activeMediaCount = 0;
 	int activeMediaCount = 0;
+	for (int i = 0; i < description.mediaCount(); ++i)
+		std::visit(rtc::overloaded{[&](const Description::Application *) { ++activeMediaCount; },
+		                           [&](const Description::Media *media) {
+			                           if (media->direction() != Description::Direction::Inactive)
+				                           ++activeMediaCount;
+		                           }},
+		           description.media(i));
 
 
-	if (hasLocalDescription())
-		throw std::logic_error("Local description is already set");
+	if (activeMediaCount == 0)
+		throw std::invalid_argument("Remote description has no active media");
+
+	if (auto local = localDescription(); local && local->iceUfrag() && local->icePwd())
+		if (*description.iceUfrag() == *local->iceUfrag() &&
+		    *description.icePwd() == *local->icePwd())
+			throw std::logic_error("Got the local description as remote description");
 
 
+	PLOG_VERBOSE << "Remote description looks valid";
+}
+
+void PeerConnection::processLocalDescription(Description description) {
 	if (auto remote = remoteDescription()) {
 	if (auto remote = remoteDescription()) {
 		// Reciprocate remote description
 		// Reciprocate remote description
 		for (int i = 0; i < remote->mediaCount(); ++i)
 		for (int i = 0; i < remote->mediaCount(); ++i)
 			std::visit( // reciprocate each media
 			std::visit( // reciprocate each media
 			    rtc::overloaded{
 			    rtc::overloaded{
-			        [&](Description::Application *app) {
-				        auto reciprocated = app->reciprocate();
+			        [&](Description::Application *remoteApp) {
+				        std::shared_lock lock(mDataChannelsMutex);
+				        if (!mDataChannels.empty()) {
+					        // Prefer local description
+					        Description::Application app(remoteApp->mid());
+					        app.setSctpPort(DEFAULT_SCTP_PORT);
+					        app.setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
+
+					        PLOG_DEBUG << "Adding application to local description, mid=\""
+					                   << app.mid() << "\"";
+
+					        description.addMedia(std::move(app));
+					        return;
+				        }
+
+				        auto reciprocated = remoteApp->reciprocate();
 				        reciprocated.hintSctpPort(DEFAULT_SCTP_PORT);
 				        reciprocated.hintSctpPort(DEFAULT_SCTP_PORT);
 				        reciprocated.setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
 				        reciprocated.setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
-				        ++activeMediaCount;
 
 
 				        PLOG_DEBUG << "Reciprocating application in local description, mid=\""
 				        PLOG_DEBUG << "Reciprocating application in local description, mid=\""
 				                   << reciprocated.mid() << "\"";
 				                   << reciprocated.mid() << "\"";
 
 
 				        description.addMedia(std::move(reciprocated));
 				        description.addMedia(std::move(reciprocated));
 			        },
 			        },
-			        [&](Description::Media *media) {
-				        auto reciprocated = media->reciprocate();
-#if RTC_ENABLE_MEDIA
-				        if (reciprocated.direction() != Description::Direction::Inactive)
-					        ++activeMediaCount;
-#else
+			        [&](Description::Media *remoteMedia) {
+				        std::shared_lock lock(mTracksMutex);
+				        if (auto it = mTracks.find(remoteMedia->mid()); it != mTracks.end()) {
+					        // Prefer local description
+					        if (auto track = it->second.lock()) {
+						        auto media = track->description();
+#if !RTC_ENABLE_MEDIA
+						        // No media support, mark as inactive
+						        media.setDirection(Description::Direction::Inactive);
+#endif
+						        PLOG_DEBUG
+						            << "Adding media to local description, mid=\"" << media.mid()
+						            << "\", active=" << std::boolalpha
+						            << (media.direction() != Description::Direction::Inactive);
+
+						        description.addMedia(std::move(media));
+					        } else {
+						        auto reciprocated = remoteMedia->reciprocate();
+						        reciprocated.setDirection(Description::Direction::Inactive);
+
+						        PLOG_DEBUG << "Adding inactive media to local description, mid=\""
+						                   << reciprocated.mid() << "\"";
+
+						        description.addMedia(std::move(reciprocated));
+					        }
+					        return;
+				        }
+
+				        auto reciprocated = remoteMedia->reciprocate();
+#if !RTC_ENABLE_MEDIA
 				        // No media support, mark as inactive
 				        // No media support, mark as inactive
 				        reciprocated.setDirection(Description::Direction::Inactive);
 				        reciprocated.setDirection(Description::Direction::Inactive);
 #endif
 #endif
@@ -771,15 +924,17 @@ void PeerConnection::processLocalDescription(Description description) {
 			        },
 			        },
 			    },
 			    },
 			    remote->media(i));
 			    remote->media(i));
-	} else {
+	}
+
+	if (description.type() == Description::Type::Offer) {
+		// This is an offer, add locally created data channels and tracks
 		// Add application for data channels
 		// Add application for data channels
-		{
+		if (!description.hasApplication()) {
 			std::shared_lock lock(mDataChannelsMutex);
 			std::shared_lock lock(mDataChannelsMutex);
 			if (!mDataChannels.empty()) {
 			if (!mDataChannels.empty()) {
 				Description::Application app("data");
 				Description::Application app("data");
 				app.setSctpPort(DEFAULT_SCTP_PORT);
 				app.setSctpPort(DEFAULT_SCTP_PORT);
 				app.setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
 				app.setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
-				++activeMediaCount;
 
 
 				PLOG_DEBUG << "Adding application to local description, mid=\"" << app.mid()
 				PLOG_DEBUG << "Adding application to local description, mid=\"" << app.mid()
 				           << "\"";
 				           << "\"";
@@ -789,45 +944,52 @@ void PeerConnection::processLocalDescription(Description description) {
 		}
 		}
 
 
 		// Add media for local tracks
 		// Add media for local tracks
-		{
-			std::shared_lock lock(mTracksMutex);
-			for (auto it = mTracks.begin(); it != mTracks.end(); ++it) {
-				if (auto track = it->second.lock()) {
-					auto media = track->description();
-#if RTC_ENABLE_MEDIA
-					if (media.direction() != Description::Direction::Inactive)
-						++activeMediaCount;
-#else
-					// No media support, mark as inactive
-					media.setDirection(Description::Direction::Inactive);
+		std::shared_lock lock(mTracksMutex);
+		for (auto it = mTracks.begin(); it != mTracks.end(); ++it) {
+			if (description.hasMid(it->first))
+				continue;
+
+			if (auto track = it->second.lock()) {
+				auto media = track->description();
+#if !RTC_ENABLE_MEDIA
+				// No media support, mark as inactive
+				media.setDirection(Description::Direction::Inactive);
 #endif
 #endif
-					PLOG_DEBUG << "Adding media to local description, mid=\"" << media.mid()
-					           << "\", active=" << std::boolalpha
-					           << (media.direction() != Description::Direction::Inactive);
+				PLOG_DEBUG << "Adding media to local description, mid=\"" << media.mid()
+				           << "\", active=" << std::boolalpha
+				           << (media.direction() != Description::Direction::Inactive);
 
 
-					description.addMedia(std::move(media));
-				}
+				description.addMedia(std::move(media));
 			}
 			}
 		}
 		}
 	}
 	}
 
 
-	// There must be at least one active media to negociate
-	if (activeMediaCount == 0)
-		throw std::runtime_error("Nothing to negociate");
-
 	// Set local fingerprint (wait for certificate if necessary)
 	// Set local fingerprint (wait for certificate if necessary)
 	description.setFingerprint(mCertificate.get()->fingerprint());
 	description.setFingerprint(mCertificate.get()->fingerprint());
 
 
 	{
 	{
 		// Set as local description
 		// Set as local description
 		std::lock_guard lock(mLocalDescriptionMutex);
 		std::lock_guard lock(mLocalDescriptionMutex);
+
+		std::vector<Candidate> existingCandidates;
+		if (mLocalDescription) {
+			existingCandidates = mLocalDescription->extractCandidates();
+			mCurrentLocalDescription.emplace(std::move(*mLocalDescription));
+		}
+
 		mLocalDescription.emplace(std::move(description));
 		mLocalDescription.emplace(std::move(description));
+		mLocalDescription->addCandidates(std::move(existingCandidates));
 	}
 	}
 
 
 	mProcessor->enqueue([this, description = *mLocalDescription]() {
 	mProcessor->enqueue([this, description = *mLocalDescription]() {
 		PLOG_VERBOSE << "Issuing local description: " << description;
 		PLOG_VERBOSE << "Issuing local description: " << description;
 		mLocalDescriptionCallback(std::move(description));
 		mLocalDescriptionCallback(std::move(description));
 	});
 	});
+
+	// Reciprocated tracks might need to be open
+	if (auto dtlsTransport = std::atomic_load(&mDtlsTransport);
+	    dtlsTransport && dtlsTransport->state() == Transport::State::Connected)
+		mProcessor->enqueue(std::bind(&PeerConnection::openTracks, this));
 }
 }
 
 
 void PeerConnection::processLocalCandidate(Candidate candidate) {
 void PeerConnection::processLocalCandidate(Candidate candidate) {
@@ -835,6 +997,7 @@ void PeerConnection::processLocalCandidate(Candidate candidate) {
 	if (!mLocalDescription)
 	if (!mLocalDescription)
 		throw std::logic_error("Got a local candidate without local description");
 		throw std::logic_error("Got a local candidate without local description");
 
 
+	candidate.resolve(Candidate::ResolveMode::Simple); // for proper SDP generation later
 	mLocalDescription->addCandidate(candidate);
 	mLocalDescription->addCandidate(candidate);
 
 
 	mProcessor->enqueue([this, candidate = std::move(candidate)]() {
 	mProcessor->enqueue([this, candidate = std::move(candidate)]() {
@@ -843,6 +1006,56 @@ void PeerConnection::processLocalCandidate(Candidate candidate) {
 	});
 	});
 }
 }
 
 
+void PeerConnection::processRemoteDescription(Description description) {
+	{
+		// Set as remote description
+		std::lock_guard lock(mRemoteDescriptionMutex);
+
+		std::vector<Candidate> existingCandidates;
+		if (mRemoteDescription)
+			existingCandidates = mRemoteDescription->extractCandidates();
+
+		mRemoteDescription.emplace(std::move(description));
+		mRemoteDescription->addCandidates(std::move(existingCandidates));
+	}
+
+	if (description.hasApplication()) {
+		auto dtlsTransport = std::atomic_load(&mDtlsTransport);
+		auto sctpTransport = std::atomic_load(&mSctpTransport);
+		if (!sctpTransport && dtlsTransport &&
+		    dtlsTransport->state() == Transport::State::Connected)
+			initSctpTransport();
+	}
+}
+
+void PeerConnection::processRemoteCandidate(Candidate candidate) {
+	auto iceTransport = std::atomic_load(&mIceTransport);
+	if (!iceTransport)
+		throw std::logic_error("Remote candidate set without remote description");
+
+	if (candidate.resolve(Candidate::ResolveMode::Simple)) {
+		iceTransport->addRemoteCandidate(candidate);
+	} else {
+		// OK, we might need a lookup, do it asynchronously
+		// We don't use the thread pool because we have no control on the timeout
+		weak_ptr<IceTransport> weakIceTransport{iceTransport};
+		std::thread t([weakIceTransport, candidate]() mutable {
+			if (candidate.resolve(Candidate::ResolveMode::Lookup))
+				if (auto iceTransport = weakIceTransport.lock())
+					iceTransport->addRemoteCandidate(candidate);
+		});
+		t.detach();
+	}
+
+	{
+		std::lock_guard lock(mRemoteDescriptionMutex);
+		if (!mRemoteDescription)
+			throw std::logic_error("Got a remote candidate without remote description");
+
+		mRemoteDescription->addCandidate(candidate);
+	}
+}
+
 void PeerConnection::triggerDataChannel(weak_ptr<DataChannel> weakDataChannel) {
 void PeerConnection::triggerDataChannel(weak_ptr<DataChannel> weakDataChannel) {
 	auto dataChannel = weakDataChannel.lock();
 	auto dataChannel = weakDataChannel.lock();
 	if (!dataChannel)
 	if (!dataChannel)
@@ -860,13 +1073,17 @@ bool PeerConnection::changeState(State state) {
 	State current;
 	State current;
 	do {
 	do {
 		current = mState.load();
 		current = mState.load();
-		if (current == state)
-			return true;
 		if (current == State::Closed)
 		if (current == State::Closed)
 			return false;
 			return false;
+		if (current == state)
+			return false;
 
 
 	} while (!mState.compare_exchange_weak(current, state));
 	} while (!mState.compare_exchange_weak(current, state));
 
 
+	std::ostringstream s;
+	s << state;
+	PLOG_INFO << "Changed state to " << s.str();
+
 	if (state == State::Closed)
 	if (state == State::Closed)
 		// This is the last state change, so we may steal the callback
 		// This is the last state change, so we may steal the callback
 		mProcessor->enqueue([cb = std::move(mStateChangeCallback)]() { cb(State::Closed); });
 		mProcessor->enqueue([cb = std::move(mStateChangeCallback)]() { cb(State::Closed); });
@@ -877,8 +1094,24 @@ bool PeerConnection::changeState(State state) {
 }
 }
 
 
 bool PeerConnection::changeGatheringState(GatheringState state) {
 bool PeerConnection::changeGatheringState(GatheringState state) {
-	if (mGatheringState.exchange(state) != state)
-		mProcessor->enqueue([this, state] { mGatheringStateChangeCallback(state); });
+	if (mGatheringState.exchange(state) == state)
+		return false;
+
+	std::ostringstream s;
+	s << state;
+	PLOG_INFO << "Changed gathering state to " << s.str();
+	mProcessor->enqueue([this, state] { mGatheringStateChangeCallback(state); });
+	return true;
+}
+
+bool PeerConnection::changeSignalingState(SignalingState state) {
+	if (mSignalingState.exchange(state) == state)
+		return false;
+
+	std::ostringstream s;
+	s << state;
+	PLOG_INFO << "Changed signaling state to " << s.str();
+	mProcessor->enqueue([this, state] { mSignalingStateChangeCallback(state); });
 	return true;
 	return true;
 }
 }
 
 
@@ -891,15 +1124,10 @@ void PeerConnection::resetCallbacks() {
 	mGatheringStateChangeCallback = nullptr;
 	mGatheringStateChangeCallback = nullptr;
 }
 }
 
 
-bool PeerConnection::getSelectedCandidatePair([[maybe_unused]] CandidateInfo *local,
-                                              [[maybe_unused]] CandidateInfo *remote) {
-#if USE_NICE
+bool PeerConnection::getSelectedCandidatePair([[maybe_unused]] Candidate *local,
+                                              [[maybe_unused]] Candidate *remote) {
 	auto iceTransport = std::atomic_load(&mIceTransport);
 	auto iceTransport = std::atomic_load(&mIceTransport);
-	return iceTransport->getSelectedCandidatePair(local, remote);
-#else
-	PLOG_WARNING << "getSelectedCandidatePair() is only implemented with libnice as ICE backend";
-	return false;
-#endif
+	return iceTransport ? iceTransport->getSelectedCandidatePair(local, remote) : false;
 }
 }
 
 
 void PeerConnection::clearStats() {
 void PeerConnection::clearStats() {
@@ -926,15 +1154,14 @@ std::optional<std::chrono::milliseconds> PeerConnection::rtt() {
 	auto sctpTransport = std::atomic_load(&mSctpTransport);
 	auto sctpTransport = std::atomic_load(&mSctpTransport);
 	if (sctpTransport)
 	if (sctpTransport)
 		return sctpTransport->rtt();
 		return sctpTransport->rtt();
-	PLOG_WARNING << "Could not load sctpTransport";
 	return std::nullopt;
 	return std::nullopt;
 }
 }
 
 
 } // namespace rtc
 } // namespace rtc
 
 
-std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::State &state) {
+std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::State state) {
 	using State = rtc::PeerConnection::State;
 	using State = rtc::PeerConnection::State;
-	std::string str;
+	const char *str;
 	switch (state) {
 	switch (state) {
 	case State::New:
 	case State::New:
 		str = "new";
 		str = "new";
@@ -961,15 +1188,15 @@ std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::State &st
 	return out << str;
 	return out << str;
 }
 }
 
 
-std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::GatheringState &state) {
+std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::GatheringState state) {
 	using GatheringState = rtc::PeerConnection::GatheringState;
 	using GatheringState = rtc::PeerConnection::GatheringState;
-	std::string str;
+	const char *str;
 	switch (state) {
 	switch (state) {
 	case GatheringState::New:
 	case GatheringState::New:
 		str = "new";
 		str = "new";
 		break;
 		break;
 	case GatheringState::InProgress:
 	case GatheringState::InProgress:
-		str = "in_progress";
+		str = "in-progress";
 		break;
 		break;
 	case GatheringState::Complete:
 	case GatheringState::Complete:
 		str = "complete";
 		str = "complete";
@@ -980,3 +1207,29 @@ std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::Gathering
 	}
 	}
 	return out << str;
 	return out << str;
 }
 }
+
+std::ostream &operator<<(std::ostream &out, rtc::PeerConnection::SignalingState state) {
+	using SignalingState = rtc::PeerConnection::SignalingState;
+	const char *str;
+	switch (state) {
+	case SignalingState::Stable:
+		str = "stable";
+		break;
+	case SignalingState::HaveLocalOffer:
+		str = "have-local-offer";
+		break;
+	case SignalingState::HaveRemoteOffer:
+		str = "have-remote-offer";
+		break;
+	case SignalingState::HaveLocalPranswer:
+		str = "have-local-pranswer";
+		break;
+	case SignalingState::HaveRemotePranswer:
+		str = "have-remote-pranswer";
+		break;
+	default:
+		str = "unknown";
+		break;
+	}
+	return out << str;
+}

+ 8 - 19
src/processor.hpp

@@ -45,7 +45,7 @@ public:
 	void join();
 	void join();
 
 
 	template <class F, class... Args>
 	template <class F, class... Args>
-	auto enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...>;
+	void enqueue(F &&f, Args &&... args);
 
 
 protected:
 protected:
 	void schedule();
 	void schedule();
@@ -60,31 +60,20 @@ protected:
 	std::condition_variable mCondition;
 	std::condition_variable mCondition;
 };
 };
 
 
-template <class F, class... Args>
-auto Processor::enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...> {
+template <class F, class... Args> void Processor::enqueue(F &&f, Args &&... args) {
 	std::unique_lock lock(mMutex);
 	std::unique_lock lock(mMutex);
-	using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
-	auto task = std::make_shared<std::packaged_task<R()>>(
-	    std::bind(std::forward<F>(f), std::forward<Args>(args)...));
-	std::future<R> result = task->get_future();
-
-	auto bundle = [this, task = std::move(task)]() {
-		try {
-			(*task)();
-		} catch (const std::exception &e) {
-			PLOG_WARNING << "Unhandled exception in task: " << e.what();
-		}
-		schedule(); // chain the next task
+	auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
+	auto task = [this, bound = std::move(bound)]() mutable {
+		scope_guard guard(std::bind(&Processor::schedule, this)); // chain the next task
+		return bound();
 	};
 	};
 
 
 	if (!mPending) {
 	if (!mPending) {
-		ThreadPool::Instance().enqueue(std::move(bundle));
+		ThreadPool::Instance().enqueue(std::move(task));
 		mPending = true;
 		mPending = true;
 	} else {
 	} else {
-		mTasks.emplace(std::move(bundle));
+		mTasks.emplace(std::move(task));
 	}
 	}
-
-	return result;
 }
 }
 
 
 } // namespace rtc
 } // namespace rtc

+ 1 - 5
src/threadpool.cpp

@@ -58,11 +58,7 @@ void ThreadPool::run() {
 
 
 bool ThreadPool::runOne() {
 bool ThreadPool::runOne() {
 	if (auto task = dequeue()) {
 	if (auto task = dequeue()) {
-		try {
-			task();
-		} catch (const std::exception &e) {
-			PLOG_WARNING << "Unhandled exception in task: " << e.what();
-		}
+		task();
 		return true;
 		return true;
 	}
 	}
 	return false;
 	return false;

+ 9 - 2
src/threadpool.hpp

@@ -73,8 +73,15 @@ template <class F, class... Args>
 auto ThreadPool::enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...> {
 auto ThreadPool::enqueue(F &&f, Args &&... args) -> invoke_future_t<F, Args...> {
 	std::unique_lock lock(mMutex);
 	std::unique_lock lock(mMutex);
 	using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
 	using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
-	auto task = std::make_shared<std::packaged_task<R()>>(
-	    std::bind(std::forward<F>(f), std::forward<Args>(args)...));
+	auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
+	auto task = std::make_shared<std::packaged_task<R()>>([bound = std::move(bound)]() mutable {
+        try {
+            return bound();
+        } catch (const std::exception &e) {
+            PLOG_WARNING << e.what();
+            throw;
+        }
+    });
 	std::future<R> result = task->get_future();
 	std::future<R> result = task->get_future();
 
 
 	mTasks.emplace([task = std::move(task), token = Init::Token()]() { return (*task)(); });
 	mTasks.emplace([task = std::move(task), token = Init::Token()]() { return (*task)(); });

+ 7 - 0
src/track.cpp

@@ -32,6 +32,13 @@ string Track::mid() const { return mMediaDescription.mid(); }
 
 
 Description::Media Track::description() const { return mMediaDescription; }
 Description::Media Track::description() const { return mMediaDescription; }
 
 
+void Track::setDescription(Description::Media description) {
+	if(description.mid() != mMediaDescription.mid())
+		throw std::logic_error("Media description mid does not match track mid");
+
+	mMediaDescription = std::move(description);
+}
+
 void Track::close() {
 void Track::close() {
 	mIsClosed = true;
 	mIsClosed = true;
 	resetCallbacks();
 	resetCallbacks();

+ 4 - 1
src/websocket.cpp

@@ -159,6 +159,7 @@ void WebSocket::incoming(message_ptr message) {
 }
 }
 
 
 shared_ptr<TcpTransport> WebSocket::initTcpTransport() {
 shared_ptr<TcpTransport> WebSocket::initTcpTransport() {
+	PLOG_VERBOSE << "Starting TCP transport";
 	using State = TcpTransport::State;
 	using State = TcpTransport::State;
 	try {
 	try {
 		std::lock_guard lock(mInitMutex);
 		std::lock_guard lock(mInitMutex);
@@ -205,6 +206,7 @@ shared_ptr<TcpTransport> WebSocket::initTcpTransport() {
 }
 }
 
 
 shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
 shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
+	PLOG_VERBOSE << "Starting TLS transport";
 	using State = TlsTransport::State;
 	using State = TlsTransport::State;
 	try {
 	try {
 		std::lock_guard lock(mInitMutex);
 		std::lock_guard lock(mInitMutex);
@@ -262,6 +264,7 @@ shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
 }
 }
 
 
 shared_ptr<WsTransport> WebSocket::initWsTransport() {
 shared_ptr<WsTransport> WebSocket::initWsTransport() {
+	PLOG_VERBOSE << "Starting WebSocket transport";
 	using State = WsTransport::State;
 	using State = WsTransport::State;
 	try {
 	try {
 		std::lock_guard lock(mInitMutex);
 		std::lock_guard lock(mInitMutex);
@@ -340,6 +343,6 @@ void WebSocket::closeTransports() {
 	});
 	});
 }
 }
 
 
-	} // namespace rtc
+} // namespace rtc
 
 
 #endif
 #endif

+ 28 - 0
test/capi_connectivity.cpp

@@ -34,6 +34,7 @@ static void sleep(unsigned int secs) { Sleep(secs * 1000); }
 typedef struct {
 typedef struct {
 	rtcState state;
 	rtcState state;
 	rtcGatheringState gatheringState;
 	rtcGatheringState gatheringState;
+	rtcSignalingState signalingState;
 	int pc;
 	int pc;
 	int dc;
 	int dc;
 	bool connected;
 	bool connected;
@@ -68,6 +69,12 @@ static void gatheringStateCallback(int pc, rtcGatheringState state, void *ptr) {
 	printf("Gathering state %d: %d\n", peer == peer1 ? 1 : 2, (int)state);
 	printf("Gathering state %d: %d\n", peer == peer1 ? 1 : 2, (int)state);
 }
 }
 
 
+static void signalingStateCallback(int pc, rtcSignalingState state, void *ptr) {
+	Peer *peer = (Peer *)ptr;
+	peer->signalingState = state;
+	printf("Signaling state %d: %d\n", peer == peer1 ? 1 : 2, (int)state);
+}
+
 static void openCallback(int id, void *ptr) {
 static void openCallback(int id, void *ptr) {
 	Peer *peer = (Peer *)ptr;
 	Peer *peer = (Peer *)ptr;
 	peer->connected = true;
 	peer->connected = true;
@@ -180,12 +187,19 @@ int test_capi_connectivity_main() {
 		goto error;
 		goto error;
 	}
 	}
 
 
+	if (peer1->signalingState != RTC_SIGNALING_STABLE ||
+	    peer2->signalingState != RTC_SIGNALING_STABLE) {
+		fprintf(stderr, "Signaling state is not stable\n");
+		goto error;
+	}
+
 	if (!peer1->connected || !peer2->connected) {
 	if (!peer1->connected || !peer2->connected) {
 		fprintf(stderr, "DataChannel is not connected\n");
 		fprintf(stderr, "DataChannel is not connected\n");
 		goto error;
 		goto error;
 	}
 	}
 
 
 	char buffer[BUFFER_SIZE];
 	char buffer[BUFFER_SIZE];
+	char buffer2[BUFFER_SIZE];
 
 
 	if (rtcGetLocalDescription(peer1->pc, buffer, BUFFER_SIZE) < 0) {
 	if (rtcGetLocalDescription(peer1->pc, buffer, BUFFER_SIZE) < 0) {
 		fprintf(stderr, "rtcGetLocalDescription failed\n");
 		fprintf(stderr, "rtcGetLocalDescription failed\n");
@@ -235,6 +249,20 @@ int test_capi_connectivity_main() {
 	}
 	}
 	printf("Remote address 2: %s\n", buffer);
 	printf("Remote address 2: %s\n", buffer);
 
 
+	if (rtcGetSelectedCandidatePair(peer1->pc, buffer, BUFFER_SIZE, buffer2, BUFFER_SIZE) < 0) {
+		fprintf(stderr, "rtcGetSelectedCandidatePair failed\n");
+		goto error;
+	}
+	printf("Local candidate 1:  %s\n", buffer);
+	printf("Remote candidate 1: %s\n", buffer2);
+
+	if (rtcGetSelectedCandidatePair(peer2->pc, buffer, BUFFER_SIZE, buffer2, BUFFER_SIZE) < 0) {
+		fprintf(stderr, "rtcGetSelectedCandidatePair failed\n");
+		goto error;
+	}
+	printf("Local candidate 2:  %s\n", buffer);
+	printf("Remote candidate 2: %s\n", buffer2);
+
 	deletePeer(peer1);
 	deletePeer(peer1);
 	sleep(1);
 	sleep(1);
 	deletePeer(peer2);
 	deletePeer(peer2);

+ 1 - 1
test/capi_track.cpp

@@ -156,7 +156,7 @@ int test_capi_track_main() {
 	rtcSetClosedCallback(peer1->tr, closedCallback);
 	rtcSetClosedCallback(peer1->tr, closedCallback);
 
 
 	// Initiate the handshake
 	// Initiate the handshake
-	rtcSetLocalDescription(peer1->pc);
+	rtcSetLocalDescription(peer1->pc, NULL);
 
 
 	attempts = 10;
 	attempts = 10;
 	while ((!peer2->connected || !peer1->connected) && attempts--)
 	while ((!peer2->connected || !peer1->connected) && attempts--)

+ 18 - 0
test/connectivity.cpp

@@ -69,6 +69,10 @@ void test_connectivity() {
 		cout << "Gathering state 1: " << state << endl;
 		cout << "Gathering state 1: " << state << endl;
 	});
 	});
 
 
+	pc1->onSignalingStateChange([](PeerConnection::SignalingState state) {
+		cout << "Signaling state 1: " << state << endl;
+	});
+
 	pc2->onLocalDescription([wpc1 = make_weak_ptr(pc1)](Description sdp) {
 	pc2->onLocalDescription([wpc1 = make_weak_ptr(pc1)](Description sdp) {
 		auto pc1 = wpc1.lock();
 		auto pc1 = wpc1.lock();
 		if (!pc1)
 		if (!pc1)
@@ -91,6 +95,10 @@ void test_connectivity() {
 		cout << "Gathering state 2: " << state << endl;
 		cout << "Gathering state 2: " << state << endl;
 	});
 	});
 
 
+	pc2->onSignalingStateChange([](PeerConnection::SignalingState state) {
+		cout << "Signaling state 2: " << state << endl;
+	});
+
 	shared_ptr<DataChannel> dc2;
 	shared_ptr<DataChannel> dc2;
 	pc2->onDataChannel([&dc2](shared_ptr<DataChannel> dc) {
 	pc2->onDataChannel([&dc2](shared_ptr<DataChannel> dc) {
 		cout << "DataChannel 2: Received with label \"" << dc->label() << "\"" << endl;
 		cout << "DataChannel 2: Received with label \"" << dc->label() << "\"" << endl;
@@ -147,6 +155,16 @@ void test_connectivity() {
 	if (auto addr = pc2->remoteAddress())
 	if (auto addr = pc2->remoteAddress())
 		cout << "Remote address 2: " << *addr << endl;
 		cout << "Remote address 2: " << *addr << endl;
 
 
+	Candidate local, remote;
+	if(pc1->getSelectedCandidatePair(&local, &remote)) {
+		cout << "Local candidate 1:  " << local << endl;
+		cout << "Remote candidate 1: " << remote << endl;
+	}
+	if(pc2->getSelectedCandidatePair(&local, &remote)) {
+		cout << "Local candidate 2:  " << local << endl;
+		cout << "Remote candidate 2: " << remote << endl;
+	}
+
 	// Try to open a second data channel with another label
 	// Try to open a second data channel with another label
 	shared_ptr<DataChannel> second2;
 	shared_ptr<DataChannel> second2;
 	pc2->onDataChannel([&second2](shared_ptr<DataChannel> dc) {
 	pc2->onDataChannel([&second2](shared_ptr<DataChannel> dc) {

+ 20 - 3
test/track.cpp

@@ -92,9 +92,10 @@ void test_track() {
 	});
 	});
 
 
 	shared_ptr<Track> t2;
 	shared_ptr<Track> t2;
-	pc2->onTrack([&t2](shared_ptr<Track> t) {
+	string newTrackMid;
+	pc2->onTrack([&t2, &newTrackMid](shared_ptr<Track> t) {
 		cout << "Track 2: Received with mid \"" << t->mid() << "\"" << endl;
 		cout << "Track 2: Received with mid \"" << t->mid() << "\"" << endl;
-		if (t->mid() != "test") {
+		if (t->mid() != newTrackMid) {
 			cerr << "Wrong track mid" << endl;
 			cerr << "Wrong track mid" << endl;
 			return;
 			return;
 		}
 		}
@@ -102,7 +103,9 @@ void test_track() {
 		std::atomic_store(&t2, t);
 		std::atomic_store(&t2, t);
 	});
 	});
 
 
-	auto t1 = pc1->addTrack(Description::Video("test"));
+	// Test opening a track
+	newTrackMid = "test";
+	auto t1 = pc1->addTrack(Description::Video(newTrackMid));
 
 
 	pc1->setLocalDescription();
 	pc1->setLocalDescription();
 
 
@@ -118,6 +121,20 @@ void test_track() {
 	if (!at2 || !at2->isOpen() || !t1->isOpen())
 	if (!at2 || !at2->isOpen() || !t1->isOpen())
 		throw runtime_error("Track is not open");
 		throw runtime_error("Track is not open");
 
 
+	// Test renegotiation
+	newTrackMid = "added";
+	t1 = pc1->addTrack(Description::Video(newTrackMid));
+
+	pc1->setLocalDescription();
+
+	attempts = 10;
+	t2.reset();
+	while ((!(at2 = std::atomic_load(&t2)) || !at2->isOpen() || !t1->isOpen()) && attempts--)
+		this_thread::sleep_for(1s);
+
+	if (!at2 || !at2->isOpen() || !t1->isOpen())
+		throw runtime_error("Renegociated track is not open");
+
 	// TODO: Test sending RTP packets in track
 	// TODO: Test sending RTP packets in track
 
 
 	// Delay close of peer 2 to check closing works properly
 	// Delay close of peer 2 to check closing works properly