api.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. */
  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. //视频通道
  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. //将一个本地视频轨道添加到一个webrtc peerConnection对象中 PeerConnectionHandle peerHandle: 一个 PeerConnection 对象的句柄
  325. #ifdef WEBRTC_LINUX
  326. bool mrsPeerConnectionAddLocalVideoTrack( PeerConnectionHandle peerHandle,
  327. RenderPosition type,
  328. int32_t index)
  329. {
  330. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  331. {
  332. if (!g_peer_connection_factory)
  333. return false;
  334. std::unique_ptr<CaptureOp > op=std::make_unique<CaptureOp>(type,index);
  335. auto ptr=op.get();
  336. peer->RegisterCaptureOp(op);
  337. rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> video_source = OpenGSMLCapture(ptr);
  338. if(!video_source) return false;
  339. rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
  340. g_peer_connection_factory->CreateVideoTrack(kLocalVideoLabel+std::to_string(type),
  341. video_source);
  342. if (!video_track) {
  343. return false;
  344. }
  345. return peer->AddLocalVideoTrack(std::move(video_track), kLocalVideoLabel+std::to_string(type));
  346. }
  347. return false;
  348. }
  349. bool mrsPeerConnectionSwitchCapture(
  350. PeerConnectionHandle peerHandle,
  351. bool front
  352. )
  353. {
  354. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  355. {
  356. peer->SwitchCapture(front);
  357. return true;
  358. }
  359. return false;
  360. }
  361. bool mrsPeerConnectionSetCtx(PeerConnectionHandle peerHandle,void * data)
  362. {
  363. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  364. {
  365. peer->SetOtherCtx(data);
  366. return true;
  367. }
  368. return false;
  369. }
  370. void * mrsPeerConnectionCurrentCtx(PeerConnectionHandle peerHandle)
  371. {
  372. if(auto peer=static_cast<PeerConnection *>(peerHandle))
  373. {
  374. return peer->GetCurrentCtx();
  375. }
  376. return nullptr;
  377. }
  378. #endif
  379. bool mrsPeerConnectionAddLocalAudioTrack(PeerConnectionHandle peerHandle) {
  380. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  381. if (!g_peer_connection_factory)
  382. return false;
  383. rtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source =
  384. g_peer_connection_factory->CreateAudioSource(cricket::AudioOptions());
  385. if (!audio_source)
  386. return false;
  387. rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track =
  388. g_peer_connection_factory->CreateAudioTrack(kLocalAudioLabel,
  389. audio_source);
  390. if (!audio_track)
  391. return false;
  392. return peer->AddLocalAudioTrack(std::move(audio_track));
  393. }
  394. return false;
  395. }
  396. mrsResult mrsPeerConnectionAddDataChannel(
  397. PeerConnectionHandle peerHandle,
  398. bool ordered,
  399. bool reliable//,
  400. // PeerConnectionDataChannelMessageCallback message_callback,
  401. // void* message_user_data,
  402. // PeerConnectionDataChannelBufferingCallback buffering_callback,
  403. // void* buffering_user_data,
  404. // PeerConnectionDataChannelStateCallback state_callback,
  405. // void* state_user_data
  406. )
  407. {
  408. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  409. return peer->AddDataChannel(kLocalDataChannel.c_str(), ordered, reliable);
  410. // DataChannelMessageCallback{ message_callback, message_user_data },
  411. // DataChannelBufferingCallback{ buffering_callback, buffering_user_data },
  412. // DataChannelStateCallback{ state_callback, state_user_data });
  413. }
  414. return MRS_E_INVALID_PEER_HANDLE;
  415. }
  416. void mrsPeerConnectionRemoveLocalVideoTrack(
  417. PeerConnectionHandle peerHandle) {
  418. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  419. peer->RemoveLocalVideoTrack();
  420. }
  421. }
  422. void mrsPeerConnectionRemoveLocalAudioTrack(
  423. PeerConnectionHandle peerHandle) {
  424. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  425. peer->RemoveLocalAudioTrack();
  426. }
  427. }
  428. bool mrsPeerConnectionRemoveDataChannel(PeerConnectionHandle peerHandle) {
  429. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  430. return peer->RemoveDataChannel();
  431. }
  432. return false;
  433. }
  434. bool mrsPeerConnectionSendDataChannelMessage(PeerConnectionHandle peerHandle,
  435. const void* data,
  436. uint64_t size) {
  437. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  438. return peer->SendDataChannelMessage(data, size);
  439. }
  440. return false;
  441. }
  442. bool mrsSdpForceCodecs(const char* message,
  443. const char* audio_codec_name,
  444. const char* video_codec_name,
  445. char* buffer,
  446. size_t* buffer_size) {
  447. RTC_CHECK(message);
  448. RTC_CHECK(buffer);
  449. RTC_CHECK(buffer_size);
  450. std::string message_str(message);
  451. std::string audio_codec_name_str;
  452. std::string video_codec_name_str;
  453. if (audio_codec_name) {
  454. audio_codec_name_str.assign(audio_codec_name);
  455. }
  456. if (video_codec_name) {
  457. video_codec_name_str.assign(video_codec_name);
  458. }
  459. std::string out_message =
  460. SdpForceCodecs(message_str, audio_codec_name_str, video_codec_name_str);
  461. const size_t capacity = *buffer_size;
  462. const size_t size = out_message.size();
  463. *buffer_size = size + 1;
  464. if (capacity < size + 1) {
  465. return false;
  466. }
  467. memcpy(buffer, out_message.c_str(), size);
  468. buffer[size] = '\0';
  469. return true;
  470. }
  471. void mrsMemCpy(void* dst, const void* src, size_t size) {
  472. memcpy(dst, src, size);
  473. }
  474. void mrsMemCpyStride(void* dst,
  475. int dst_stride,
  476. const void* src,
  477. int src_stride,
  478. int elem_size,
  479. int elem_count) {
  480. RTC_CHECK(dst);
  481. RTC_CHECK(dst_stride >= elem_size);
  482. RTC_CHECK(src);
  483. RTC_CHECK(src_stride >= elem_size);
  484. if ((dst_stride == elem_size) && (src_stride == elem_size)) {
  485. // If tightly packed, do a single memcpy() for performance
  486. const size_t total_size = (size_t)elem_size * elem_count;
  487. memcpy(dst, src, total_size);
  488. }
  489. else {
  490. // Otherwise, copy row by row
  491. for (int i = 0; i < elem_count; ++i) {
  492. memcpy(dst, src, elem_size);
  493. dst = (char*)dst + dst_stride;
  494. src = (const char*)src + src_stride;
  495. }
  496. }
  497. }