api.cpp 16 KB

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