api.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 "p2p/client/basic_port_allocator.h"
  7. #include "video_frame_observer.h"
  8. #include "data_channel_observer.h"
  9. #include "audio_frame_observer.h"
  10. #include "peer_connection.h"
  11. #include "sdp_utils.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. CreateDecoderFactory(nullCodec),
  157. /*
  158. std::unique_ptr<webrtc::VideoDecoderFactory>(
  159. new webrtc::MultiplexDecoderFactory(
  160. std::make_unique<webrtc::InternalDecoderFactory>()))*/
  161. nullptr, nullptr);
  162. }
  163. if (!g_peer_connection_factory.get()) {
  164. return false;
  165. }
  166. return true;
  167. }
  168. PeerConnectionHandle mrsPeerConnectionCreate(int32_t MinPort,int32_t MaxPort) {
  169. // Ensure the factory exists
  170. // Setup the connection configuration
  171. webrtc::PeerConnectionInterface::RTCConfiguration config;
  172. config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
  173. config.enable_dtls_srtp = false;
  174. config.enable_rtp_data_channel = true;
  175. webrtc::PeerConnectionInterface::IceServer server;
  176. server.uri = "stun:stun1.l.google.com:19302";
  177. config.servers.push_back(server);
  178. server.uri = "turn:58.34.98.12:3478";
  179. server.username = "ubuntu12";
  180. server.password = "ubuntu12@123";
  181. config.servers.push_back(server);
  182. std::unique_ptr<cricket::PortAllocator> port_allocator(new cricket::BasicPortAllocator(new rtc::BasicNetworkManager()));
  183. port_allocator->SetPortRange(MinPort, MaxPort);
  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. /*
  190. rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
  191. g_peer_connection_factory->CreatePeerConnection(config, nullptr, nullptr,
  192. peer.get());*/
  193. rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
  194. g_peer_connection_factory->CreatePeerConnection(config, std::move(port_allocator), nullptr,
  195. peer.get());
  196. //20240318
  197. auto bit_rate_setting = webrtc::BitrateSettings();
  198. bit_rate_setting.min_bitrate_bps = 5000;
  199. bit_rate_setting.max_bitrate_bps = 3000000;
  200. bit_rate_setting.start_bitrate_bps = 2000000;
  201. peer_connection->SetBitrate(bit_rate_setting);
  202. if (peer_connection.get() == nullptr)
  203. return {};
  204. peer->SetPeerImpl(peer_connection);
  205. const PeerConnectionHandle handle{ peer.get() };
  206. g_peer_connection_map.insert({ handle, std::move(peer) });
  207. return handle;
  208. }
  209. void mrsPeerConnectionRegisterConnectedCallback(
  210. PeerConnectionHandle peerHandle,
  211. PeerConnectionConnectedCallback callback,
  212. void* user_data) {
  213. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  214. peer->RegisterConnectedCallback(Callback<>{callback, user_data});
  215. }
  216. }
  217. void mrsPeerConnectionRegisterLocalSdpReadytoSendCallback(
  218. PeerConnectionHandle peerHandle,
  219. int32_t pid,
  220. int32_t index,
  221. PeerConnectionLocalSdpReadytoSendCallback callback,
  222. void* user_data) {
  223. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  224. peer->RegisterLocalSdpReadytoSendCallback(
  225. Callback<int32_t,int32_t,const char*, const char*>{callback,user_data,pid,index});
  226. }
  227. }
  228. void mrsPeerConnectionRegisterIceCandidateReadytoSendCallback(
  229. PeerConnectionHandle peerHandle,
  230. int32_t pid,
  231. int32_t view,
  232. PeerConnectionIceCandidateReadytoSendCallback callback,
  233. void* user_data) {
  234. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  235. peer->RegisterIceCandidateReadytoSendCallback(
  236. Callback<int32_t,int32_t,const char*, int, const char*>{callback, user_data,pid,view});
  237. }
  238. }
  239. void mrsPeerConnectionRegisterARGBLocalVideoFrameCallback(
  240. PeerConnectionHandle peerHandle,
  241. PeerConnectionARGBVideoFrameCallback callback,
  242. void* user_data) {
  243. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  244. peer->RegisterLocalVideoFrameCallback(
  245. ARGBFrameReadyCallback{callback, user_data });
  246. }
  247. }
  248. void mrsPeerConnectionRegisterARGBRemoteVideoFrameCallback(
  249. PeerConnectionHandle peerHandle,
  250. PeerConnectionARGBVideoFrameCallback callback,
  251. void* user_data) {
  252. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  253. peer->RegisterRemoteVideoFrameCallback(
  254. ARGBFrameReadyCallback{callback, user_data });
  255. }
  256. }
  257. void mrsPeerConnectionRegisterChannelCallback(PeerConnectionHandle peerHandle,
  258. PeerConnectionDataChannelMessageCallback message_callback, void* message_user_data,
  259. PeerConnectionDataChannelBufferingCallback buffering_callback, void* buffering_user_data,
  260. PeerConnectionDataChannelStateCallback state_callback,
  261. void* state_user_data) {
  262. if (auto peer = static_cast<PeerConnection*>(peerHandle))
  263. {
  264. peer->RegisterDataChannelCallback(
  265. DataChannelMessageCallback{ message_callback, message_user_data },
  266. DataChannelBufferingCallback{ buffering_callback, buffering_user_data },
  267. DataChannelStateCallback{ state_callback, state_user_data });
  268. }
  269. }
  270. bool mrsPeerConnectionAddIceCandidate(PeerConnectionHandle peerHandle,
  271. const char* sdp,
  272. const int sdp_mline_index,
  273. const char* sdp_mid) {
  274. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  275. return peer->AddIceCandidate(sdp_mid, sdp_mline_index, sdp);
  276. }
  277. return false;
  278. }
  279. bool mrsPeerConnectionCreateOffer(PeerConnectionHandle peerHandle) {
  280. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  281. return peer->CreateOffer();
  282. }
  283. return false;
  284. }
  285. bool mrsPeerConnectionCreateAnswer(PeerConnectionHandle peerHandle) {
  286. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  287. return peer->CreateAnswer();
  288. }
  289. return false;
  290. }
  291. bool mrsPeerConnectionSetRemoteDescription(PeerConnectionHandle peerHandle,
  292. const char* type,
  293. const char* sdp) {
  294. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  295. return peer->SetRemoteDescription(type, sdp);
  296. }
  297. return false;
  298. }
  299. void mrsPeerConnectionClose(PeerConnectionHandle* peerHandlePtr) {
  300. if (peerHandlePtr) {
  301. if (auto peer = static_cast<PeerConnection*>(*peerHandlePtr)) {
  302. auto it = g_peer_connection_map.find(peer);
  303. if (it != g_peer_connection_map.end()) {
  304. // This generally removes the last reference to the PeerConnection and
  305. // leads to its destruction, unless some background running task is
  306. // still using the connection.
  307. g_peer_connection_map.erase(it);
  308. if (g_peer_connection_map.empty()) {
  309. // Release the factory so that the threads are stopped and the DLL can
  310. // be unloaded. This is mandatory to be able to unload/reload in the
  311. // Unity Editor and be able to Play/Stop multiple times per Editor
  312. // process run.
  313. g_peer_connection_factory = nullptr;
  314. g_signaling_thread.reset();
  315. g_worker_thread.reset();
  316. }
  317. }
  318. }
  319. *peerHandlePtr = nullptr;
  320. }
  321. }
  322. #ifdef WEBRTC_LINUX
  323. bool mrsPeerConnectionAddLocalVideoTrack( PeerConnectionHandle peerHandle,
  324. RenderPosition type,
  325. int32_t index)
  326. {
  327. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  328. {
  329. if (!g_peer_connection_factory)
  330. return false;
  331. std::unique_ptr<CaptureOp > op=std::make_unique<CaptureOp>(type,index);
  332. auto ptr=op.get();
  333. peer->RegisterCaptureOp(op);
  334. rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> video_source = OpenGSMLCapture(ptr);
  335. if(!video_source) return false;
  336. rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
  337. g_peer_connection_factory->CreateVideoTrack(kLocalVideoLabel+std::to_string(type),
  338. video_source);
  339. if (!video_track) {
  340. return false;
  341. }
  342. return peer->AddLocalVideoTrack(std::move(video_track), kLocalVideoLabel+std::to_string(type));
  343. }
  344. return false;
  345. }
  346. bool mrsPeerConnectionSwitchCapture(
  347. PeerConnectionHandle peerHandle,
  348. bool front
  349. )
  350. {
  351. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  352. {
  353. peer->SwitchCapture(front);
  354. return true;
  355. }
  356. return false;
  357. }
  358. bool mrsPeerConnectionSetCtx(PeerConnectionHandle peerHandle,void * data)
  359. {
  360. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  361. {
  362. peer->SetOtherCtx(data);
  363. return true;
  364. }
  365. return false;
  366. }
  367. void * mrsPeerConnectionCurrentCtx(PeerConnectionHandle peerHandle)
  368. {
  369. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  370. {
  371. return peer->GetCurrentCtx();
  372. }
  373. return nullptr;
  374. }
  375. #endif
  376. bool mrsPeerConnectionAddLocalAudioTrack(PeerConnectionHandle peerHandle) {
  377. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  378. if (!g_peer_connection_factory)
  379. return false;
  380. rtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source =
  381. g_peer_connection_factory->CreateAudioSource(cricket::AudioOptions());
  382. if (!audio_source)
  383. return false;
  384. rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track =
  385. g_peer_connection_factory->CreateAudioTrack(kLocalAudioLabel,
  386. audio_source);
  387. if (!audio_track)
  388. return false;
  389. return peer->AddLocalAudioTrack(std::move(audio_track));
  390. }
  391. return false;
  392. }
  393. mrsResult mrsPeerConnectionAddDataChannel(
  394. PeerConnectionHandle peerHandle,
  395. bool ordered,
  396. bool reliable//,
  397. // PeerConnectionDataChannelMessageCallback message_callback,
  398. // void* message_user_data,
  399. // PeerConnectionDataChannelBufferingCallback buffering_callback,
  400. // void* buffering_user_data,
  401. // PeerConnectionDataChannelStateCallback state_callback,
  402. // void* state_user_data
  403. )
  404. {
  405. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  406. return peer->AddDataChannel(kLocalDataChannel.c_str(), ordered, reliable);
  407. // DataChannelMessageCallback{ message_callback, message_user_data },
  408. // DataChannelBufferingCallback{ buffering_callback, buffering_user_data },
  409. // DataChannelStateCallback{ state_callback, state_user_data });
  410. }
  411. return MRS_E_INVALID_PEER_HANDLE;
  412. }
  413. void mrsPeerConnectionRemoveLocalVideoTrack(
  414. PeerConnectionHandle peerHandle) {
  415. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  416. peer->RemoveLocalVideoTrack();
  417. }
  418. }
  419. void mrsPeerConnectionRemoveLocalAudioTrack(
  420. PeerConnectionHandle peerHandle) {
  421. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  422. peer->RemoveLocalAudioTrack();
  423. }
  424. }
  425. bool mrsPeerConnectionRemoveDataChannel(PeerConnectionHandle peerHandle) {
  426. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  427. return peer->RemoveDataChannel();
  428. }
  429. return false;
  430. }
  431. bool mrsPeerConnectionSendDataChannelMessage(PeerConnectionHandle peerHandle,
  432. const void* data,
  433. uint64_t size) {
  434. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  435. return peer->SendDataChannelMessage(data, size);
  436. }
  437. return false;
  438. }
  439. bool mrsSdpForceCodecs(const char* message,
  440. const char* audio_codec_name,
  441. const char* video_codec_name,
  442. char* buffer,
  443. size_t* buffer_size) {
  444. RTC_CHECK(message);
  445. RTC_CHECK(buffer);
  446. RTC_CHECK(buffer_size);
  447. std::string message_str(message);
  448. std::string audio_codec_name_str;
  449. std::string video_codec_name_str;
  450. if (audio_codec_name) {
  451. audio_codec_name_str.assign(audio_codec_name);
  452. }
  453. if (video_codec_name) {
  454. video_codec_name_str.assign(video_codec_name);
  455. }
  456. std::string out_message =
  457. SdpForceCodecs(message_str, audio_codec_name_str, video_codec_name_str);
  458. const size_t capacity = *buffer_size;
  459. const size_t size = out_message.size();
  460. *buffer_size = size + 1;
  461. if (capacity < size + 1) {
  462. return false;
  463. }
  464. memcpy(buffer, out_message.c_str(), size);
  465. buffer[size] = '\0';
  466. return true;
  467. }
  468. void mrsMemCpy(void* dst, const void* src, size_t size) {
  469. memcpy(dst, src, size);
  470. }
  471. void mrsMemCpyStride(void* dst,
  472. int dst_stride,
  473. const void* src,
  474. int src_stride,
  475. int elem_size,
  476. int elem_count) {
  477. RTC_CHECK(dst);
  478. RTC_CHECK(dst_stride >= elem_size);
  479. RTC_CHECK(src);
  480. RTC_CHECK(src_stride >= elem_size);
  481. if ((dst_stride == elem_size) && (src_stride == elem_size)) {
  482. // If tightly packed, do a single memcpy() for performance
  483. const size_t total_size = (size_t)elem_size * elem_count;
  484. memcpy(dst, src, total_size);
  485. }
  486. else {
  487. // Otherwise, copy row by row
  488. for (int i = 0; i < elem_count; ++i) {
  489. memcpy(dst, src, elem_size);
  490. dst = (char*)dst + dst_stride;
  491. src = (const char*)src + src_stride;
  492. }
  493. }
  494. }