api.cpp 16 KB

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