api.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. #include "sri_build_encoder_factory.h"
  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. */
  159. CreateDecoderFactory(nullCodec),
  160. /*
  161. std::unique_ptr<webrtc::VideoDecoderFactory>(
  162. new webrtc::MultiplexDecoderFactory(
  163. std::make_unique<webrtc::InternalDecoderFactory>())),*/
  164. nullptr, nullptr);
  165. }
  166. if (!g_peer_connection_factory.get()) {
  167. return false;
  168. }
  169. return true;
  170. }
  171. //视频通道
  172. PeerConnectionHandle mrsPeerConnectionCreate(int32_t MinPort,int32_t MaxPort) {
  173. // Ensure the factory exists
  174. // Setup the connection configuration
  175. webrtc::PeerConnectionInterface::RTCConfiguration config;
  176. config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
  177. config.enable_dtls_srtp = false;
  178. config.enable_rtp_data_channel = true;
  179. webrtc::PeerConnectionInterface::IceServer server;
  180. server.uri = "stun:stun1.l.google.com:19302";
  181. config.servers.push_back(server);
  182. server.uri = "turn:58.34.98.12:3478";
  183. server.username = "ubuntu12";
  184. server.password = "ubuntu12@123";
  185. config.servers.push_back(server);
  186. std::unique_ptr<cricket::PortAllocator> port_allocator(new cricket::BasicPortAllocator(new rtc::BasicNetworkManager()));
  187. port_allocator->SetPortRange(MinPort, MaxPort);
  188. config.enable_dtls_srtp = false; //< TODO - Should be true/unset for security
  189. // Create the new peer connection
  190. rtc::scoped_refptr<PeerConnection> peer =
  191. new rtc::RefCountedObject<PeerConnection>();
  192. webrtc::PeerConnectionDependencies dependencies(peer);
  193. /*
  194. rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
  195. g_peer_connection_factory->CreatePeerConnection(config, nullptr, nullptr,
  196. peer.get());*/
  197. rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection =
  198. g_peer_connection_factory->CreatePeerConnection(config, std::move(port_allocator), nullptr,
  199. peer.get());
  200. //20240318
  201. auto bit_rate_setting = webrtc::BitrateSettings();
  202. bit_rate_setting.min_bitrate_bps = 5000;
  203. bit_rate_setting.max_bitrate_bps = 3000000;
  204. bit_rate_setting.start_bitrate_bps = 2000000;
  205. peer_connection->SetBitrate(bit_rate_setting);
  206. if (peer_connection.get() == nullptr)
  207. return {};
  208. peer->SetPeerImpl(peer_connection);
  209. const PeerConnectionHandle handle{ peer.get() };
  210. g_peer_connection_map.insert({ handle, std::move(peer) });
  211. return handle;
  212. }
  213. void mrsPeerConnectionRegisterConnectedCallback(
  214. PeerConnectionHandle peerHandle,
  215. PeerConnectionConnectedCallback callback,
  216. void* user_data) {
  217. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  218. peer->RegisterConnectedCallback(Callback<>{callback, user_data});
  219. }
  220. }
  221. void mrsPeerConnectionRegisterLocalSdpReadytoSendCallback(
  222. PeerConnectionHandle peerHandle,
  223. int32_t pid,
  224. int32_t index,
  225. PeerConnectionLocalSdpReadytoSendCallback callback,
  226. void* user_data) {
  227. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  228. peer->RegisterLocalSdpReadytoSendCallback(
  229. Callback<int32_t,int32_t,const char*, const char*>{callback,user_data,pid,index});
  230. }
  231. }
  232. void mrsPeerConnectionRegisterIceCandidateReadytoSendCallback(
  233. PeerConnectionHandle peerHandle,
  234. int32_t pid,
  235. int32_t view,
  236. PeerConnectionIceCandidateReadytoSendCallback callback,
  237. void* user_data) {
  238. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  239. peer->RegisterIceCandidateReadytoSendCallback(
  240. Callback<int32_t,int32_t,const char*, int, const char*>{callback, user_data,pid,view});
  241. }
  242. }
  243. void mrsPeerConnectionRegisterARGBLocalVideoFrameCallback(
  244. PeerConnectionHandle peerHandle,
  245. PeerConnectionARGBVideoFrameCallback callback,
  246. void* user_data) {
  247. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  248. peer->RegisterLocalVideoFrameCallback(
  249. ARGBFrameReadyCallback{callback, user_data });
  250. }
  251. }
  252. void mrsPeerConnectionRegisterARGBRemoteVideoFrameCallback(
  253. PeerConnectionHandle peerHandle,
  254. PeerConnectionARGBVideoFrameCallback callback,
  255. void* user_data) {
  256. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  257. peer->RegisterRemoteVideoFrameCallback(
  258. ARGBFrameReadyCallback{callback, user_data });
  259. }
  260. }
  261. void mrsPeerConnectionRegisterChannelCallback(PeerConnectionHandle peerHandle,
  262. PeerConnectionDataChannelMessageCallback message_callback, void* message_user_data,
  263. PeerConnectionDataChannelBufferingCallback buffering_callback, void* buffering_user_data,
  264. PeerConnectionDataChannelStateCallback state_callback,
  265. void* state_user_data) {
  266. if (auto peer = static_cast<PeerConnection*>(peerHandle))
  267. {
  268. peer->RegisterDataChannelCallback(
  269. DataChannelMessageCallback{ message_callback, message_user_data },
  270. DataChannelBufferingCallback{ buffering_callback, buffering_user_data },
  271. DataChannelStateCallback{ state_callback, state_user_data });
  272. }
  273. }
  274. bool mrsPeerConnectionAddIceCandidate(PeerConnectionHandle peerHandle,
  275. const char* sdp,
  276. const int sdp_mline_index,
  277. const char* sdp_mid) {
  278. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  279. return peer->AddIceCandidate(sdp_mid, sdp_mline_index, sdp);
  280. }
  281. return false;
  282. }
  283. bool mrsPeerConnectionCreateOffer(PeerConnectionHandle peerHandle) {
  284. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  285. return peer->CreateOffer();
  286. }
  287. return false;
  288. }
  289. bool mrsPeerConnectionCreateAnswer(PeerConnectionHandle peerHandle) {
  290. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  291. return peer->CreateAnswer();
  292. }
  293. return false;
  294. }
  295. bool mrsPeerConnectionSetRemoteDescription(PeerConnectionHandle peerHandle,
  296. const char* type,
  297. const char* sdp) {
  298. if (auto peer = static_cast<PeerConnection*>(peerHandle)) {
  299. return peer->SetRemoteDescription(type, sdp);
  300. }
  301. return false;
  302. }
  303. void mrsPeerConnectionClose(PeerConnectionHandle* peerHandlePtr) {
  304. if (peerHandlePtr) {
  305. if (auto peer = static_cast<PeerConnection*>(*peerHandlePtr)) {
  306. auto it = g_peer_connection_map.find(peer);
  307. if (it != g_peer_connection_map.end()) {
  308. // This generally removes the last reference to the PeerConnection and
  309. // leads to its destruction, unless some background running task is
  310. // still using the connection.
  311. g_peer_connection_map.erase(it);
  312. if (g_peer_connection_map.empty()) {
  313. // Release the factory so that the threads are stopped and the DLL can
  314. // be unloaded. This is mandatory to be able to unload/reload in the
  315. // Unity Editor and be able to Play/Stop multiple times per Editor
  316. // process run.
  317. g_peer_connection_factory = nullptr;
  318. g_signaling_thread.reset();
  319. g_worker_thread.reset();
  320. }
  321. }
  322. }
  323. *peerHandlePtr = nullptr;
  324. }
  325. }
  326. //将一个本地视频轨道添加到一个webrtc peerConnection对象中 PeerConnectionHandle peerHandle: 一个 PeerConnection 对象的句柄
  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. }