Debian Codegraph @

Xpjproject/pjsip-apps/src/pjsua/ios/ipjsua/ipjsuaAppDelegate.m

raw
1 //
2 // ipjsuaAppDelegate.m
3 // ipjsua
4 /*
5 * Copyright (C) 2013-2014 Teluu Inc. (http://www.teluu.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21 #import "ipjsuaAppDelegate.h"
22 #import <pjlib.h>
23 #import <pjsua.h>
24 #import <pj/log.h>
25 #import <AVFoundation/AVFoundation.h>
26 #import <CallKit/CallKit.h>
27
28 #include "../../pjsua_app.h"
29 #include "../../pjsua_app_config.h"
30
31 #import "ipjsuaViewController.h"
32 #import "Reachability.h"
33
34 @implementation ipjsuaAppDelegate
35
36 #define THIS_FILE "ipjsuaAppDelegate.m"
37
38 /* Specify if we use push notification.
39 * Note that you need to setup your SIP server first to support it.
40 */
41 #define USE_PUSH_NOTIFICATION 0
42
43 /* Specify if we want to use video.
44 * Note that video can only work in the foreground.
45 */
46 #define USE_VIDEO 1
47
48 /* Specify the timeout (in sec) to wait for the incoming INVITE
49 * to come after we receive push notification.
50 */
51 #define MAX_INV_TIMEOUT 10
52
53 /* Account details. */
54 #define SIP_DOMAIN "sip.pjsip.org"
55 #define SIP_USER "test"
56 #define SIP_PASSWD "test"
57
58 ipjsuaAppDelegate *app;
59 static pjsua_app_cfg_t app_cfg;
60 static bool isShuttingDown;
61 static char **restartArgv;
62 static int restartArgc;
63 Reachability *internetReach;
64
65 /* Mapping between CallKit UUID and pjsua_call_id. */
66 NSMutableDictionary<NSUUID *, NSNumber *> *call_map;
67
68 enum {
69 REREGISTER = 1,
70 ANSWER_CALL,
71 END_CALL,
72 ACTIVATE_AUDIO,
73 DEACTIVATE_AUDIO,
74 HANDLE_IP_CHANGE,
75 HANDLE_ORI_CHANGE
76 };
77
78 #define REGISTER_THREAD \
79 static pj_thread_desc a_thread_desc; \
80 static pj_thread_t *a_thread; \
81 if (!pj_thread_is_registered()) { \
82 pj_thread_register("ipjsua", a_thread_desc, &a_thread); \
83 }
84
85 #define SCHEDULE_TIMER(action) \
86 { \
87 REGISTER_THREAD \
88 pjsua_schedule_timer2(pjsip_funcs, (void *)action, 0); \
89 }
90
91 static void pjsip_funcs(void *user_data)
92 {
93 /* IMPORTANT:
94 * We need to call PJSIP API from a separate thread since
95 * PJSIP API can potentially block the main/GUI thread.
96 * And make sure we don't use Apple's Dispatch / gcd since
97 * it's incompatible with POSIX threads.
98 * In this example, we take advantage of PJSUA's timer thread
99 * to invoke PJSIP APIs. For a more complex application,
100 * it is recommended to create your own separate thread
101 * instead for this purpose.
102 */
103 long code = (long)user_data & 0xF;
104 if (code == REREGISTER) {
105 for (unsigned i = 0; i < pjsua_acc_get_count(); ++i) {
106 if (pjsua_acc_is_valid(i)) {
107 pjsua_acc_set_registration(i, PJ_TRUE);
108 }
109 }
110 } else if (code == ANSWER_CALL) {
111 pj_status_t status;
112 pjsua_call_id call_id = (pjsua_call_id)((long)user_data & 0xFF0) >> 4;
113
114 status = pjsua_call_answer(call_id, PJSIP_SC_OK, NULL, NULL);
115 if (status != PJ_SUCCESS) {
116 NSUUID *uuid =(__bridge NSUUID *)pjsua_call_get_user_data(call_id);
117 if (uuid) {
118 [app.provider reportCallWithUUID:uuid
119 endedAtDate:[NSDate date]
120 reason:CXCallEndedReasonFailed];
121 }
122 }
123 } else if (code == END_CALL) {
124 pj_status_t status;
125 pjsua_call_id call_id = (pjsua_call_id)((long)user_data & 0xFF0) >> 4;
126
127 status = pjsua_call_hangup(call_id, PJSIP_SC_OK, NULL, NULL);
128 if (status != PJ_SUCCESS) {
129 NSUUID *uuid =(__bridge NSUUID *)pjsua_call_get_user_data(call_id);
130 if (uuid) {
131 [app.provider reportCallWithUUID:uuid
132 endedAtDate:[NSDate date]
133 reason:CXCallEndedReasonFailed];
134 }
135 }
136 } else if (code == ACTIVATE_AUDIO) {
137 pjsua_call_info call_info;
138 pjsua_call_id ids[PJSUA_MAX_CALLS];
139 unsigned count = PJSUA_MAX_CALLS;
140
141 /* If we use CallKit, sound device may not work until audio session
142 * becomes active, so we need to force reopen sound device here.
143 */
144 pjsua_set_no_snd_dev();
145 pjsua_set_snd_dev(PJSUA_SND_DEFAULT_CAPTURE_DEV,
146 PJSUA_SND_DEFAULT_PLAYBACK_DEV);
147
148 pjsua_enum_calls(ids, &count);
149 for (unsigned i = 0; i < count; i++) {
150 pjsua_call_get_info(i, &call_info);
151
152 for (unsigned mi = 0; mi < call_info.media_cnt; ++mi) {
153 if (call_info.media[mi].type == PJMEDIA_TYPE_AUDIO &&
154 (call_info.media[mi].status == PJSUA_CALL_MEDIA_ACTIVE ||
155 call_info.media[mi].status == PJSUA_CALL_MEDIA_REMOTE_HOLD))
156 {
157 pjsua_conf_port_id call_conf_slot;
158 call_conf_slot = call_info.media[mi].stream.aud.conf_slot;
159 pjsua_conf_connect(0, call_conf_slot);
160 pjsua_conf_connect(call_conf_slot, 0);
161 }
162 }
163 }
164 } else if (code == DEACTIVATE_AUDIO) {
165 NSLog(@"Deactivating audio session, is sound active: %d",
166 pjsua_snd_is_active());
167 if (!pjsua_snd_is_active()) {
168 [[AVAudioSession sharedInstance] setActive:NO
169 withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation
170 error:nil];
171 }
172 } else if (code == HANDLE_IP_CHANGE) {
173 pjsua_ip_change_param param;
174 pjsua_ip_change_param_default(&param);
175 pjsua_handle_ip_change(&param);
176 } else if (code == HANDLE_ORI_CHANGE) {
177 #if PJSUA_HAS_VIDEO
178 const pjmedia_orient pj_ori[4] =
179 {
180 PJMEDIA_ORIENT_ROTATE_90DEG, /* UIDeviceOrientationPortrait */
181 PJMEDIA_ORIENT_ROTATE_270DEG, /* UIDeviceOrientationPortraitUpsideDown */
182 PJMEDIA_ORIENT_ROTATE_180DEG, /* UIDeviceOrientationLandscapeLeft,
183 home button on the right side */
184 PJMEDIA_ORIENT_NATURAL /* UIDeviceOrientationLandscapeRight,
185 home button on the left side */
186 };
187 static UIDeviceOrientation prev_ori = 0;
188 UIDeviceOrientation dev_ori = [[UIDevice currentDevice] orientation];
189 int i;
190
191 if (dev_ori == prev_ori) return;
192
193 NSLog(@"Device orientation changed: %d", (int)(prev_ori = dev_ori));
194
195 if (dev_ori >= UIDeviceOrientationPortrait &&
196 dev_ori <= UIDeviceOrientationLandscapeRight)
197 {
198 /* Here we set the orientation for all video devices.
199 * This may return failure for renderer devices or for
200 * capture devices which do not support orientation setting,
201 * we can simply ignore them.
202 */
203 for (i = pjsua_vid_dev_count()-1; i >= 0; i--) {
204 pjsua_vid_dev_set_setting(i, PJMEDIA_VID_DEV_CAP_ORIENTATION,
205 &pj_ori[dev_ori-1], PJ_TRUE);
206 }
207 }
208 #endif
209 }
210 }
211
212 - (void) updateWithReachability: (Reachability *)curReach
213 {
214 NetworkStatus netStatus = [curReach currentReachabilityStatus];
215 BOOL connectionRequired = [curReach connectionRequired];
216 switch (netStatus) {
217 case NotReachable:
218 NSLog(@"Access Not Available..");
219 connectionRequired= NO;
220 break;
221 case ReachableViaWiFi:
222 NSLog(@"Reachable WiFi..");
223 break;
224 case ReachableViaWWAN:
225 NSLog(@"Reachable WWAN..");
226 break;
227 }
228 if (connectionRequired) {
229 NSLog(@"Connection Required");
230 }
231 }
232
233 /* Called by Reachability whenever status changes. */
234 - (void)reachabilityChanged: (NSNotification *)note
235 {
236 Reachability* curReach = [note object];
237 NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
238 NSLog(@"reachability changed..");
239 [self updateWithReachability: curReach];
240
241 if ([curReach currentReachabilityStatus] != NotReachable &&
242 ![curReach connectionRequired])
243 {
244 SCHEDULE_TIMER(HANDLE_IP_CHANGE);
245 }
246 }
247
248 - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type
249 {
250 if ([credentials.token length] == 0) {
251 NSLog(@"voip token NULL");
252 return;
253 }
254
255 /* Get device token */
256 const char *data = [credentials.token bytes];
257 self.token = [NSMutableString string];
258 for (NSUInteger i = 0; i < [credentials.token length]; i++) {
259 [self.token appendFormat:@"%02.2hhx", data[i]];
260 }
261 NSLog(@"VOIP Push Notification Token: %@", self.token);
262
263 /* Now start pjsua */
264 [NSThread detachNewThreadSelector:@selector(pjsuaStart) toTarget:self withObject:nil];
265 }
266
267 void displayLog(const char *msg, int len)
268 {
269 NSLog(@"%.*s", len, msg);
270 }
271
272 static void displayMsg(const char *msg)
273 {
274 NSString *str = [NSString stringWithFormat:@"%s", msg];
275 dispatch_async(dispatch_get_main_queue(),
276 ^{app.viewController.textLabel.text = str;});
277 }
278
279 static void pjsuaOnStartedCb(pj_status_t status, const char* msg)
280 {
281 char errmsg[PJ_ERR_MSG_SIZE];
282
283 if (status != PJ_SUCCESS && (!msg || !*msg)) {
284 pj_strerror(status, errmsg, sizeof(errmsg));
285 PJ_LOG(3,(THIS_FILE, "Error: %s", errmsg));
286 msg = errmsg;
287 } else {
288 PJ_LOG(3,(THIS_FILE, "Started: %s", msg));
289 }
290
291 displayMsg(msg);
292 }
293
294 static void pjsuaOnStoppedCb(pj_bool_t restart,
295 int argc, char** argv)
296 {
297 PJ_LOG(3,("ipjsua", "CLI %s request", (restart? "restart" : "shutdown")));
298 if (restart) {
299 displayMsg("Restarting..");
300 pj_thread_sleep(100);
301 app_cfg.argc = argc;
302 app_cfg.argv = argv;
303 } else {
304 displayMsg("Shutting down..");
305 pj_thread_sleep(100);
306 isShuttingDown = true;
307 }
308 }
309
310 static void pjsuaOnAppConfigCb(pjsua_app_config *cfg)
311 {
312 PJ_UNUSED_ARG(cfg);
313 }
314
315 - (void)pjsuaStart
316 {
317 // TODO: read from config?
318 const char **argv = pjsua_app_def_argv;
319 int argc = PJ_ARRAY_SIZE(pjsua_app_def_argv) -1;
320 pj_status_t status;
321
322 REGISTER_THREAD;
323
324 isShuttingDown = false;
325 displayMsg("Starting..");
326
327 pj_bzero(&app_cfg, sizeof(app_cfg));
328 if (restartArgc) {
329 app_cfg.argc = restartArgc;
330 app_cfg.argv = restartArgv;
331 } else {
332 app_cfg.argc = argc;
333 app_cfg.argv = (char**)argv;
334 }
335 app_cfg.on_started = &pjsuaOnStartedCb;
336 app_cfg.on_stopped = &pjsuaOnStoppedCb;
337 app_cfg.on_config_init = &pjsuaOnAppConfigCb;
338
339 while (!isShuttingDown) {
340 status = pjsua_app_init(&app_cfg);
341 if (status != PJ_SUCCESS) {
342 char errmsg[PJ_ERR_MSG_SIZE];
343 pj_strerror(status, errmsg, sizeof(errmsg));
344 displayMsg(errmsg);
345 pjsua_app_destroy();
346 return;
347 }
348
349 /* Setup device orientation change notification */
350 dispatch_async(dispatch_get_main_queue(),
351 ^{
352 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
353 [[NSNotificationCenter defaultCenter] addObserver:app
354 selector:@selector(orientationChanged:)
355 name:UIDeviceOrientationDidChangeNotification
356 object:[UIDevice currentDevice]];
357 });
358
359 static char contact_uri_buf[1024];
360 pjsua_acc_config cfg;
361
362 pjsua_acc_config_default(&cfg);
363 cfg.id = pj_str("sip:" SIP_USER "@" SIP_DOMAIN);
364 cfg.reg_uri = pj_str("sip:" SIP_DOMAIN ";transport=tcp");
365 cfg.cred_count = 1;
366 cfg.cred_info[0].realm = pj_str(SIP_DOMAIN);
367 cfg.cred_info[0].scheme = pj_str("digest");
368 cfg.cred_info[0].username = pj_str(SIP_USER);
369 cfg.cred_info[0].data = pj_str(SIP_PASSWD);
370
371 #if USE_VIDEO
372 app_config_init_video(&cfg);
373 #endif
374
375 /* If we have Push Notification token, put it in the registration
376 * Contact URI params.
377 */
378 if ([self.token length]) {
379 /* According to RFC 8599:
380 * - pn-provider is the Push Notification Service provider. Here
381 * we use APNS (Apple Push Notification Service).
382 * - pn-param is composed of Team ID and Topic separated by
383 * a period (.).
384 * The Topic consists of the Bundle ID, the app's unique ID,
385 * and the app's service value ("voip" for VoIP apps), separated
386 * by a period (.).
387 * - pn-prid is the PN token.
388 */
389 NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
390 NSString *bundleID = infoDictionary[@"CFBundleIdentifier"];
391 NSString *teamID = infoDictionary[@"AppIdentifierPrefix"];
392 NSLog(@"Team ID from settings: %@", teamID);
393
394 pj_ansi_snprintf(contact_uri_buf, sizeof(contact_uri_buf),
395 ";pn-provider=apns"
396 ";pn-param=%s%s.voip"
397 ";pn-prid=%s",
398 (teamID? [teamID UTF8String]: "93NHJQ455P."),
399 [bundleID UTF8String],
400 [self.token UTF8String]);
401 cfg.reg_contact_uri_params = pj_str(contact_uri_buf);
402 }
403 status = pjsua_acc_add(&cfg, PJ_TRUE, NULL);
404 if (status != PJ_SUCCESS) {
405 char errmsg[PJ_ERR_MSG_SIZE];
406 pj_strerror(status, errmsg, sizeof(errmsg));
407 displayMsg(errmsg);
408 }
409
410 status = pjsua_app_run(PJ_TRUE);
411 if (status != PJ_SUCCESS) {
412 char errmsg[PJ_ERR_MSG_SIZE];
413 pj_strerror(status, errmsg, sizeof(errmsg));
414 displayMsg(errmsg);
415 }
416
417 [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
418
419 pjsua_app_destroy();
420 }
421
422 restartArgv = NULL;
423 restartArgc = 0;
424 }
425
426 - (void) provider:(CXProvider *) provider
427 didActivateAudioSession:(AVAudioSession *) audioSession
428 {
429 NSLog(@"Did activate Audio Session");
430
431 pjsua_schedule_timer2(pjsip_funcs, (void *)ACTIVATE_AUDIO, 0);
432 }
433
434 - (void) provider:(CXProvider *) provider
435 didDectivateAudioSession:(AVAudioSession *) audioSession
436 {
437 NSLog(@"Did deactivate Audio Session");
438 }
439
440 - (void)provider:(CXProvider *)provider
441 performAnswerCallAction:(CXAnswerCallAction *)action
442 {
443 NSLog(@"Perform answer call %@", action.callUUID.UUIDString);
444
445 /* User has answered the call, but we may need to wait for
446 * the incoming INVITE to come.
447 */
448 for (int i = MAX_INV_TIMEOUT * 1000 / 100; i >= 0; i--) {
449 if (call_map[action.callUUID].intValue != PJSUA_INVALID_ID) break;
450 [NSThread sleepForTimeInterval:0.1];
451 }
452
453 [action fulfill];
454
455 pjsua_call_id call_id = call_map[action.callUUID].intValue;
456 if (call_id == PJSUA_INVALID_ID) {
457 [app.provider reportCallWithUUID:action.callUUID
458 endedAtDate:[NSDate date]
459 reason:CXCallEndedReasonFailed];
460 return;
461 }
462
463 long code = (long)ANSWER_CALL | (call_id << 4);
464 pjsua_schedule_timer2(pjsip_funcs, (void *)code, 0);
465 }
466
467 - (void)provider:(CXProvider *)provider
468 performEndCallAction:(CXEndCallAction *)action
469 {
470 NSLog(@"Perform end call %@", action.callUUID.UUIDString);
471
472 /* User has answered the call, but we may need to wait for
473 * the incoming INVITE to come.
474 */
475 for (int i = MAX_INV_TIMEOUT * 1000 / 100; i >= 0; i--) {
476 if (call_map[action.callUUID].intValue != PJSUA_INVALID_ID) break;
477 [NSThread sleepForTimeInterval:0.1];
478 }
479
480 [action fulfill];
481
482 pjsua_call_id call_id = call_map[action.callUUID].intValue;
483 if (call_id == PJSUA_INVALID_ID) {
484 [app.provider reportCallWithUUID:action.callUUID
485 endedAtDate:[NSDate date]
486 reason:CXCallEndedReasonFailed];
487 return;
488 }
489
490 long code = (long)END_CALL | (call_id << 4);
491 pjsua_schedule_timer2(pjsip_funcs, (void *)code, 0);
492 }
493
494 - (void)providerDidReset:(nonnull CXProvider *)provider {
495 }
496
497 - (void)pushRegistry:(PKPushRegistry *)registry
498 didReceiveIncomingPushWithPayload:(PKPushPayload *)payload
499 forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion
500 {
501 /* Handle incoming VoIP push notification. */
502 NSUUID *uuid = [NSUUID UUID];
503 call_map[uuid] = @(PJSUA_INVALID_ID);
504 NSLog(@"Receiving push notification %@", uuid.UUIDString);
505
506 /* Re-register, so the server will send us the suspended INVITE. */
507 SCHEDULE_TIMER(REREGISTER);
508
509 /* Activate audio session. */
510 AVAudioSession *audioSession = [AVAudioSession sharedInstance];
511 NSError *error = nil;
512 if (![audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
513 mode:AVAudioSessionModeVoiceChat
514 options:0 error:&error])
515 {
516 NSLog(@"Error setting up audio session: %@", error.localizedDescription);
517 }
518 if (![audioSession setActive:YES error:&error]) {
519 NSLog(@"Error activating audio session: %@", error.localizedDescription);
520 }
521
522 /* Report the incoming call to the system using CallKit. */
523 CXCallUpdate *callUpdate = [[CXCallUpdate alloc] init];
524 [self.provider reportNewIncomingCallWithUUID:uuid
525 update:callUpdate
526 completion:^(NSError * _Nullable error)
527 {
528 if (error) {
529 NSLog(@"Error reporting incoming call: %@",
530 error.localizedDescription);
531 [call_map removeObjectForKey:uuid];
532 }
533 }];
534
535 /* Call the completion handler when you have finished processing the incoming call. */
536 completion();
537 }
538
539 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
540 {
541 self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
542 // Override point for customization after application launch.
543 if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
544 self.viewController = [[ipjsuaViewController alloc] initWithNibName:@"ipjsuaViewController_iPhone" bundle:nil];
545 } else {
546 self.viewController = [[ipjsuaViewController alloc] initWithNibName:@"ipjsuaViewController_iPad" bundle:nil];
547 }
548 self.window.rootViewController = self.viewController;
549 [self.window makeKeyAndVisible];
550
551 #if USE_PUSH_NOTIFICATION
552 call_map = [NSMutableDictionary dictionary];
553
554 /* Set up a push notification registry for Voice over IP (VoIP). */
555 self.voipRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
556 self.voipRegistry.delegate = self;
557 self.voipRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
558
559 /* Request permission for push notifications. */
560 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
561 center.delegate = self;
562 [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert |
563 UNAuthorizationOptionBadge |
564 UNAuthorizationOptionSound)
565 completionHandler:^(BOOL granted, NSError * _Nullable error)
566 {
567 NSLog(@"Notification request %sgranted", (granted ? "" : "not"));
568
569 if (granted) {
570 dispatch_async(dispatch_get_main_queue(), ^{
571 [application registerForRemoteNotifications];
572 });
573 }
574 }];
575
576 /* Note that opening audio device when in the background will not trigger
577 * permission request, so we won't be able to use audio device.
578 * Thus, we need to request permission now.
579 */
580 [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted)
581 {
582 NSLog(@"Microphone access %sgranted", (granted ? "" : "not"));
583 }];
584
585 /* We need to request local network access permission as well to
586 * immediately send media traffic when in the background.
587 * Due to its complexity, the code is not included here in the sample app.
588 * Please refer to the Apple "Local Network Privacy" FAQ for more details.
589 */
590
591 /* Create CallKit provider. */
592 CXProviderConfiguration *configuration = [[CXProviderConfiguration alloc]
593 initWithLocalizedName:@"ipjsua"];
594 configuration.maximumCallGroups = 1;
595 configuration.maximumCallsPerCallGroup = 1;
596 self.provider = [[CXProvider alloc] initWithConfiguration:configuration];
597 [self.provider setDelegate:self queue:nil];
598 #else
599 /* Start pjsua app thread immediately, otherwise we do it after push
600 * notification setup completes.
601 */
602 [NSThread detachNewThreadSelector:@selector(pjsuaStart) toTarget:self
603 withObject:nil];
604 #endif
605
606 /* Observe the kNetworkReachabilityChangedNotification. When that
607 * notification is posted, the method "reachabilityChanged" will be called.
608 */
609 [[NSNotificationCenter defaultCenter] addObserver: self
610 selector: @selector(reachabilityChanged:)
611 name: kReachabilityChangedNotification object: nil];
612
613 internetReach = [Reachability reachabilityForInternetConnection];
614 [internetReach startNotifier];
615 [self updateWithReachability: internetReach];
616
617 app = self;
618
619 return YES;
620 }
621
622 - (void)applicationWillResignActive:(UIApplication *)application
623 {
624 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
625 // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
626 }
627
628 - (void)orientationChanged:(NSNotification *)note
629 {
630 SCHEDULE_TIMER(HANDLE_ORI_CHANGE);
631 }
632
633 - (void)applicationDidEnterBackground:(UIApplication *)application
634 {
635 SCHEDULE_TIMER(REREGISTER);
636 /* Allow the re-registration to complete. */
637 [NSThread sleepForTimeInterval:0.3];
638 }
639
640 - (void)applicationWillEnterForeground:(UIApplication *)application
641 {
642 // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
643 }
644
645 - (void)applicationDidBecomeActive:(UIApplication *)application
646 {
647 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
648 }
649
650 - (void)applicationWillTerminate:(UIApplication *)application
651 {
652 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
653 }
654
655
656 pj_bool_t reportCallState(pjsua_call_id call_id)
657 {
658 pjsua_call_info info;
659
660 pjsua_call_get_info(call_id, &info);
661
662 if (info.state == PJSIP_INV_STATE_DISCONNECTED) {
663 NSUUID *uuid = (__bridge NSUUID *)pjsua_call_get_user_data(call_id);
664 if (uuid && call_map[uuid].intValue == call_id) {
665 [app.provider reportCallWithUUID:uuid
666 endedAtDate:[NSDate date]
667 reason:CXCallEndedReasonRemoteEnded];
668 [call_map removeObjectForKey:uuid];
669 }
670
671 /* Check if we need to deactivate audio session. Note that sound device
672 * will only be closed after pjsua_media_config.snd_auto_close_time.
673 */
674 pjsua_schedule_timer2(pjsip_funcs, (void *)DEACTIVATE_AUDIO, 1500);
675 }
676
677 return PJ_FALSE;
678 }
679
680 pj_bool_t showNotification(pjsua_call_id call_id)
681 {
682 #if USE_PUSH_NOTIFICATION
683 NSLog(@"Receiving incoming call %d", call_id);
684
685 for (NSUUID *uuid in call_map) {
686 if (call_map[uuid].intValue == PJSUA_INVALID_ID) {
687 NSLog(@"Associating incoming call %d with UUID %@",
688 call_id, uuid.UUIDString);
689 call_map[uuid] = @(call_id);
690 pjsua_call_set_user_data(call_id, (__bridge void *)uuid);
691
692 break;
693 }
694 }
695 #endif
696
697 return PJ_FALSE;
698 }
699
700 void displayWindow(pjsua_vid_win_id wid)
701 {
702 #if PJSUA_HAS_VIDEO
703 int i, last;
704
705 i = (wid == PJSUA_INVALID_ID) ? 0 : wid;
706 last = (wid == PJSUA_INVALID_ID) ? PJSUA_MAX_VID_WINS : wid+1;
707
708 for (;i < last; ++i) {
709 pjsua_vid_win_info wi;
710
711 if (pjsua_vid_win_get_info(i, &wi) == PJ_SUCCESS &&
712 wi.hwnd.info.ios.window)
713 {
714 dispatch_async(dispatch_get_main_queue(), ^{
715 UIView *parent = app.viewController.view;
716 UIView *view = (__bridge UIView *)wi.hwnd.info.ios.window;
717
718 if (![view isDescendantOfView:parent])
719 [parent addSubview:view];
720
721 if (!wi.is_native) {
722 /* Video window */
723 view.contentMode = UIViewContentModeScaleAspectFit;
724 view.center = parent.center;
725 view.frame = parent.bounds;
726 } else {
727 /* Preview window */
728 view.contentMode = UIViewContentModeBottomLeft;
729 view.frame = CGRectMake(0, parent.frame.size.height - view.frame.size.height,
730 view.frame.size.width, view.frame.size.height);
731 }
732 });
733 }
734 }
735 #endif
736 }
737
738 @end