api.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. #include "pch.h"
  2. #include "../common/comm.h"
  3. #include "api.h"
  4. #include "callback.h"
  5. #include "api/create_peerconnection_factory.h"
  6. #include "video_frame_observer.h"
  7. #include "data_channel_observer.h"
  8. #include "audio_frame_observer.h"
  9. #include "peer_connection.h"
  10. #include "sdp_utils.h"
  11. #ifdef WEBRTC_LINUX
  12. //#include <opencv2/opencv.hpp>
  13. //#include <opencv2/core/core.hpp>
  14. //#include <opencv2/opencv.hpp>
  15. #include "capture_op.h"
  16. #include "gsml_capturer.h"
  17. #else
  18. #include "cap_interface.h"
  19. #include "overlay_video.h"
  20. #endif
  21. #include "NullEncoder.h"
  22. #include "NullDecoder.h"
  23. #ifdef WEBRTC_LINUX
  24. #include "sanitize_string.h"
  25. #include "capture_op.h"
  26. #include "gsml_capturer.h"
  27. #include "VideoScaler.h"
  28. #include "VideoFilter.h"
  29. #endif
  30. struct mrsEnumerator {
  31. virtual ~mrsEnumerator() = default;
  32. virtual void dispose() = 0;
  33. };
  34. rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
  35. g_peer_connection_factory;
  36. /*
  37. #ifdef WEBRTC_LINUX
  38. std::unique_ptr<webrtc::VideoDecoderFactory> g_video_decode_factory;
  39. #endif
  40. */
  41. /// WebRTC worker thread.
  42. std::unique_ptr<rtc::Thread> g_worker_thread;
  43. // #ifdef WIN32
  44. // //rtc::Win32SocketServer w32_ss;
  45. // std::unique_ptr<rtc::Thread> g_network_thread;
  46. // #else
  47. // rtc::AutoSocketServerThread g_network_thread;
  48. // #endif
  49. /// WebRTC signaling thread.
  50. std::unique_ptr<rtc::Thread> g_signaling_thread;
  51. std::unordered_map<
  52. PeerConnectionHandle,
  53. rtc::scoped_refptr<PeerConnection>>
  54. g_peer_connection_map;
  55. /// Predefined name of the local video track.
  56. const std::string kLocalVideoLabel("local_video");
  57. /// Predefined name of the local audio track.
  58. const std::string kLocalAudioLabel("local_audio");
  59. const std::string kLocalDataChannel("local_channel");
  60. /// WebRTC worker thread.
  61. const std::unique_ptr<rtc::Thread>& GetWorkerThread() {
  62. return g_worker_thread;
  63. }
  64. /// WebRTC signaling thread.
  65. const std::unique_ptr<rtc::Thread>& GetSignalingThread() {
  66. return g_signaling_thread;
  67. }
  68. void mrsCloseEnum(mrsEnumHandle* handleRef) {
  69. if (handleRef) {
  70. if (auto& handle = *handleRef) {
  71. handle->dispose();
  72. delete handle;
  73. handle = nullptr;
  74. }
  75. }
  76. }
  77. void mrsEnumVideoCaptureDevicesAsync(
  78. mrsVideoCaptureDeviceEnumCallback callback,
  79. void* userData,
  80. mrsVideoCaptureDeviceEnumCompletedCallback completedCallback,
  81. void* completedCallbackUserData) {
  82. if (!callback) {
  83. return;
  84. }
  85. std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(
  86. webrtc::VideoCaptureFactory::CreateDeviceInfo());
  87. if (!info) {
  88. if (completedCallback) {
  89. (*completedCallback)(completedCallbackUserData);
  90. }
  91. }
  92. int num_devices = info->NumberOfDevices();
  93. for (int i = 0; i < num_devices; ++i) {
  94. constexpr uint32_t kSize = 256;
  95. char name[kSize] = { 0 };
  96. char id[kSize] = { 0 };
  97. if (info->GetDeviceName(i, name, kSize, id, kSize) != -1) {
  98. (*callback)(id, name, userData);
  99. }
  100. }
  101. if (completedCallback) {
  102. (*completedCallback)(completedCallbackUserData);
  103. }
  104. }
  105. std::unique_ptr<webrtc::VideoEncoderFactory> CreateEncoderFactory(bool bNullCodec)
  106. {
  107. std::unique_ptr<webrtc::VideoEncoderFactory> factory;
  108. #ifdef WIN32
  109. if (bNullCodec) {
  110. factory=std::make_unique<VideoEncoderFactory>();
  111. }
  112. else {
  113. #endif
  114. factory=webrtc::CreateBuiltinVideoEncoderFactory();
  115. #ifdef WIN32
  116. }
  117. #endif
  118. return factory;
  119. }
  120. std::unique_ptr<webrtc::VideoDecoderFactory> CreateDecoderFactory(bool nullCodec) {
  121. std::unique_ptr<webrtc::VideoDecoderFactory> factory;
  122. #ifdef WEBRTC_LINUX
  123. //factory= webrtc::CreateBuiltinVideoDecoderFactory();
  124. factory = std::make_unique<VideoDecoderFactory>();
  125. #else
  126. if (nullCodec) {
  127. factory = std::make_unique<VideoDecoderFactory>();
  128. }
  129. else
  130. {
  131. factory = webrtc::CreateBuiltinVideoDecoderFactory();
  132. }
  133. #endif
  134. return factory;
  135. }
  136. bool mrsWebrtcCreateFactory(bool NullEnCodec, bool NullDecode)
  137. {
  138. if (g_peer_connection_factory == nullptr) {
  139. g_worker_thread=(rtc::Thread::Create());
  140. g_worker_thread->Start();
  141. g_signaling_thread=(rtc::Thread::Create());
  142. g_signaling_thread->Start();
  143. g_peer_connection_factory = webrtc::CreatePeerConnectionFactory(
  144. nullptr, g_worker_thread.get(), g_signaling_thread.get(),
  145. nullptr, webrtc::CreateBuiltinAudioEncoderFactory(),
  146. webrtc::CreateBuiltinAudioDecoderFactory(),
  147. CreateEncoderFactory(NullEnCodec),
  148. /*
  149. std::unique_ptr<webrtc::VideoEncoderFactory>(
  150. new webrtc::MultiplexEncoderFactory(
  151. #ifdef WEBRTC_AARCH
  152. std::make_unique<webrtc::InternalEncoderFactory>()
  153. #else
  154. std::make_unique<webrtc::NvVideoEncoderFactory>()
  155. #endif
  156. )),
  157. */
  158. CreateDecoderFactory(NullDecode),
  159. /*
  160. std::unique_ptr<webrtc::VideoDecoderFactory>(
  161. new webrtc::MultiplexDecoderFactory(
  162. std::make_unique<webrtc::InternalDecoderFactory>())),*/
  163. nullptr, nullptr);
  164. }
  165. if (!g_peer_connection_factory.get()) {
  166. return false;
  167. }
  168. return true;
  169. }
  170. PeerConnectionHandle mrsPeerConnectionCreate() {
  171. // Ensure the factory exists
  172. // Setup the connection configuration
  173. webrtc::PeerConnectionInterface::RTCConfiguration config;
  174. config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
  175. config.enable_dtls_srtp = false;
  176. config.enable_rtp_data_channel = true;
  177. webrtc::PeerConnectionInterface::IceServer server;
  178. server.uri = "stun:stun1.l.google.com:19302";
  179. config.servers.push_back(server);
  180. server.uri = "turn:58.34.98.12:3478";
  181. server.username = "ubuntu12";
  182. server.password = "ubuntu12@123";
  183. config.servers.push_back(server);
  184. config.enable_dtls_srtp = false; //< TODO - Should be true/unset for security
  185. // Create the new peer connection
  186. rtc::scoped_refptr<PeerConnection> peer =
  187. new rtc::RefCountedObject<PeerConnection>();
  188. /* webrtc::PeerConnectionDependencies dependencies(peer);*/
  189. rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
  190. g_peer_connection_factory->CreatePeerConnection(config, nullptr, nullptr,
  191. peer.get());
  192. if (peer_connection.get() == nullptr)
  193. return {};
  194. peer->SetPeerImpl(peer_connection);
  195. const PeerConnectionHandle handle{ peer.get() };
  196. g_peer_connection_map.insert({ handle, std::move(peer) });
  197. return handle;
  198. }
  199. void mrsPeerConnectionRegisterConnectedCallback(
  200. PeerConnectionHandle peerHandle,
  201. PeerConnectionConnectedCallback callback,
  202. void* user_data) {
  203. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  204. peer->RegisterConnectedCallback(Callback<>{callback, user_data});
  205. }
  206. }
  207. void mrsPeerConnectionRegisterLocalSdpReadytoSendCallback(
  208. PeerConnectionHandle peerHandle,
  209. int32_t pid,
  210. int32_t index,
  211. PeerConnectionLocalSdpReadytoSendCallback callback,
  212. void* user_data) {
  213. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  214. peer->RegisterLocalSdpReadytoSendCallback(
  215. Callback<int32_t,int32_t,const char*, const char*>{callback,user_data,pid,index});
  216. }
  217. }
  218. void mrsPeerConnectionRegisterIceCandidateReadytoSendCallback(
  219. PeerConnectionHandle peerHandle,
  220. int32_t pid,
  221. int32_t view,
  222. PeerConnectionIceCandidateReadytoSendCallback callback,
  223. void* user_data) {
  224. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  225. peer->RegisterIceCandidateReadytoSendCallback(
  226. Callback<int32_t,int32_t,const char*, int, const char*>{callback, user_data,pid,view});
  227. }
  228. }
  229. void mrsPeerConnectionRegisterLocalVideoFrameCallback(
  230. PeerConnectionHandle peerHandle,
  231. PeerConnectionVideoFrameCallback callback,
  232. void* user_data) {
  233. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  234. peer->RegisterLocalVideoFrameCallback(
  235. VideoFrameReadyCallback{callback, user_data });
  236. }
  237. }
  238. void mrsPeerConnectionRegisterRemoteVideoFrameCallback(
  239. PeerConnectionHandle peerHandle,
  240. PeerConnectionVideoFrameCallback callback,
  241. void* user_data) {
  242. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  243. peer->RegisterRemoteVideoFrameCallback(
  244. VideoFrameReadyCallback{callback, user_data });
  245. }
  246. }
  247. void mrsPeerConnectionRegisterChannelCallback(PeerConnectionHandle peerHandle,
  248. PeerConnectionDataChannelMessageCallback message_callback, void* message_user_data,
  249. PeerConnectionDataChannelBufferingCallback buffering_callback, void* buffering_user_data,
  250. PeerConnectionDataChannelStateCallback state_callback,
  251. void* state_user_data) {
  252. if (auto peer = static_cast<PeerConnection*>(peerHandle))
  253. {
  254. peer->RegisterDataChannelCallback(
  255. DataChannelMessageCallback{ message_callback, message_user_data },
  256. DataChannelBufferingCallback{ buffering_callback, buffering_user_data },
  257. DataChannelStateCallback{ state_callback, state_user_data });
  258. }
  259. }
  260. bool mrsPeerConnectionAddIceCandidate(PeerConnectionHandle peerHandle,
  261. const char* sdp,
  262. const int sdp_mline_index,
  263. const char* sdp_mid) {
  264. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  265. return peer->AddIceCandidate(sdp_mid, sdp_mline_index, sdp);
  266. }
  267. return false;
  268. }
  269. bool mrsPeerConnectionCreateOffer(PeerConnectionHandle peerHandle) {
  270. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  271. return peer->CreateOffer();
  272. }
  273. return false;
  274. }
  275. bool mrsPeerConnectionCreateAnswer(PeerConnectionHandle peerHandle) {
  276. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  277. return peer->CreateAnswer();
  278. }
  279. return false;
  280. }
  281. bool mrsPeerConnectionSetRemoteDescription(PeerConnectionHandle peerHandle,
  282. const char* type,
  283. const char* sdp) {
  284. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  285. return peer->SetRemoteDescription(type, sdp);
  286. }
  287. return false;
  288. }
  289. void mrsPeerConnectionClose(PeerConnectionHandle* peerHandlePtr) {
  290. if (peerHandlePtr) {
  291. if (auto peer = static_cast<PeerConnection*>(*peerHandlePtr)) {
  292. auto it = g_peer_connection_map.find(peer);
  293. if (it != g_peer_connection_map.end()) {
  294. // This generally removes the last reference to the PeerConnection and
  295. // leads to its destruction, unless some background running task is
  296. // still using the connection.
  297. g_peer_connection_map.erase(it);
  298. if (g_peer_connection_map.empty()) {
  299. // Release the factory so that the threads are stopped and the DLL can
  300. // be unloaded. This is mandatory to be able to unload/reload in the
  301. // Unity Editor and be able to Play/Stop multiple times per Editor
  302. // process run.
  303. g_peer_connection_factory = nullptr;
  304. g_signaling_thread.reset();
  305. g_worker_thread.reset();
  306. }
  307. }
  308. }
  309. *peerHandlePtr = nullptr;
  310. }
  311. }
  312. #ifdef WEBRTC_LINUX
  313. bool mrsPeerConnectionAddLocalVideoTrack( PeerConnectionHandle peerHandle,
  314. RenderPosition type,
  315. int32_t index)
  316. {
  317. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  318. {
  319. if (!g_peer_connection_factory)
  320. return false;
  321. std::unique_ptr<CaptureOp > op=std::make_unique<CaptureOp>(type,index);
  322. auto ptr=op.get();
  323. peer->RegisterCaptureOp(op);
  324. rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> video_source = OpenGSMLCapture(ptr);
  325. if(!video_source) return false;
  326. rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
  327. g_peer_connection_factory->CreateVideoTrack(kLocalVideoLabel+std::to_string(type),
  328. video_source);
  329. if (!video_track) {
  330. return false;
  331. }
  332. return peer->AddLocalVideoTrack(std::move(video_track), kLocalVideoLabel+std::to_string(type));
  333. }
  334. return false;
  335. }
  336. bool mrsPeerConnectionSwitchCapture(
  337. PeerConnectionHandle peerHandle,
  338. bool front
  339. )
  340. {
  341. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  342. {
  343. peer->SwitchCapture(front);
  344. return true;
  345. }
  346. return false;
  347. }
  348. bool mrsPeerConnectionSetCtx(PeerConnectionHandle peerHandle,void * data)
  349. {
  350. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  351. {
  352. peer->SetOtherCtx(data);
  353. return true;
  354. }
  355. return false;
  356. }
  357. void * mrsPeerConnectionCurrentCtx(PeerConnectionHandle peerHandle)
  358. {
  359. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  360. {
  361. return peer->GetCurrentCtx();
  362. }
  363. return nullptr;
  364. }
  365. #else
  366. bool mrsPeerConnectionAddLocalVideoTrack(
  367. PeerConnectionHandle peerHandle,
  368. IOverlayVideo* video)
  369. {
  370. if (auto peer = static_cast<PeerConnection*>(peerHandle))
  371. {
  372. if (!g_peer_connection_factory)
  373. return false;
  374. rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> video_source = OpenOverlayVideoTrack(video);
  375. if (!video_source) return false;
  376. rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
  377. g_peer_connection_factory->CreateVideoTrack(kLocalVideoLabel + std::string("native"),
  378. video_source);
  379. return peer->AddLocalVideoTrack(std::move(video_track), kLocalVideoLabel + std::string("native"));
  380. }
  381. return false;
  382. }
  383. IOverlayVideo* mrsPeerConnectionCreateOverlayVideo()
  384. {
  385. return CreateOverlayVideo();
  386. }
  387. #endif
  388. bool mrsPeerConnectionAddLocalAudioTrack(PeerConnectionHandle peerHandle) {
  389. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  390. if (!g_peer_connection_factory)
  391. return false;
  392. rtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source =
  393. g_peer_connection_factory->CreateAudioSource(cricket::AudioOptions());
  394. if (!audio_source)
  395. return false;
  396. rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track =
  397. g_peer_connection_factory->CreateAudioTrack(kLocalAudioLabel,
  398. audio_source);
  399. if (!audio_track)
  400. return false;
  401. return peer->AddLocalAudioTrack(std::move(audio_track));
  402. }
  403. return false;
  404. }
  405. mrsResult mrsPeerConnectionAddDataChannel(
  406. PeerConnectionHandle peerHandle,
  407. bool ordered,
  408. bool reliable//,
  409. // PeerConnectionDataChannelMessageCallback message_callback,
  410. // void* message_user_data,
  411. // PeerConnectionDataChannelBufferingCallback buffering_callback,
  412. // void* buffering_user_data,
  413. // PeerConnectionDataChannelStateCallback state_callback,
  414. // void* state_user_data
  415. )
  416. {
  417. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  418. return peer->AddDataChannel(kLocalDataChannel.c_str(), ordered, reliable);
  419. // DataChannelMessageCallback{ message_callback, message_user_data },
  420. // DataChannelBufferingCallback{ buffering_callback, buffering_user_data },
  421. // DataChannelStateCallback{ state_callback, state_user_data });
  422. }
  423. return MRS_E_INVALID_PEER_HANDLE;
  424. }
  425. void mrsPeerConnectionRemoveLocalVideoTrack(
  426. PeerConnectionHandle peerHandle) {
  427. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  428. peer->RemoveLocalVideoTrack();
  429. }
  430. }
  431. void mrsPeerConnectionRemoveLocalAudioTrack(
  432. PeerConnectionHandle peerHandle) {
  433. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  434. peer->RemoveLocalAudioTrack();
  435. }
  436. }
  437. bool mrsPeerConnectionRemoveDataChannel(PeerConnectionHandle peerHandle) {
  438. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  439. return peer->RemoveDataChannel();
  440. }
  441. return false;
  442. }
  443. bool mrsPeerConnectionSendDataChannelMessage(PeerConnectionHandle peerHandle,
  444. const void* data,
  445. uint64_t size) {
  446. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  447. return peer->SendDataChannelMessage(data, size);
  448. }
  449. return false;
  450. }
  451. bool mrsSdpForceCodecs(const char* message,
  452. const char* audio_codec_name,
  453. const char* video_codec_name,
  454. char* buffer,
  455. size_t* buffer_size) {
  456. RTC_CHECK(message);
  457. RTC_CHECK(buffer);
  458. RTC_CHECK(buffer_size);
  459. std::string message_str(message);
  460. std::string audio_codec_name_str;
  461. std::string video_codec_name_str;
  462. if (audio_codec_name) {
  463. audio_codec_name_str.assign(audio_codec_name);
  464. }
  465. if (video_codec_name) {
  466. video_codec_name_str.assign(video_codec_name);
  467. }
  468. std::string out_message =
  469. SdpForceCodecs(message_str, audio_codec_name_str, video_codec_name_str);
  470. const size_t capacity = *buffer_size;
  471. const size_t size = out_message.size();
  472. *buffer_size = size + 1;
  473. if (capacity < size + 1) {
  474. return false;
  475. }
  476. memcpy(buffer, out_message.c_str(), size);
  477. buffer[size] = '\0';
  478. return true;
  479. }
  480. void mrsMemCpy(void* dst, const void* src, size_t size) {
  481. memcpy(dst, src, size);
  482. }
  483. void mrsMemCpyStride(void* dst,
  484. int dst_stride,
  485. const void* src,
  486. int src_stride,
  487. int elem_size,
  488. int elem_count) {
  489. RTC_CHECK(dst);
  490. RTC_CHECK(dst_stride >= elem_size);
  491. RTC_CHECK(src);
  492. RTC_CHECK(src_stride >= elem_size);
  493. if ((dst_stride == elem_size) && (src_stride == elem_size)) {
  494. // If tightly packed, do a single memcpy() for performance
  495. const size_t total_size = (size_t)elem_size * elem_count;
  496. memcpy(dst, src, total_size);
  497. }
  498. else {
  499. // Otherwise, copy row by row
  500. for (int i = 0; i < elem_count; ++i) {
  501. memcpy(dst, src, elem_size);
  502. dst = (char*)dst + dst_stride;
  503. src = (const char*)src + src_stride;
  504. }
  505. }
  506. }