blob: 843ce95ff37cddf76fef29fe33e7aa6c5ffdf53b [file] [log] [blame]
Zeke Chinb3fb71c2016-02-18 15:44:07 -08001/*
2 * Copyright 2016 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
Anders Carlsson7bca8ca2018-08-30 09:30:29 +020011#import "RTCAudioSession+Private.h"
Zeke Chinb3fb71c2016-02-18 15:44:07 -080012
tkchin93dd6342016-07-27 10:17:14 -070013#import <UIKit/UIKit.h>
14
Joe Chen0b3a6e32019-12-26 23:01:42 -080015#include <vector>
16
Steve Anton10542f22019-01-11 09:11:00 -080017#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/checks.h"
Niels Möller072c0082021-02-15 16:30:44 +010019#include "rtc_base/synchronization/mutex.h"
denicija59ee91b2017-06-05 05:48:47 -070020
Anders Carlsson7bca8ca2018-08-30 09:30:29 +020021#import "RTCAudioSessionConfiguration.h"
22#import "base/RTCLogging.h"
denicija59ee91b2017-06-05 05:48:47 -070023
Mirko Bonadeia81e9c82020-05-04 16:14:32 +020024NSString *const kRTCAudioSessionErrorDomain = @"org.webrtc.RTC_OBJC_TYPE(RTCAudioSession)";
Zeke Chinb3fb71c2016-02-18 15:44:07 -080025NSInteger const kRTCAudioSessionErrorLockRequired = -1;
tkchin9f987d32016-03-12 20:06:28 -080026NSInteger const kRTCAudioSessionErrorConfiguration = -2;
jtteh13ae11a2017-05-25 17:52:20 -070027NSString * const kRTCAudioSessionOutputVolumeSelector = @"outputVolume";
Zeke Chinb3fb71c2016-02-18 15:44:07 -080028
Mirko Bonadeia81e9c82020-05-04 16:14:32 +020029@interface RTC_OBJC_TYPE (RTCAudioSession)
30() @property(nonatomic,
31 readonly) std::vector<__weak id<RTC_OBJC_TYPE(RTCAudioSessionDelegate)> > delegates;
Joe Chen0b3a6e32019-12-26 23:01:42 -080032@end
33
Zeke Chinb3fb71c2016-02-18 15:44:07 -080034// This class needs to be thread-safe because it is accessed from many threads.
35// TODO(tkchin): Consider more granular locking. We're not expecting a lot of
36// lock contention so coarse locks should be fine for now.
Mirko Bonadeia81e9c82020-05-04 16:14:32 +020037@implementation RTC_OBJC_TYPE (RTCAudioSession) {
Niels Möller072c0082021-02-15 16:30:44 +010038 webrtc::Mutex _mutex;
Zeke Chinb3fb71c2016-02-18 15:44:07 -080039 AVAudioSession *_session;
Tze Kwang Chin307a0922016-03-21 13:57:40 -070040 volatile int _activationCount;
Tze Kwang Chin307a0922016-03-21 13:57:40 -070041 volatile int _webRTCSessionCount;
Zeke Chinb3fb71c2016-02-18 15:44:07 -080042 BOOL _isActive;
tkchind2511962016-05-06 18:54:15 -070043 BOOL _useManualAudio;
44 BOOL _isAudioEnabled;
45 BOOL _canPlayOrRecord;
tkchin93dd6342016-07-27 10:17:14 -070046 BOOL _isInterrupted;
Zeke Chinb3fb71c2016-02-18 15:44:07 -080047}
48
49@synthesize session = _session;
tkchine54467f2016-03-15 16:54:03 -070050@synthesize delegates = _delegates;
Joe Chen0c05b1a2019-05-07 10:46:22 -070051@synthesize ignoresPreferredAttributeConfigurationErrors =
52 _ignoresPreferredAttributeConfigurationErrors;
Zeke Chinb3fb71c2016-02-18 15:44:07 -080053
54+ (instancetype)sharedInstance {
55 static dispatch_once_t onceToken;
Mirko Bonadeia81e9c82020-05-04 16:14:32 +020056 static RTC_OBJC_TYPE(RTCAudioSession) *sharedInstance = nil;
Zeke Chinb3fb71c2016-02-18 15:44:07 -080057 dispatch_once(&onceToken, ^{
Tze Kwang Chin307a0922016-03-21 13:57:40 -070058 sharedInstance = [[self alloc] init];
Zeke Chinb3fb71c2016-02-18 15:44:07 -080059 });
60 return sharedInstance;
61}
62
63- (instancetype)init {
Peter Hanspers47217362017-10-05 11:39:15 +020064 return [self initWithAudioSession:[AVAudioSession sharedInstance]];
65}
66
67/** This initializer provides a way for unit tests to inject a fake/mock audio session. */
68- (instancetype)initWithAudioSession:(id)audioSession {
Zeke Chinb3fb71c2016-02-18 15:44:07 -080069 if (self = [super init]) {
Peter Hanspers47217362017-10-05 11:39:15 +020070 _session = audioSession;
tkchin0ce3bf92016-03-12 16:52:04 -080071
Zeke Chinb3fb71c2016-02-18 15:44:07 -080072 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
73 [center addObserver:self
74 selector:@selector(handleInterruptionNotification:)
75 name:AVAudioSessionInterruptionNotification
76 object:nil];
77 [center addObserver:self
78 selector:@selector(handleRouteChangeNotification:)
79 name:AVAudioSessionRouteChangeNotification
80 object:nil];
Zeke Chinb3fb71c2016-02-18 15:44:07 -080081 [center addObserver:self
82 selector:@selector(handleMediaServicesWereLost:)
83 name:AVAudioSessionMediaServicesWereLostNotification
84 object:nil];
85 [center addObserver:self
86 selector:@selector(handleMediaServicesWereReset:)
87 name:AVAudioSessionMediaServicesWereResetNotification
88 object:nil];
henrikaf1363fd2016-09-27 06:06:44 -070089 // Posted on the main thread when the primary audio from other applications
90 // starts and stops. Foreground applications may use this notification as a
91 // hint to enable or disable audio that is secondary.
92 [center addObserver:self
93 selector:@selector(handleSilenceSecondaryAudioHintNotification:)
94 name:AVAudioSessionSilenceSecondaryAudioHintNotification
95 object:nil];
tkchin93dd6342016-07-27 10:17:14 -070096 // Also track foreground event in order to deal with interruption ended situation.
97 [center addObserver:self
98 selector:@selector(handleApplicationDidBecomeActive:)
99 name:UIApplicationDidBecomeActiveNotification
100 object:nil];
jtteh13ae11a2017-05-25 17:52:20 -0700101 [_session addObserver:self
102 forKeyPath:kRTCAudioSessionOutputVolumeSelector
103 options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200104 context:(__bridge void *)RTC_OBJC_TYPE(RTCAudioSession).class];
jtteh13ae11a2017-05-25 17:52:20 -0700105
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200106 RTCLog(@"RTC_OBJC_TYPE(RTCAudioSession) (%p): init.", self);
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800107 }
108 return self;
109}
110
111- (void)dealloc {
112 [[NSNotificationCenter defaultCenter] removeObserver:self];
Peter Hanspers47217362017-10-05 11:39:15 +0200113 [_session removeObserver:self
114 forKeyPath:kRTCAudioSessionOutputVolumeSelector
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200115 context:(__bridge void *)RTC_OBJC_TYPE(RTCAudioSession).class];
116 RTCLog(@"RTC_OBJC_TYPE(RTCAudioSession) (%p): dealloc.", self);
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800117}
118
Zeke Chin1300caa2016-03-18 14:39:11 -0700119- (NSString *)description {
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200120 NSString *format = @"RTC_OBJC_TYPE(RTCAudioSession): {\n"
121 " category: %@\n"
122 " categoryOptions: %ld\n"
123 " mode: %@\n"
124 " isActive: %d\n"
125 " sampleRate: %.2f\n"
126 " IOBufferDuration: %f\n"
127 " outputNumberOfChannels: %ld\n"
128 " inputNumberOfChannels: %ld\n"
129 " outputLatency: %f\n"
130 " inputLatency: %f\n"
131 " outputVolume: %f\n"
132 "}";
Zeke Chin1300caa2016-03-18 14:39:11 -0700133 NSString *description = [NSString stringWithFormat:format,
tkchind2511962016-05-06 18:54:15 -0700134 self.category, (long)self.categoryOptions, self.mode,
Zeke Chin1300caa2016-03-18 14:39:11 -0700135 self.isActive, self.sampleRate, self.IOBufferDuration,
136 self.outputNumberOfChannels, self.inputNumberOfChannels,
henrikac5aea652016-09-21 07:45:55 -0700137 self.outputLatency, self.inputLatency, self.outputVolume];
Zeke Chin1300caa2016-03-18 14:39:11 -0700138 return description;
139}
140
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800141- (void)setIsActive:(BOOL)isActive {
142 @synchronized(self) {
143 _isActive = isActive;
144 }
145}
146
147- (BOOL)isActive {
148 @synchronized(self) {
149 return _isActive;
150 }
151}
152
tkchind2511962016-05-06 18:54:15 -0700153- (void)setUseManualAudio:(BOOL)useManualAudio {
tkchin9f987d32016-03-12 20:06:28 -0800154 @synchronized(self) {
tkchind2511962016-05-06 18:54:15 -0700155 if (_useManualAudio == useManualAudio) {
tkchin9f987d32016-03-12 20:06:28 -0800156 return;
157 }
tkchind2511962016-05-06 18:54:15 -0700158 _useManualAudio = useManualAudio;
159 }
160 [self updateCanPlayOrRecord];
161}
162
163- (BOOL)useManualAudio {
164 @synchronized(self) {
165 return _useManualAudio;
tkchin9f987d32016-03-12 20:06:28 -0800166 }
167}
168
tkchind2511962016-05-06 18:54:15 -0700169- (void)setIsAudioEnabled:(BOOL)isAudioEnabled {
tkchin9f987d32016-03-12 20:06:28 -0800170 @synchronized(self) {
tkchind2511962016-05-06 18:54:15 -0700171 if (_isAudioEnabled == isAudioEnabled) {
172 return;
173 }
174 _isAudioEnabled = isAudioEnabled;
175 }
176 [self updateCanPlayOrRecord];
177}
178
179- (BOOL)isAudioEnabled {
180 @synchronized(self) {
181 return _isAudioEnabled;
tkchin9f987d32016-03-12 20:06:28 -0800182 }
183}
184
Joe Chen0c05b1a2019-05-07 10:46:22 -0700185- (void)setIgnoresPreferredAttributeConfigurationErrors:
186 (BOOL)ignoresPreferredAttributeConfigurationErrors {
187 @synchronized(self) {
188 if (_ignoresPreferredAttributeConfigurationErrors ==
189 ignoresPreferredAttributeConfigurationErrors) {
190 return;
191 }
192 _ignoresPreferredAttributeConfigurationErrors = ignoresPreferredAttributeConfigurationErrors;
193 }
194}
195
196- (BOOL)ignoresPreferredAttributeConfigurationErrors {
197 @synchronized(self) {
198 return _ignoresPreferredAttributeConfigurationErrors;
199 }
200}
201
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700202// TODO(tkchin): Check for duplicates.
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200203- (void)addDelegate:(id<RTC_OBJC_TYPE(RTCAudioSessionDelegate)>)delegate {
haysc7735b1e2017-03-29 14:53:32 -0700204 RTCLog(@"Adding delegate: (%p)", delegate);
tkchine54467f2016-03-15 16:54:03 -0700205 if (!delegate) {
206 return;
207 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800208 @synchronized(self) {
tkchine54467f2016-03-15 16:54:03 -0700209 _delegates.push_back(delegate);
210 [self removeZeroedDelegates];
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800211 }
212}
213
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200214- (void)removeDelegate:(id<RTC_OBJC_TYPE(RTCAudioSessionDelegate)>)delegate {
haysc7735b1e2017-03-29 14:53:32 -0700215 RTCLog(@"Removing delegate: (%p)", delegate);
tkchine54467f2016-03-15 16:54:03 -0700216 if (!delegate) {
217 return;
218 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800219 @synchronized(self) {
tkchine54467f2016-03-15 16:54:03 -0700220 _delegates.erase(std::remove(_delegates.begin(),
221 _delegates.end(),
tkchinefdd9302016-04-11 12:00:59 -0700222 delegate),
223 _delegates.end());
tkchine54467f2016-03-15 16:54:03 -0700224 [self removeZeroedDelegates];
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800225 }
226}
227
kthelgasonee8b8612017-03-31 04:50:27 -0700228#pragma clang diagnostic push
229#pragma clang diagnostic ignored "-Wthread-safety-analysis"
230
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800231- (void)lockForConfiguration {
Niels Möller072c0082021-02-15 16:30:44 +0100232 _mutex.Lock();
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800233}
234
235- (void)unlockForConfiguration {
Niels Möller072c0082021-02-15 16:30:44 +0100236 _mutex.Unlock();
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800237}
238
kthelgasonee8b8612017-03-31 04:50:27 -0700239#pragma clang diagnostic pop
240
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800241#pragma mark - AVAudioSession proxy methods
242
243- (NSString *)category {
244 return self.session.category;
245}
246
247- (AVAudioSessionCategoryOptions)categoryOptions {
248 return self.session.categoryOptions;
249}
250
251- (NSString *)mode {
252 return self.session.mode;
253}
254
255- (BOOL)secondaryAudioShouldBeSilencedHint {
256 return self.session.secondaryAudioShouldBeSilencedHint;
257}
258
259- (AVAudioSessionRouteDescription *)currentRoute {
260 return self.session.currentRoute;
261}
262
263- (NSInteger)maximumInputNumberOfChannels {
264 return self.session.maximumInputNumberOfChannels;
265}
266
267- (NSInteger)maximumOutputNumberOfChannels {
268 return self.session.maximumOutputNumberOfChannels;
269}
270
271- (float)inputGain {
272 return self.session.inputGain;
273}
274
275- (BOOL)inputGainSettable {
276 return self.session.inputGainSettable;
277}
278
279- (BOOL)inputAvailable {
280 return self.session.inputAvailable;
281}
282
283- (NSArray<AVAudioSessionDataSourceDescription *> *)inputDataSources {
284 return self.session.inputDataSources;
285}
286
287- (AVAudioSessionDataSourceDescription *)inputDataSource {
288 return self.session.inputDataSource;
289}
290
291- (NSArray<AVAudioSessionDataSourceDescription *> *)outputDataSources {
292 return self.session.outputDataSources;
293}
294
295- (AVAudioSessionDataSourceDescription *)outputDataSource {
296 return self.session.outputDataSource;
297}
298
299- (double)sampleRate {
300 return self.session.sampleRate;
301}
302
tkchind2511962016-05-06 18:54:15 -0700303- (double)preferredSampleRate {
304 return self.session.preferredSampleRate;
305}
306
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800307- (NSInteger)inputNumberOfChannels {
308 return self.session.inputNumberOfChannels;
309}
310
311- (NSInteger)outputNumberOfChannels {
312 return self.session.outputNumberOfChannels;
313}
314
315- (float)outputVolume {
316 return self.session.outputVolume;
317}
318
319- (NSTimeInterval)inputLatency {
320 return self.session.inputLatency;
321}
322
323- (NSTimeInterval)outputLatency {
324 return self.session.outputLatency;
325}
326
327- (NSTimeInterval)IOBufferDuration {
328 return self.session.IOBufferDuration;
329}
330
tkchind2511962016-05-06 18:54:15 -0700331- (NSTimeInterval)preferredIOBufferDuration {
332 return self.session.preferredIOBufferDuration;
333}
334
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800335- (BOOL)setActive:(BOOL)active
336 error:(NSError **)outError {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700337 int activationCount = _activationCount;
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800338 if (!active && activationCount == 0) {
339 RTCLogWarning(@"Attempting to deactivate without prior activation.");
340 }
JT Tehc1f083d2018-04-25 09:19:35 -0700341 [self notifyWillSetActive:active];
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800342 BOOL success = YES;
343 BOOL isActive = self.isActive;
344 // Keep a local error so we can log it.
345 NSError *error = nil;
346 BOOL shouldSetActive =
347 (active && !isActive) || (!active && isActive && activationCount == 1);
348 // Attempt to activate if we're not active.
349 // Attempt to deactivate if we're active and it's the last unbalanced call.
350 if (shouldSetActive) {
351 AVAudioSession *session = self.session;
352 // AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation is used to ensure
353 // that other audio sessions that were interrupted by our session can return
354 // to their active state. It is recommended for VoIP apps to use this
355 // option.
356 AVAudioSessionSetActiveOptions options =
357 active ? 0 : AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation;
358 success = [session setActive:active
359 withOptions:options
360 error:&error];
361 if (outError) {
362 *outError = error;
363 }
364 }
365 if (success) {
366 if (shouldSetActive) {
367 self.isActive = active;
Joe Chen81dcfda2019-12-23 11:18:02 -0800368 if (active && self.isInterrupted) {
369 self.isInterrupted = NO;
370 [self notifyDidEndInterruptionWithShouldResumeSession:YES];
371 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800372 }
373 if (active) {
374 [self incrementActivationCount];
375 }
JT Tehc1f083d2018-04-25 09:19:35 -0700376 [self notifyDidSetActive:active];
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800377 } else {
tkchin9f987d32016-03-12 20:06:28 -0800378 RTCLogError(@"Failed to setActive:%d. Error: %@",
379 active, error.localizedDescription);
JT Tehc1f083d2018-04-25 09:19:35 -0700380 [self notifyFailedToSetActive:active error:error];
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800381 }
382 // Decrement activation count on deactivation whether or not it succeeded.
383 if (!active) {
384 [self decrementActivationCount];
385 }
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700386 RTCLog(@"Number of current activations: %d", _activationCount);
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800387 return success;
388}
389
390- (BOOL)setCategory:(NSString *)category
391 withOptions:(AVAudioSessionCategoryOptions)options
392 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800393 return [self.session setCategory:category withOptions:options error:outError];
394}
395
396- (BOOL)setMode:(NSString *)mode error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800397 return [self.session setMode:mode error:outError];
398}
399
400- (BOOL)setInputGain:(float)gain error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800401 return [self.session setInputGain:gain error:outError];
402}
403
404- (BOOL)setPreferredSampleRate:(double)sampleRate error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800405 return [self.session setPreferredSampleRate:sampleRate error:outError];
406}
407
408- (BOOL)setPreferredIOBufferDuration:(NSTimeInterval)duration
409 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800410 return [self.session setPreferredIOBufferDuration:duration error:outError];
411}
412
413- (BOOL)setPreferredInputNumberOfChannels:(NSInteger)count
414 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800415 return [self.session setPreferredInputNumberOfChannels:count error:outError];
416}
417- (BOOL)setPreferredOutputNumberOfChannels:(NSInteger)count
418 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800419 return [self.session setPreferredOutputNumberOfChannels:count error:outError];
420}
421
422- (BOOL)overrideOutputAudioPort:(AVAudioSessionPortOverride)portOverride
423 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800424 return [self.session overrideOutputAudioPort:portOverride error:outError];
425}
426
427- (BOOL)setPreferredInput:(AVAudioSessionPortDescription *)inPort
428 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800429 return [self.session setPreferredInput:inPort error:outError];
430}
431
432- (BOOL)setInputDataSource:(AVAudioSessionDataSourceDescription *)dataSource
433 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800434 return [self.session setInputDataSource:dataSource error:outError];
435}
436
437- (BOOL)setOutputDataSource:(AVAudioSessionDataSourceDescription *)dataSource
438 error:(NSError **)outError {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800439 return [self.session setOutputDataSource:dataSource error:outError];
440}
441
442#pragma mark - Notifications
443
444- (void)handleInterruptionNotification:(NSNotification *)notification {
445 NSNumber* typeNumber =
446 notification.userInfo[AVAudioSessionInterruptionTypeKey];
447 AVAudioSessionInterruptionType type =
448 (AVAudioSessionInterruptionType)typeNumber.unsignedIntegerValue;
449 switch (type) {
450 case AVAudioSessionInterruptionTypeBegan:
451 RTCLog(@"Audio session interruption began.");
452 self.isActive = NO;
tkchin93dd6342016-07-27 10:17:14 -0700453 self.isInterrupted = YES;
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800454 [self notifyDidBeginInterruption];
455 break;
456 case AVAudioSessionInterruptionTypeEnded: {
457 RTCLog(@"Audio session interruption ended.");
tkchin93dd6342016-07-27 10:17:14 -0700458 self.isInterrupted = NO;
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800459 [self updateAudioSessionAfterEvent];
460 NSNumber *optionsNumber =
461 notification.userInfo[AVAudioSessionInterruptionOptionKey];
462 AVAudioSessionInterruptionOptions options =
463 optionsNumber.unsignedIntegerValue;
464 BOOL shouldResume =
465 options & AVAudioSessionInterruptionOptionShouldResume;
466 [self notifyDidEndInterruptionWithShouldResumeSession:shouldResume];
467 break;
468 }
469 }
470}
471
472- (void)handleRouteChangeNotification:(NSNotification *)notification {
473 // Get reason for current route change.
474 NSNumber* reasonNumber =
475 notification.userInfo[AVAudioSessionRouteChangeReasonKey];
476 AVAudioSessionRouteChangeReason reason =
477 (AVAudioSessionRouteChangeReason)reasonNumber.unsignedIntegerValue;
478 RTCLog(@"Audio route changed:");
479 switch (reason) {
480 case AVAudioSessionRouteChangeReasonUnknown:
481 RTCLog(@"Audio route changed: ReasonUnknown");
482 break;
483 case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
484 RTCLog(@"Audio route changed: NewDeviceAvailable");
485 break;
486 case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
487 RTCLog(@"Audio route changed: OldDeviceUnavailable");
488 break;
489 case AVAudioSessionRouteChangeReasonCategoryChange:
490 RTCLog(@"Audio route changed: CategoryChange to :%@",
491 self.session.category);
492 break;
493 case AVAudioSessionRouteChangeReasonOverride:
494 RTCLog(@"Audio route changed: Override");
495 break;
496 case AVAudioSessionRouteChangeReasonWakeFromSleep:
497 RTCLog(@"Audio route changed: WakeFromSleep");
498 break;
499 case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
500 RTCLog(@"Audio route changed: NoSuitableRouteForCategory");
501 break;
502 case AVAudioSessionRouteChangeReasonRouteConfigurationChange:
503 RTCLog(@"Audio route changed: RouteConfigurationChange");
504 break;
505 }
506 AVAudioSessionRouteDescription* previousRoute =
507 notification.userInfo[AVAudioSessionRouteChangePreviousRouteKey];
508 // Log previous route configuration.
509 RTCLog(@"Previous route: %@\nCurrent route:%@",
510 previousRoute, self.session.currentRoute);
511 [self notifyDidChangeRouteWithReason:reason previousRoute:previousRoute];
512}
513
514- (void)handleMediaServicesWereLost:(NSNotification *)notification {
515 RTCLog(@"Media services were lost.");
516 [self updateAudioSessionAfterEvent];
517 [self notifyMediaServicesWereLost];
518}
519
520- (void)handleMediaServicesWereReset:(NSNotification *)notification {
521 RTCLog(@"Media services were reset.");
522 [self updateAudioSessionAfterEvent];
523 [self notifyMediaServicesWereReset];
524}
525
henrikaf1363fd2016-09-27 06:06:44 -0700526- (void)handleSilenceSecondaryAudioHintNotification:(NSNotification *)notification {
527 // TODO(henrika): just adding logs here for now until we know if we are ever
528 // see this notification and might be affected by it or if further actions
529 // are required.
530 NSNumber *typeNumber =
531 notification.userInfo[AVAudioSessionSilenceSecondaryAudioHintTypeKey];
532 AVAudioSessionSilenceSecondaryAudioHintType type =
533 (AVAudioSessionSilenceSecondaryAudioHintType)typeNumber.unsignedIntegerValue;
534 switch (type) {
535 case AVAudioSessionSilenceSecondaryAudioHintTypeBegin:
536 RTCLog(@"Another application's primary audio has started.");
537 break;
538 case AVAudioSessionSilenceSecondaryAudioHintTypeEnd:
539 RTCLog(@"Another application's primary audio has stopped.");
540 break;
541 }
542}
543
tkchin93dd6342016-07-27 10:17:14 -0700544- (void)handleApplicationDidBecomeActive:(NSNotification *)notification {
Zeke Chin8280a562018-07-10 13:53:55 -0700545 BOOL isInterrupted = self.isInterrupted;
haysc7735b1e2017-03-29 14:53:32 -0700546 RTCLog(@"Application became active after an interruption. Treating as interruption "
Zeke Chin8280a562018-07-10 13:53:55 -0700547 "end. isInterrupted changed from %d to 0.",
548 isInterrupted);
549 if (isInterrupted) {
tkchin93dd6342016-07-27 10:17:14 -0700550 self.isInterrupted = NO;
551 [self updateAudioSessionAfterEvent];
tkchin93dd6342016-07-27 10:17:14 -0700552 }
haysc7735b1e2017-03-29 14:53:32 -0700553 // Always treat application becoming active as an interruption end event.
554 [self notifyDidEndInterruptionWithShouldResumeSession:YES];
tkchin93dd6342016-07-27 10:17:14 -0700555}
556
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800557#pragma mark - Private
558
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200559- (std::vector<__weak id<RTC_OBJC_TYPE(RTCAudioSessionDelegate)> >)delegates {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800560 @synchronized(self) {
tkchine54467f2016-03-15 16:54:03 -0700561 // Note: this returns a copy.
562 return _delegates;
563 }
564}
565
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700566// TODO(tkchin): check for duplicates.
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200567- (void)pushDelegate:(id<RTC_OBJC_TYPE(RTCAudioSessionDelegate)>)delegate {
tkchine54467f2016-03-15 16:54:03 -0700568 @synchronized(self) {
569 _delegates.insert(_delegates.begin(), delegate);
570 }
571}
572
573- (void)removeZeroedDelegates {
574 @synchronized(self) {
tkchinefdd9302016-04-11 12:00:59 -0700575 _delegates.erase(
576 std::remove_if(_delegates.begin(),
577 _delegates.end(),
578 [](id delegate) -> bool { return delegate == nil; }),
579 _delegates.end());
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800580 }
581}
582
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700583- (int)activationCount {
584 return _activationCount;
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800585}
586
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700587- (int)incrementActivationCount {
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800588 RTCLog(@"Incrementing activation count.");
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700589 return rtc::AtomicOps::Increment(&_activationCount);
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800590}
591
592- (NSInteger)decrementActivationCount {
593 RTCLog(@"Decrementing activation count.");
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700594 return rtc::AtomicOps::Decrement(&_activationCount);
595}
596
597- (int)webRTCSessionCount {
598 return _webRTCSessionCount;
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800599}
600
tkchind2511962016-05-06 18:54:15 -0700601- (BOOL)canPlayOrRecord {
602 return !self.useManualAudio || self.isAudioEnabled;
603}
604
tkchin93dd6342016-07-27 10:17:14 -0700605- (BOOL)isInterrupted {
606 @synchronized(self) {
607 return _isInterrupted;
608 }
609}
610
611- (void)setIsInterrupted:(BOOL)isInterrupted {
612 @synchronized(self) {
613 if (_isInterrupted == isInterrupted) {
614 return;
615 }
616 _isInterrupted = isInterrupted;
617 }
618}
619
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700620- (BOOL)beginWebRTCSession:(NSError **)outError {
621 if (outError) {
622 *outError = nil;
623 }
tkchind2511962016-05-06 18:54:15 -0700624 rtc::AtomicOps::Increment(&_webRTCSessionCount);
625 [self notifyDidStartPlayOrRecord];
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700626 return YES;
627}
628
629- (BOOL)endWebRTCSession:(NSError **)outError {
630 if (outError) {
631 *outError = nil;
632 }
tkchind2511962016-05-06 18:54:15 -0700633 rtc::AtomicOps::Decrement(&_webRTCSessionCount);
634 [self notifyDidStopPlayOrRecord];
635 return YES;
636}
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700637
tkchind2511962016-05-06 18:54:15 -0700638- (BOOL)configureWebRTCSession:(NSError **)outError {
639 if (outError) {
640 *outError = nil;
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700641 }
tkchind2511962016-05-06 18:54:15 -0700642 RTCLog(@"Configuring audio session for WebRTC.");
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700643
tkchind2511962016-05-06 18:54:15 -0700644 // Configure the AVAudioSession and activate it.
645 // Provide an error even if there isn't one so we can log it.
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700646 NSError *error = nil;
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200647 RTC_OBJC_TYPE(RTCAudioSessionConfiguration) *webRTCConfig =
648 [RTC_OBJC_TYPE(RTCAudioSessionConfiguration) webRTCConfiguration];
tkchind2511962016-05-06 18:54:15 -0700649 if (![self setConfiguration:webRTCConfig active:YES error:&error]) {
650 RTCLogError(@"Failed to set WebRTC audio configuration: %@",
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700651 error.localizedDescription);
jttehf84c1d62017-04-21 13:56:39 -0700652 // Do not call setActive:NO if setActive:YES failed.
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700653 if (outError) {
654 *outError = error;
655 }
656 return NO;
657 }
658
tkchind2511962016-05-06 18:54:15 -0700659 // Ensure that the device currently supports audio input.
660 // TODO(tkchin): Figure out if this is really necessary.
661 if (!self.inputAvailable) {
662 RTCLogError(@"No audio input path is available!");
663 [self unconfigureWebRTCSession:nil];
664 if (outError) {
665 *outError = [self configurationErrorWithDescription:@"No input path."];
666 }
667 return NO;
668 }
669
henrika2d014be2016-06-16 14:26:55 +0200670 // It can happen (e.g. in combination with BT devices) that the attempt to set
671 // the preferred sample rate for WebRTC (48kHz) fails. If so, make a new
672 // configuration attempt using the sample rate that worked using the active
673 // audio session. A typical case is that only 8 or 16kHz can be set, e.g. in
674 // combination with BT headsets. Using this "trick" seems to avoid a state
675 // where Core Audio asks for a different number of audio frames than what the
676 // session's I/O buffer duration corresponds to.
677 // TODO(henrika): this fix resolves bugs.webrtc.org/6004 but it has only been
678 // tested on a limited set of iOS devices and BT devices.
679 double sessionSampleRate = self.sampleRate;
680 double preferredSampleRate = webRTCConfig.sampleRate;
681 if (sessionSampleRate != preferredSampleRate) {
682 RTCLogWarning(
683 @"Current sample rate (%.2f) is not the preferred rate (%.2f)",
684 sessionSampleRate, preferredSampleRate);
685 if (![self setPreferredSampleRate:sessionSampleRate
686 error:&error]) {
687 RTCLogError(@"Failed to set preferred sample rate: %@",
688 error.localizedDescription);
689 if (outError) {
690 *outError = error;
691 }
692 }
693 }
694
tkchind2511962016-05-06 18:54:15 -0700695 return YES;
696}
697
698- (BOOL)unconfigureWebRTCSession:(NSError **)outError {
699 if (outError) {
700 *outError = nil;
701 }
tkchind2511962016-05-06 18:54:15 -0700702 RTCLog(@"Unconfiguring audio session for WebRTC.");
703 [self setActive:NO error:outError];
704
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700705 return YES;
706}
707
708- (NSError *)configurationErrorWithDescription:(NSString *)description {
709 NSDictionary* userInfo = @{
710 NSLocalizedDescriptionKey: description,
711 };
712 return [[NSError alloc] initWithDomain:kRTCAudioSessionErrorDomain
713 code:kRTCAudioSessionErrorConfiguration
714 userInfo:userInfo];
715}
716
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800717- (void)updateAudioSessionAfterEvent {
718 BOOL shouldActivate = self.activationCount > 0;
719 AVAudioSessionSetActiveOptions options = shouldActivate ?
720 0 : AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation;
721 NSError *error = nil;
722 if ([self.session setActive:shouldActivate
723 withOptions:options
724 error:&error]) {
725 self.isActive = shouldActivate;
726 } else {
727 RTCLogError(@"Failed to set session active to %d. Error:%@",
728 shouldActivate, error.localizedDescription);
729 }
730}
731
tkchind2511962016-05-06 18:54:15 -0700732- (void)updateCanPlayOrRecord {
733 BOOL canPlayOrRecord = NO;
734 BOOL shouldNotify = NO;
735 @synchronized(self) {
736 canPlayOrRecord = !self.useManualAudio || self.isAudioEnabled;
737 if (_canPlayOrRecord == canPlayOrRecord) {
738 return;
739 }
740 _canPlayOrRecord = canPlayOrRecord;
741 shouldNotify = YES;
742 }
743 if (shouldNotify) {
744 [self notifyDidChangeCanPlayOrRecord:canPlayOrRecord];
745 }
746}
747
jtteh3c9a6c02017-04-18 09:09:35 -0700748- (void)audioSessionDidActivate:(AVAudioSession *)session {
749 if (_session != session) {
750 RTCLogError(@"audioSessionDidActivate called on different AVAudioSession");
751 }
Zeke Chin8280a562018-07-10 13:53:55 -0700752 RTCLog(@"Audio session was externally activated.");
jtteh3c9a6c02017-04-18 09:09:35 -0700753 [self incrementActivationCount];
754 self.isActive = YES;
Zeke Chin8280a562018-07-10 13:53:55 -0700755 // When a CallKit call begins, it's possible that we receive an interruption
756 // begin without a corresponding end. Since we know that we have an activated
757 // audio session at this point, just clear any saved interruption flag since
758 // the app may never be foregrounded during the duration of the call.
759 if (self.isInterrupted) {
760 RTCLog(@"Clearing interrupted state due to external activation.");
761 self.isInterrupted = NO;
762 }
763 // Treat external audio session activation as an end interruption event.
764 [self notifyDidEndInterruptionWithShouldResumeSession:YES];
jtteh3c9a6c02017-04-18 09:09:35 -0700765}
766
767- (void)audioSessionDidDeactivate:(AVAudioSession *)session {
768 if (_session != session) {
769 RTCLogError(@"audioSessionDidDeactivate called on different AVAudioSession");
770 }
Zeke Chin8280a562018-07-10 13:53:55 -0700771 RTCLog(@"Audio session was externally deactivated.");
jtteh3c9a6c02017-04-18 09:09:35 -0700772 self.isActive = NO;
773 [self decrementActivationCount];
774}
775
jtteh13ae11a2017-05-25 17:52:20 -0700776- (void)observeValueForKeyPath:(NSString *)keyPath
777 ofObject:(id)object
778 change:(NSDictionary *)change
779 context:(void *)context {
Mirko Bonadeia81e9c82020-05-04 16:14:32 +0200780 if (context == (__bridge void *)RTC_OBJC_TYPE(RTCAudioSession).class) {
Peter Hanspers47217362017-10-05 11:39:15 +0200781 if (object == _session) {
782 NSNumber *newVolume = change[NSKeyValueChangeNewKey];
783 RTCLog(@"OutputVolumeDidChange to %f", newVolume.floatValue);
784 [self notifyDidChangeOutputVolume:newVolume.floatValue];
785 }
jtteh13ae11a2017-05-25 17:52:20 -0700786 } else {
787 [super observeValueForKeyPath:keyPath
788 ofObject:object
789 change:change
790 context:context];
791 }
792}
793
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800794- (void)notifyDidBeginInterruption {
tkchine54467f2016-03-15 16:54:03 -0700795 for (auto delegate : self.delegates) {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700796 SEL sel = @selector(audioSessionDidBeginInterruption:);
797 if ([delegate respondsToSelector:sel]) {
798 [delegate audioSessionDidBeginInterruption:self];
799 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800800 }
801}
802
803- (void)notifyDidEndInterruptionWithShouldResumeSession:
804 (BOOL)shouldResumeSession {
tkchine54467f2016-03-15 16:54:03 -0700805 for (auto delegate : self.delegates) {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700806 SEL sel = @selector(audioSessionDidEndInterruption:shouldResumeSession:);
807 if ([delegate respondsToSelector:sel]) {
808 [delegate audioSessionDidEndInterruption:self
809 shouldResumeSession:shouldResumeSession];
810 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800811 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800812}
813
814- (void)notifyDidChangeRouteWithReason:(AVAudioSessionRouteChangeReason)reason
815 previousRoute:(AVAudioSessionRouteDescription *)previousRoute {
tkchine54467f2016-03-15 16:54:03 -0700816 for (auto delegate : self.delegates) {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700817 SEL sel = @selector(audioSessionDidChangeRoute:reason:previousRoute:);
818 if ([delegate respondsToSelector:sel]) {
819 [delegate audioSessionDidChangeRoute:self
820 reason:reason
821 previousRoute:previousRoute];
822 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800823 }
824}
825
826- (void)notifyMediaServicesWereLost {
tkchine54467f2016-03-15 16:54:03 -0700827 for (auto delegate : self.delegates) {
kthelgason1634e162017-02-07 02:48:55 -0800828 SEL sel = @selector(audioSessionMediaServerTerminated:);
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700829 if ([delegate respondsToSelector:sel]) {
kthelgason1634e162017-02-07 02:48:55 -0800830 [delegate audioSessionMediaServerTerminated:self];
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700831 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800832 }
833}
834
835- (void)notifyMediaServicesWereReset {
tkchine54467f2016-03-15 16:54:03 -0700836 for (auto delegate : self.delegates) {
kthelgason1634e162017-02-07 02:48:55 -0800837 SEL sel = @selector(audioSessionMediaServerReset:);
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700838 if ([delegate respondsToSelector:sel]) {
kthelgason1634e162017-02-07 02:48:55 -0800839 [delegate audioSessionMediaServerReset:self];
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700840 }
841 }
842}
843
tkchind2511962016-05-06 18:54:15 -0700844- (void)notifyDidChangeCanPlayOrRecord:(BOOL)canPlayOrRecord {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700845 for (auto delegate : self.delegates) {
tkchind2511962016-05-06 18:54:15 -0700846 SEL sel = @selector(audioSession:didChangeCanPlayOrRecord:);
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700847 if ([delegate respondsToSelector:sel]) {
tkchind2511962016-05-06 18:54:15 -0700848 [delegate audioSession:self didChangeCanPlayOrRecord:canPlayOrRecord];
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700849 }
850 }
851}
852
tkchind2511962016-05-06 18:54:15 -0700853- (void)notifyDidStartPlayOrRecord {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700854 for (auto delegate : self.delegates) {
tkchind2511962016-05-06 18:54:15 -0700855 SEL sel = @selector(audioSessionDidStartPlayOrRecord:);
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700856 if ([delegate respondsToSelector:sel]) {
tkchind2511962016-05-06 18:54:15 -0700857 [delegate audioSessionDidStartPlayOrRecord:self];
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700858 }
859 }
860}
861
tkchind2511962016-05-06 18:54:15 -0700862- (void)notifyDidStopPlayOrRecord {
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700863 for (auto delegate : self.delegates) {
tkchind2511962016-05-06 18:54:15 -0700864 SEL sel = @selector(audioSessionDidStopPlayOrRecord:);
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700865 if ([delegate respondsToSelector:sel]) {
tkchind2511962016-05-06 18:54:15 -0700866 [delegate audioSessionDidStopPlayOrRecord:self];
Tze Kwang Chin307a0922016-03-21 13:57:40 -0700867 }
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800868 }
869}
870
jtteh13ae11a2017-05-25 17:52:20 -0700871- (void)notifyDidChangeOutputVolume:(float)volume {
872 for (auto delegate : self.delegates) {
873 SEL sel = @selector(audioSession:didChangeOutputVolume:);
874 if ([delegate respondsToSelector:sel]) {
875 [delegate audioSession:self didChangeOutputVolume:volume];
876 }
877 }
878}
879
Anders Carlsson121ea322017-06-26 15:34:47 +0200880- (void)notifyDidDetectPlayoutGlitch:(int64_t)totalNumberOfGlitches {
881 for (auto delegate : self.delegates) {
882 SEL sel = @selector(audioSession:didDetectPlayoutGlitch:);
883 if ([delegate respondsToSelector:sel]) {
884 [delegate audioSession:self didDetectPlayoutGlitch:totalNumberOfGlitches];
885 }
886 }
887}
888
JT Tehc1f083d2018-04-25 09:19:35 -0700889- (void)notifyWillSetActive:(BOOL)active {
890 for (id delegate : self.delegates) {
891 SEL sel = @selector(audioSession:willSetActive:);
892 if ([delegate respondsToSelector:sel]) {
893 [delegate audioSession:self willSetActive:active];
894 }
895 }
896}
897
898- (void)notifyDidSetActive:(BOOL)active {
899 for (id delegate : self.delegates) {
900 SEL sel = @selector(audioSession:didSetActive:);
901 if ([delegate respondsToSelector:sel]) {
902 [delegate audioSession:self didSetActive:active];
903 }
904 }
905}
906
907- (void)notifyFailedToSetActive:(BOOL)active error:(NSError *)error {
908 for (id delegate : self.delegates) {
909 SEL sel = @selector(audioSession:failedToSetActive:error:);
910 if ([delegate respondsToSelector:sel]) {
911 [delegate audioSession:self failedToSetActive:active error:error];
912 }
913 }
914}
915
Zeke Chinb3fb71c2016-02-18 15:44:07 -0800916@end