api.cpp 16 KB

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