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