blob: 34aa7520cbf5c11d5901b2998ba67e86f4faa6f6 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2013, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#import "APPRTCAppDelegate.h"
29
30#import "APPRTCViewController.h"
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000031#import "RTCICECandidate.h"
32#import "RTCICEServer.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#import "RTCMediaConstraints.h"
34#import "RTCMediaStream.h"
35#import "RTCPair.h"
36#import "RTCPeerConnection.h"
37#import "RTCPeerConnectionDelegate.h"
38#import "RTCPeerConnectionFactory.h"
39#import "RTCSessionDescription.h"
40
41@interface PCObserver : NSObject<RTCPeerConnectionDelegate>
42
43- (id)initWithDelegate:(id<APPRTCSendMessage>)delegate;
44
45@end
46
47@implementation PCObserver {
48 id<APPRTCSendMessage> _delegate;
49}
50
51- (id)initWithDelegate:(id<APPRTCSendMessage>)delegate {
52 if (self = [super init]) {
53 _delegate = delegate;
54 }
55 return self;
56}
57
58- (void)peerConnectionOnError:(RTCPeerConnection *)peerConnection {
59 NSLog(@"PCO onError.");
60 NSAssert(NO, @"PeerConnection failed.");
61}
62
63- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000064 signalingStateChanged:(RTCSignalingState)stateChanged {
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +000065 NSLog(@"PCO onSignalingStateChange: %d", stateChanged);
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066}
67
68- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000069 addedStream:(RTCMediaStream *)stream {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070 NSLog(@"PCO onAddStream.");
71 dispatch_async(dispatch_get_main_queue(), ^(void) {
72 NSAssert([stream.audioTracks count] >= 1,
73 @"Expected at least 1 audio stream");
74 //NSAssert([stream.videoTracks count] >= 1,
75 // @"Expected at least 1 video stream");
76 // TODO(hughv): Add video support
77 });
78}
79
80- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000081 removedStream:(RTCMediaStream *)stream {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082 NSLog(@"PCO onRemoveStream.");
83 // TODO(hughv): Remove video track.
84}
85
86- (void)
87 peerConnectionOnRenegotiationNeeded:(RTCPeerConnection *)peerConnection {
88 NSLog(@"PCO onRenegotiationNeeded.");
89 // TODO(hughv): Handle this.
90}
91
92- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000093 gotICECandidate:(RTCICECandidate *)candidate {
94 NSLog(@"PCO onICECandidate.\n Mid[%@] Index[%d] Sdp[%@]",
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095 candidate.sdpMid,
96 candidate.sdpMLineIndex,
97 candidate.sdp);
98 NSDictionary *json =
99 @{ @"type" : @"candidate",
100 @"label" : [NSNumber numberWithInt:candidate.sdpMLineIndex],
101 @"id" : candidate.sdpMid,
102 @"candidate" : candidate.sdp };
103 NSError *error;
104 NSData *data =
105 [NSJSONSerialization dataWithJSONObject:json options:0 error:&error];
106 if (!error) {
107 [_delegate sendData:data];
108 } else {
109 NSAssert(NO, @"Unable to serialize JSON object with error: %@",
110 error.localizedDescription);
111 }
112}
113
114- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000115 iceGatheringChanged:(RTCICEGatheringState)newState {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 NSLog(@"PCO onIceGatheringChange. %d", newState);
117}
118
119- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000120 iceConnectionChanged:(RTCICEConnectionState)newState {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121 NSLog(@"PCO onIceConnectionChange. %d", newState);
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000122 if (newState == RTCICEConnectionConnected)
123 [self displayLogMessage:@"ICE Connection Connected."];
124 NSAssert(newState != RTCICEConnectionFailed, @"ICE Connection failed!");
125}
126
127- (void)displayLogMessage:(NSString *)message {
128 [_delegate displayLogMessage:message];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000129}
130
131@end
132
133@interface APPRTCAppDelegate ()
134
135@property(nonatomic, strong) APPRTCAppClient *client;
136@property(nonatomic, strong) PCObserver *pcObserver;
137@property(nonatomic, strong) RTCPeerConnection *peerConnection;
138@property(nonatomic, strong) RTCPeerConnectionFactory *peerConnectionFactory;
139@property(nonatomic, strong) NSMutableArray *queuedRemoteCandidates;
140
141@end
142
143@implementation APPRTCAppDelegate
144
145#pragma mark - UIApplicationDelegate methods
146
147- (BOOL)application:(UIApplication *)application
148 didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000149 [RTCPeerConnectionFactory initializeSSL];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150 self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
151 self.viewController =
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000152 [[APPRTCViewController alloc] initWithNibName:@"APPRTCViewController"
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000153 bundle:nil];
154 self.window.rootViewController = self.viewController;
155 [self.window makeKeyAndVisible];
156 return YES;
157}
158
159- (void)applicationWillResignActive:(UIApplication *)application {
160 [self displayLogMessage:@"Application lost focus, connection broken."];
161 [self disconnect];
162 [self.viewController resetUI];
163}
164
165- (void)applicationDidEnterBackground:(UIApplication *)application {
166}
167
168- (void)applicationWillEnterForeground:(UIApplication *)application {
169}
170
171- (void)applicationDidBecomeActive:(UIApplication *)application {
172}
173
174- (void)applicationWillTerminate:(UIApplication *)application {
175}
176
177- (BOOL)application:(UIApplication *)application
178 openURL:(NSURL *)url
179 sourceApplication:(NSString *)sourceApplication
180 annotation:(id)annotation {
181 if (self.client) {
182 return NO;
183 }
184 self.client = [[APPRTCAppClient alloc] init];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000185 self.client.ICEServerDelegate = self;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186 self.client.messageHandler = self;
187 [self.client connectToRoom:url];
188 return YES;
189}
190
191- (void)displayLogMessage:(NSString *)message {
192 NSLog(@"%@", message);
193 [self.viewController displayText:message];
194}
195
196#pragma mark - RTCSendMessage method
197
198- (void)sendData:(NSData *)data {
199 [self.client sendData:data];
200}
201
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000202#pragma mark - ICEServerDelegate method
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000204- (void)onICEServers:(NSArray *)servers {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000205 self.queuedRemoteCandidates = [NSMutableArray array];
206 self.peerConnectionFactory = [[RTCPeerConnectionFactory alloc] init];
207 RTCMediaConstraints *constraints = [[RTCMediaConstraints alloc] init];
208 self.pcObserver = [[PCObserver alloc] initWithDelegate:self];
209 self.peerConnection =
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000210 [self.peerConnectionFactory peerConnectionWithICEServers:servers
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000211 constraints:constraints
212 delegate:self.pcObserver];
213 RTCMediaStream *lms =
214 [self.peerConnectionFactory mediaStreamWithLabel:@"ARDAMS"];
215 // TODO(hughv): Add video.
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000216 [lms addAudioTrack:[self.peerConnectionFactory audioTrackWithID:@"ARDAMSa0"]];
217 [self.peerConnection addStream:lms constraints:constraints];
218 [self displayLogMessage:@"onICEServers - add local stream."];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219}
220
221#pragma mark - GAEMessageHandler methods
222
223- (void)onOpen {
224 [self displayLogMessage:@"GAE onOpen - create offer."];
225 RTCPair *audio =
226 [[RTCPair alloc] initWithKey:@"OfferToReceiveAudio" value:@"true"];
227 // TODO(hughv): Add video.
228 // RTCPair *video = [[RTCPair alloc] initWithKey:@"OfferToReceiveVideo"
229 // value:@"true"];
230 NSArray *mandatory = @[ audio /*, video*/ ];
231 RTCMediaConstraints *constraints =
232 [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatory
233 optionalConstraints:nil];
234 [self.peerConnection createOfferWithDelegate:self constraints:constraints];
235 [self displayLogMessage:@"PC - createOffer."];
236}
237
238- (void)onMessage:(NSString *)data {
239 NSString *message = [self unHTMLifyString:data];
240 NSError *error;
241 NSDictionary *objects = [NSJSONSerialization
242 JSONObjectWithData:[message dataUsingEncoding:NSUTF8StringEncoding]
243 options:0
244 error:&error];
245 NSAssert(!error,
246 @"%@",
247 [NSString stringWithFormat:@"Error: %@", error.description]);
248 NSAssert([objects count] > 0, @"Invalid JSON object");
249 NSString *value = [objects objectForKey:@"type"];
250 [self displayLogMessage:
251 [NSString stringWithFormat:@"GAE onMessage type - %@", value]];
252 if ([value compare:@"candidate"] == NSOrderedSame) {
253 NSString *mid = [objects objectForKey:@"id"];
254 NSNumber *sdpLineIndex = [objects objectForKey:@"label"];
255 NSString *sdp = [objects objectForKey:@"candidate"];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000256 RTCICECandidate *candidate =
257 [[RTCICECandidate alloc] initWithMid:mid
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258 index:sdpLineIndex.intValue
259 sdp:sdp];
260 if (self.queuedRemoteCandidates) {
261 [self.queuedRemoteCandidates addObject:candidate];
262 } else {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000263 [self.peerConnection addICECandidate:candidate];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 }
265 } else if (([value compare:@"offer"] == NSOrderedSame) ||
266 ([value compare:@"answer"] == NSOrderedSame)) {
267 NSString *sdpString = [objects objectForKey:@"sdp"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000268 RTCSessionDescription *sdp = [[RTCSessionDescription alloc]
269 initWithType:value sdp:[APPRTCAppDelegate preferISAC:sdpString]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 [self.peerConnection setRemoteDescriptionWithDelegate:self
271 sessionDescription:sdp];
272 [self displayLogMessage:@"PC - setRemoteDescription."];
273 } else if ([value compare:@"bye"] == NSOrderedSame) {
274 [self disconnect];
275 } else {
276 NSAssert(NO, @"Invalid message: %@", data);
277 }
278}
279
280- (void)onClose {
281 [self displayLogMessage:@"GAE onClose."];
282 [self disconnect];
283}
284
285- (void)onError:(int)code withDescription:(NSString *)description {
286 [self displayLogMessage:
287 [NSString stringWithFormat:@"GAE onError: %@", description]];
288 [self disconnect];
289}
290
291#pragma mark - RTCSessionDescriptonDelegate methods
292
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000293// Match |pattern| to |string| and return the first group of the first
294// match, or nil if no match was found.
295+ (NSString *)firstMatch:(NSRegularExpression *)pattern
296 withString:(NSString *)string {
297 NSTextCheckingResult* result =
298 [pattern firstMatchInString:string
299 options:0
300 range:NSMakeRange(0, [string length])];
301 if (!result)
302 return nil;
303 return [string substringWithRange:[result rangeAtIndex:1]];
304}
305
306// Mangle |origSDP| to prefer the ISAC/16k audio codec.
307+ (NSString *)preferISAC:(NSString *)origSDP {
308 int mLineIndex = -1;
309 NSString* isac16kRtpMap = nil;
310 NSArray* lines = [origSDP componentsSeparatedByString:@"\n"];
311 NSRegularExpression* isac16kRegex = [NSRegularExpression
312 regularExpressionWithPattern:@"^a=rtpmap:(\\d+) ISAC/16000[\r]?$"
313 options:0
314 error:nil];
315 for (int i = 0;
316 (i < [lines count]) && (mLineIndex == -1 || isac16kRtpMap == nil);
317 ++i) {
318 NSString* line = [lines objectAtIndex:i];
319 if ([line hasPrefix:@"m=audio "]) {
320 mLineIndex = i;
321 continue;
322 }
323 isac16kRtpMap = [self firstMatch:isac16kRegex withString:line];
324 }
325 if (mLineIndex == -1) {
326 NSLog(@"No m=audio line, so can't prefer iSAC");
327 return origSDP;
328 }
329 if (isac16kRtpMap == nil) {
330 NSLog(@"No ISAC/16000 line, so can't prefer iSAC");
331 return origSDP;
332 }
333 NSArray* origMLineParts =
334 [[lines objectAtIndex:mLineIndex] componentsSeparatedByString:@" "];
335 NSMutableArray* newMLine =
336 [NSMutableArray arrayWithCapacity:[origMLineParts count]];
337 int origPartIndex = 0;
338 // Format is: m=<media> <port> <proto> <fmt> ...
339 [newMLine addObject:[origMLineParts objectAtIndex:origPartIndex++]];
340 [newMLine addObject:[origMLineParts objectAtIndex:origPartIndex++]];
341 [newMLine addObject:[origMLineParts objectAtIndex:origPartIndex++]];
342 [newMLine addObject:isac16kRtpMap];
343 for (; origPartIndex < [origMLineParts count]; ++origPartIndex) {
344 if ([isac16kRtpMap compare:[origMLineParts objectAtIndex:origPartIndex]]
345 != NSOrderedSame) {
346 [newMLine addObject:[origMLineParts objectAtIndex:origPartIndex]];
347 }
348 }
349 NSMutableArray* newLines = [NSMutableArray arrayWithCapacity:[lines count]];
350 [newLines addObjectsFromArray:lines];
351 [newLines replaceObjectAtIndex:mLineIndex
352 withObject:[newMLine componentsJoinedByString:@" "]];
353 return [newLines componentsJoinedByString:@"\n"];
354}
355
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000357 didCreateSessionDescription:(RTCSessionDescription *)origSdp
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000358 error:(NSError *)error {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000359 if (error) {
360 [self displayLogMessage:@"SDP onFailure."];
361 NSAssert(NO, error.description);
362 return;
363 }
364
365 [self displayLogMessage:@"SDP onSuccess(SDP) - set local description."];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000366 RTCSessionDescription* sdp =
367 [[RTCSessionDescription alloc]
368 initWithType:origSdp.type
369 sdp:[APPRTCAppDelegate preferISAC:origSdp.description]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 [self.peerConnection setLocalDescriptionWithDelegate:self
371 sessionDescription:sdp];
372 [self displayLogMessage:@"PC setLocalDescription."];
373 dispatch_async(dispatch_get_main_queue(), ^(void) {
374 NSDictionary *json = @{ @"type" : sdp.type, @"sdp" : sdp.description };
375 NSError *error;
376 NSData *data =
377 [NSJSONSerialization dataWithJSONObject:json options:0 error:&error];
378 NSAssert(!error,
379 @"%@",
380 [NSString stringWithFormat:@"Error: %@", error.description]);
381 [self sendData:data];
382 });
383}
384
385- (void)peerConnection:(RTCPeerConnection *)peerConnection
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000386 didSetSessionDescriptionWithError:(NSError *)error {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387 if (error) {
388 [self displayLogMessage:@"SDP onFailure."];
389 NSAssert(NO, error.description);
390 return;
391 }
392
393 [self displayLogMessage:@"SDP onSuccess() - possibly drain candidates"];
394 dispatch_async(dispatch_get_main_queue(), ^(void) {
395 // TODO(hughv): Handle non-initiator case. http://s10/46622051
396 if (self.peerConnection.remoteDescription) {
397 [self displayLogMessage:@"SDP onSuccess - drain candidates"];
398 [self drainRemoteCandidates];
399 }
400 });
401}
402
403#pragma mark - internal methods
404
405- (void)disconnect {
406 [self.client
407 sendData:[@"{\"type\": \"bye\"}" dataUsingEncoding:NSUTF8StringEncoding]];
408 self.peerConnection = nil;
409 self.peerConnectionFactory = nil;
410 self.pcObserver = nil;
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000411 self.client.ICEServerDelegate = nil;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000412 self.client.messageHandler = nil;
413 self.client = nil;
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000414 [RTCPeerConnectionFactory deinitializeSSL];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000415}
416
417- (void)drainRemoteCandidates {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000418 for (RTCICECandidate *candidate in self.queuedRemoteCandidates) {
419 [self.peerConnection addICECandidate:candidate];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000420 }
421 self.queuedRemoteCandidates = nil;
422}
423
424- (NSString *)unHTMLifyString:(NSString *)base {
425 // TODO(hughv): Investigate why percent escapes are being added. Removing
426 // them isn't necessary on Android.
427 // convert HTML escaped characters to UTF8.
428 NSString *removePercent =
429 [base stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
430 // remove leading and trailing ".
431 NSRange range;
432 range.length = [removePercent length] - 2;
433 range.location = 1;
434 NSString *removeQuotes = [removePercent substringWithRange:range];
435 // convert \" to ".
436 NSString *removeEscapedQuotes =
437 [removeQuotes stringByReplacingOccurrencesOfString:@"\\\""
438 withString:@"\""];
439 // convert \\ to \.
440 NSString *removeBackslash =
441 [removeEscapedQuotes stringByReplacingOccurrencesOfString:@"\\\\"
442 withString:@"\\"];
443 return removeBackslash;
444}
445
446@end