You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

844 lines
33 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2015 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #import "RTCPeerConnection+Private.h"
  11. #import "RTCConfiguration+Private.h"
  12. #import "RTCDataChannel+Private.h"
  13. #import "RTCIceCandidate+Private.h"
  14. #import "RTCLegacyStatsReport+Private.h"
  15. #import "RTCMediaConstraints+Private.h"
  16. #import "RTCMediaStream+Private.h"
  17. #import "RTCMediaStreamTrack+Private.h"
  18. #import "RTCPeerConnectionFactory+Private.h"
  19. #import "RTCRtpReceiver+Private.h"
  20. #import "RTCRtpSender+Private.h"
  21. #import "RTCRtpTransceiver+Private.h"
  22. #import "RTCSessionDescription+Private.h"
  23. #import "base/RTCLogging.h"
  24. #import "helpers/NSString+StdString.h"
  25. #include <memory>
  26. #include "api/jsep_ice_candidate.h"
  27. #include "api/rtc_event_log_output_file.h"
  28. #include "api/transport/media/media_transport_interface.h"
  29. #include "rtc_base/checks.h"
  30. #include "rtc_base/numerics/safe_conversions.h"
  31. NSString * const kRTCPeerConnectionErrorDomain =
  32. @"org.webrtc.RTCPeerConnection";
  33. int const kRTCPeerConnnectionSessionDescriptionError = -1;
  34. namespace webrtc {
  35. class CreateSessionDescriptionObserverAdapter
  36. : public CreateSessionDescriptionObserver {
  37. public:
  38. CreateSessionDescriptionObserverAdapter(
  39. void (^completionHandler)(RTCSessionDescription *sessionDescription,
  40. NSError *error)) {
  41. completion_handler_ = completionHandler;
  42. }
  43. ~CreateSessionDescriptionObserverAdapter() override { completion_handler_ = nil; }
  44. void OnSuccess(SessionDescriptionInterface *desc) override {
  45. RTC_DCHECK(completion_handler_);
  46. std::unique_ptr<webrtc::SessionDescriptionInterface> description =
  47. std::unique_ptr<webrtc::SessionDescriptionInterface>(desc);
  48. RTCSessionDescription* session =
  49. [[RTCSessionDescription alloc] initWithNativeDescription:
  50. description.get()];
  51. completion_handler_(session, nil);
  52. completion_handler_ = nil;
  53. }
  54. void OnFailure(RTCError error) override {
  55. RTC_DCHECK(completion_handler_);
  56. // TODO(hta): Add handling of error.type()
  57. NSString *str = [NSString stringForStdString:error.message()];
  58. NSError* err =
  59. [NSError errorWithDomain:kRTCPeerConnectionErrorDomain
  60. code:kRTCPeerConnnectionSessionDescriptionError
  61. userInfo:@{ NSLocalizedDescriptionKey : str }];
  62. completion_handler_(nil, err);
  63. completion_handler_ = nil;
  64. }
  65. private:
  66. void (^completion_handler_)
  67. (RTCSessionDescription *sessionDescription, NSError *error);
  68. };
  69. class SetSessionDescriptionObserverAdapter :
  70. public SetSessionDescriptionObserver {
  71. public:
  72. SetSessionDescriptionObserverAdapter(void (^completionHandler)
  73. (NSError *error)) {
  74. completion_handler_ = completionHandler;
  75. }
  76. ~SetSessionDescriptionObserverAdapter() override { completion_handler_ = nil; }
  77. void OnSuccess() override {
  78. RTC_DCHECK(completion_handler_);
  79. completion_handler_(nil);
  80. completion_handler_ = nil;
  81. }
  82. void OnFailure(RTCError error) override {
  83. RTC_DCHECK(completion_handler_);
  84. // TODO(hta): Add handling of error.type()
  85. NSString *str = [NSString stringForStdString:error.message()];
  86. NSError* err =
  87. [NSError errorWithDomain:kRTCPeerConnectionErrorDomain
  88. code:kRTCPeerConnnectionSessionDescriptionError
  89. userInfo:@{ NSLocalizedDescriptionKey : str }];
  90. completion_handler_(err);
  91. completion_handler_ = nil;
  92. }
  93. private:
  94. void (^completion_handler_)(NSError *error);
  95. };
  96. PeerConnectionDelegateAdapter::PeerConnectionDelegateAdapter(
  97. RTCPeerConnection *peerConnection) {
  98. peer_connection_ = peerConnection;
  99. }
  100. PeerConnectionDelegateAdapter::~PeerConnectionDelegateAdapter() {
  101. peer_connection_ = nil;
  102. }
  103. void PeerConnectionDelegateAdapter::OnSignalingChange(
  104. PeerConnectionInterface::SignalingState new_state) {
  105. RTCSignalingState state =
  106. [[RTCPeerConnection class] signalingStateForNativeState:new_state];
  107. RTCPeerConnection *peer_connection = peer_connection_;
  108. [peer_connection.delegate peerConnection:peer_connection
  109. didChangeSignalingState:state];
  110. }
  111. void PeerConnectionDelegateAdapter::OnAddStream(
  112. rtc::scoped_refptr<MediaStreamInterface> stream) {
  113. RTCPeerConnection *peer_connection = peer_connection_;
  114. RTCMediaStream *mediaStream =
  115. [[RTCMediaStream alloc] initWithFactory:peer_connection.factory nativeMediaStream:stream];
  116. [peer_connection.delegate peerConnection:peer_connection
  117. didAddStream:mediaStream];
  118. }
  119. void PeerConnectionDelegateAdapter::OnRemoveStream(
  120. rtc::scoped_refptr<MediaStreamInterface> stream) {
  121. RTCPeerConnection *peer_connection = peer_connection_;
  122. RTCMediaStream *mediaStream =
  123. [[RTCMediaStream alloc] initWithFactory:peer_connection.factory nativeMediaStream:stream];
  124. [peer_connection.delegate peerConnection:peer_connection
  125. didRemoveStream:mediaStream];
  126. }
  127. void PeerConnectionDelegateAdapter::OnTrack(
  128. rtc::scoped_refptr<RtpTransceiverInterface> nativeTransceiver) {
  129. RTCPeerConnection *peer_connection = peer_connection_;
  130. RTCRtpTransceiver *transceiver =
  131. [[RTCRtpTransceiver alloc] initWithFactory:peer_connection.factory
  132. nativeRtpTransceiver:nativeTransceiver];
  133. if ([peer_connection.delegate
  134. respondsToSelector:@selector(peerConnection:didStartReceivingOnTransceiver:)]) {
  135. [peer_connection.delegate peerConnection:peer_connection
  136. didStartReceivingOnTransceiver:transceiver];
  137. }
  138. }
  139. void PeerConnectionDelegateAdapter::OnDataChannel(
  140. rtc::scoped_refptr<DataChannelInterface> data_channel) {
  141. RTCPeerConnection *peer_connection = peer_connection_;
  142. RTCDataChannel *dataChannel = [[RTCDataChannel alloc] initWithFactory:peer_connection.factory
  143. nativeDataChannel:data_channel];
  144. [peer_connection.delegate peerConnection:peer_connection
  145. didOpenDataChannel:dataChannel];
  146. }
  147. void PeerConnectionDelegateAdapter::OnRenegotiationNeeded() {
  148. RTCPeerConnection *peer_connection = peer_connection_;
  149. [peer_connection.delegate peerConnectionShouldNegotiate:peer_connection];
  150. }
  151. void PeerConnectionDelegateAdapter::OnIceConnectionChange(
  152. PeerConnectionInterface::IceConnectionState new_state) {
  153. RTCIceConnectionState state = [RTCPeerConnection iceConnectionStateForNativeState:new_state];
  154. [peer_connection_.delegate peerConnection:peer_connection_ didChangeIceConnectionState:state];
  155. }
  156. void PeerConnectionDelegateAdapter::OnStandardizedIceConnectionChange(
  157. PeerConnectionInterface::IceConnectionState new_state) {
  158. if ([peer_connection_.delegate
  159. respondsToSelector:@selector(peerConnection:didChangeStandardizedIceConnectionState:)]) {
  160. RTCIceConnectionState state = [RTCPeerConnection iceConnectionStateForNativeState:new_state];
  161. [peer_connection_.delegate peerConnection:peer_connection_
  162. didChangeStandardizedIceConnectionState:state];
  163. }
  164. }
  165. void PeerConnectionDelegateAdapter::OnConnectionChange(
  166. PeerConnectionInterface::PeerConnectionState new_state) {
  167. if ([peer_connection_.delegate
  168. respondsToSelector:@selector(peerConnection:didChangeConnectionState:)]) {
  169. RTCPeerConnectionState state = [RTCPeerConnection connectionStateForNativeState:new_state];
  170. [peer_connection_.delegate peerConnection:peer_connection_ didChangeConnectionState:state];
  171. }
  172. }
  173. void PeerConnectionDelegateAdapter::OnIceGatheringChange(
  174. PeerConnectionInterface::IceGatheringState new_state) {
  175. RTCIceGatheringState state =
  176. [[RTCPeerConnection class] iceGatheringStateForNativeState:new_state];
  177. RTCPeerConnection *peer_connection = peer_connection_;
  178. [peer_connection.delegate peerConnection:peer_connection
  179. didChangeIceGatheringState:state];
  180. }
  181. void PeerConnectionDelegateAdapter::OnIceCandidate(
  182. const IceCandidateInterface *candidate) {
  183. RTCIceCandidate *iceCandidate =
  184. [[RTCIceCandidate alloc] initWithNativeCandidate:candidate];
  185. RTCPeerConnection *peer_connection = peer_connection_;
  186. [peer_connection.delegate peerConnection:peer_connection
  187. didGenerateIceCandidate:iceCandidate];
  188. }
  189. void PeerConnectionDelegateAdapter::OnIceCandidatesRemoved(
  190. const std::vector<cricket::Candidate>& candidates) {
  191. NSMutableArray* ice_candidates =
  192. [NSMutableArray arrayWithCapacity:candidates.size()];
  193. for (const auto& candidate : candidates) {
  194. std::unique_ptr<JsepIceCandidate> candidate_wrapper(
  195. new JsepIceCandidate(candidate.transport_name(), -1, candidate));
  196. RTCIceCandidate* ice_candidate = [[RTCIceCandidate alloc]
  197. initWithNativeCandidate:candidate_wrapper.get()];
  198. [ice_candidates addObject:ice_candidate];
  199. }
  200. RTCPeerConnection* peer_connection = peer_connection_;
  201. [peer_connection.delegate peerConnection:peer_connection
  202. didRemoveIceCandidates:ice_candidates];
  203. }
  204. void PeerConnectionDelegateAdapter::OnIceSelectedCandidatePairChanged(
  205. const cricket::CandidatePairChangeEvent &event) {
  206. const auto &selected_pair = event.selected_candidate_pair;
  207. auto local_candidate_wrapper = std::make_unique<JsepIceCandidate>(
  208. selected_pair.local_candidate().transport_name(), -1, selected_pair.local_candidate());
  209. RTCIceCandidate *local_candidate =
  210. [[RTCIceCandidate alloc] initWithNativeCandidate:local_candidate_wrapper.release()];
  211. auto remote_candidate_wrapper = std::make_unique<JsepIceCandidate>(
  212. selected_pair.remote_candidate().transport_name(), -1, selected_pair.remote_candidate());
  213. RTCIceCandidate *remote_candidate =
  214. [[RTCIceCandidate alloc] initWithNativeCandidate:remote_candidate_wrapper.release()];
  215. RTCPeerConnection *peer_connection = peer_connection_;
  216. NSString *nsstr_reason = [NSString stringForStdString:event.reason];
  217. if ([peer_connection.delegate
  218. respondsToSelector:@selector
  219. (peerConnection:didChangeLocalCandidate:remoteCandidate:lastReceivedMs:changeReason:)]) {
  220. [peer_connection.delegate peerConnection:peer_connection
  221. didChangeLocalCandidate:local_candidate
  222. remoteCandidate:remote_candidate
  223. lastReceivedMs:event.last_data_received_ms
  224. changeReason:nsstr_reason];
  225. }
  226. }
  227. void PeerConnectionDelegateAdapter::OnAddTrack(
  228. rtc::scoped_refptr<RtpReceiverInterface> receiver,
  229. const std::vector<rtc::scoped_refptr<MediaStreamInterface>> &streams) {
  230. RTCPeerConnection *peer_connection = peer_connection_;
  231. if ([peer_connection.delegate respondsToSelector:@selector(peerConnection:
  232. didAddReceiver:streams:)]) {
  233. NSMutableArray *mediaStreams = [NSMutableArray arrayWithCapacity:streams.size()];
  234. for (const auto &nativeStream : streams) {
  235. RTCMediaStream *mediaStream = [[RTCMediaStream alloc] initWithFactory:peer_connection.factory
  236. nativeMediaStream:nativeStream];
  237. [mediaStreams addObject:mediaStream];
  238. }
  239. RTCRtpReceiver *rtpReceiver = [[RTCRtpReceiver alloc] initWithFactory:peer_connection.factory
  240. nativeRtpReceiver:receiver];
  241. [peer_connection.delegate peerConnection:peer_connection
  242. didAddReceiver:rtpReceiver
  243. streams:mediaStreams];
  244. }
  245. }
  246. void PeerConnectionDelegateAdapter::OnRemoveTrack(
  247. rtc::scoped_refptr<RtpReceiverInterface> receiver) {
  248. RTCPeerConnection *peer_connection = peer_connection_;
  249. if ([peer_connection.delegate respondsToSelector:@selector(peerConnection:didRemoveReceiver:)]) {
  250. RTCRtpReceiver *rtpReceiver = [[RTCRtpReceiver alloc] initWithFactory:peer_connection.factory
  251. nativeRtpReceiver:receiver];
  252. [peer_connection.delegate peerConnection:peer_connection didRemoveReceiver:rtpReceiver];
  253. }
  254. }
  255. } // namespace webrtc
  256. @implementation RTCPeerConnection {
  257. RTCPeerConnectionFactory *_factory;
  258. NSMutableArray<RTCMediaStream *> *_localStreams;
  259. std::unique_ptr<webrtc::PeerConnectionDelegateAdapter> _observer;
  260. rtc::scoped_refptr<webrtc::PeerConnectionInterface> _peerConnection;
  261. std::unique_ptr<webrtc::MediaConstraints> _nativeConstraints;
  262. BOOL _hasStartedRtcEventLog;
  263. }
  264. @synthesize delegate = _delegate;
  265. @synthesize factory = _factory;
  266. - (instancetype)initWithFactory:(RTCPeerConnectionFactory *)factory
  267. configuration:(RTCConfiguration *)configuration
  268. constraints:(RTCMediaConstraints *)constraints
  269. delegate:(id<RTCPeerConnectionDelegate>)delegate {
  270. NSParameterAssert(factory);
  271. std::unique_ptr<webrtc::PeerConnectionInterface::RTCConfiguration> config(
  272. [configuration createNativeConfiguration]);
  273. if (!config) {
  274. return nil;
  275. }
  276. if (self = [super init]) {
  277. _observer.reset(new webrtc::PeerConnectionDelegateAdapter(self));
  278. _nativeConstraints = constraints.nativeConstraints;
  279. CopyConstraintsIntoRtcConfiguration(_nativeConstraints.get(),
  280. config.get());
  281. _peerConnection =
  282. factory.nativeFactory->CreatePeerConnection(*config,
  283. nullptr,
  284. nullptr,
  285. _observer.get());
  286. if (!_peerConnection) {
  287. return nil;
  288. }
  289. _factory = factory;
  290. _localStreams = [[NSMutableArray alloc] init];
  291. _delegate = delegate;
  292. }
  293. return self;
  294. }
  295. - (NSArray<RTCMediaStream *> *)localStreams {
  296. return [_localStreams copy];
  297. }
  298. - (RTCSessionDescription *)localDescription {
  299. const webrtc::SessionDescriptionInterface *description =
  300. _peerConnection->local_description();
  301. return description ?
  302. [[RTCSessionDescription alloc] initWithNativeDescription:description]
  303. : nil;
  304. }
  305. - (RTCSessionDescription *)remoteDescription {
  306. const webrtc::SessionDescriptionInterface *description =
  307. _peerConnection->remote_description();
  308. return description ?
  309. [[RTCSessionDescription alloc] initWithNativeDescription:description]
  310. : nil;
  311. }
  312. - (RTCSignalingState)signalingState {
  313. return [[self class]
  314. signalingStateForNativeState:_peerConnection->signaling_state()];
  315. }
  316. - (RTCIceConnectionState)iceConnectionState {
  317. return [[self class] iceConnectionStateForNativeState:
  318. _peerConnection->ice_connection_state()];
  319. }
  320. - (RTCPeerConnectionState)connectionState {
  321. return [[self class] connectionStateForNativeState:_peerConnection->peer_connection_state()];
  322. }
  323. - (RTCIceGatheringState)iceGatheringState {
  324. return [[self class] iceGatheringStateForNativeState:
  325. _peerConnection->ice_gathering_state()];
  326. }
  327. - (BOOL)setConfiguration:(RTCConfiguration *)configuration {
  328. std::unique_ptr<webrtc::PeerConnectionInterface::RTCConfiguration> config(
  329. [configuration createNativeConfiguration]);
  330. if (!config) {
  331. return NO;
  332. }
  333. CopyConstraintsIntoRtcConfiguration(_nativeConstraints.get(),
  334. config.get());
  335. return _peerConnection->SetConfiguration(*config).ok();
  336. }
  337. - (RTCConfiguration *)configuration {
  338. webrtc::PeerConnectionInterface::RTCConfiguration config =
  339. _peerConnection->GetConfiguration();
  340. return [[RTCConfiguration alloc] initWithNativeConfiguration:config];
  341. }
  342. - (void)close {
  343. _peerConnection->Close();
  344. }
  345. - (void)addIceCandidate:(RTCIceCandidate *)candidate {
  346. std::unique_ptr<const webrtc::IceCandidateInterface> iceCandidate(
  347. candidate.nativeCandidate);
  348. _peerConnection->AddIceCandidate(iceCandidate.get());
  349. }
  350. - (void)removeIceCandidates:(NSArray<RTCIceCandidate *> *)iceCandidates {
  351. std::vector<cricket::Candidate> candidates;
  352. for (RTCIceCandidate *iceCandidate in iceCandidates) {
  353. std::unique_ptr<const webrtc::IceCandidateInterface> candidate(
  354. iceCandidate.nativeCandidate);
  355. if (candidate) {
  356. candidates.push_back(candidate->candidate());
  357. // Need to fill the transport name from the sdp_mid.
  358. candidates.back().set_transport_name(candidate->sdp_mid());
  359. }
  360. }
  361. if (!candidates.empty()) {
  362. _peerConnection->RemoveIceCandidates(candidates);
  363. }
  364. }
  365. - (void)addStream:(RTCMediaStream *)stream {
  366. if (!_peerConnection->AddStream(stream.nativeMediaStream)) {
  367. RTCLogError(@"Failed to add stream: %@", stream);
  368. return;
  369. }
  370. [_localStreams addObject:stream];
  371. }
  372. - (void)removeStream:(RTCMediaStream *)stream {
  373. _peerConnection->RemoveStream(stream.nativeMediaStream);
  374. [_localStreams removeObject:stream];
  375. }
  376. - (RTCRtpSender *)addTrack:(RTCMediaStreamTrack *)track streamIds:(NSArray<NSString *> *)streamIds {
  377. std::vector<std::string> nativeStreamIds;
  378. for (NSString *streamId in streamIds) {
  379. nativeStreamIds.push_back([streamId UTF8String]);
  380. }
  381. webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpSenderInterface>> nativeSenderOrError =
  382. _peerConnection->AddTrack(track.nativeTrack, nativeStreamIds);
  383. if (!nativeSenderOrError.ok()) {
  384. RTCLogError(@"Failed to add track %@: %s", track, nativeSenderOrError.error().message());
  385. return nil;
  386. }
  387. return [[RTCRtpSender alloc] initWithFactory:self.factory
  388. nativeRtpSender:nativeSenderOrError.MoveValue()];
  389. }
  390. - (BOOL)removeTrack:(RTCRtpSender *)sender {
  391. bool result = _peerConnection->RemoveTrack(sender.nativeRtpSender);
  392. if (!result) {
  393. RTCLogError(@"Failed to remote track %@", sender);
  394. }
  395. return result;
  396. }
  397. - (RTCRtpTransceiver *)addTransceiverWithTrack:(RTCMediaStreamTrack *)track {
  398. return [self addTransceiverWithTrack:track init:[[RTCRtpTransceiverInit alloc] init]];
  399. }
  400. - (RTCRtpTransceiver *)addTransceiverWithTrack:(RTCMediaStreamTrack *)track
  401. init:(RTCRtpTransceiverInit *)init {
  402. webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> nativeTransceiverOrError =
  403. _peerConnection->AddTransceiver(track.nativeTrack, init.nativeInit);
  404. if (!nativeTransceiverOrError.ok()) {
  405. RTCLogError(
  406. @"Failed to add transceiver %@: %s", track, nativeTransceiverOrError.error().message());
  407. return nil;
  408. }
  409. return [[RTCRtpTransceiver alloc] initWithFactory:self.factory
  410. nativeRtpTransceiver:nativeTransceiverOrError.MoveValue()];
  411. }
  412. - (RTCRtpTransceiver *)addTransceiverOfType:(RTCRtpMediaType)mediaType {
  413. return [self addTransceiverOfType:mediaType init:[[RTCRtpTransceiverInit alloc] init]];
  414. }
  415. - (RTCRtpTransceiver *)addTransceiverOfType:(RTCRtpMediaType)mediaType
  416. init:(RTCRtpTransceiverInit *)init {
  417. webrtc::RTCErrorOr<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> nativeTransceiverOrError =
  418. _peerConnection->AddTransceiver([RTCRtpReceiver nativeMediaTypeForMediaType:mediaType],
  419. init.nativeInit);
  420. if (!nativeTransceiverOrError.ok()) {
  421. RTCLogError(@"Failed to add transceiver %@: %s",
  422. [RTCRtpReceiver stringForMediaType:mediaType],
  423. nativeTransceiverOrError.error().message());
  424. return nil;
  425. }
  426. return [[RTCRtpTransceiver alloc] initWithFactory:self.factory
  427. nativeRtpTransceiver:nativeTransceiverOrError.MoveValue()];
  428. }
  429. - (void)offerForConstraints:(RTCMediaConstraints *)constraints
  430. completionHandler:
  431. (void (^)(RTCSessionDescription *sessionDescription,
  432. NSError *error))completionHandler {
  433. rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserverAdapter>
  434. observer(new rtc::RefCountedObject
  435. <webrtc::CreateSessionDescriptionObserverAdapter>(completionHandler));
  436. webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
  437. CopyConstraintsIntoOfferAnswerOptions(constraints.nativeConstraints.get(), &options);
  438. _peerConnection->CreateOffer(observer, options);
  439. }
  440. - (void)answerForConstraints:(RTCMediaConstraints *)constraints
  441. completionHandler:
  442. (void (^)(RTCSessionDescription *sessionDescription,
  443. NSError *error))completionHandler {
  444. rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserverAdapter>
  445. observer(new rtc::RefCountedObject
  446. <webrtc::CreateSessionDescriptionObserverAdapter>(completionHandler));
  447. webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
  448. CopyConstraintsIntoOfferAnswerOptions(constraints.nativeConstraints.get(), &options);
  449. _peerConnection->CreateAnswer(observer, options);
  450. }
  451. - (void)setLocalDescription:(RTCSessionDescription *)sdp
  452. completionHandler:(void (^)(NSError *error))completionHandler {
  453. rtc::scoped_refptr<webrtc::SetSessionDescriptionObserverAdapter> observer(
  454. new rtc::RefCountedObject<webrtc::SetSessionDescriptionObserverAdapter>(
  455. completionHandler));
  456. _peerConnection->SetLocalDescription(observer, sdp.nativeDescription);
  457. }
  458. - (void)setRemoteDescription:(RTCSessionDescription *)sdp
  459. completionHandler:(void (^)(NSError *error))completionHandler {
  460. rtc::scoped_refptr<webrtc::SetSessionDescriptionObserverAdapter> observer(
  461. new rtc::RefCountedObject<webrtc::SetSessionDescriptionObserverAdapter>(
  462. completionHandler));
  463. _peerConnection->SetRemoteDescription(observer, sdp.nativeDescription);
  464. }
  465. - (BOOL)setBweMinBitrateBps:(nullable NSNumber *)minBitrateBps
  466. currentBitrateBps:(nullable NSNumber *)currentBitrateBps
  467. maxBitrateBps:(nullable NSNumber *)maxBitrateBps {
  468. webrtc::PeerConnectionInterface::BitrateParameters params;
  469. if (minBitrateBps != nil) {
  470. params.min_bitrate_bps = absl::optional<int>(minBitrateBps.intValue);
  471. }
  472. if (currentBitrateBps != nil) {
  473. params.current_bitrate_bps = absl::optional<int>(currentBitrateBps.intValue);
  474. }
  475. if (maxBitrateBps != nil) {
  476. params.max_bitrate_bps = absl::optional<int>(maxBitrateBps.intValue);
  477. }
  478. return _peerConnection->SetBitrate(params).ok();
  479. }
  480. - (BOOL)startRtcEventLogWithFilePath:(NSString *)filePath
  481. maxSizeInBytes:(int64_t)maxSizeInBytes {
  482. RTC_DCHECK(filePath.length);
  483. RTC_DCHECK_GT(maxSizeInBytes, 0);
  484. RTC_DCHECK(!_hasStartedRtcEventLog);
  485. if (_hasStartedRtcEventLog) {
  486. RTCLogError(@"Event logging already started.");
  487. return NO;
  488. }
  489. FILE *f = fopen(filePath.UTF8String, "wb");
  490. if (!f) {
  491. RTCLogError(@"Error opening file: %@. Error: %d", filePath, errno);
  492. return NO;
  493. }
  494. // TODO(eladalon): It would be better to not allow negative values into PC.
  495. const size_t max_size = (maxSizeInBytes < 0) ? webrtc::RtcEventLog::kUnlimitedOutput :
  496. rtc::saturated_cast<size_t>(maxSizeInBytes);
  497. _hasStartedRtcEventLog = _peerConnection->StartRtcEventLog(
  498. std::make_unique<webrtc::RtcEventLogOutputFile>(f, max_size));
  499. return _hasStartedRtcEventLog;
  500. }
  501. - (void)stopRtcEventLog {
  502. _peerConnection->StopRtcEventLog();
  503. _hasStartedRtcEventLog = NO;
  504. }
  505. - (RTCRtpSender *)senderWithKind:(NSString *)kind
  506. streamId:(NSString *)streamId {
  507. std::string nativeKind = [NSString stdStringForString:kind];
  508. std::string nativeStreamId = [NSString stdStringForString:streamId];
  509. rtc::scoped_refptr<webrtc::RtpSenderInterface> nativeSender(
  510. _peerConnection->CreateSender(nativeKind, nativeStreamId));
  511. return nativeSender ?
  512. [[RTCRtpSender alloc] initWithFactory:self.factory nativeRtpSender:nativeSender] :
  513. nil;
  514. }
  515. - (NSArray<RTCRtpSender *> *)senders {
  516. std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> nativeSenders(
  517. _peerConnection->GetSenders());
  518. NSMutableArray *senders = [[NSMutableArray alloc] init];
  519. for (const auto &nativeSender : nativeSenders) {
  520. RTCRtpSender *sender =
  521. [[RTCRtpSender alloc] initWithFactory:self.factory nativeRtpSender:nativeSender];
  522. [senders addObject:sender];
  523. }
  524. return senders;
  525. }
  526. - (NSArray<RTCRtpReceiver *> *)receivers {
  527. std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> nativeReceivers(
  528. _peerConnection->GetReceivers());
  529. NSMutableArray *receivers = [[NSMutableArray alloc] init];
  530. for (const auto &nativeReceiver : nativeReceivers) {
  531. RTCRtpReceiver *receiver =
  532. [[RTCRtpReceiver alloc] initWithFactory:self.factory nativeRtpReceiver:nativeReceiver];
  533. [receivers addObject:receiver];
  534. }
  535. return receivers;
  536. }
  537. - (NSArray<RTCRtpTransceiver *> *)transceivers {
  538. std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> nativeTransceivers(
  539. _peerConnection->GetTransceivers());
  540. NSMutableArray *transceivers = [[NSMutableArray alloc] init];
  541. for (const auto &nativeTransceiver : nativeTransceivers) {
  542. RTCRtpTransceiver *transceiver = [[RTCRtpTransceiver alloc] initWithFactory:self.factory
  543. nativeRtpTransceiver:nativeTransceiver];
  544. [transceivers addObject:transceiver];
  545. }
  546. return transceivers;
  547. }
  548. #pragma mark - Private
  549. + (webrtc::PeerConnectionInterface::SignalingState)nativeSignalingStateForState:
  550. (RTCSignalingState)state {
  551. switch (state) {
  552. case RTCSignalingStateStable:
  553. return webrtc::PeerConnectionInterface::kStable;
  554. case RTCSignalingStateHaveLocalOffer:
  555. return webrtc::PeerConnectionInterface::kHaveLocalOffer;
  556. case RTCSignalingStateHaveLocalPrAnswer:
  557. return webrtc::PeerConnectionInterface::kHaveLocalPrAnswer;
  558. case RTCSignalingStateHaveRemoteOffer:
  559. return webrtc::PeerConnectionInterface::kHaveRemoteOffer;
  560. case RTCSignalingStateHaveRemotePrAnswer:
  561. return webrtc::PeerConnectionInterface::kHaveRemotePrAnswer;
  562. case RTCSignalingStateClosed:
  563. return webrtc::PeerConnectionInterface::kClosed;
  564. }
  565. }
  566. + (RTCSignalingState)signalingStateForNativeState:
  567. (webrtc::PeerConnectionInterface::SignalingState)nativeState {
  568. switch (nativeState) {
  569. case webrtc::PeerConnectionInterface::kStable:
  570. return RTCSignalingStateStable;
  571. case webrtc::PeerConnectionInterface::kHaveLocalOffer:
  572. return RTCSignalingStateHaveLocalOffer;
  573. case webrtc::PeerConnectionInterface::kHaveLocalPrAnswer:
  574. return RTCSignalingStateHaveLocalPrAnswer;
  575. case webrtc::PeerConnectionInterface::kHaveRemoteOffer:
  576. return RTCSignalingStateHaveRemoteOffer;
  577. case webrtc::PeerConnectionInterface::kHaveRemotePrAnswer:
  578. return RTCSignalingStateHaveRemotePrAnswer;
  579. case webrtc::PeerConnectionInterface::kClosed:
  580. return RTCSignalingStateClosed;
  581. }
  582. }
  583. + (NSString *)stringForSignalingState:(RTCSignalingState)state {
  584. switch (state) {
  585. case RTCSignalingStateStable:
  586. return @"STABLE";
  587. case RTCSignalingStateHaveLocalOffer:
  588. return @"HAVE_LOCAL_OFFER";
  589. case RTCSignalingStateHaveLocalPrAnswer:
  590. return @"HAVE_LOCAL_PRANSWER";
  591. case RTCSignalingStateHaveRemoteOffer:
  592. return @"HAVE_REMOTE_OFFER";
  593. case RTCSignalingStateHaveRemotePrAnswer:
  594. return @"HAVE_REMOTE_PRANSWER";
  595. case RTCSignalingStateClosed:
  596. return @"CLOSED";
  597. }
  598. }
  599. + (webrtc::PeerConnectionInterface::PeerConnectionState)nativeConnectionStateForState:
  600. (RTCPeerConnectionState)state {
  601. switch (state) {
  602. case RTCPeerConnectionStateNew:
  603. return webrtc::PeerConnectionInterface::PeerConnectionState::kNew;
  604. case RTCPeerConnectionStateConnecting:
  605. return webrtc::PeerConnectionInterface::PeerConnectionState::kConnecting;
  606. case RTCPeerConnectionStateConnected:
  607. return webrtc::PeerConnectionInterface::PeerConnectionState::kConnected;
  608. case RTCPeerConnectionStateFailed:
  609. return webrtc::PeerConnectionInterface::PeerConnectionState::kFailed;
  610. case RTCPeerConnectionStateDisconnected:
  611. return webrtc::PeerConnectionInterface::PeerConnectionState::kDisconnected;
  612. case RTCPeerConnectionStateClosed:
  613. return webrtc::PeerConnectionInterface::PeerConnectionState::kClosed;
  614. }
  615. }
  616. + (RTCPeerConnectionState)connectionStateForNativeState:
  617. (webrtc::PeerConnectionInterface::PeerConnectionState)nativeState {
  618. switch (nativeState) {
  619. case webrtc::PeerConnectionInterface::PeerConnectionState::kNew:
  620. return RTCPeerConnectionStateNew;
  621. case webrtc::PeerConnectionInterface::PeerConnectionState::kConnecting:
  622. return RTCPeerConnectionStateConnecting;
  623. case webrtc::PeerConnectionInterface::PeerConnectionState::kConnected:
  624. return RTCPeerConnectionStateConnected;
  625. case webrtc::PeerConnectionInterface::PeerConnectionState::kFailed:
  626. return RTCPeerConnectionStateFailed;
  627. case webrtc::PeerConnectionInterface::PeerConnectionState::kDisconnected:
  628. return RTCPeerConnectionStateDisconnected;
  629. case webrtc::PeerConnectionInterface::PeerConnectionState::kClosed:
  630. return RTCPeerConnectionStateClosed;
  631. }
  632. }
  633. + (NSString *)stringForConnectionState:(RTCPeerConnectionState)state {
  634. switch (state) {
  635. case RTCPeerConnectionStateNew:
  636. return @"NEW";
  637. case RTCPeerConnectionStateConnecting:
  638. return @"CONNECTING";
  639. case RTCPeerConnectionStateConnected:
  640. return @"CONNECTED";
  641. case RTCPeerConnectionStateFailed:
  642. return @"FAILED";
  643. case RTCPeerConnectionStateDisconnected:
  644. return @"DISCONNECTED";
  645. case RTCPeerConnectionStateClosed:
  646. return @"CLOSED";
  647. }
  648. }
  649. + (webrtc::PeerConnectionInterface::IceConnectionState)
  650. nativeIceConnectionStateForState:(RTCIceConnectionState)state {
  651. switch (state) {
  652. case RTCIceConnectionStateNew:
  653. return webrtc::PeerConnectionInterface::kIceConnectionNew;
  654. case RTCIceConnectionStateChecking:
  655. return webrtc::PeerConnectionInterface::kIceConnectionChecking;
  656. case RTCIceConnectionStateConnected:
  657. return webrtc::PeerConnectionInterface::kIceConnectionConnected;
  658. case RTCIceConnectionStateCompleted:
  659. return webrtc::PeerConnectionInterface::kIceConnectionCompleted;
  660. case RTCIceConnectionStateFailed:
  661. return webrtc::PeerConnectionInterface::kIceConnectionFailed;
  662. case RTCIceConnectionStateDisconnected:
  663. return webrtc::PeerConnectionInterface::kIceConnectionDisconnected;
  664. case RTCIceConnectionStateClosed:
  665. return webrtc::PeerConnectionInterface::kIceConnectionClosed;
  666. case RTCIceConnectionStateCount:
  667. return webrtc::PeerConnectionInterface::kIceConnectionMax;
  668. }
  669. }
  670. + (RTCIceConnectionState)iceConnectionStateForNativeState:
  671. (webrtc::PeerConnectionInterface::IceConnectionState)nativeState {
  672. switch (nativeState) {
  673. case webrtc::PeerConnectionInterface::kIceConnectionNew:
  674. return RTCIceConnectionStateNew;
  675. case webrtc::PeerConnectionInterface::kIceConnectionChecking:
  676. return RTCIceConnectionStateChecking;
  677. case webrtc::PeerConnectionInterface::kIceConnectionConnected:
  678. return RTCIceConnectionStateConnected;
  679. case webrtc::PeerConnectionInterface::kIceConnectionCompleted:
  680. return RTCIceConnectionStateCompleted;
  681. case webrtc::PeerConnectionInterface::kIceConnectionFailed:
  682. return RTCIceConnectionStateFailed;
  683. case webrtc::PeerConnectionInterface::kIceConnectionDisconnected:
  684. return RTCIceConnectionStateDisconnected;
  685. case webrtc::PeerConnectionInterface::kIceConnectionClosed:
  686. return RTCIceConnectionStateClosed;
  687. case webrtc::PeerConnectionInterface::kIceConnectionMax:
  688. return RTCIceConnectionStateCount;
  689. }
  690. }
  691. + (NSString *)stringForIceConnectionState:(RTCIceConnectionState)state {
  692. switch (state) {
  693. case RTCIceConnectionStateNew:
  694. return @"NEW";
  695. case RTCIceConnectionStateChecking:
  696. return @"CHECKING";
  697. case RTCIceConnectionStateConnected:
  698. return @"CONNECTED";
  699. case RTCIceConnectionStateCompleted:
  700. return @"COMPLETED";
  701. case RTCIceConnectionStateFailed:
  702. return @"FAILED";
  703. case RTCIceConnectionStateDisconnected:
  704. return @"DISCONNECTED";
  705. case RTCIceConnectionStateClosed:
  706. return @"CLOSED";
  707. case RTCIceConnectionStateCount:
  708. return @"COUNT";
  709. }
  710. }
  711. + (webrtc::PeerConnectionInterface::IceGatheringState)
  712. nativeIceGatheringStateForState:(RTCIceGatheringState)state {
  713. switch (state) {
  714. case RTCIceGatheringStateNew:
  715. return webrtc::PeerConnectionInterface::kIceGatheringNew;
  716. case RTCIceGatheringStateGathering:
  717. return webrtc::PeerConnectionInterface::kIceGatheringGathering;
  718. case RTCIceGatheringStateComplete:
  719. return webrtc::PeerConnectionInterface::kIceGatheringComplete;
  720. }
  721. }
  722. + (RTCIceGatheringState)iceGatheringStateForNativeState:
  723. (webrtc::PeerConnectionInterface::IceGatheringState)nativeState {
  724. switch (nativeState) {
  725. case webrtc::PeerConnectionInterface::kIceGatheringNew:
  726. return RTCIceGatheringStateNew;
  727. case webrtc::PeerConnectionInterface::kIceGatheringGathering:
  728. return RTCIceGatheringStateGathering;
  729. case webrtc::PeerConnectionInterface::kIceGatheringComplete:
  730. return RTCIceGatheringStateComplete;
  731. }
  732. }
  733. + (NSString *)stringForIceGatheringState:(RTCIceGatheringState)state {
  734. switch (state) {
  735. case RTCIceGatheringStateNew:
  736. return @"NEW";
  737. case RTCIceGatheringStateGathering:
  738. return @"GATHERING";
  739. case RTCIceGatheringStateComplete:
  740. return @"COMPLETE";
  741. }
  742. }
  743. + (webrtc::PeerConnectionInterface::StatsOutputLevel)
  744. nativeStatsOutputLevelForLevel:(RTCStatsOutputLevel)level {
  745. switch (level) {
  746. case RTCStatsOutputLevelStandard:
  747. return webrtc::PeerConnectionInterface::kStatsOutputLevelStandard;
  748. case RTCStatsOutputLevelDebug:
  749. return webrtc::PeerConnectionInterface::kStatsOutputLevelDebug;
  750. }
  751. }
  752. - (rtc::scoped_refptr<webrtc::PeerConnectionInterface>)nativePeerConnection {
  753. return _peerConnection;
  754. }
  755. @end