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.

995 lines
30 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #import "RTCAudioSession+Private.h"
  11. #import <UIKit/UIKit.h>
  12. #include "rtc_base/atomic_ops.h"
  13. #include "rtc_base/checks.h"
  14. #include "rtc_base/critical_section.h"
  15. #import "RTCAudioSessionConfiguration.h"
  16. #import "base/RTCLogging.h"
  17. NSString * const kRTCAudioSessionErrorDomain = @"org.webrtc.RTCAudioSession";
  18. NSInteger const kRTCAudioSessionErrorLockRequired = -1;
  19. NSInteger const kRTCAudioSessionErrorConfiguration = -2;
  20. NSString * const kRTCAudioSessionOutputVolumeSelector = @"outputVolume";
  21. // This class needs to be thread-safe because it is accessed from many threads.
  22. // TODO(tkchin): Consider more granular locking. We're not expecting a lot of
  23. // lock contention so coarse locks should be fine for now.
  24. @implementation RTCAudioSession {
  25. rtc::CriticalSection _crit;
  26. AVAudioSession *_session;
  27. volatile int _activationCount;
  28. volatile int _lockRecursionCount;
  29. volatile int _webRTCSessionCount;
  30. BOOL _isActive;
  31. BOOL _useManualAudio;
  32. BOOL _isAudioEnabled;
  33. BOOL _canPlayOrRecord;
  34. BOOL _isInterrupted;
  35. }
  36. @synthesize session = _session;
  37. @synthesize delegates = _delegates;
  38. @synthesize ignoresPreferredAttributeConfigurationErrors =
  39. _ignoresPreferredAttributeConfigurationErrors;
  40. + (instancetype)sharedInstance {
  41. static dispatch_once_t onceToken;
  42. static RTCAudioSession *sharedInstance = nil;
  43. dispatch_once(&onceToken, ^{
  44. sharedInstance = [[self alloc] init];
  45. });
  46. return sharedInstance;
  47. }
  48. - (instancetype)init {
  49. return [self initWithAudioSession:[AVAudioSession sharedInstance]];
  50. }
  51. /** This initializer provides a way for unit tests to inject a fake/mock audio session. */
  52. - (instancetype)initWithAudioSession:(id)audioSession {
  53. if (self = [super init]) {
  54. _session = audioSession;
  55. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  56. [center addObserver:self
  57. selector:@selector(handleInterruptionNotification:)
  58. name:AVAudioSessionInterruptionNotification
  59. object:nil];
  60. [center addObserver:self
  61. selector:@selector(handleRouteChangeNotification:)
  62. name:AVAudioSessionRouteChangeNotification
  63. object:nil];
  64. [center addObserver:self
  65. selector:@selector(handleMediaServicesWereLost:)
  66. name:AVAudioSessionMediaServicesWereLostNotification
  67. object:nil];
  68. [center addObserver:self
  69. selector:@selector(handleMediaServicesWereReset:)
  70. name:AVAudioSessionMediaServicesWereResetNotification
  71. object:nil];
  72. // Posted on the main thread when the primary audio from other applications
  73. // starts and stops. Foreground applications may use this notification as a
  74. // hint to enable or disable audio that is secondary.
  75. [center addObserver:self
  76. selector:@selector(handleSilenceSecondaryAudioHintNotification:)
  77. name:AVAudioSessionSilenceSecondaryAudioHintNotification
  78. object:nil];
  79. // Also track foreground event in order to deal with interruption ended situation.
  80. [center addObserver:self
  81. selector:@selector(handleApplicationDidBecomeActive:)
  82. name:UIApplicationDidBecomeActiveNotification
  83. object:nil];
  84. [_session addObserver:self
  85. forKeyPath:kRTCAudioSessionOutputVolumeSelector
  86. options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
  87. context:(__bridge void*)RTCAudioSession.class];
  88. RTCLog(@"RTCAudioSession (%p): init.", self);
  89. }
  90. return self;
  91. }
  92. - (void)dealloc {
  93. [[NSNotificationCenter defaultCenter] removeObserver:self];
  94. [_session removeObserver:self
  95. forKeyPath:kRTCAudioSessionOutputVolumeSelector
  96. context:(__bridge void*)RTCAudioSession.class];
  97. RTCLog(@"RTCAudioSession (%p): dealloc.", self);
  98. }
  99. - (NSString *)description {
  100. NSString *format =
  101. @"RTCAudioSession: {\n"
  102. " category: %@\n"
  103. " categoryOptions: %ld\n"
  104. " mode: %@\n"
  105. " isActive: %d\n"
  106. " sampleRate: %.2f\n"
  107. " IOBufferDuration: %f\n"
  108. " outputNumberOfChannels: %ld\n"
  109. " inputNumberOfChannels: %ld\n"
  110. " outputLatency: %f\n"
  111. " inputLatency: %f\n"
  112. " outputVolume: %f\n"
  113. "}";
  114. NSString *description = [NSString stringWithFormat:format,
  115. self.category, (long)self.categoryOptions, self.mode,
  116. self.isActive, self.sampleRate, self.IOBufferDuration,
  117. self.outputNumberOfChannels, self.inputNumberOfChannels,
  118. self.outputLatency, self.inputLatency, self.outputVolume];
  119. return description;
  120. }
  121. - (void)setIsActive:(BOOL)isActive {
  122. @synchronized(self) {
  123. _isActive = isActive;
  124. }
  125. }
  126. - (BOOL)isActive {
  127. @synchronized(self) {
  128. return _isActive;
  129. }
  130. }
  131. - (BOOL)isLocked {
  132. return _lockRecursionCount > 0;
  133. }
  134. - (void)setUseManualAudio:(BOOL)useManualAudio {
  135. @synchronized(self) {
  136. if (_useManualAudio == useManualAudio) {
  137. return;
  138. }
  139. _useManualAudio = useManualAudio;
  140. }
  141. [self updateCanPlayOrRecord];
  142. }
  143. - (BOOL)useManualAudio {
  144. @synchronized(self) {
  145. return _useManualAudio;
  146. }
  147. }
  148. - (void)setIsAudioEnabled:(BOOL)isAudioEnabled {
  149. @synchronized(self) {
  150. if (_isAudioEnabled == isAudioEnabled) {
  151. return;
  152. }
  153. _isAudioEnabled = isAudioEnabled;
  154. }
  155. [self updateCanPlayOrRecord];
  156. }
  157. - (BOOL)isAudioEnabled {
  158. @synchronized(self) {
  159. return _isAudioEnabled;
  160. }
  161. }
  162. - (void)setIgnoresPreferredAttributeConfigurationErrors:
  163. (BOOL)ignoresPreferredAttributeConfigurationErrors {
  164. @synchronized(self) {
  165. if (_ignoresPreferredAttributeConfigurationErrors ==
  166. ignoresPreferredAttributeConfigurationErrors) {
  167. return;
  168. }
  169. _ignoresPreferredAttributeConfigurationErrors = ignoresPreferredAttributeConfigurationErrors;
  170. }
  171. }
  172. - (BOOL)ignoresPreferredAttributeConfigurationErrors {
  173. @synchronized(self) {
  174. return _ignoresPreferredAttributeConfigurationErrors;
  175. }
  176. }
  177. // TODO(tkchin): Check for duplicates.
  178. - (void)addDelegate:(id<RTCAudioSessionDelegate>)delegate {
  179. RTCLog(@"Adding delegate: (%p)", delegate);
  180. if (!delegate) {
  181. return;
  182. }
  183. @synchronized(self) {
  184. _delegates.push_back(delegate);
  185. [self removeZeroedDelegates];
  186. }
  187. }
  188. - (void)removeDelegate:(id<RTCAudioSessionDelegate>)delegate {
  189. RTCLog(@"Removing delegate: (%p)", delegate);
  190. if (!delegate) {
  191. return;
  192. }
  193. @synchronized(self) {
  194. _delegates.erase(std::remove(_delegates.begin(),
  195. _delegates.end(),
  196. delegate),
  197. _delegates.end());
  198. [self removeZeroedDelegates];
  199. }
  200. }
  201. #pragma clang diagnostic push
  202. #pragma clang diagnostic ignored "-Wthread-safety-analysis"
  203. - (void)lockForConfiguration {
  204. _crit.Enter();
  205. rtc::AtomicOps::Increment(&_lockRecursionCount);
  206. }
  207. - (void)unlockForConfiguration {
  208. // Don't let threads other than the one that called lockForConfiguration
  209. // unlock.
  210. if (_crit.TryEnter()) {
  211. rtc::AtomicOps::Decrement(&_lockRecursionCount);
  212. // One unlock for the tryLock, and another one to actually unlock. If this
  213. // was called without anyone calling lock, we will hit an assertion.
  214. _crit.Leave();
  215. _crit.Leave();
  216. }
  217. }
  218. #pragma clang diagnostic pop
  219. #pragma mark - AVAudioSession proxy methods
  220. - (NSString *)category {
  221. return self.session.category;
  222. }
  223. - (AVAudioSessionCategoryOptions)categoryOptions {
  224. return self.session.categoryOptions;
  225. }
  226. - (NSString *)mode {
  227. return self.session.mode;
  228. }
  229. - (BOOL)secondaryAudioShouldBeSilencedHint {
  230. return self.session.secondaryAudioShouldBeSilencedHint;
  231. }
  232. - (AVAudioSessionRouteDescription *)currentRoute {
  233. return self.session.currentRoute;
  234. }
  235. - (NSInteger)maximumInputNumberOfChannels {
  236. return self.session.maximumInputNumberOfChannels;
  237. }
  238. - (NSInteger)maximumOutputNumberOfChannels {
  239. return self.session.maximumOutputNumberOfChannels;
  240. }
  241. - (float)inputGain {
  242. return self.session.inputGain;
  243. }
  244. - (BOOL)inputGainSettable {
  245. return self.session.inputGainSettable;
  246. }
  247. - (BOOL)inputAvailable {
  248. return self.session.inputAvailable;
  249. }
  250. - (NSArray<AVAudioSessionDataSourceDescription *> *)inputDataSources {
  251. return self.session.inputDataSources;
  252. }
  253. - (AVAudioSessionDataSourceDescription *)inputDataSource {
  254. return self.session.inputDataSource;
  255. }
  256. - (NSArray<AVAudioSessionDataSourceDescription *> *)outputDataSources {
  257. return self.session.outputDataSources;
  258. }
  259. - (AVAudioSessionDataSourceDescription *)outputDataSource {
  260. return self.session.outputDataSource;
  261. }
  262. - (double)sampleRate {
  263. return self.session.sampleRate;
  264. }
  265. - (double)preferredSampleRate {
  266. return self.session.preferredSampleRate;
  267. }
  268. - (NSInteger)inputNumberOfChannels {
  269. return self.session.inputNumberOfChannels;
  270. }
  271. - (NSInteger)outputNumberOfChannels {
  272. return self.session.outputNumberOfChannels;
  273. }
  274. - (float)outputVolume {
  275. return self.session.outputVolume;
  276. }
  277. - (NSTimeInterval)inputLatency {
  278. return self.session.inputLatency;
  279. }
  280. - (NSTimeInterval)outputLatency {
  281. return self.session.outputLatency;
  282. }
  283. - (NSTimeInterval)IOBufferDuration {
  284. return self.session.IOBufferDuration;
  285. }
  286. - (NSTimeInterval)preferredIOBufferDuration {
  287. return self.session.preferredIOBufferDuration;
  288. }
  289. // TODO(tkchin): Simplify the amount of locking happening here. Likely that we
  290. // can just do atomic increments / decrements.
  291. - (BOOL)setActive:(BOOL)active
  292. error:(NSError **)outError {
  293. if (![self checkLock:outError]) {
  294. return NO;
  295. }
  296. int activationCount = _activationCount;
  297. if (!active && activationCount == 0) {
  298. RTCLogWarning(@"Attempting to deactivate without prior activation.");
  299. }
  300. [self notifyWillSetActive:active];
  301. BOOL success = YES;
  302. BOOL isActive = self.isActive;
  303. // Keep a local error so we can log it.
  304. NSError *error = nil;
  305. BOOL shouldSetActive =
  306. (active && !isActive) || (!active && isActive && activationCount == 1);
  307. // Attempt to activate if we're not active.
  308. // Attempt to deactivate if we're active and it's the last unbalanced call.
  309. if (shouldSetActive) {
  310. AVAudioSession *session = self.session;
  311. // AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation is used to ensure
  312. // that other audio sessions that were interrupted by our session can return
  313. // to their active state. It is recommended for VoIP apps to use this
  314. // option.
  315. AVAudioSessionSetActiveOptions options =
  316. active ? 0 : AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation;
  317. success = [session setActive:active
  318. withOptions:options
  319. error:&error];
  320. if (outError) {
  321. *outError = error;
  322. }
  323. }
  324. if (success) {
  325. if (shouldSetActive) {
  326. self.isActive = active;
  327. }
  328. if (active) {
  329. [self incrementActivationCount];
  330. }
  331. [self notifyDidSetActive:active];
  332. } else {
  333. RTCLogError(@"Failed to setActive:%d. Error: %@",
  334. active, error.localizedDescription);
  335. [self notifyFailedToSetActive:active error:error];
  336. }
  337. // Decrement activation count on deactivation whether or not it succeeded.
  338. if (!active) {
  339. [self decrementActivationCount];
  340. }
  341. RTCLog(@"Number of current activations: %d", _activationCount);
  342. return success;
  343. }
  344. - (BOOL)setCategory:(NSString *)category
  345. withOptions:(AVAudioSessionCategoryOptions)options
  346. error:(NSError **)outError {
  347. if (![self checkLock:outError]) {
  348. return NO;
  349. }
  350. return [self.session setCategory:category withOptions:options error:outError];
  351. }
  352. - (BOOL)setMode:(NSString *)mode error:(NSError **)outError {
  353. if (![self checkLock:outError]) {
  354. return NO;
  355. }
  356. return [self.session setMode:mode error:outError];
  357. }
  358. - (BOOL)setInputGain:(float)gain error:(NSError **)outError {
  359. if (![self checkLock:outError]) {
  360. return NO;
  361. }
  362. return [self.session setInputGain:gain error:outError];
  363. }
  364. - (BOOL)setPreferredSampleRate:(double)sampleRate error:(NSError **)outError {
  365. if (![self checkLock:outError]) {
  366. return NO;
  367. }
  368. return [self.session setPreferredSampleRate:sampleRate error:outError];
  369. }
  370. - (BOOL)setPreferredIOBufferDuration:(NSTimeInterval)duration
  371. error:(NSError **)outError {
  372. if (![self checkLock:outError]) {
  373. return NO;
  374. }
  375. return [self.session setPreferredIOBufferDuration:duration error:outError];
  376. }
  377. - (BOOL)setPreferredInputNumberOfChannels:(NSInteger)count
  378. error:(NSError **)outError {
  379. if (![self checkLock:outError]) {
  380. return NO;
  381. }
  382. return [self.session setPreferredInputNumberOfChannels:count error:outError];
  383. }
  384. - (BOOL)setPreferredOutputNumberOfChannels:(NSInteger)count
  385. error:(NSError **)outError {
  386. if (![self checkLock:outError]) {
  387. return NO;
  388. }
  389. return [self.session setPreferredOutputNumberOfChannels:count error:outError];
  390. }
  391. - (BOOL)overrideOutputAudioPort:(AVAudioSessionPortOverride)portOverride
  392. error:(NSError **)outError {
  393. if (![self checkLock:outError]) {
  394. return NO;
  395. }
  396. return [self.session overrideOutputAudioPort:portOverride error:outError];
  397. }
  398. - (BOOL)setPreferredInput:(AVAudioSessionPortDescription *)inPort
  399. error:(NSError **)outError {
  400. if (![self checkLock:outError]) {
  401. return NO;
  402. }
  403. return [self.session setPreferredInput:inPort error:outError];
  404. }
  405. - (BOOL)setInputDataSource:(AVAudioSessionDataSourceDescription *)dataSource
  406. error:(NSError **)outError {
  407. if (![self checkLock:outError]) {
  408. return NO;
  409. }
  410. return [self.session setInputDataSource:dataSource error:outError];
  411. }
  412. - (BOOL)setOutputDataSource:(AVAudioSessionDataSourceDescription *)dataSource
  413. error:(NSError **)outError {
  414. if (![self checkLock:outError]) {
  415. return NO;
  416. }
  417. return [self.session setOutputDataSource:dataSource error:outError];
  418. }
  419. #pragma mark - Notifications
  420. - (void)handleInterruptionNotification:(NSNotification *)notification {
  421. NSNumber* typeNumber =
  422. notification.userInfo[AVAudioSessionInterruptionTypeKey];
  423. AVAudioSessionInterruptionType type =
  424. (AVAudioSessionInterruptionType)typeNumber.unsignedIntegerValue;
  425. switch (type) {
  426. case AVAudioSessionInterruptionTypeBegan:
  427. RTCLog(@"Audio session interruption began.");
  428. self.isActive = NO;
  429. self.isInterrupted = YES;
  430. [self notifyDidBeginInterruption];
  431. break;
  432. case AVAudioSessionInterruptionTypeEnded: {
  433. RTCLog(@"Audio session interruption ended.");
  434. self.isInterrupted = NO;
  435. [self updateAudioSessionAfterEvent];
  436. NSNumber *optionsNumber =
  437. notification.userInfo[AVAudioSessionInterruptionOptionKey];
  438. AVAudioSessionInterruptionOptions options =
  439. optionsNumber.unsignedIntegerValue;
  440. BOOL shouldResume =
  441. options & AVAudioSessionInterruptionOptionShouldResume;
  442. [self notifyDidEndInterruptionWithShouldResumeSession:shouldResume];
  443. break;
  444. }
  445. }
  446. }
  447. - (void)handleRouteChangeNotification:(NSNotification *)notification {
  448. // Get reason for current route change.
  449. NSNumber* reasonNumber =
  450. notification.userInfo[AVAudioSessionRouteChangeReasonKey];
  451. AVAudioSessionRouteChangeReason reason =
  452. (AVAudioSessionRouteChangeReason)reasonNumber.unsignedIntegerValue;
  453. RTCLog(@"Audio route changed:");
  454. switch (reason) {
  455. case AVAudioSessionRouteChangeReasonUnknown:
  456. RTCLog(@"Audio route changed: ReasonUnknown");
  457. break;
  458. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  459. RTCLog(@"Audio route changed: NewDeviceAvailable");
  460. break;
  461. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
  462. RTCLog(@"Audio route changed: OldDeviceUnavailable");
  463. break;
  464. case AVAudioSessionRouteChangeReasonCategoryChange:
  465. RTCLog(@"Audio route changed: CategoryChange to :%@",
  466. self.session.category);
  467. break;
  468. case AVAudioSessionRouteChangeReasonOverride:
  469. RTCLog(@"Audio route changed: Override");
  470. break;
  471. case AVAudioSessionRouteChangeReasonWakeFromSleep:
  472. RTCLog(@"Audio route changed: WakeFromSleep");
  473. break;
  474. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
  475. RTCLog(@"Audio route changed: NoSuitableRouteForCategory");
  476. break;
  477. case AVAudioSessionRouteChangeReasonRouteConfigurationChange:
  478. RTCLog(@"Audio route changed: RouteConfigurationChange");
  479. break;
  480. }
  481. AVAudioSessionRouteDescription* previousRoute =
  482. notification.userInfo[AVAudioSessionRouteChangePreviousRouteKey];
  483. // Log previous route configuration.
  484. RTCLog(@"Previous route: %@\nCurrent route:%@",
  485. previousRoute, self.session.currentRoute);
  486. [self notifyDidChangeRouteWithReason:reason previousRoute:previousRoute];
  487. }
  488. - (void)handleMediaServicesWereLost:(NSNotification *)notification {
  489. RTCLog(@"Media services were lost.");
  490. [self updateAudioSessionAfterEvent];
  491. [self notifyMediaServicesWereLost];
  492. }
  493. - (void)handleMediaServicesWereReset:(NSNotification *)notification {
  494. RTCLog(@"Media services were reset.");
  495. [self updateAudioSessionAfterEvent];
  496. [self notifyMediaServicesWereReset];
  497. }
  498. - (void)handleSilenceSecondaryAudioHintNotification:(NSNotification *)notification {
  499. // TODO(henrika): just adding logs here for now until we know if we are ever
  500. // see this notification and might be affected by it or if further actions
  501. // are required.
  502. NSNumber *typeNumber =
  503. notification.userInfo[AVAudioSessionSilenceSecondaryAudioHintTypeKey];
  504. AVAudioSessionSilenceSecondaryAudioHintType type =
  505. (AVAudioSessionSilenceSecondaryAudioHintType)typeNumber.unsignedIntegerValue;
  506. switch (type) {
  507. case AVAudioSessionSilenceSecondaryAudioHintTypeBegin:
  508. RTCLog(@"Another application's primary audio has started.");
  509. break;
  510. case AVAudioSessionSilenceSecondaryAudioHintTypeEnd:
  511. RTCLog(@"Another application's primary audio has stopped.");
  512. break;
  513. }
  514. }
  515. - (void)handleApplicationDidBecomeActive:(NSNotification *)notification {
  516. BOOL isInterrupted = self.isInterrupted;
  517. RTCLog(@"Application became active after an interruption. Treating as interruption "
  518. "end. isInterrupted changed from %d to 0.",
  519. isInterrupted);
  520. if (isInterrupted) {
  521. self.isInterrupted = NO;
  522. [self updateAudioSessionAfterEvent];
  523. }
  524. // Always treat application becoming active as an interruption end event.
  525. [self notifyDidEndInterruptionWithShouldResumeSession:YES];
  526. }
  527. #pragma mark - Private
  528. + (NSError *)lockError {
  529. NSDictionary *userInfo = @{
  530. NSLocalizedDescriptionKey:
  531. @"Must call lockForConfiguration before calling this method."
  532. };
  533. NSError *error =
  534. [[NSError alloc] initWithDomain:kRTCAudioSessionErrorDomain
  535. code:kRTCAudioSessionErrorLockRequired
  536. userInfo:userInfo];
  537. return error;
  538. }
  539. - (std::vector<__weak id<RTCAudioSessionDelegate> >)delegates {
  540. @synchronized(self) {
  541. // Note: this returns a copy.
  542. return _delegates;
  543. }
  544. }
  545. // TODO(tkchin): check for duplicates.
  546. - (void)pushDelegate:(id<RTCAudioSessionDelegate>)delegate {
  547. @synchronized(self) {
  548. _delegates.insert(_delegates.begin(), delegate);
  549. }
  550. }
  551. - (void)removeZeroedDelegates {
  552. @synchronized(self) {
  553. _delegates.erase(
  554. std::remove_if(_delegates.begin(),
  555. _delegates.end(),
  556. [](id delegate) -> bool { return delegate == nil; }),
  557. _delegates.end());
  558. }
  559. }
  560. - (int)activationCount {
  561. return _activationCount;
  562. }
  563. - (int)incrementActivationCount {
  564. RTCLog(@"Incrementing activation count.");
  565. return rtc::AtomicOps::Increment(&_activationCount);
  566. }
  567. - (NSInteger)decrementActivationCount {
  568. RTCLog(@"Decrementing activation count.");
  569. return rtc::AtomicOps::Decrement(&_activationCount);
  570. }
  571. - (int)webRTCSessionCount {
  572. return _webRTCSessionCount;
  573. }
  574. - (BOOL)canPlayOrRecord {
  575. return !self.useManualAudio || self.isAudioEnabled;
  576. }
  577. - (BOOL)isInterrupted {
  578. @synchronized(self) {
  579. return _isInterrupted;
  580. }
  581. }
  582. - (void)setIsInterrupted:(BOOL)isInterrupted {
  583. @synchronized(self) {
  584. if (_isInterrupted == isInterrupted) {
  585. return;
  586. }
  587. _isInterrupted = isInterrupted;
  588. }
  589. }
  590. - (BOOL)checkLock:(NSError **)outError {
  591. // Check ivar instead of trying to acquire lock so that we won't accidentally
  592. // acquire lock if it hasn't already been called.
  593. if (!self.isLocked) {
  594. if (outError) {
  595. *outError = [RTCAudioSession lockError];
  596. }
  597. return NO;
  598. }
  599. return YES;
  600. }
  601. - (BOOL)beginWebRTCSession:(NSError **)outError {
  602. if (outError) {
  603. *outError = nil;
  604. }
  605. if (![self checkLock:outError]) {
  606. return NO;
  607. }
  608. rtc::AtomicOps::Increment(&_webRTCSessionCount);
  609. [self notifyDidStartPlayOrRecord];
  610. return YES;
  611. }
  612. - (BOOL)endWebRTCSession:(NSError **)outError {
  613. if (outError) {
  614. *outError = nil;
  615. }
  616. if (![self checkLock:outError]) {
  617. return NO;
  618. }
  619. rtc::AtomicOps::Decrement(&_webRTCSessionCount);
  620. [self notifyDidStopPlayOrRecord];
  621. return YES;
  622. }
  623. - (BOOL)configureWebRTCSession:(NSError **)outError {
  624. if (outError) {
  625. *outError = nil;
  626. }
  627. if (![self checkLock:outError]) {
  628. return NO;
  629. }
  630. RTCLog(@"Configuring audio session for WebRTC.");
  631. // Configure the AVAudioSession and activate it.
  632. // Provide an error even if there isn't one so we can log it.
  633. NSError *error = nil;
  634. RTCAudioSessionConfiguration *webRTCConfig =
  635. [RTCAudioSessionConfiguration webRTCConfiguration];
  636. if (![self setConfiguration:webRTCConfig active:YES error:&error]) {
  637. RTCLogError(@"Failed to set WebRTC audio configuration: %@",
  638. error.localizedDescription);
  639. // Do not call setActive:NO if setActive:YES failed.
  640. if (outError) {
  641. *outError = error;
  642. }
  643. return NO;
  644. }
  645. // Ensure that the device currently supports audio input.
  646. // TODO(tkchin): Figure out if this is really necessary.
  647. if (!self.inputAvailable) {
  648. RTCLogError(@"No audio input path is available!");
  649. [self unconfigureWebRTCSession:nil];
  650. if (outError) {
  651. *outError = [self configurationErrorWithDescription:@"No input path."];
  652. }
  653. return NO;
  654. }
  655. // It can happen (e.g. in combination with BT devices) that the attempt to set
  656. // the preferred sample rate for WebRTC (48kHz) fails. If so, make a new
  657. // configuration attempt using the sample rate that worked using the active
  658. // audio session. A typical case is that only 8 or 16kHz can be set, e.g. in
  659. // combination with BT headsets. Using this "trick" seems to avoid a state
  660. // where Core Audio asks for a different number of audio frames than what the
  661. // session's I/O buffer duration corresponds to.
  662. // TODO(henrika): this fix resolves bugs.webrtc.org/6004 but it has only been
  663. // tested on a limited set of iOS devices and BT devices.
  664. double sessionSampleRate = self.sampleRate;
  665. double preferredSampleRate = webRTCConfig.sampleRate;
  666. if (sessionSampleRate != preferredSampleRate) {
  667. RTCLogWarning(
  668. @"Current sample rate (%.2f) is not the preferred rate (%.2f)",
  669. sessionSampleRate, preferredSampleRate);
  670. if (![self setPreferredSampleRate:sessionSampleRate
  671. error:&error]) {
  672. RTCLogError(@"Failed to set preferred sample rate: %@",
  673. error.localizedDescription);
  674. if (outError) {
  675. *outError = error;
  676. }
  677. }
  678. }
  679. return YES;
  680. }
  681. - (BOOL)unconfigureWebRTCSession:(NSError **)outError {
  682. if (outError) {
  683. *outError = nil;
  684. }
  685. if (![self checkLock:outError]) {
  686. return NO;
  687. }
  688. RTCLog(@"Unconfiguring audio session for WebRTC.");
  689. [self setActive:NO error:outError];
  690. return YES;
  691. }
  692. - (NSError *)configurationErrorWithDescription:(NSString *)description {
  693. NSDictionary* userInfo = @{
  694. NSLocalizedDescriptionKey: description,
  695. };
  696. return [[NSError alloc] initWithDomain:kRTCAudioSessionErrorDomain
  697. code:kRTCAudioSessionErrorConfiguration
  698. userInfo:userInfo];
  699. }
  700. - (void)updateAudioSessionAfterEvent {
  701. BOOL shouldActivate = self.activationCount > 0;
  702. AVAudioSessionSetActiveOptions options = shouldActivate ?
  703. 0 : AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation;
  704. NSError *error = nil;
  705. if ([self.session setActive:shouldActivate
  706. withOptions:options
  707. error:&error]) {
  708. self.isActive = shouldActivate;
  709. } else {
  710. RTCLogError(@"Failed to set session active to %d. Error:%@",
  711. shouldActivate, error.localizedDescription);
  712. }
  713. }
  714. - (void)updateCanPlayOrRecord {
  715. BOOL canPlayOrRecord = NO;
  716. BOOL shouldNotify = NO;
  717. @synchronized(self) {
  718. canPlayOrRecord = !self.useManualAudio || self.isAudioEnabled;
  719. if (_canPlayOrRecord == canPlayOrRecord) {
  720. return;
  721. }
  722. _canPlayOrRecord = canPlayOrRecord;
  723. shouldNotify = YES;
  724. }
  725. if (shouldNotify) {
  726. [self notifyDidChangeCanPlayOrRecord:canPlayOrRecord];
  727. }
  728. }
  729. - (void)audioSessionDidActivate:(AVAudioSession *)session {
  730. if (_session != session) {
  731. RTCLogError(@"audioSessionDidActivate called on different AVAudioSession");
  732. }
  733. RTCLog(@"Audio session was externally activated.");
  734. [self incrementActivationCount];
  735. self.isActive = YES;
  736. // When a CallKit call begins, it's possible that we receive an interruption
  737. // begin without a corresponding end. Since we know that we have an activated
  738. // audio session at this point, just clear any saved interruption flag since
  739. // the app may never be foregrounded during the duration of the call.
  740. if (self.isInterrupted) {
  741. RTCLog(@"Clearing interrupted state due to external activation.");
  742. self.isInterrupted = NO;
  743. }
  744. // Treat external audio session activation as an end interruption event.
  745. [self notifyDidEndInterruptionWithShouldResumeSession:YES];
  746. }
  747. - (void)audioSessionDidDeactivate:(AVAudioSession *)session {
  748. if (_session != session) {
  749. RTCLogError(@"audioSessionDidDeactivate called on different AVAudioSession");
  750. }
  751. RTCLog(@"Audio session was externally deactivated.");
  752. self.isActive = NO;
  753. [self decrementActivationCount];
  754. }
  755. - (void)observeValueForKeyPath:(NSString *)keyPath
  756. ofObject:(id)object
  757. change:(NSDictionary *)change
  758. context:(void *)context {
  759. if (context == (__bridge void*)RTCAudioSession.class) {
  760. if (object == _session) {
  761. NSNumber *newVolume = change[NSKeyValueChangeNewKey];
  762. RTCLog(@"OutputVolumeDidChange to %f", newVolume.floatValue);
  763. [self notifyDidChangeOutputVolume:newVolume.floatValue];
  764. }
  765. } else {
  766. [super observeValueForKeyPath:keyPath
  767. ofObject:object
  768. change:change
  769. context:context];
  770. }
  771. }
  772. - (void)notifyDidBeginInterruption {
  773. for (auto delegate : self.delegates) {
  774. SEL sel = @selector(audioSessionDidBeginInterruption:);
  775. if ([delegate respondsToSelector:sel]) {
  776. [delegate audioSessionDidBeginInterruption:self];
  777. }
  778. }
  779. }
  780. - (void)notifyDidEndInterruptionWithShouldResumeSession:
  781. (BOOL)shouldResumeSession {
  782. for (auto delegate : self.delegates) {
  783. SEL sel = @selector(audioSessionDidEndInterruption:shouldResumeSession:);
  784. if ([delegate respondsToSelector:sel]) {
  785. [delegate audioSessionDidEndInterruption:self
  786. shouldResumeSession:shouldResumeSession];
  787. }
  788. }
  789. }
  790. - (void)notifyDidChangeRouteWithReason:(AVAudioSessionRouteChangeReason)reason
  791. previousRoute:(AVAudioSessionRouteDescription *)previousRoute {
  792. for (auto delegate : self.delegates) {
  793. SEL sel = @selector(audioSessionDidChangeRoute:reason:previousRoute:);
  794. if ([delegate respondsToSelector:sel]) {
  795. [delegate audioSessionDidChangeRoute:self
  796. reason:reason
  797. previousRoute:previousRoute];
  798. }
  799. }
  800. }
  801. - (void)notifyMediaServicesWereLost {
  802. for (auto delegate : self.delegates) {
  803. SEL sel = @selector(audioSessionMediaServerTerminated:);
  804. if ([delegate respondsToSelector:sel]) {
  805. [delegate audioSessionMediaServerTerminated:self];
  806. }
  807. }
  808. }
  809. - (void)notifyMediaServicesWereReset {
  810. for (auto delegate : self.delegates) {
  811. SEL sel = @selector(audioSessionMediaServerReset:);
  812. if ([delegate respondsToSelector:sel]) {
  813. [delegate audioSessionMediaServerReset:self];
  814. }
  815. }
  816. }
  817. - (void)notifyDidChangeCanPlayOrRecord:(BOOL)canPlayOrRecord {
  818. for (auto delegate : self.delegates) {
  819. SEL sel = @selector(audioSession:didChangeCanPlayOrRecord:);
  820. if ([delegate respondsToSelector:sel]) {
  821. [delegate audioSession:self didChangeCanPlayOrRecord:canPlayOrRecord];
  822. }
  823. }
  824. }
  825. - (void)notifyDidStartPlayOrRecord {
  826. for (auto delegate : self.delegates) {
  827. SEL sel = @selector(audioSessionDidStartPlayOrRecord:);
  828. if ([delegate respondsToSelector:sel]) {
  829. [delegate audioSessionDidStartPlayOrRecord:self];
  830. }
  831. }
  832. }
  833. - (void)notifyDidStopPlayOrRecord {
  834. for (auto delegate : self.delegates) {
  835. SEL sel = @selector(audioSessionDidStopPlayOrRecord:);
  836. if ([delegate respondsToSelector:sel]) {
  837. [delegate audioSessionDidStopPlayOrRecord:self];
  838. }
  839. }
  840. }
  841. - (void)notifyDidChangeOutputVolume:(float)volume {
  842. for (auto delegate : self.delegates) {
  843. SEL sel = @selector(audioSession:didChangeOutputVolume:);
  844. if ([delegate respondsToSelector:sel]) {
  845. [delegate audioSession:self didChangeOutputVolume:volume];
  846. }
  847. }
  848. }
  849. - (void)notifyDidDetectPlayoutGlitch:(int64_t)totalNumberOfGlitches {
  850. for (auto delegate : self.delegates) {
  851. SEL sel = @selector(audioSession:didDetectPlayoutGlitch:);
  852. if ([delegate respondsToSelector:sel]) {
  853. [delegate audioSession:self didDetectPlayoutGlitch:totalNumberOfGlitches];
  854. }
  855. }
  856. }
  857. - (void)notifyWillSetActive:(BOOL)active {
  858. for (id delegate : self.delegates) {
  859. SEL sel = @selector(audioSession:willSetActive:);
  860. if ([delegate respondsToSelector:sel]) {
  861. [delegate audioSession:self willSetActive:active];
  862. }
  863. }
  864. }
  865. - (void)notifyDidSetActive:(BOOL)active {
  866. for (id delegate : self.delegates) {
  867. SEL sel = @selector(audioSession:didSetActive:);
  868. if ([delegate respondsToSelector:sel]) {
  869. [delegate audioSession:self didSetActive:active];
  870. }
  871. }
  872. }
  873. - (void)notifyFailedToSetActive:(BOOL)active error:(NSError *)error {
  874. for (id delegate : self.delegates) {
  875. SEL sel = @selector(audioSession:failedToSetActive:error:);
  876. if ([delegate respondsToSelector:sel]) {
  877. [delegate audioSession:self failedToSetActive:active error:error];
  878. }
  879. }
  880. }
  881. @end