WebRTCPlugin.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. #include "pch.h"
  2. #include "Context.h"
  3. #include "CreateSessionDescriptionObserver.h"
  4. #include "GraphicsDevice/GraphicsUtility.h"
  5. #include "MediaStreamObserver.h"
  6. #include "PeerConnectionObject.h"
  7. #include "SetSessionDescriptionObserver.h"
  8. #include "UnityAudioTrackSource.h"
  9. #include "UnityLogStream.h"
  10. #include "WebRTCPlugin.h"
  11. namespace unity
  12. {
  13. namespace webrtc
  14. {
  15. #pragma clang diagnostic push
  16. #pragma clang diagnostic ignored "-Wmissing-prototypes"
  17. static DelegateSetResolution delegateSetResolution = nullptr;
  18. void SetResolution(int32* width, int32* length)
  19. {
  20. if (delegateSetResolution != nullptr)
  21. {
  22. delegateSetResolution(width, length);
  23. }
  24. }
  25. template<class T>
  26. T** ConvertPtrArrayFromRefPtrArray(std::vector<rtc::scoped_refptr<T>> vec, size_t* length)
  27. {
  28. *length = vec.size();
  29. const auto buf = CoTaskMemAlloc(sizeof(T*) * vec.size());
  30. const auto ret = static_cast<T**>(buf);
  31. std::copy(vec.begin(), vec.end(), ret);
  32. return ret;
  33. }
  34. template<typename T>
  35. T* ConvertArray(std::vector<T> vec, size_t* length)
  36. {
  37. *length = vec.size();
  38. size_t size = sizeof(T*) * vec.size();
  39. auto dst = CoTaskMemAlloc(size);
  40. auto src = vec.data();
  41. std::memcpy(dst, src, size);
  42. return static_cast<T*>(dst);
  43. }
  44. template<typename T>
  45. struct MarshallArray
  46. {
  47. size_t length;
  48. T* values;
  49. T& operator[](size_t i) const { return values[i]; }
  50. template<typename U>
  51. MarshallArray& operator=(const std::vector<U>& src)
  52. {
  53. length = static_cast<int32_t>(src.size());
  54. values = static_cast<T*>(CoTaskMemAlloc(sizeof(T) * src.size()));
  55. for (size_t i = 0; i < src.size(); i++)
  56. {
  57. values[i] = src[i];
  58. }
  59. return *this;
  60. }
  61. };
  62. template<typename T, typename U>
  63. void ConvertArray(const MarshallArray<T>& src, std::vector<U>& dst)
  64. {
  65. dst.resize(src.length);
  66. for (size_t i = 0; i < dst.size(); i++)
  67. {
  68. dst[i] = src.values[i];
  69. }
  70. }
  71. template<typename T>
  72. struct Optional
  73. {
  74. bool hasValue;
  75. T value;
  76. template<typename U>
  77. Optional& operator=(const absl::optional<U>& src)
  78. {
  79. hasValue = src.has_value();
  80. if (hasValue)
  81. {
  82. value = static_cast<T>(src.value());
  83. }
  84. else
  85. {
  86. value = T();
  87. }
  88. return *this;
  89. }
  90. #if defined(__clang__) || defined(__GNUC__)
  91. __attribute__((optnone))
  92. #endif
  93. explicit
  94. operator const absl::optional<T>() const
  95. {
  96. absl::optional<T> dst = absl::nullopt;
  97. if (hasValue)
  98. dst = value;
  99. return dst;
  100. }
  101. const T& value_or(const T& v) const { return hasValue ? value : v; }
  102. };
  103. template<typename T>
  104. absl::optional<T> ConvertOptional(const Optional<T>& value)
  105. {
  106. absl::optional<T> dst = absl::nullopt;
  107. if (value.hasValue)
  108. {
  109. dst = value.value;
  110. }
  111. return dst;
  112. }
  113. std::string ConvertSdp(const std::map<std::string, std::string>& map)
  114. {
  115. std::string str = "";
  116. for (const auto& pair : map)
  117. {
  118. if (!str.empty())
  119. {
  120. str += ";";
  121. }
  122. str += pair.first + "=" + pair.second;
  123. }
  124. return str;
  125. }
  126. std::vector<std::string> Split(const std::string& str, const std::string& delimiter)
  127. {
  128. std::vector<std::string> dst;
  129. std::string s = str;
  130. size_t pos = 0;
  131. while (true)
  132. {
  133. pos = s.find(delimiter);
  134. size_t length = pos;
  135. if (pos == std::string::npos)
  136. length = str.length();
  137. if (length == 0)
  138. break;
  139. dst.push_back(s.substr(0, length));
  140. if (pos == std::string::npos)
  141. break;
  142. s.erase(0, pos + delimiter.length());
  143. }
  144. return dst;
  145. }
  146. std::tuple<cricket::MediaType, std::string> ConvertMimeType(const std::string& mimeType)
  147. {
  148. const std::vector<std::string> vec = Split(mimeType, "/");
  149. const std::string kind = vec[0];
  150. const std::string name = vec[1];
  151. cricket::MediaType mediaType;
  152. if (kind == "video")
  153. {
  154. mediaType = cricket::MEDIA_TYPE_VIDEO;
  155. }
  156. else if (kind == "audio")
  157. {
  158. mediaType = cricket::MEDIA_TYPE_AUDIO;
  159. }
  160. return std::make_tuple(mediaType, name);
  161. }
  162. std::map<std::string, std::string> ConvertSdp(const std::string& src)
  163. {
  164. std::map<std::string, std::string> map;
  165. std::vector<std::string> vec = Split(src, ";");
  166. for (const auto& str : vec)
  167. {
  168. std::vector<std::string> pair = Split(str, "=");
  169. map.emplace(pair[0], pair[1]);
  170. }
  171. return map;
  172. }
  173. ///
  174. /// avoid compile error for vector<bool>
  175. /// https://en.cppreference.com/w/cpp/container/vector_bool
  176. bool* ConvertArray(std::vector<bool> vec, size_t* length)
  177. {
  178. *length = vec.size();
  179. size_t size = sizeof(bool*) * vec.size();
  180. auto dst = CoTaskMemAlloc(size);
  181. bool* ret = static_cast<bool*>(dst);
  182. for (size_t i = 0; i < vec.size(); i++)
  183. {
  184. ret[i] = vec[i];
  185. }
  186. return ret;
  187. }
  188. char* ConvertString(const std::string str)
  189. {
  190. const size_t size = str.size();
  191. char* ret = static_cast<char*>(CoTaskMemAlloc(size + sizeof(char)));
  192. str.copy(ret, size);
  193. ret[size] = '\0';
  194. return ret;
  195. }
  196. } // end namespace webrtc
  197. } // end namespace unity
  198. using namespace unity::webrtc;
  199. using namespace ::webrtc;
  200. extern "C"
  201. {
  202. UNITY_INTERFACE_EXPORT MediaStreamInterface* ContextCreateMediaStream(Context* context, const char* streamId)
  203. {
  204. return context->CreateMediaStream(streamId);
  205. }
  206. UNITY_INTERFACE_EXPORT void ContextRegisterMediaStreamObserver(Context* context, MediaStreamInterface* stream)
  207. {
  208. context->RegisterMediaStreamObserver(stream);
  209. }
  210. UNITY_INTERFACE_EXPORT void ContextUnRegisterMediaStreamObserver(Context* context, MediaStreamInterface* stream)
  211. {
  212. context->UnRegisterMediaStreamObserver(stream);
  213. }
  214. UNITY_INTERFACE_EXPORT MediaStreamTrackInterface*
  215. ContextCreateVideoTrack(Context* context, const char* label, webrtc::VideoTrackSourceInterface* source)
  216. {
  217. return context->CreateVideoTrack(label, source);
  218. }
  219. UNITY_INTERFACE_EXPORT void
  220. ContextStopMediaStreamTrack(Context* context, ::webrtc::MediaStreamTrackInterface* track)
  221. {
  222. context->StopMediaStreamTrack(track);
  223. }
  224. UNITY_INTERFACE_EXPORT webrtc::VideoTrackSourceInterface* ContextCreateVideoTrackSource(Context* context)
  225. {
  226. return context->CreateVideoSource();
  227. }
  228. UNITY_INTERFACE_EXPORT webrtc::AudioSourceInterface* ContextCreateAudioTrackSource(Context* context)
  229. {
  230. return context->CreateAudioSource();
  231. }
  232. UNITY_INTERFACE_EXPORT webrtc::MediaStreamTrackInterface*
  233. ContextCreateAudioTrack(Context* context, const char* label, webrtc::AudioSourceInterface* source)
  234. {
  235. return context->CreateAudioTrack(label, source);
  236. }
  237. UNITY_INTERFACE_EXPORT void ContextAddRefPtr(Context* context, rtc::RefCountInterface* ptr)
  238. {
  239. context->AddRefPtr(ptr);
  240. }
  241. UNITY_INTERFACE_EXPORT void ContextDeleteRefPtr(Context* context, rtc::RefCountInterface* ptr)
  242. {
  243. context->RemoveRefPtr(ptr);
  244. }
  245. UNITY_INTERFACE_EXPORT bool MediaStreamAddTrack(MediaStreamInterface* stream, MediaStreamTrackInterface* track)
  246. {
  247. if (track->kind() == "audio")
  248. {
  249. return stream->AddTrack(static_cast<AudioTrackInterface*>(track));
  250. }
  251. else
  252. {
  253. return stream->AddTrack(static_cast<VideoTrackInterface*>(track));
  254. }
  255. }
  256. UNITY_INTERFACE_EXPORT bool MediaStreamRemoveTrack(MediaStreamInterface* stream, MediaStreamTrackInterface* track)
  257. {
  258. if (track->kind() == "audio")
  259. {
  260. return stream->RemoveTrack(static_cast<AudioTrackInterface*>(track));
  261. }
  262. else
  263. {
  264. return stream->RemoveTrack(static_cast<VideoTrackInterface*>(track));
  265. }
  266. }
  267. UNITY_INTERFACE_EXPORT char* MediaStreamGetID(MediaStreamInterface* stream) { return ConvertString(stream->id()); }
  268. UNITY_INTERFACE_EXPORT void MediaStreamRegisterOnAddTrack(
  269. Context* context, MediaStreamInterface* stream, DelegateMediaStreamOnAddTrack callback)
  270. {
  271. context->GetObserver(stream)->RegisterOnAddTrack(callback);
  272. }
  273. UNITY_INTERFACE_EXPORT void MediaStreamRegisterOnRemoveTrack(
  274. Context* context, MediaStreamInterface* stream, DelegateMediaStreamOnRemoveTrack callback)
  275. {
  276. context->GetObserver(stream)->RegisterOnRemoveTrack(callback);
  277. }
  278. UNITY_INTERFACE_EXPORT VideoTrackInterface** MediaStreamGetVideoTracks(MediaStreamInterface* stream, size_t* length)
  279. {
  280. return ConvertPtrArrayFromRefPtrArray<VideoTrackInterface>(stream->GetVideoTracks(), length);
  281. }
  282. UNITY_INTERFACE_EXPORT AudioTrackInterface** MediaStreamGetAudioTracks(MediaStreamInterface* stream, size_t* length)
  283. {
  284. return ConvertPtrArrayFromRefPtrArray<AudioTrackInterface>(stream->GetAudioTracks(), length);
  285. }
  286. UNITY_INTERFACE_EXPORT VideoTrackSourceInterface*
  287. ContextGetVideoSource(Context* context, VideoTrackInterface* track)
  288. {
  289. return track->GetSource();
  290. }
  291. UNITY_INTERFACE_EXPORT TrackKind MediaStreamTrackGetKind(MediaStreamTrackInterface* track)
  292. {
  293. const auto kindStr = track->kind();
  294. if (kindStr == "audio")
  295. {
  296. return TrackKind::Audio;
  297. }
  298. else
  299. {
  300. return TrackKind::Video;
  301. }
  302. }
  303. UNITY_INTERFACE_EXPORT MediaStreamTrackInterface::TrackState
  304. MediaStreamTrackGetReadyState(MediaStreamTrackInterface* track)
  305. {
  306. return track->state();
  307. }
  308. UNITY_INTERFACE_EXPORT char* MediaStreamTrackGetID(MediaStreamTrackInterface* track)
  309. {
  310. return ConvertString(track->id());
  311. }
  312. UNITY_INTERFACE_EXPORT bool MediaStreamTrackGetEnabled(MediaStreamTrackInterface* track)
  313. {
  314. return track->enabled();
  315. }
  316. UNITY_INTERFACE_EXPORT void MediaStreamTrackSetEnabled(MediaStreamTrackInterface* track, bool enabled)
  317. {
  318. track->set_enabled(enabled);
  319. }
  320. UNITY_INTERFACE_EXPORT UnityVideoRenderer*
  321. CreateVideoRenderer(Context* context, DelegateVideoFrameResize callback, bool needFlipVertical)
  322. {
  323. return context->CreateVideoRenderer(callback, needFlipVertical);
  324. }
  325. UNITY_INTERFACE_EXPORT uint32_t GetVideoRendererId(UnityVideoRenderer* sink) { return sink->GetId(); }
  326. UNITY_INTERFACE_EXPORT void DeleteVideoRenderer(Context* context, UnityVideoRenderer* sink)
  327. {
  328. context->DeleteVideoRenderer(sink);
  329. }
  330. UNITY_INTERFACE_EXPORT void VideoTrackAddOrUpdateSink(VideoTrackInterface* track, UnityVideoRenderer* sink)
  331. {
  332. track->AddOrUpdateSink(sink, rtc::VideoSinkWants());
  333. }
  334. UNITY_INTERFACE_EXPORT void VideoTrackRemoveSink(VideoTrackInterface* track, UnityVideoRenderer* sink)
  335. {
  336. track->RemoveSink(sink);
  337. }
  338. UNITY_INTERFACE_EXPORT void
  339. RegisterDebugLog(DelegateDebugLog func, bool enableNativeLog, rtc::LoggingSeverity loggingSeverity)
  340. {
  341. delegateDebugLog = func;
  342. if (func != nullptr && enableNativeLog)
  343. {
  344. UnityLogStream::AddLogStream(func, loggingSeverity);
  345. }
  346. else if (func == nullptr)
  347. {
  348. UnityLogStream::RemoveLogStream();
  349. }
  350. }
  351. UNITY_INTERFACE_EXPORT void RegisterSetResolution(DelegateSetResolution func) { delegateSetResolution = func; }
  352. UNITY_INTERFACE_EXPORT Context* ContextCreate(int uid)
  353. {
  354. auto ctx = ContextManager::GetInstance()->GetContext(uid);
  355. if (ctx != nullptr)
  356. {
  357. DebugLog("Already created context with ID %d", uid);
  358. return ctx;
  359. }
  360. ContextDependencies dependencies;
  361. dependencies.device = Plugin::GraphicsDevice();
  362. dependencies.profiler = Plugin::ProfilerMarkerFactory();
  363. ctx = ContextManager::GetInstance()->CreateContext(uid, dependencies);
  364. return ctx;
  365. }
  366. UNITY_INTERFACE_EXPORT void ContextDestroy(int uid) { ContextManager::GetInstance()->DestroyContext(uid); }
  367. UNITY_INTERFACE_EXPORT PeerConnectionObject* ContextCreatePeerConnection(Context* context)
  368. {
  369. PeerConnectionInterface::RTCConfiguration config;
  370. config.sdp_semantics = SdpSemantics::kUnifiedPlan;
  371. config.enable_implicit_rollback = true;
  372. return context->CreatePeerConnection(config);
  373. }
  374. UNITY_INTERFACE_EXPORT PeerConnectionObject*
  375. ContextCreatePeerConnectionWithConfig(Context* context, const char* conf)
  376. {
  377. PeerConnectionInterface::RTCConfiguration config;
  378. if (!Convert(conf, config))
  379. return nullptr;
  380. config.sdp_semantics = SdpSemantics::kUnifiedPlan;
  381. config.enable_implicit_rollback = true;
  382. return context->CreatePeerConnection(config);
  383. }
  384. UNITY_INTERFACE_EXPORT void ContextDeletePeerConnection(Context* context, PeerConnectionObject* obj)
  385. {
  386. obj->Close();
  387. context->DeletePeerConnection(obj);
  388. }
  389. UNITY_INTERFACE_EXPORT void PeerConnectionClose(PeerConnectionObject* obj) { obj->Close(); }
  390. UNITY_INTERFACE_EXPORT void PeerConnectionRestartIce(PeerConnectionObject* obj) { obj->connection->RestartIce(); }
  391. UNITY_INTERFACE_EXPORT RTCErrorType PeerConnectionAddTrack(
  392. PeerConnectionObject* obj, MediaStreamTrackInterface* track, const char* streamId, RtpSenderInterface** sender)
  393. {
  394. std::vector<std::string> streams;
  395. if (streamId)
  396. streams.push_back(streamId);
  397. auto result = obj->connection->AddTrack(rtc::scoped_refptr<MediaStreamTrackInterface>(track), streams);
  398. if (result.ok())
  399. {
  400. *sender = result.value();
  401. }
  402. return result.error().type();
  403. }
  404. struct RTCRtpEncodingParameters
  405. {
  406. bool active;
  407. Optional<uint64_t> maxBitrate;
  408. Optional<uint64_t> minBitrate;
  409. Optional<uint32_t> maxFramerate;
  410. Optional<double> scaleResolutionDownBy;
  411. char* rid;
  412. RTCRtpEncodingParameters& operator=(const RtpEncodingParameters& obj)
  413. {
  414. active = obj.active;
  415. maxBitrate = obj.max_bitrate_bps;
  416. minBitrate = obj.min_bitrate_bps;
  417. maxFramerate = obj.max_framerate;
  418. scaleResolutionDownBy = obj.scale_resolution_down_by;
  419. rid = ConvertString(obj.rid);
  420. return *this;
  421. }
  422. operator RtpEncodingParameters() const
  423. {
  424. RtpEncodingParameters dst = {};
  425. dst.active = active;
  426. dst.max_bitrate_bps = static_cast<absl::optional<int>>(ConvertOptional(maxBitrate));
  427. dst.min_bitrate_bps = static_cast<absl::optional<int>>(ConvertOptional(minBitrate));
  428. dst.max_framerate = static_cast<absl::optional<double>>(ConvertOptional(maxFramerate));
  429. dst.scale_resolution_down_by = ConvertOptional(scaleResolutionDownBy);
  430. if (rid != nullptr)
  431. dst.rid = std::string(rid);
  432. return dst;
  433. }
  434. };
  435. struct RTCRtpTransceiverInit
  436. {
  437. RtpTransceiverDirection direction;
  438. MarshallArray<RTCRtpEncodingParameters> sendEncodings;
  439. MarshallArray<MediaStreamInterface*> streams;
  440. operator RtpTransceiverInit() const
  441. {
  442. RtpTransceiverInit dst = {};
  443. dst.direction = direction;
  444. dst.send_encodings.resize(sendEncodings.length);
  445. for (size_t i = 0; i < dst.send_encodings.size(); i++)
  446. {
  447. dst.send_encodings[i] = sendEncodings[i];
  448. }
  449. dst.stream_ids.resize(streams.length);
  450. for (size_t i = 0; i < dst.stream_ids.size(); i++)
  451. {
  452. dst.stream_ids[i] = streams[i]->id();
  453. }
  454. return dst;
  455. }
  456. };
  457. UNITY_INTERFACE_EXPORT RtpTransceiverInterface*
  458. PeerConnectionAddTransceiver(PeerConnectionObject* obj, MediaStreamTrackInterface* track)
  459. {
  460. auto result = obj->connection->AddTransceiver(track);
  461. if (!result.ok())
  462. return nullptr;
  463. return result.value();
  464. }
  465. UNITY_INTERFACE_EXPORT RtpTransceiverInterface* PeerConnectionAddTransceiverWithInit(
  466. PeerConnectionObject* obj, MediaStreamTrackInterface* track, const RTCRtpTransceiverInit* init)
  467. {
  468. auto result = obj->connection->AddTransceiver(track, *init);
  469. if (!result.ok())
  470. return nullptr;
  471. return result.value();
  472. }
  473. UNITY_INTERFACE_EXPORT RtpTransceiverInterface*
  474. PeerConnectionAddTransceiverWithType(PeerConnectionObject* obj, cricket::MediaType type)
  475. {
  476. auto result = obj->connection->AddTransceiver(type);
  477. if (!result.ok())
  478. return nullptr;
  479. return result.value();
  480. }
  481. UNITY_INTERFACE_EXPORT RtpTransceiverInterface* PeerConnectionAddTransceiverWithTypeAndInit(
  482. PeerConnectionObject* obj, cricket::MediaType type, const RTCRtpTransceiverInit* init)
  483. {
  484. auto result = obj->connection->AddTransceiver(type, *init);
  485. if (!result.ok())
  486. return nullptr;
  487. return result.value();
  488. }
  489. UNITY_INTERFACE_EXPORT RTCErrorType PeerConnectionRemoveTrack(PeerConnectionObject* obj, RtpSenderInterface* sender)
  490. {
  491. webrtc::RTCError error = obj->connection->RemoveTrackNew(sender);
  492. return error.type();
  493. }
  494. UNITY_INTERFACE_EXPORT RTCErrorType PeerConnectionSetConfiguration(PeerConnectionObject* obj, const char* conf)
  495. {
  496. return obj->SetConfiguration(std::string(conf));
  497. }
  498. UNITY_INTERFACE_EXPORT char* PeerConnectionGetConfiguration(PeerConnectionObject* obj)
  499. {
  500. const std::string str = obj->GetConfiguration();
  501. return ConvertString(str);
  502. }
  503. UNITY_INTERFACE_EXPORT PeerConnectionStatsCollectorCallback* PeerConnectionGetStats(PeerConnectionObject* obj)
  504. {
  505. PeerConnectionStatsCollectorCallback* callback = PeerConnectionStatsCollectorCallback::Create(obj);
  506. obj->connection->GetStats(callback);
  507. return callback;
  508. }
  509. UNITY_INTERFACE_EXPORT PeerConnectionStatsCollectorCallback*
  510. PeerConnectionSenderGetStats(PeerConnectionObject* obj, RtpSenderInterface* sender)
  511. {
  512. PeerConnectionStatsCollectorCallback* callback = PeerConnectionStatsCollectorCallback::Create(obj);
  513. obj->connection->GetStats(sender, callback);
  514. return callback;
  515. }
  516. UNITY_INTERFACE_EXPORT PeerConnectionStatsCollectorCallback*
  517. PeerConnectionReceiverGetStats(PeerConnectionObject* obj, RtpReceiverInterface* receiver)
  518. {
  519. PeerConnectionStatsCollectorCallback* callback = PeerConnectionStatsCollectorCallback::Create(obj);
  520. obj->connection->GetStats(receiver, callback);
  521. return callback;
  522. }
  523. UNITY_INTERFACE_EXPORT const RTCStats**
  524. ContextGetStatsList(Context* context, const RTCStatsReport* report, size_t* length, uint32_t** types)
  525. {
  526. return context->GetStatsList(report, length, types);
  527. }
  528. UNITY_INTERFACE_EXPORT void ContextDeleteStatsReport(Context* context, const RTCStatsReport* report)
  529. {
  530. context->DeleteStatsReport(report);
  531. }
  532. UNITY_INTERFACE_EXPORT const char* StatsGetJson(const RTCStats* stats) { return ConvertString(stats->ToJson()); }
  533. UNITY_INTERFACE_EXPORT int64_t StatsGetTimestamp(const RTCStats* stats) { return stats->timestamp_us(); }
  534. UNITY_INTERFACE_EXPORT const char* StatsGetId(const RTCStats* stats) { return ConvertString(stats->id()); }
  535. UNITY_INTERFACE_EXPORT uint32_t StatsGetType(const RTCStats* stats) { return statsTypes.at(stats->type()); }
  536. UNITY_INTERFACE_EXPORT const RTCStatsMemberInterface** StatsGetMembers(const RTCStats* stats, size_t* length)
  537. {
  538. return ConvertArray(stats->Members(), length);
  539. }
  540. UNITY_INTERFACE_EXPORT bool StatsMemberIsDefined(const RTCStatsMemberInterface* member)
  541. {
  542. return member->is_defined();
  543. }
  544. UNITY_INTERFACE_EXPORT const char* StatsMemberGetName(const RTCStatsMemberInterface* member)
  545. {
  546. return ConvertString(std::string(member->name()));
  547. }
  548. UNITY_INTERFACE_EXPORT bool StatsMemberGetBool(const RTCStatsMemberInterface* member)
  549. {
  550. return *member->cast_to<::webrtc::RTCStatsMember<bool>>();
  551. }
  552. UNITY_INTERFACE_EXPORT int32_t StatsMemberGetInt(const RTCStatsMemberInterface* member)
  553. {
  554. return *member->cast_to<::webrtc::RTCStatsMember<int32_t>>();
  555. }
  556. UNITY_INTERFACE_EXPORT uint32_t StatsMemberGetUnsignedInt(const RTCStatsMemberInterface* member)
  557. {
  558. return *member->cast_to<::webrtc::RTCStatsMember<uint32_t>>();
  559. }
  560. UNITY_INTERFACE_EXPORT int64_t StatsMemberGetLong(const RTCStatsMemberInterface* member)
  561. {
  562. return *member->cast_to<::webrtc::RTCStatsMember<int64_t>>();
  563. }
  564. UNITY_INTERFACE_EXPORT uint64_t StatsMemberGetUnsignedLong(const RTCStatsMemberInterface* member)
  565. {
  566. return *member->cast_to<::webrtc::RTCStatsMember<uint64_t>>();
  567. }
  568. UNITY_INTERFACE_EXPORT double StatsMemberGetDouble(const RTCStatsMemberInterface* member)
  569. {
  570. return *member->cast_to<::webrtc::RTCStatsMember<double>>();
  571. }
  572. UNITY_INTERFACE_EXPORT const char* StatsMemberGetString(const RTCStatsMemberInterface* member)
  573. {
  574. return ConvertString(member->ValueToString());
  575. }
  576. UNITY_INTERFACE_EXPORT bool* StatsMemberGetBoolArray(const RTCStatsMemberInterface* member, size_t* length)
  577. {
  578. return ConvertArray(*member->cast_to<::webrtc::RTCStatsMember<std::vector<bool>>>(), length);
  579. }
  580. UNITY_INTERFACE_EXPORT int32_t* StatsMemberGetIntArray(const RTCStatsMemberInterface* member, size_t* length)
  581. {
  582. return ConvertArray(*member->cast_to<::webrtc::RTCStatsMember<std::vector<int>>>(), length);
  583. }
  584. UNITY_INTERFACE_EXPORT uint32_t*
  585. StatsMemberGetUnsignedIntArray(const RTCStatsMemberInterface* member, size_t* length)
  586. {
  587. return ConvertArray(*member->cast_to<::webrtc::RTCStatsMember<std::vector<uint32_t>>>(), length);
  588. }
  589. UNITY_INTERFACE_EXPORT int64_t* StatsMemberGetLongArray(const RTCStatsMemberInterface* member, size_t* length)
  590. {
  591. return ConvertArray(*member->cast_to<::webrtc::RTCStatsMember<std::vector<int64_t>>>(), length);
  592. }
  593. UNITY_INTERFACE_EXPORT uint64_t*
  594. StatsMemberGetUnsignedLongArray(const RTCStatsMemberInterface* member, size_t* length)
  595. {
  596. return ConvertArray(*member->cast_to<::webrtc::RTCStatsMember<std::vector<uint64_t>>>(), length);
  597. }
  598. UNITY_INTERFACE_EXPORT double* StatsMemberGetDoubleArray(const RTCStatsMemberInterface* member, size_t* length)
  599. {
  600. return ConvertArray(*member->cast_to<::webrtc::RTCStatsMember<std::vector<double>>>(), length);
  601. }
  602. UNITY_INTERFACE_EXPORT const char** StatsMemberGetStringArray(const RTCStatsMemberInterface* member, size_t* length)
  603. {
  604. std::vector<std::string> vec = *member->cast_to<::webrtc::RTCStatsMember<std::vector<std::string>>>();
  605. std::vector<const char*> vc;
  606. std::transform(vec.begin(), vec.end(), std::back_inserter(vc), ConvertString);
  607. return ConvertArray(vc, length);
  608. }
  609. UNITY_INTERFACE_EXPORT RTCStatsMemberInterface::Type StatsMemberGetType(const RTCStatsMemberInterface* member)
  610. {
  611. return member->type();
  612. }
  613. UNITY_INTERFACE_EXPORT unity::webrtc::SetSessionDescriptionObserver* PeerConnectionSetLocalDescription(
  614. PeerConnectionObject* obj,
  615. const RTCSessionDescription* desc,
  616. RTCErrorType* errorType,
  617. char* error[])
  618. {
  619. std::string error_;
  620. auto observer = unity::webrtc::SetSessionDescriptionObserver::Create(obj);
  621. *errorType = obj->SetLocalDescription(*desc, observer, error_);
  622. *error = ConvertString(error_);
  623. return observer.get();
  624. }
  625. UNITY_INTERFACE_EXPORT unity::webrtc::SetSessionDescriptionObserver*
  626. PeerConnectionSetLocalDescriptionWithoutDescription(
  627. PeerConnectionObject* obj, RTCErrorType* errorType, char* error[])
  628. {
  629. std::string error_;
  630. auto observer = unity::webrtc::SetSessionDescriptionObserver::Create(obj);
  631. *errorType = obj->SetLocalDescriptionWithoutDescription(observer, error_);
  632. *error = ConvertString(error_);
  633. return observer.get();
  634. }
  635. UNITY_INTERFACE_EXPORT unity::webrtc::SetSessionDescriptionObserver* PeerConnectionSetRemoteDescription(
  636. PeerConnectionObject* obj,
  637. const RTCSessionDescription* desc,
  638. RTCErrorType* errorType,
  639. char* error[])
  640. {
  641. std::string error_;
  642. auto observer = unity::webrtc::SetSessionDescriptionObserver::Create(obj);
  643. *errorType = obj->SetRemoteDescription(*desc, observer, error_);
  644. *error = ConvertString(error_);
  645. return observer.get();
  646. }
  647. UNITY_INTERFACE_EXPORT bool
  648. PeerConnectionGetLocalDescription(PeerConnectionObject* obj, RTCSessionDescription* desc)
  649. {
  650. return obj->GetSessionDescription(obj->connection->local_description(), *desc);
  651. }
  652. UNITY_INTERFACE_EXPORT bool
  653. PeerConnectionGetRemoteDescription(PeerConnectionObject* obj, RTCSessionDescription* desc)
  654. {
  655. return obj->GetSessionDescription(obj->connection->remote_description(), *desc);
  656. }
  657. UNITY_INTERFACE_EXPORT bool
  658. PeerConnectionGetPendingLocalDescription(PeerConnectionObject* obj, RTCSessionDescription* desc)
  659. {
  660. return obj->GetSessionDescription(obj->connection->pending_local_description(), *desc);
  661. }
  662. UNITY_INTERFACE_EXPORT bool
  663. PeerConnectionGetPendingRemoteDescription(PeerConnectionObject* obj, RTCSessionDescription* desc)
  664. {
  665. return obj->GetSessionDescription(obj->connection->pending_remote_description(), *desc);
  666. }
  667. UNITY_INTERFACE_EXPORT bool
  668. PeerConnectionGetCurrentLocalDescription(PeerConnectionObject* obj, RTCSessionDescription* desc)
  669. {
  670. return obj->GetSessionDescription(obj->connection->current_local_description(), *desc);
  671. }
  672. UNITY_INTERFACE_EXPORT bool
  673. PeerConnectionGetCurrentRemoteDescription(PeerConnectionObject* obj, RTCSessionDescription* desc)
  674. {
  675. return obj->GetSessionDescription(obj->connection->current_remote_description(), *desc);
  676. }
  677. UNITY_INTERFACE_EXPORT RtpReceiverInterface**
  678. PeerConnectionGetReceivers(Context* context, PeerConnectionObject* obj, size_t* length)
  679. {
  680. auto receivers = obj->connection->GetReceivers();
  681. return ConvertPtrArrayFromRefPtrArray<RtpReceiverInterface>(receivers, length);
  682. }
  683. UNITY_INTERFACE_EXPORT RtpSenderInterface**
  684. PeerConnectionGetSenders(Context* context, PeerConnectionObject* obj, size_t* length)
  685. {
  686. auto senders = obj->connection->GetSenders();
  687. return ConvertPtrArrayFromRefPtrArray<RtpSenderInterface>(senders, length);
  688. }
  689. UNITY_INTERFACE_EXPORT RtpTransceiverInterface**
  690. PeerConnectionGetTransceivers(Context* context, PeerConnectionObject* obj, size_t* length)
  691. {
  692. auto transceivers = obj->connection->GetTransceivers();
  693. return ConvertPtrArrayFromRefPtrArray<RtpTransceiverInterface>(transceivers, length);
  694. }
  695. UNITY_INTERFACE_EXPORT unity::webrtc::CreateSessionDescriptionObserver*
  696. PeerConnectionCreateOffer(PeerConnectionObject* obj, const RTCOfferAnswerOptions* options)
  697. {
  698. auto observer = unity::webrtc::CreateSessionDescriptionObserver::Create(obj);
  699. obj->CreateOffer(*options, observer);
  700. return observer;
  701. }
  702. UNITY_INTERFACE_EXPORT unity::webrtc::CreateSessionDescriptionObserver*
  703. PeerConnectionCreateAnswer(PeerConnectionObject* obj, const RTCOfferAnswerOptions* options)
  704. {
  705. auto observer = unity::webrtc::CreateSessionDescriptionObserver::Create(obj);
  706. obj->CreateAnswer(*options, observer);
  707. return observer;
  708. }
  709. struct RTCDataChannelInit
  710. {
  711. Optional<bool> ordered;
  712. Optional<int32_t> maxRetransmitTime;
  713. Optional<int32_t> maxRetransmits;
  714. char* protocol;
  715. Optional<bool> negotiated;
  716. Optional<int32_t> id;
  717. };
  718. UNITY_INTERFACE_EXPORT DataChannelInterface* ContextCreateDataChannel(
  719. Context* ctx, PeerConnectionObject* obj, const char* label, const RTCDataChannelInit* options)
  720. {
  721. DataChannelInit _options;
  722. _options.ordered = options->ordered.value_or(true);
  723. _options.maxRetransmitTime = static_cast<absl::optional<int32_t>>(options->maxRetransmitTime);
  724. _options.maxRetransmits = static_cast<absl::optional<int32_t>>(options->maxRetransmits);
  725. _options.protocol = options->protocol == nullptr ? "" : options->protocol;
  726. _options.negotiated = options->negotiated.value_or(false);
  727. _options.id = options->id.value_or(-1);
  728. return ctx->CreateDataChannel(obj, label, _options);
  729. }
  730. UNITY_INTERFACE_EXPORT void ContextDeleteDataChannel(Context* ctx, DataChannelInterface* channel)
  731. {
  732. ctx->DeleteDataChannel(channel);
  733. }
  734. UNITY_INTERFACE_EXPORT void
  735. PeerConnectionRegisterIceConnectionChange(PeerConnectionObject* obj, DelegateOnIceConnectionChange callback)
  736. {
  737. obj->RegisterIceConnectionChange(callback);
  738. }
  739. UNITY_INTERFACE_EXPORT void
  740. PeerConnectionRegisterIceGatheringChange(PeerConnectionObject* obj, DelegateOnIceGatheringChange callback)
  741. {
  742. obj->RegisterIceGatheringChange(callback);
  743. }
  744. UNITY_INTERFACE_EXPORT void
  745. PeerConnectionRegisterConnectionStateChange(PeerConnectionObject* obj, DelegateOnConnectionStateChange callback)
  746. {
  747. obj->RegisterConnectionStateChange(callback);
  748. }
  749. UNITY_INTERFACE_EXPORT void
  750. PeerConnectionRegisterOnIceCandidate(PeerConnectionObject* obj, DelegateIceCandidate callback)
  751. {
  752. obj->RegisterIceCandidate(callback);
  753. }
  754. UNITY_INTERFACE_EXPORT void StatsCollectorRegisterCallback(DelegateCollectStats callback)
  755. {
  756. PeerConnectionStatsCollectorCallback::RegisterOnGetStats(callback);
  757. }
  758. UNITY_INTERFACE_EXPORT void CreateSessionDescriptionObserverRegisterCallback(DelegateCreateSessionDesc callback)
  759. {
  760. unity::webrtc::CreateSessionDescriptionObserver::RegisterCallback(callback);
  761. }
  762. UNITY_INTERFACE_EXPORT void SetSessionDescriptionObserverRegisterCallback(DelegateSetSessionDesc callback)
  763. {
  764. unity::webrtc::SetSessionDescriptionObserver::RegisterCallback(callback);
  765. }
  766. UNITY_INTERFACE_EXPORT bool
  767. PeerConnectionAddIceCandidate(PeerConnectionObject* obj, const IceCandidateInterface* candidate)
  768. {
  769. return obj->connection->AddIceCandidate(candidate);
  770. }
  771. struct RTCIceCandidateInit
  772. {
  773. char* candidate;
  774. char* sdpMid;
  775. int32_t sdpMLineIndex;
  776. };
  777. struct Candidate
  778. {
  779. char* candidate;
  780. int32_t component;
  781. char* foundation;
  782. char* ip;
  783. uint16_t port;
  784. uint32_t priority;
  785. char* address;
  786. char* protocol;
  787. char* relatedAddress;
  788. uint16_t relatedPort;
  789. char* tcpType;
  790. char* type;
  791. char* usernameFragment;
  792. Candidate& operator=(const cricket::Candidate& obj)
  793. {
  794. candidate = ConvertString(obj.ToString());
  795. component = obj.component();
  796. foundation = ConvertString(obj.foundation());
  797. ip = ConvertString(obj.address().ipaddr().ToString());
  798. port = obj.address().port();
  799. priority = obj.priority();
  800. address = ConvertString(obj.address().ToString());
  801. protocol = ConvertString(obj.protocol());
  802. relatedAddress = ConvertString(obj.related_address().ToString());
  803. relatedPort = obj.related_address().port();
  804. tcpType = ConvertString(obj.tcptype());
  805. type = ConvertString(obj.type());
  806. usernameFragment = ConvertString(obj.username());
  807. return *this;
  808. }
  809. };
  810. UNITY_INTERFACE_EXPORT RTCErrorType
  811. CreateIceCandidate(const RTCIceCandidateInit* options, IceCandidateInterface** candidate)
  812. {
  813. SdpParseError error;
  814. IceCandidateInterface* _candidate =
  815. CreateIceCandidate(options->sdpMid, options->sdpMLineIndex, options->candidate, &error);
  816. if (_candidate == nullptr)
  817. return RTCErrorType::INVALID_PARAMETER;
  818. *candidate = _candidate;
  819. return RTCErrorType::NONE;
  820. }
  821. UNITY_INTERFACE_EXPORT void DeleteIceCandidate(IceCandidateInterface* candidate) { delete candidate; }
  822. UNITY_INTERFACE_EXPORT void IceCandidateGetCandidate(const IceCandidateInterface* candidate, Candidate* dst)
  823. {
  824. *dst = candidate->candidate();
  825. }
  826. UNITY_INTERFACE_EXPORT int32_t IceCandidateGetSdpLineIndex(const IceCandidateInterface* candidate)
  827. {
  828. return candidate->sdp_mline_index();
  829. }
  830. UNITY_INTERFACE_EXPORT const char* IceCandidateGetSdp(const IceCandidateInterface* candidate)
  831. {
  832. std::string str;
  833. if (!candidate->ToString(&str))
  834. return nullptr;
  835. return ConvertString(str);
  836. }
  837. UNITY_INTERFACE_EXPORT const char* IceCandidateGetSdpMid(const IceCandidateInterface* candidate)
  838. {
  839. return ConvertString(candidate->sdp_mid());
  840. }
  841. UNITY_INTERFACE_EXPORT PeerConnectionInterface::PeerConnectionState PeerConnectionState(PeerConnectionObject* obj)
  842. {
  843. return obj->connection->peer_connection_state();
  844. }
  845. UNITY_INTERFACE_EXPORT PeerConnectionInterface::IceConnectionState
  846. PeerConnectionIceConditionState(PeerConnectionObject* obj)
  847. {
  848. return obj->connection->ice_connection_state();
  849. }
  850. UNITY_INTERFACE_EXPORT PeerConnectionInterface::SignalingState
  851. PeerConnectionSignalingState(PeerConnectionObject* obj)
  852. {
  853. return obj->connection->signaling_state();
  854. }
  855. UNITY_INTERFACE_EXPORT PeerConnectionInterface::IceGatheringState
  856. PeerConnectionIceGatheringState(PeerConnectionObject* obj)
  857. {
  858. return obj->connection->ice_gathering_state();
  859. }
  860. UNITY_INTERFACE_EXPORT void
  861. PeerConnectionRegisterOnDataChannel(PeerConnectionObject* obj, DelegateOnDataChannel callback)
  862. {
  863. obj->RegisterOnDataChannel(callback);
  864. }
  865. UNITY_INTERFACE_EXPORT void
  866. PeerConnectionRegisterOnRenegotiationNeeded(PeerConnectionObject* obj, DelegateOnRenegotiationNeeded callback)
  867. {
  868. obj->RegisterOnRenegotiationNeeded(callback);
  869. }
  870. UNITY_INTERFACE_EXPORT void PeerConnectionRegisterOnTrack(PeerConnectionObject* obj, DelegateOnTrack callback)
  871. {
  872. obj->RegisterOnTrack(callback);
  873. }
  874. UNITY_INTERFACE_EXPORT void
  875. PeerConnectionRegisterOnRemoveTrack(PeerConnectionObject* obj, DelegateOnRemoveTrack callback)
  876. {
  877. obj->RegisterOnRemoveTrack(callback);
  878. }
  879. UNITY_INTERFACE_EXPORT bool
  880. TransceiverGetCurrentDirection(RtpTransceiverInterface* transceiver, RtpTransceiverDirection* direction)
  881. {
  882. if (transceiver->current_direction().has_value())
  883. {
  884. *direction = transceiver->current_direction().value();
  885. return true;
  886. }
  887. return false;
  888. }
  889. UNITY_INTERFACE_EXPORT RTCErrorType TransceiverStop(RtpTransceiverInterface* transceiver)
  890. {
  891. auto error = transceiver->StopStandard();
  892. return error.type();
  893. }
  894. UNITY_INTERFACE_EXPORT RtpTransceiverDirection TransceiverGetDirection(RtpTransceiverInterface* transceiver)
  895. {
  896. return transceiver->direction();
  897. }
  898. UNITY_INTERFACE_EXPORT RTCErrorType
  899. TransceiverSetDirection(RtpTransceiverInterface* transceiver, RtpTransceiverDirection direction)
  900. {
  901. RTCError error = transceiver->SetDirectionWithError(direction);
  902. return error.type();
  903. }
  904. struct RTCRtpCodecCapability
  905. {
  906. char* mimeType;
  907. Optional<int32_t> clockRate;
  908. Optional<int32_t> channels;
  909. char* sdpFmtpLine;
  910. RTCRtpCodecCapability& operator=(const RtpCodecCapability& obj)
  911. {
  912. this->mimeType = ConvertString(obj.mime_type());
  913. this->clockRate = obj.clock_rate;
  914. this->channels = obj.num_channels;
  915. this->sdpFmtpLine = ConvertString(ConvertSdp(obj.parameters));
  916. return *this;
  917. }
  918. };
  919. UNITY_INTERFACE_EXPORT RTCErrorType
  920. TransceiverSetCodecPreferences(RtpTransceiverInterface* transceiver, RTCRtpCodecCapability* codecs, size_t length)
  921. {
  922. std::vector<RtpCodecCapability> _codecs(length);
  923. for (size_t i = 0; i < length; i++)
  924. {
  925. std::string mimeType = ConvertString(codecs[i].mimeType);
  926. std::tie(_codecs[i].kind, _codecs[i].name) = ConvertMimeType(mimeType);
  927. _codecs[i].clock_rate = ConvertOptional(codecs[i].clockRate);
  928. _codecs[i].num_channels = ConvertOptional(codecs[i].channels);
  929. _codecs[i].parameters = ConvertSdp(codecs[i].sdpFmtpLine);
  930. }
  931. auto error = transceiver->SetCodecPreferences(_codecs);
  932. if (error.type() != RTCErrorType::NONE)
  933. RTC_LOG(LS_ERROR) << error.message();
  934. return error.type();
  935. }
  936. UNITY_INTERFACE_EXPORT char* TransceiverGetMid(RtpTransceiverInterface* transceiver)
  937. {
  938. auto mid = transceiver->mid();
  939. if (!mid.has_value())
  940. {
  941. return nullptr;
  942. }
  943. return ConvertString(mid.value());
  944. }
  945. UNITY_INTERFACE_EXPORT RtpReceiverInterface* TransceiverGetReceiver(RtpTransceiverInterface* transceiver)
  946. {
  947. return transceiver->receiver().get();
  948. }
  949. UNITY_INTERFACE_EXPORT RtpSenderInterface* TransceiverGetSender(RtpTransceiverInterface* transceiver)
  950. {
  951. return transceiver->sender().get();
  952. }
  953. struct RTCRtpCodecParameters
  954. {
  955. int payloadType;
  956. char* mimeType;
  957. Optional<uint64_t> clockRate;
  958. Optional<uint16_t> channels;
  959. char* sdpFmtpLine;
  960. RTCRtpCodecParameters& operator=(const RtpCodecParameters& src)
  961. {
  962. payloadType = src.payload_type;
  963. mimeType = ConvertString(src.mime_type());
  964. clockRate = src.clock_rate;
  965. channels = src.num_channels;
  966. sdpFmtpLine = ConvertString(ConvertSdp(src.parameters));
  967. return *this;
  968. }
  969. };
  970. struct RTCRtpExtension
  971. {
  972. char* uri;
  973. uint16_t id;
  974. bool encrypted;
  975. RTCRtpExtension& operator=(const RtpExtension& src)
  976. {
  977. uri = ConvertString(src.uri);
  978. id = static_cast<uint16_t>(src.id);
  979. encrypted = src.encrypt;
  980. return *this;
  981. }
  982. };
  983. struct RTCRtcpParameters
  984. {
  985. char* cname;
  986. bool reducedSize;
  987. RTCRtcpParameters& operator=(const RtcpParameters& src)
  988. {
  989. cname = ConvertString(src.cname);
  990. reducedSize = src.reduced_size;
  991. return *this;
  992. }
  993. };
  994. struct RTCRtpSendParameters
  995. {
  996. MarshallArray<RTCRtpEncodingParameters> encodings;
  997. char* transactionId;
  998. MarshallArray<RTCRtpCodecParameters> codecs;
  999. MarshallArray<RTCRtpExtension> headerExtensions;
  1000. RTCRtcpParameters rtcp;
  1001. RTCRtpSendParameters& operator=(const RtpParameters& src)
  1002. {
  1003. encodings = src.encodings;
  1004. transactionId = ConvertString(src.transaction_id);
  1005. codecs = src.codecs;
  1006. headerExtensions = src.header_extensions;
  1007. rtcp = src.rtcp;
  1008. return *this;
  1009. }
  1010. };
  1011. UNITY_INTERFACE_EXPORT void SenderGetParameters(RtpSenderInterface* sender, RTCRtpSendParameters** parameters)
  1012. {
  1013. const RtpParameters src = sender->GetParameters();
  1014. RTCRtpSendParameters* dst = static_cast<RTCRtpSendParameters*>(CoTaskMemAlloc(sizeof(RTCRtpSendParameters)));
  1015. *dst = src;
  1016. *parameters = dst;
  1017. }
  1018. UNITY_INTERFACE_EXPORT RTCErrorType SenderSetParameters(RtpSenderInterface* sender, const RTCRtpSendParameters* src)
  1019. {
  1020. RtpParameters dst = sender->GetParameters();
  1021. for (size_t i = 0; i < dst.encodings.size(); i++)
  1022. {
  1023. dst.encodings[i].active = src->encodings[i].active;
  1024. dst.encodings[i].max_bitrate_bps =
  1025. static_cast<absl::optional<int>>(ConvertOptional(src->encodings[i].maxBitrate));
  1026. dst.encodings[i].min_bitrate_bps =
  1027. static_cast<absl::optional<int>>(ConvertOptional(src->encodings[i].minBitrate));
  1028. dst.encodings[i].max_framerate =
  1029. static_cast<absl::optional<double>>(ConvertOptional(src->encodings[i].maxFramerate));
  1030. dst.encodings[i].scale_resolution_down_by = ConvertOptional(src->encodings[i].scaleResolutionDownBy);
  1031. if (src->encodings[i].rid != nullptr)
  1032. dst.encodings[i].rid = std::string(src->encodings[i].rid);
  1033. }
  1034. const ::webrtc::RTCError error = sender->SetParameters(dst);
  1035. return error.type();
  1036. }
  1037. struct RTCRtpHeaderExtensionCapability
  1038. {
  1039. char* uri;
  1040. RTCRtpHeaderExtensionCapability& operator=(const RtpHeaderExtensionCapability& obj)
  1041. {
  1042. this->uri = ConvertString(obj.uri);
  1043. return *this;
  1044. }
  1045. };
  1046. struct RTCRtpCapabilities
  1047. {
  1048. MarshallArray<RTCRtpCodecCapability> codecs;
  1049. MarshallArray<RTCRtpHeaderExtensionCapability> extensionHeaders;
  1050. RTCRtpCapabilities& operator=(const RtpCapabilities& src)
  1051. {
  1052. codecs = src.codecs;
  1053. extensionHeaders = src.header_extensions;
  1054. return *this;
  1055. }
  1056. };
  1057. UNITY_INTERFACE_EXPORT void
  1058. ContextGetSenderCapabilities(Context* context, TrackKind trackKind, RTCRtpCapabilities** parameters)
  1059. {
  1060. RtpCapabilities src;
  1061. cricket::MediaType type = trackKind == TrackKind::Audio ? cricket::MEDIA_TYPE_AUDIO : cricket::MEDIA_TYPE_VIDEO;
  1062. context->GetRtpSenderCapabilities(type, &src);
  1063. RTCRtpCapabilities* dst = static_cast<RTCRtpCapabilities*>(CoTaskMemAlloc(sizeof(RTCRtpCapabilities)));
  1064. *dst = src;
  1065. *parameters = dst;
  1066. }
  1067. UNITY_INTERFACE_EXPORT void
  1068. ContextGetReceiverCapabilities(Context* context, TrackKind trackKind, RTCRtpCapabilities** parameters)
  1069. {
  1070. RtpCapabilities src;
  1071. cricket::MediaType type = trackKind == TrackKind::Audio ? cricket::MEDIA_TYPE_AUDIO : cricket::MEDIA_TYPE_VIDEO;
  1072. context->GetRtpReceiverCapabilities(type, &src);
  1073. RTCRtpCapabilities* dst = static_cast<RTCRtpCapabilities*>(CoTaskMemAlloc(sizeof(RTCRtpCapabilities)));
  1074. *dst = src;
  1075. *parameters = dst;
  1076. }
  1077. UNITY_INTERFACE_EXPORT bool SenderReplaceTrack(RtpSenderInterface* sender, MediaStreamTrackInterface* track)
  1078. {
  1079. return sender->SetTrack(track);
  1080. }
  1081. UNITY_INTERFACE_EXPORT MediaStreamTrackInterface* SenderGetTrack(RtpSenderInterface* sender)
  1082. {
  1083. return sender->track().get();
  1084. }
  1085. UNITY_INTERFACE_EXPORT MediaStreamTrackInterface* ReceiverGetTrack(RtpReceiverInterface* receiver)
  1086. {
  1087. return receiver->track().get();
  1088. }
  1089. UNITY_INTERFACE_EXPORT MediaStreamInterface** ReceiverGetStreams(RtpReceiverInterface* receiver, size_t* length)
  1090. {
  1091. return ConvertPtrArrayFromRefPtrArray<MediaStreamInterface>(receiver->streams(), length);
  1092. }
  1093. UNITY_INTERFACE_EXPORT int DataChannelGetID(DataChannelInterface* channel) { return channel->id(); }
  1094. UNITY_INTERFACE_EXPORT char* DataChannelGetLabel(DataChannelInterface* channel)
  1095. {
  1096. return ConvertString(channel->label());
  1097. }
  1098. UNITY_INTERFACE_EXPORT char* DataChannelGetProtocol(DataChannelInterface* channel)
  1099. {
  1100. return ConvertString(channel->protocol());
  1101. }
  1102. UNITY_INTERFACE_EXPORT uint16_t DataChannelGetMaxRetransmits(DataChannelInterface* channel)
  1103. {
  1104. return channel->maxRetransmits();
  1105. }
  1106. UNITY_INTERFACE_EXPORT uint16_t DataChannelGetMaxRetransmitTime(DataChannelInterface* channel)
  1107. {
  1108. return channel->maxRetransmitTime();
  1109. }
  1110. UNITY_INTERFACE_EXPORT bool DataChannelGetOrdered(DataChannelInterface* channel) { return channel->ordered(); }
  1111. UNITY_INTERFACE_EXPORT uint64_t DataChannelGetBufferedAmount(DataChannelInterface* channel)
  1112. {
  1113. return channel->buffered_amount();
  1114. }
  1115. UNITY_INTERFACE_EXPORT bool DataChannelGetNegotiated(DataChannelInterface* channel)
  1116. {
  1117. return channel->negotiated();
  1118. }
  1119. UNITY_INTERFACE_EXPORT DataChannelInterface::DataState DataChannelGetReadyState(DataChannelInterface* channel)
  1120. {
  1121. return channel->state();
  1122. }
  1123. UNITY_INTERFACE_EXPORT void DataChannelSend(DataChannelInterface* channel, const char* data)
  1124. {
  1125. channel->Send(webrtc::DataBuffer(std::string(data)));
  1126. }
  1127. UNITY_INTERFACE_EXPORT void DataChannelSendBinary(DataChannelInterface* channel, const byte* data, int length)
  1128. {
  1129. rtc::CopyOnWriteBuffer buf(data, static_cast<size_t>(length));
  1130. channel->Send(webrtc::DataBuffer(buf, true));
  1131. }
  1132. UNITY_INTERFACE_EXPORT void DataChannelClose(DataChannelInterface* channel) { channel->Close(); }
  1133. UNITY_INTERFACE_EXPORT void
  1134. DataChannelRegisterOnMessage(Context* context, DataChannelInterface* channel, DelegateOnMessage callback)
  1135. {
  1136. context->GetDataChannelObject(channel)->RegisterOnMessage(callback);
  1137. }
  1138. UNITY_INTERFACE_EXPORT void
  1139. DataChannelRegisterOnOpen(Context* context, DataChannelInterface* channel, DelegateOnOpen callback)
  1140. {
  1141. context->GetDataChannelObject(channel)->RegisterOnOpen(callback);
  1142. }
  1143. UNITY_INTERFACE_EXPORT void
  1144. DataChannelRegisterOnClose(Context* context, DataChannelInterface* channel, DelegateOnClose callback)
  1145. {
  1146. context->GetDataChannelObject(channel)->RegisterOnClose(callback);
  1147. }
  1148. UNITY_INTERFACE_EXPORT void SetCurrentContext(Context* context)
  1149. {
  1150. ContextManager::GetInstance()->curContext = context;
  1151. }
  1152. UNITY_INTERFACE_EXPORT void AudioSourceProcessLocalAudio(
  1153. UnityAudioTrackSource* source,
  1154. float* audio_data,
  1155. int32 sample_rate,
  1156. int32 number_of_channels,
  1157. int32 number_of_frames)
  1158. {
  1159. if (source != nullptr)
  1160. {
  1161. source->PushAudioData(
  1162. audio_data,
  1163. sample_rate,
  1164. static_cast<size_t>(number_of_channels),
  1165. static_cast<size_t>(number_of_frames));
  1166. }
  1167. }
  1168. UNITY_INTERFACE_EXPORT AudioTrackSinkAdapter* ContextCreateAudioTrackSink(Context* context)
  1169. {
  1170. return context->CreateAudioTrackSinkAdapter();
  1171. }
  1172. UNITY_INTERFACE_EXPORT void ContextDeleteAudioTrackSink(Context* context, AudioTrackSinkAdapter* sink)
  1173. {
  1174. return context->DeleteAudioTrackSinkAdapter(sink);
  1175. }
  1176. UNITY_INTERFACE_EXPORT void AudioTrackAddSink(AudioTrackInterface* track, AudioTrackSinkInterface* sink)
  1177. {
  1178. track->AddSink(sink);
  1179. }
  1180. UNITY_INTERFACE_EXPORT void AudioTrackRemoveSink(AudioTrackInterface* track, AudioTrackSinkInterface* sink)
  1181. {
  1182. track->RemoveSink(sink);
  1183. }
  1184. UNITY_INTERFACE_EXPORT void
  1185. AudioTrackSinkProcessAudio(AudioTrackSinkAdapter* sink, float* data, size_t length, int channels, int sampleRate)
  1186. {
  1187. sink->ProcessAudio(data, length, static_cast<size_t>(channels), sampleRate);
  1188. }
  1189. #pragma clang diagnostic pop
  1190. }