api.cpp 16 KB

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