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.

878 lines
31 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2014 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 "ARDAppClient+Internal.h"
  11. #import <WebRTC/RTCAudioTrack.h>
  12. #import <WebRTC/RTCCameraVideoCapturer.h>
  13. #import <WebRTC/RTCConfiguration.h>
  14. #import <WebRTC/RTCDefaultVideoDecoderFactory.h>
  15. #import <WebRTC/RTCDefaultVideoEncoderFactory.h>
  16. #import <WebRTC/RTCFileLogger.h>
  17. #import <WebRTC/RTCFileVideoCapturer.h>
  18. #import <WebRTC/RTCIceServer.h>
  19. #import <WebRTC/RTCLogging.h>
  20. #import <WebRTC/RTCMediaConstraints.h>
  21. #import <WebRTC/RTCMediaStream.h>
  22. #import <WebRTC/RTCPeerConnectionFactory.h>
  23. #import <WebRTC/RTCRtpSender.h>
  24. #import <WebRTC/RTCRtpTransceiver.h>
  25. #import <WebRTC/RTCTracing.h>
  26. #import <WebRTC/RTCVideoSource.h>
  27. #import <WebRTC/RTCVideoTrack.h>
  28. #import "ARDAppEngineClient.h"
  29. #import "ARDExternalSampleCapturer.h"
  30. #import "ARDJoinResponse.h"
  31. #import "ARDMessageResponse.h"
  32. #import "ARDSettingsModel.h"
  33. #import "ARDSignalingMessage.h"
  34. #import "ARDTURNClient+Internal.h"
  35. #import "ARDUtilities.h"
  36. #import "ARDWebSocketChannel.h"
  37. #import "RTCIceCandidate+JSON.h"
  38. #import "RTCSessionDescription+JSON.h"
  39. static NSString * const kARDIceServerRequestUrl = @"https://appr.tc/params";
  40. static NSString * const kARDAppClientErrorDomain = @"ARDAppClient";
  41. static NSInteger const kARDAppClientErrorUnknown = -1;
  42. static NSInteger const kARDAppClientErrorRoomFull = -2;
  43. static NSInteger const kARDAppClientErrorCreateSDP = -3;
  44. static NSInteger const kARDAppClientErrorSetSDP = -4;
  45. static NSInteger const kARDAppClientErrorInvalidClient = -5;
  46. static NSInteger const kARDAppClientErrorInvalidRoom = -6;
  47. static NSString * const kARDMediaStreamId = @"ARDAMS";
  48. static NSString * const kARDAudioTrackId = @"ARDAMSa0";
  49. static NSString * const kARDVideoTrackId = @"ARDAMSv0";
  50. static NSString * const kARDVideoTrackKind = @"video";
  51. // TODO(tkchin): Add these as UI options.
  52. #if defined(WEBRTC_IOS)
  53. static BOOL const kARDAppClientEnableTracing = NO;
  54. static BOOL const kARDAppClientEnableRtcEventLog = YES;
  55. static int64_t const kARDAppClientAecDumpMaxSizeInBytes = 5e6; // 5 MB.
  56. static int64_t const kARDAppClientRtcEventLogMaxSizeInBytes = 5e6; // 5 MB.
  57. #endif
  58. static int const kKbpsMultiplier = 1000;
  59. // We need a proxy to NSTimer because it causes a strong retain cycle. When
  60. // using the proxy, |invalidate| must be called before it properly deallocs.
  61. @interface ARDTimerProxy : NSObject
  62. - (instancetype)initWithInterval:(NSTimeInterval)interval
  63. repeats:(BOOL)repeats
  64. timerHandler:(void (^)(void))timerHandler;
  65. - (void)invalidate;
  66. @end
  67. @implementation ARDTimerProxy {
  68. NSTimer *_timer;
  69. void (^_timerHandler)(void);
  70. }
  71. - (instancetype)initWithInterval:(NSTimeInterval)interval
  72. repeats:(BOOL)repeats
  73. timerHandler:(void (^)(void))timerHandler {
  74. NSParameterAssert(timerHandler);
  75. if (self = [super init]) {
  76. _timerHandler = timerHandler;
  77. _timer = [NSTimer scheduledTimerWithTimeInterval:interval
  78. target:self
  79. selector:@selector(timerDidFire:)
  80. userInfo:nil
  81. repeats:repeats];
  82. }
  83. return self;
  84. }
  85. - (void)invalidate {
  86. [_timer invalidate];
  87. }
  88. - (void)timerDidFire:(NSTimer *)timer {
  89. _timerHandler();
  90. }
  91. @end
  92. @implementation ARDAppClient {
  93. RTCFileLogger *_fileLogger;
  94. ARDTimerProxy *_statsTimer;
  95. ARDSettingsModel *_settings;
  96. RTCVideoTrack *_localVideoTrack;
  97. }
  98. @synthesize shouldGetStats = _shouldGetStats;
  99. @synthesize state = _state;
  100. @synthesize delegate = _delegate;
  101. @synthesize roomServerClient = _roomServerClient;
  102. @synthesize channel = _channel;
  103. @synthesize loopbackChannel = _loopbackChannel;
  104. @synthesize turnClient = _turnClient;
  105. @synthesize peerConnection = _peerConnection;
  106. @synthesize factory = _factory;
  107. @synthesize messageQueue = _messageQueue;
  108. @synthesize isTurnComplete = _isTurnComplete;
  109. @synthesize hasReceivedSdp = _hasReceivedSdp;
  110. @synthesize roomId = _roomId;
  111. @synthesize clientId = _clientId;
  112. @synthesize isInitiator = _isInitiator;
  113. @synthesize iceServers = _iceServers;
  114. @synthesize webSocketURL = _websocketURL;
  115. @synthesize webSocketRestURL = _websocketRestURL;
  116. @synthesize defaultPeerConnectionConstraints =
  117. _defaultPeerConnectionConstraints;
  118. @synthesize isLoopback = _isLoopback;
  119. @synthesize broadcast = _broadcast;
  120. - (instancetype)init {
  121. return [self initWithDelegate:nil];
  122. }
  123. - (instancetype)initWithDelegate:(id<ARDAppClientDelegate>)delegate {
  124. if (self = [super init]) {
  125. _roomServerClient = [[ARDAppEngineClient alloc] init];
  126. _delegate = delegate;
  127. NSURL *turnRequestURL = [NSURL URLWithString:kARDIceServerRequestUrl];
  128. _turnClient = [[ARDTURNClient alloc] initWithURL:turnRequestURL];
  129. [self configure];
  130. }
  131. return self;
  132. }
  133. // TODO(tkchin): Provide signaling channel factory interface so we can recreate
  134. // channel if we need to on network failure. Also, make this the default public
  135. // constructor.
  136. - (instancetype)initWithRoomServerClient:(id<ARDRoomServerClient>)rsClient
  137. signalingChannel:(id<ARDSignalingChannel>)channel
  138. turnClient:(id<ARDTURNClient>)turnClient
  139. delegate:(id<ARDAppClientDelegate>)delegate {
  140. NSParameterAssert(rsClient);
  141. NSParameterAssert(channel);
  142. NSParameterAssert(turnClient);
  143. if (self = [super init]) {
  144. _roomServerClient = rsClient;
  145. _channel = channel;
  146. _turnClient = turnClient;
  147. _delegate = delegate;
  148. [self configure];
  149. }
  150. return self;
  151. }
  152. - (void)configure {
  153. _messageQueue = [NSMutableArray array];
  154. _iceServers = [NSMutableArray array];
  155. _fileLogger = [[RTCFileLogger alloc] init];
  156. [_fileLogger start];
  157. }
  158. - (void)dealloc {
  159. self.shouldGetStats = NO;
  160. [self disconnect];
  161. }
  162. - (void)setShouldGetStats:(BOOL)shouldGetStats {
  163. if (_shouldGetStats == shouldGetStats) {
  164. return;
  165. }
  166. if (shouldGetStats) {
  167. __weak ARDAppClient *weakSelf = self;
  168. _statsTimer = [[ARDTimerProxy alloc] initWithInterval:1
  169. repeats:YES
  170. timerHandler:^{
  171. ARDAppClient *strongSelf = weakSelf;
  172. [strongSelf.peerConnection statsForTrack:nil
  173. statsOutputLevel:RTCStatsOutputLevelDebug
  174. completionHandler:^(NSArray *stats) {
  175. dispatch_async(dispatch_get_main_queue(), ^{
  176. ARDAppClient *strongSelf = weakSelf;
  177. [strongSelf.delegate appClient:strongSelf didGetStats:stats];
  178. });
  179. }];
  180. }];
  181. } else {
  182. [_statsTimer invalidate];
  183. _statsTimer = nil;
  184. }
  185. _shouldGetStats = shouldGetStats;
  186. }
  187. - (void)setState:(ARDAppClientState)state {
  188. if (_state == state) {
  189. return;
  190. }
  191. _state = state;
  192. [_delegate appClient:self didChangeState:_state];
  193. }
  194. - (void)connectToRoomWithId:(NSString *)roomId
  195. settings:(ARDSettingsModel *)settings
  196. isLoopback:(BOOL)isLoopback {
  197. NSParameterAssert(roomId.length);
  198. NSParameterAssert(_state == kARDAppClientStateDisconnected);
  199. _settings = settings;
  200. _isLoopback = isLoopback;
  201. self.state = kARDAppClientStateConnecting;
  202. RTCDefaultVideoDecoderFactory *decoderFactory = [[RTCDefaultVideoDecoderFactory alloc] init];
  203. RTCDefaultVideoEncoderFactory *encoderFactory = [[RTCDefaultVideoEncoderFactory alloc] init];
  204. encoderFactory.preferredCodec = [settings currentVideoCodecSettingFromStore];
  205. _factory = [[RTCPeerConnectionFactory alloc] initWithEncoderFactory:encoderFactory
  206. decoderFactory:decoderFactory];
  207. #if defined(WEBRTC_IOS)
  208. if (kARDAppClientEnableTracing) {
  209. NSString *filePath = [self documentsFilePathForFileName:@"webrtc-trace.txt"];
  210. RTCStartInternalCapture(filePath);
  211. }
  212. #endif
  213. // Request TURN.
  214. __weak ARDAppClient *weakSelf = self;
  215. [_turnClient requestServersWithCompletionHandler:^(NSArray *turnServers,
  216. NSError *error) {
  217. if (error) {
  218. RTCLogError(@"Error retrieving TURN servers: %@", error.localizedDescription);
  219. }
  220. ARDAppClient *strongSelf = weakSelf;
  221. [strongSelf.iceServers addObjectsFromArray:turnServers];
  222. strongSelf.isTurnComplete = YES;
  223. [strongSelf startSignalingIfReady];
  224. }];
  225. // Join room on room server.
  226. [_roomServerClient joinRoomWithRoomId:roomId
  227. isLoopback:isLoopback
  228. completionHandler:^(ARDJoinResponse *response, NSError *error) {
  229. ARDAppClient *strongSelf = weakSelf;
  230. if (error) {
  231. [strongSelf.delegate appClient:strongSelf didError:error];
  232. return;
  233. }
  234. NSError *joinError =
  235. [[strongSelf class] errorForJoinResultType:response.result];
  236. if (joinError) {
  237. RTCLogError(@"Failed to join room:%@ on room server.", roomId);
  238. [strongSelf disconnect];
  239. [strongSelf.delegate appClient:strongSelf didError:joinError];
  240. return;
  241. }
  242. RTCLog(@"Joined room:%@ on room server.", roomId);
  243. strongSelf.roomId = response.roomId;
  244. strongSelf.clientId = response.clientId;
  245. strongSelf.isInitiator = response.isInitiator;
  246. for (ARDSignalingMessage *message in response.messages) {
  247. if (message.type == kARDSignalingMessageTypeOffer ||
  248. message.type == kARDSignalingMessageTypeAnswer) {
  249. strongSelf.hasReceivedSdp = YES;
  250. [strongSelf.messageQueue insertObject:message atIndex:0];
  251. } else {
  252. [strongSelf.messageQueue addObject:message];
  253. }
  254. }
  255. strongSelf.webSocketURL = response.webSocketURL;
  256. strongSelf.webSocketRestURL = response.webSocketRestURL;
  257. [strongSelf registerWithColliderIfReady];
  258. [strongSelf startSignalingIfReady];
  259. }];
  260. }
  261. - (void)disconnect {
  262. if (_state == kARDAppClientStateDisconnected) {
  263. return;
  264. }
  265. if (self.hasJoinedRoomServerRoom) {
  266. [_roomServerClient leaveRoomWithRoomId:_roomId
  267. clientId:_clientId
  268. completionHandler:nil];
  269. }
  270. if (_channel) {
  271. if (_channel.state == kARDSignalingChannelStateRegistered) {
  272. // Tell the other client we're hanging up.
  273. ARDByeMessage *byeMessage = [[ARDByeMessage alloc] init];
  274. [_channel sendMessage:byeMessage];
  275. }
  276. // Disconnect from collider.
  277. _channel = nil;
  278. }
  279. _clientId = nil;
  280. _roomId = nil;
  281. _isInitiator = NO;
  282. _hasReceivedSdp = NO;
  283. _messageQueue = [NSMutableArray array];
  284. _localVideoTrack = nil;
  285. #if defined(WEBRTC_IOS)
  286. [_factory stopAecDump];
  287. [_peerConnection stopRtcEventLog];
  288. #endif
  289. [_peerConnection close];
  290. _peerConnection = nil;
  291. self.state = kARDAppClientStateDisconnected;
  292. #if defined(WEBRTC_IOS)
  293. if (kARDAppClientEnableTracing) {
  294. RTCStopInternalCapture();
  295. }
  296. #endif
  297. }
  298. #pragma mark - ARDSignalingChannelDelegate
  299. - (void)channel:(id<ARDSignalingChannel>)channel
  300. didReceiveMessage:(ARDSignalingMessage *)message {
  301. switch (message.type) {
  302. case kARDSignalingMessageTypeOffer:
  303. case kARDSignalingMessageTypeAnswer:
  304. // Offers and answers must be processed before any other message, so we
  305. // place them at the front of the queue.
  306. _hasReceivedSdp = YES;
  307. [_messageQueue insertObject:message atIndex:0];
  308. break;
  309. case kARDSignalingMessageTypeCandidate:
  310. case kARDSignalingMessageTypeCandidateRemoval:
  311. [_messageQueue addObject:message];
  312. break;
  313. case kARDSignalingMessageTypeBye:
  314. // Disconnects can be processed immediately.
  315. [self processSignalingMessage:message];
  316. return;
  317. }
  318. [self drainMessageQueueIfReady];
  319. }
  320. - (void)channel:(id<ARDSignalingChannel>)channel
  321. didChangeState:(ARDSignalingChannelState)state {
  322. switch (state) {
  323. case kARDSignalingChannelStateOpen:
  324. break;
  325. case kARDSignalingChannelStateRegistered:
  326. break;
  327. case kARDSignalingChannelStateClosed:
  328. case kARDSignalingChannelStateError:
  329. // TODO(tkchin): reconnection scenarios. Right now we just disconnect
  330. // completely if the websocket connection fails.
  331. [self disconnect];
  332. break;
  333. }
  334. }
  335. #pragma mark - RTCPeerConnectionDelegate
  336. // Callbacks for this delegate occur on non-main thread and need to be
  337. // dispatched back to main queue as needed.
  338. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  339. didChangeSignalingState:(RTCSignalingState)stateChanged {
  340. RTCLog(@"Signaling state changed: %ld", (long)stateChanged);
  341. }
  342. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  343. didAddStream:(RTCMediaStream *)stream {
  344. RTCLog(@"Stream with %lu video tracks and %lu audio tracks was added.",
  345. (unsigned long)stream.videoTracks.count,
  346. (unsigned long)stream.audioTracks.count);
  347. }
  348. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  349. didStartReceivingOnTransceiver:(RTCRtpTransceiver *)transceiver {
  350. RTCMediaStreamTrack *track = transceiver.receiver.track;
  351. RTCLog(@"Now receiving %@ on track %@.", track.kind, track.trackId);
  352. }
  353. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  354. didRemoveStream:(RTCMediaStream *)stream {
  355. RTCLog(@"Stream was removed.");
  356. }
  357. - (void)peerConnectionShouldNegotiate:(RTCPeerConnection *)peerConnection {
  358. RTCLog(@"WARNING: Renegotiation needed but unimplemented.");
  359. }
  360. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  361. didChangeIceConnectionState:(RTCIceConnectionState)newState {
  362. RTCLog(@"ICE state changed: %ld", (long)newState);
  363. dispatch_async(dispatch_get_main_queue(), ^{
  364. [self.delegate appClient:self didChangeConnectionState:newState];
  365. });
  366. }
  367. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  368. didChangeConnectionState:(RTCPeerConnectionState)newState {
  369. RTCLog(@"ICE+DTLS state changed: %ld", (long)newState);
  370. }
  371. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  372. didChangeIceGatheringState:(RTCIceGatheringState)newState {
  373. RTCLog(@"ICE gathering state changed: %ld", (long)newState);
  374. }
  375. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  376. didGenerateIceCandidate:(RTCIceCandidate *)candidate {
  377. dispatch_async(dispatch_get_main_queue(), ^{
  378. ARDICECandidateMessage *message =
  379. [[ARDICECandidateMessage alloc] initWithCandidate:candidate];
  380. [self sendSignalingMessage:message];
  381. });
  382. }
  383. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  384. didRemoveIceCandidates:(NSArray<RTCIceCandidate *> *)candidates {
  385. dispatch_async(dispatch_get_main_queue(), ^{
  386. ARDICECandidateRemovalMessage *message =
  387. [[ARDICECandidateRemovalMessage alloc]
  388. initWithRemovedCandidates:candidates];
  389. [self sendSignalingMessage:message];
  390. });
  391. }
  392. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  393. didChangeLocalCandidate:(RTCIceCandidate *)local
  394. didChangeRemoteCandidate:(RTCIceCandidate *)remote
  395. lastReceivedMs:(int)lastDataReceivedMs
  396. didHaveReason:(NSString *)reason {
  397. RTCLog(@"ICE candidate pair changed because: %@", reason);
  398. }
  399. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  400. didOpenDataChannel:(RTCDataChannel *)dataChannel {
  401. }
  402. #pragma mark - RTCSessionDescriptionDelegate
  403. // Callbacks for this delegate occur on non-main thread and need to be
  404. // dispatched back to main queue as needed.
  405. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  406. didCreateSessionDescription:(RTCSessionDescription *)sdp
  407. error:(NSError *)error {
  408. dispatch_async(dispatch_get_main_queue(), ^{
  409. if (error) {
  410. RTCLogError(@"Failed to create session description. Error: %@", error);
  411. [self disconnect];
  412. NSDictionary *userInfo = @{
  413. NSLocalizedDescriptionKey: @"Failed to create session description.",
  414. };
  415. NSError *sdpError =
  416. [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  417. code:kARDAppClientErrorCreateSDP
  418. userInfo:userInfo];
  419. [self.delegate appClient:self didError:sdpError];
  420. return;
  421. }
  422. __weak ARDAppClient *weakSelf = self;
  423. [self.peerConnection setLocalDescription:sdp
  424. completionHandler:^(NSError *error) {
  425. ARDAppClient *strongSelf = weakSelf;
  426. [strongSelf peerConnection:strongSelf.peerConnection
  427. didSetSessionDescriptionWithError:error];
  428. }];
  429. ARDSessionDescriptionMessage *message =
  430. [[ARDSessionDescriptionMessage alloc] initWithDescription:sdp];
  431. [self sendSignalingMessage:message];
  432. [self setMaxBitrateForPeerConnectionVideoSender];
  433. });
  434. }
  435. - (void)peerConnection:(RTCPeerConnection *)peerConnection
  436. didSetSessionDescriptionWithError:(NSError *)error {
  437. dispatch_async(dispatch_get_main_queue(), ^{
  438. if (error) {
  439. RTCLogError(@"Failed to set session description. Error: %@", error);
  440. [self disconnect];
  441. NSDictionary *userInfo = @{
  442. NSLocalizedDescriptionKey: @"Failed to set session description.",
  443. };
  444. NSError *sdpError =
  445. [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  446. code:kARDAppClientErrorSetSDP
  447. userInfo:userInfo];
  448. [self.delegate appClient:self didError:sdpError];
  449. return;
  450. }
  451. // If we're answering and we've just set the remote offer we need to create
  452. // an answer and set the local description.
  453. if (!self.isInitiator && !self.peerConnection.localDescription) {
  454. RTCMediaConstraints *constraints = [self defaultAnswerConstraints];
  455. __weak ARDAppClient *weakSelf = self;
  456. [self.peerConnection answerForConstraints:constraints
  457. completionHandler:^(RTCSessionDescription *sdp, NSError *error) {
  458. ARDAppClient *strongSelf = weakSelf;
  459. [strongSelf peerConnection:strongSelf.peerConnection
  460. didCreateSessionDescription:sdp
  461. error:error];
  462. }];
  463. }
  464. });
  465. }
  466. #pragma mark - Private
  467. #if defined(WEBRTC_IOS)
  468. - (NSString *)documentsFilePathForFileName:(NSString *)fileName {
  469. NSParameterAssert(fileName.length);
  470. NSArray *paths = NSSearchPathForDirectoriesInDomains(
  471. NSDocumentDirectory, NSUserDomainMask, YES);
  472. NSString *documentsDirPath = paths.firstObject;
  473. NSString *filePath =
  474. [documentsDirPath stringByAppendingPathComponent:fileName];
  475. return filePath;
  476. }
  477. #endif
  478. - (BOOL)hasJoinedRoomServerRoom {
  479. return _clientId.length;
  480. }
  481. // Begins the peer connection connection process if we have both joined a room
  482. // on the room server and tried to obtain a TURN server. Otherwise does nothing.
  483. // A peer connection object will be created with a stream that contains local
  484. // audio and video capture. If this client is the caller, an offer is created as
  485. // well, otherwise the client will wait for an offer to arrive.
  486. - (void)startSignalingIfReady {
  487. if (!_isTurnComplete || !self.hasJoinedRoomServerRoom) {
  488. return;
  489. }
  490. self.state = kARDAppClientStateConnected;
  491. // Create peer connection.
  492. RTCMediaConstraints *constraints = [self defaultPeerConnectionConstraints];
  493. RTCConfiguration *config = [[RTCConfiguration alloc] init];
  494. RTCCertificate *pcert = [RTCCertificate generateCertificateWithParams:@{
  495. @"expires" : @100000,
  496. @"name" : @"RSASSA-PKCS1-v1_5"
  497. }];
  498. config.iceServers = _iceServers;
  499. config.sdpSemantics = RTCSdpSemanticsUnifiedPlan;
  500. config.certificate = pcert;
  501. _peerConnection = [_factory peerConnectionWithConfiguration:config
  502. constraints:constraints
  503. delegate:self];
  504. // Create AV senders.
  505. [self createMediaSenders];
  506. if (_isInitiator) {
  507. // Send offer.
  508. __weak ARDAppClient *weakSelf = self;
  509. [_peerConnection offerForConstraints:[self defaultOfferConstraints]
  510. completionHandler:^(RTCSessionDescription *sdp,
  511. NSError *error) {
  512. ARDAppClient *strongSelf = weakSelf;
  513. [strongSelf peerConnection:strongSelf.peerConnection
  514. didCreateSessionDescription:sdp
  515. error:error];
  516. }];
  517. } else {
  518. // Check if we've received an offer.
  519. [self drainMessageQueueIfReady];
  520. }
  521. #if defined(WEBRTC_IOS)
  522. // Start event log.
  523. if (kARDAppClientEnableRtcEventLog) {
  524. NSString *filePath = [self documentsFilePathForFileName:@"webrtc-rtceventlog"];
  525. if (![_peerConnection startRtcEventLogWithFilePath:filePath
  526. maxSizeInBytes:kARDAppClientRtcEventLogMaxSizeInBytes]) {
  527. RTCLogError(@"Failed to start event logging.");
  528. }
  529. }
  530. // Start aecdump diagnostic recording.
  531. if ([_settings currentCreateAecDumpSettingFromStore]) {
  532. NSString *filePath = [self documentsFilePathForFileName:@"webrtc-audio.aecdump"];
  533. if (![_factory startAecDumpWithFilePath:filePath
  534. maxSizeInBytes:kARDAppClientAecDumpMaxSizeInBytes]) {
  535. RTCLogError(@"Failed to start aec dump.");
  536. }
  537. }
  538. #endif
  539. }
  540. // Processes the messages that we've received from the room server and the
  541. // signaling channel. The offer or answer message must be processed before other
  542. // signaling messages, however they can arrive out of order. Hence, this method
  543. // only processes pending messages if there is a peer connection object and
  544. // if we have received either an offer or answer.
  545. - (void)drainMessageQueueIfReady {
  546. if (!_peerConnection || !_hasReceivedSdp) {
  547. return;
  548. }
  549. for (ARDSignalingMessage *message in _messageQueue) {
  550. [self processSignalingMessage:message];
  551. }
  552. [_messageQueue removeAllObjects];
  553. }
  554. // Processes the given signaling message based on its type.
  555. - (void)processSignalingMessage:(ARDSignalingMessage *)message {
  556. NSParameterAssert(_peerConnection ||
  557. message.type == kARDSignalingMessageTypeBye);
  558. switch (message.type) {
  559. case kARDSignalingMessageTypeOffer:
  560. case kARDSignalingMessageTypeAnswer: {
  561. ARDSessionDescriptionMessage *sdpMessage =
  562. (ARDSessionDescriptionMessage *)message;
  563. RTCSessionDescription *description = sdpMessage.sessionDescription;
  564. __weak ARDAppClient *weakSelf = self;
  565. [_peerConnection setRemoteDescription:description
  566. completionHandler:^(NSError *error) {
  567. ARDAppClient *strongSelf = weakSelf;
  568. [strongSelf peerConnection:strongSelf.peerConnection
  569. didSetSessionDescriptionWithError:error];
  570. }];
  571. break;
  572. }
  573. case kARDSignalingMessageTypeCandidate: {
  574. ARDICECandidateMessage *candidateMessage =
  575. (ARDICECandidateMessage *)message;
  576. [_peerConnection addIceCandidate:candidateMessage.candidate];
  577. break;
  578. }
  579. case kARDSignalingMessageTypeCandidateRemoval: {
  580. ARDICECandidateRemovalMessage *candidateMessage =
  581. (ARDICECandidateRemovalMessage *)message;
  582. [_peerConnection removeIceCandidates:candidateMessage.candidates];
  583. break;
  584. }
  585. case kARDSignalingMessageTypeBye:
  586. // Other client disconnected.
  587. // TODO(tkchin): support waiting in room for next client. For now just
  588. // disconnect.
  589. [self disconnect];
  590. break;
  591. }
  592. }
  593. // Sends a signaling message to the other client. The caller will send messages
  594. // through the room server, whereas the callee will send messages over the
  595. // signaling channel.
  596. - (void)sendSignalingMessage:(ARDSignalingMessage *)message {
  597. if (_isInitiator) {
  598. __weak ARDAppClient *weakSelf = self;
  599. [_roomServerClient sendMessage:message
  600. forRoomId:_roomId
  601. clientId:_clientId
  602. completionHandler:^(ARDMessageResponse *response,
  603. NSError *error) {
  604. ARDAppClient *strongSelf = weakSelf;
  605. if (error) {
  606. [strongSelf.delegate appClient:strongSelf didError:error];
  607. return;
  608. }
  609. NSError *messageError =
  610. [[strongSelf class] errorForMessageResultType:response.result];
  611. if (messageError) {
  612. [strongSelf.delegate appClient:strongSelf didError:messageError];
  613. return;
  614. }
  615. }];
  616. } else {
  617. [_channel sendMessage:message];
  618. }
  619. }
  620. - (void)setMaxBitrateForPeerConnectionVideoSender {
  621. for (RTCRtpSender *sender in _peerConnection.senders) {
  622. if (sender.track != nil) {
  623. if ([sender.track.kind isEqualToString:kARDVideoTrackKind]) {
  624. [self setMaxBitrate:[_settings currentMaxBitrateSettingFromStore] forVideoSender:sender];
  625. }
  626. }
  627. }
  628. }
  629. - (void)setMaxBitrate:(NSNumber *)maxBitrate forVideoSender:(RTCRtpSender *)sender {
  630. if (maxBitrate.intValue <= 0) {
  631. return;
  632. }
  633. RTCRtpParameters *parametersToModify = sender.parameters;
  634. for (RTCRtpEncodingParameters *encoding in parametersToModify.encodings) {
  635. encoding.maxBitrateBps = @(maxBitrate.intValue * kKbpsMultiplier);
  636. }
  637. [sender setParameters:parametersToModify];
  638. }
  639. - (RTCRtpTransceiver *)videoTransceiver {
  640. for (RTCRtpTransceiver *transceiver in _peerConnection.transceivers) {
  641. if (transceiver.mediaType == RTCRtpMediaTypeVideo) {
  642. return transceiver;
  643. }
  644. }
  645. return nil;
  646. }
  647. - (void)createMediaSenders {
  648. RTCMediaConstraints *constraints = [self defaultMediaAudioConstraints];
  649. RTCAudioSource *source = [_factory audioSourceWithConstraints:constraints];
  650. RTCAudioTrack *track = [_factory audioTrackWithSource:source
  651. trackId:kARDAudioTrackId];
  652. [_peerConnection addTrack:track streamIds:@[ kARDMediaStreamId ]];
  653. _localVideoTrack = [self createLocalVideoTrack];
  654. if (_localVideoTrack) {
  655. [_peerConnection addTrack:_localVideoTrack streamIds:@[ kARDMediaStreamId ]];
  656. [_delegate appClient:self didReceiveLocalVideoTrack:_localVideoTrack];
  657. // We can set up rendering for the remote track right away since the transceiver already has an
  658. // RTCRtpReceiver with a track. The track will automatically get unmuted and produce frames
  659. // once RTP is received.
  660. RTCVideoTrack *track = (RTCVideoTrack *)([self videoTransceiver].receiver.track);
  661. [_delegate appClient:self didReceiveRemoteVideoTrack:track];
  662. }
  663. }
  664. - (RTCVideoTrack *)createLocalVideoTrack {
  665. if ([_settings currentAudioOnlySettingFromStore]) {
  666. return nil;
  667. }
  668. RTCVideoSource *source = [_factory videoSource];
  669. #if !TARGET_IPHONE_SIMULATOR
  670. if (self.isBroadcast) {
  671. ARDExternalSampleCapturer *capturer =
  672. [[ARDExternalSampleCapturer alloc] initWithDelegate:source];
  673. [_delegate appClient:self didCreateLocalExternalSampleCapturer:capturer];
  674. } else {
  675. RTCCameraVideoCapturer *capturer = [[RTCCameraVideoCapturer alloc] initWithDelegate:source];
  676. [_delegate appClient:self didCreateLocalCapturer:capturer];
  677. }
  678. #else
  679. #if defined(__IPHONE_11_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0)
  680. if (@available(iOS 10, *)) {
  681. RTCFileVideoCapturer *fileCapturer = [[RTCFileVideoCapturer alloc] initWithDelegate:source];
  682. [_delegate appClient:self didCreateLocalFileCapturer:fileCapturer];
  683. }
  684. #endif
  685. #endif
  686. return [_factory videoTrackWithSource:source trackId:kARDVideoTrackId];
  687. }
  688. #pragma mark - Collider methods
  689. - (void)registerWithColliderIfReady {
  690. if (!self.hasJoinedRoomServerRoom) {
  691. return;
  692. }
  693. // Open WebSocket connection.
  694. if (!_channel) {
  695. _channel =
  696. [[ARDWebSocketChannel alloc] initWithURL:_websocketURL
  697. restURL:_websocketRestURL
  698. delegate:self];
  699. if (_isLoopback) {
  700. _loopbackChannel =
  701. [[ARDLoopbackWebSocketChannel alloc] initWithURL:_websocketURL
  702. restURL:_websocketRestURL];
  703. }
  704. }
  705. [_channel registerForRoomId:_roomId clientId:_clientId];
  706. if (_isLoopback) {
  707. [_loopbackChannel registerForRoomId:_roomId clientId:@"LOOPBACK_CLIENT_ID"];
  708. }
  709. }
  710. #pragma mark - Defaults
  711. - (RTCMediaConstraints *)defaultMediaAudioConstraints {
  712. NSDictionary *mandatoryConstraints = @{};
  713. RTCMediaConstraints *constraints =
  714. [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints
  715. optionalConstraints:nil];
  716. return constraints;
  717. }
  718. - (RTCMediaConstraints *)defaultAnswerConstraints {
  719. return [self defaultOfferConstraints];
  720. }
  721. - (RTCMediaConstraints *)defaultOfferConstraints {
  722. NSDictionary *mandatoryConstraints = @{
  723. @"OfferToReceiveAudio" : @"true",
  724. @"OfferToReceiveVideo" : @"true"
  725. };
  726. RTCMediaConstraints* constraints =
  727. [[RTCMediaConstraints alloc]
  728. initWithMandatoryConstraints:mandatoryConstraints
  729. optionalConstraints:nil];
  730. return constraints;
  731. }
  732. - (RTCMediaConstraints *)defaultPeerConnectionConstraints {
  733. if (_defaultPeerConnectionConstraints) {
  734. return _defaultPeerConnectionConstraints;
  735. }
  736. NSString *value = _isLoopback ? @"false" : @"true";
  737. NSDictionary *optionalConstraints = @{ @"DtlsSrtpKeyAgreement" : value };
  738. RTCMediaConstraints* constraints =
  739. [[RTCMediaConstraints alloc]
  740. initWithMandatoryConstraints:nil
  741. optionalConstraints:optionalConstraints];
  742. return constraints;
  743. }
  744. #pragma mark - Errors
  745. + (NSError *)errorForJoinResultType:(ARDJoinResultType)resultType {
  746. NSError *error = nil;
  747. switch (resultType) {
  748. case kARDJoinResultTypeSuccess:
  749. break;
  750. case kARDJoinResultTypeUnknown: {
  751. error = [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  752. code:kARDAppClientErrorUnknown
  753. userInfo:@{
  754. NSLocalizedDescriptionKey: @"Unknown error.",
  755. }];
  756. break;
  757. }
  758. case kARDJoinResultTypeFull: {
  759. error = [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  760. code:kARDAppClientErrorRoomFull
  761. userInfo:@{
  762. NSLocalizedDescriptionKey: @"Room is full.",
  763. }];
  764. break;
  765. }
  766. }
  767. return error;
  768. }
  769. + (NSError *)errorForMessageResultType:(ARDMessageResultType)resultType {
  770. NSError *error = nil;
  771. switch (resultType) {
  772. case kARDMessageResultTypeSuccess:
  773. break;
  774. case kARDMessageResultTypeUnknown:
  775. error = [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  776. code:kARDAppClientErrorUnknown
  777. userInfo:@{
  778. NSLocalizedDescriptionKey: @"Unknown error.",
  779. }];
  780. break;
  781. case kARDMessageResultTypeInvalidClient:
  782. error = [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  783. code:kARDAppClientErrorInvalidClient
  784. userInfo:@{
  785. NSLocalizedDescriptionKey: @"Invalid client.",
  786. }];
  787. break;
  788. case kARDMessageResultTypeInvalidRoom:
  789. error = [[NSError alloc] initWithDomain:kARDAppClientErrorDomain
  790. code:kARDAppClientErrorInvalidRoom
  791. userInfo:@{
  792. NSLocalizedDescriptionKey: @"Invalid room.",
  793. }];
  794. break;
  795. }
  796. return error;
  797. }
  798. @end