Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1127)

Side by Side Diff: webrtc/modules/audio_device/ios/audio_device_ios.mm

Issue 1401963002: Adds support for Bluetooth headsets to the iOS audio layer (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: nits Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. 2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 * 3 *
4 * Use of this source code is governed by a BSD-style license 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 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 6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may 7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree. 8 * be found in the AUTHORS file in the root of the source tree.
9 */ 9 */
10 10
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
70 using ios::CheckAndLogError; 70 using ios::CheckAndLogError;
71 71
72 // Activates an audio session suitable for full duplex VoIP sessions when 72 // Activates an audio session suitable for full duplex VoIP sessions when
73 // |activate| is true. Also sets the preferred sample rate and IO buffer 73 // |activate| is true. Also sets the preferred sample rate and IO buffer
74 // duration. Deactivates an active audio session if |activate| is set to false. 74 // duration. Deactivates an active audio session if |activate| is set to false.
75 static void ActivateAudioSession(AVAudioSession* session, bool activate) { 75 static void ActivateAudioSession(AVAudioSession* session, bool activate) {
76 LOG(LS_INFO) << "ActivateAudioSession(" << activate << ")"; 76 LOG(LS_INFO) << "ActivateAudioSession(" << activate << ")";
77 @autoreleasepool { 77 @autoreleasepool {
78 NSError* error = nil; 78 NSError* error = nil;
79 BOOL success = NO; 79 BOOL success = NO;
80
80 // Deactivate the audio session and return if |activate| is false. 81 // Deactivate the audio session and return if |activate| is false.
81 if (!activate) { 82 if (!activate) {
82 success = [session setActive:NO error:&error]; 83 success = [session setActive:NO error:&error];
83 RTC_DCHECK(CheckAndLogError(success, error)); 84 RTC_DCHECK(CheckAndLogError(success, error));
84 return; 85 return;
85 } 86 }
87
86 // Use a category which supports simultaneous recording and playback. 88 // Use a category which supports simultaneous recording and playback.
87 // By default, using this category implies that our app’s audio is 89 // By default, using this category implies that our app’s audio is
88 // nonmixable, hence activating the session will interrupt any other 90 // nonmixable, hence activating the session will interrupt any other
89 // audio sessions which are also nonmixable. 91 // audio sessions which are also nonmixable.
90 if (session.category != AVAudioSessionCategoryPlayAndRecord) { 92 if (session.category != AVAudioSessionCategoryPlayAndRecord) {
91 error = nil; 93 error = nil;
92 success = [session setCategory:AVAudioSessionCategoryPlayAndRecord 94 success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
93 error:&error]; 95 error:&error];
94 RTC_DCHECK(CheckAndLogError(success, error)); 96 RTC_DCHECK(CheckAndLogError(success, error));
95 } 97 }
98
96 // Specify mode for two-way voice communication (e.g. VoIP). 99 // Specify mode for two-way voice communication (e.g. VoIP).
97 if (session.mode != AVAudioSessionModeVoiceChat) { 100 if (session.mode != AVAudioSessionModeVoiceChat) {
98 error = nil; 101 error = nil;
99 success = [session setMode:AVAudioSessionModeVoiceChat error:&error]; 102 success = [session setMode:AVAudioSessionModeVoiceChat error:&error];
100 RTC_DCHECK(CheckAndLogError(success, error)); 103 RTC_DCHECK(CheckAndLogError(success, error));
101 } 104 }
105
102 // Set the session's sample rate or the hardware sample rate. 106 // Set the session's sample rate or the hardware sample rate.
103 // It is essential that we use the same sample rate as stream format 107 // It is essential that we use the same sample rate as stream format
104 // to ensure that the I/O unit does not have to do sample rate conversion. 108 // to ensure that the I/O unit does not have to do sample rate conversion.
105 error = nil; 109 error = nil;
106 success = 110 success =
107 [session setPreferredSampleRate:kPreferredSampleRate error:&error]; 111 [session setPreferredSampleRate:kPreferredSampleRate error:&error];
108 RTC_DCHECK(CheckAndLogError(success, error)); 112 RTC_DCHECK(CheckAndLogError(success, error));
113
109 // Set the preferred audio I/O buffer duration, in seconds. 114 // Set the preferred audio I/O buffer duration, in seconds.
110 // TODO(henrika): add more comments here. 115 // TODO(henrika): add more comments here.
111 error = nil; 116 error = nil;
112 success = [session setPreferredIOBufferDuration:kPreferredIOBufferDuration 117 success = [session setPreferredIOBufferDuration:kPreferredIOBufferDuration
113 error:&error]; 118 error:&error];
114 RTC_DCHECK(CheckAndLogError(success, error)); 119 RTC_DCHECK(CheckAndLogError(success, error));
115 120
116 // TODO(henrika): add observers here...
117
118 // Activate the audio session. Activation can fail if another active audio 121 // Activate the audio session. Activation can fail if another active audio
119 // session (e.g. phone call) has higher priority than ours. 122 // session (e.g. phone call) has higher priority than ours.
120 error = nil; 123 error = nil;
121 success = [session setActive:YES error:&error]; 124 success = [session setActive:YES error:&error];
122 RTC_DCHECK(CheckAndLogError(success, error)); 125 RTC_DCHECK(CheckAndLogError(success, error));
123 RTC_CHECK(session.isInputAvailable) << "No input path is available!"; 126 RTC_CHECK(session.isInputAvailable) << "No input path is available!";
127
124 // Ensure that category and mode are actually activated. 128 // Ensure that category and mode are actually activated.
125 RTC_DCHECK( 129 RTC_DCHECK(
126 [session.category isEqualToString:AVAudioSessionCategoryPlayAndRecord]); 130 [session.category isEqualToString:AVAudioSessionCategoryPlayAndRecord]);
127 RTC_DCHECK([session.mode isEqualToString:AVAudioSessionModeVoiceChat]); 131 RTC_DCHECK([session.mode isEqualToString:AVAudioSessionModeVoiceChat]);
132
128 // Try to set the preferred number of hardware audio channels. These calls 133 // Try to set the preferred number of hardware audio channels. These calls
129 // must be done after setting the audio session’s category and mode and 134 // must be done after setting the audio session’s category and mode and
130 // activating the session. 135 // activating the session.
131 // We try to use mono in both directions to save resources and format 136 // We try to use mono in both directions to save resources and format
132 // conversions in the audio unit. Some devices does only support stereo; 137 // conversions in the audio unit. Some devices does only support stereo;
133 // e.g. wired headset on iPhone 6. 138 // e.g. wired headset on iPhone 6.
134 // TODO(henrika): add support for stereo if needed. 139 // TODO(henrika): add support for stereo if needed.
135 error = nil; 140 error = nil;
136 success = 141 success =
137 [session setPreferredInputNumberOfChannels:kPreferredNumberOfChannels 142 [session setPreferredInputNumberOfChannels:kPreferredNumberOfChannels
(...skipping 259 matching lines...) Expand 10 before | Expand all | Expand 10 after
397 // just in case. 402 // just in case.
398 RTC_DCHECK(audio_device_buffer_) << "AttachAudioBuffer must be called first"; 403 RTC_DCHECK(audio_device_buffer_) << "AttachAudioBuffer must be called first";
399 // Inform the audio device buffer (ADB) about the new audio format. 404 // Inform the audio device buffer (ADB) about the new audio format.
400 audio_device_buffer_->SetPlayoutSampleRate(playout_parameters_.sample_rate()); 405 audio_device_buffer_->SetPlayoutSampleRate(playout_parameters_.sample_rate());
401 audio_device_buffer_->SetPlayoutChannels(playout_parameters_.channels()); 406 audio_device_buffer_->SetPlayoutChannels(playout_parameters_.channels());
402 audio_device_buffer_->SetRecordingSampleRate( 407 audio_device_buffer_->SetRecordingSampleRate(
403 record_parameters_.sample_rate()); 408 record_parameters_.sample_rate());
404 audio_device_buffer_->SetRecordingChannels(record_parameters_.channels()); 409 audio_device_buffer_->SetRecordingChannels(record_parameters_.channels());
405 } 410 }
406 411
412 void AudioDeviceIOS::RegisterNotificationObservers() {
413 LOGI() << "RegisterNotificationObservers";
414 // Get the default notification center of the current process.
415 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
416
417 // Add AVAudioSessionInterruptionNotification observer.
418 // TODO(henrika): improve this section and try to merge actions with actions
tkchin_webrtc 2015/10/16 16:23:32 imo we should make changes to depot_tools to allow
henrika_webrtc 2015/10/20 10:18:16 No action on adding 100 lines support. Thanks for
419 // for the detected route change.
420 id interruption_observer = [center
421 addObserverForName:AVAudioSessionInterruptionNotification
422 object:nil
423 queue:[NSOperationQueue mainQueue]
424 usingBlock:^(NSNotification* notification) {
425 NSNumber* typeNumber =
426 [notification userInfo][AVAudioSessionInterruptionTypeKey];
tkchin_webrtc 2015/10/16 16:23:32 style: notification.userInfo[AVAudioSessionInterru
henrika_webrtc 2015/10/20 10:18:16 Done.
427 AVAudioSessionInterruptionType type =
428 (AVAudioSessionInterruptionType)[typeNumber
429 unsignedIntegerValue];
430 switch (type) {
431 case AVAudioSessionInterruptionTypeBegan:
432 // At this point our audio session has been deactivated and
433 // the audio unit render callbacks no longer occur.
434 // Nothing to do.
435 break;
436 case AVAudioSessionInterruptionTypeEnded: {
437 NSError* error = nil;
438 AVAudioSession* session = [AVAudioSession sharedInstance];
439 [session setActive:YES error:&error];
440 if (error != nil) {
441 LOG_F(LS_ERROR) << "Failed to active audio session";
442 }
443 // Post interruption the audio unit render callbacks don't
tkchin_webrtc 2015/10/16 16:23:32 Is this still true today?
henrika_webrtc 2015/10/20 10:18:16 See TODO above. I will check and make changes in t
444 // automatically continue, so we restart the unit manually
445 // here.
446 AudioOutputUnitStop(vpio_unit_);
447 AudioOutputUnitStart(vpio_unit_);
448 break;
449 }
450 }
451 }];
452
453 // Add AVAudioSessionRouteChangeNotification observer.
454 id route_change_observer = [center
455 addObserverForName:AVAudioSessionRouteChangeNotification
456 object:nil
457 queue:[NSOperationQueue mainQueue]
458 usingBlock:^(NSNotification* notification) {
459 // Get reason for current route change.
460 NSUInteger reason_value = [[notification.userInfo
tkchin_webrtc 2015/10/16 16:23:32 style: NSNumber *reason_number = notification.user
henrika_webrtc 2015/10/20 10:18:16 Done.
461 valueForKey:AVAudioSessionRouteChangeReasonKey]
462 unsignedIntegerValue];
463 bool valid_route_change = true;
464 LOG(LS_INFO) << "Route change:";
465 switch (reason_value) {
466 case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
467 LOG(LS_INFO) << " NewDeviceAvailable";
468 break;
469 case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
470 LOG(LS_INFO) << " OldDeviceUnavailable";
471 break;
472 case AVAudioSessionRouteChangeReasonCategoryChange:
473 LOG(LS_INFO) << " CategoryChange";
474 LOG(LS_INFO) << " New category: "
475 << ios::GetAudioSessionCategory();
476 break;
477 case AVAudioSessionRouteChangeReasonOverride:
478 LOG(LS_INFO) << " Override";
479 break;
480 case AVAudioSessionRouteChangeReasonWakeFromSleep:
481 LOG(LS_INFO) << " WakeFromSleep";
482 break;
483 case AVAudioSessionRouteChangeReasonRouteConfigurationChange:
484 // Ignore this type of route change since we are focusing
485 // on detecting headset changes.
486 LOG(LS_INFO) << " RouteConfigurationChange";
487 valid_route_change = false;
488 break;
489 default:
490 LOG(LS_INFO) << " ReasonUnknown";
491 }
492
493 if (valid_route_change) {
494 // Log previous route configuration.
495 AVAudioSessionRouteDescription* prev_route = [notification
496 userInfo][AVAudioSessionRouteChangePreviousRouteKey];
tkchin_webrtc 2015/10/16 16:23:32 ditto .userInfo
henrika_webrtc 2015/10/20 10:18:16 Done.
497 LOG(LS_INFO) << "Previous route:";
498 LOG(LS_INFO) << ios::StdStringFromNSString(
499 [NSString stringWithFormat:@"%@", prev_route]);
500
501 // Only restart audio for a valid route change and if the
502 // session sample rate has changed.
503 const double session_sample_rate =
504 [[AVAudioSession sharedInstance] sampleRate];
tkchin_webrtc 2015/10/16 16:23:32 ditto dot syntax for properties
henrika_webrtc 2015/10/20 10:18:16 Done.
505 if (playout_parameters_.sample_rate() !=
506 session_sample_rate) {
507 if (!RestartAudioUnitWithNewFormat(session_sample_rate)) {
508 LOG(LS_ERROR) << "Audio restart failed";
509 }
510 }
511 }
512
513 }];
514
515 // Increment refcount on observers using ARC bridge. Instance variable is a
516 // void* instead of an id because header is included in other pure C++
517 // files.
518 audio_interruption_observer_ = (__bridge_retained void*)interruption_observer;
519 route_change_observer_ = (__bridge_retained void*)route_change_observer;
520 }
521
522 void AudioDeviceIOS::UnregisterNotificationObservers() {
523 LOGI() << "UnregisterNotificationObservers";
524 // Transfer ownership of observer back to ARC, which will deallocate the
525 // observer once it exits this scope.
526 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
527 if (audio_interruption_observer_ != nullptr) {
528 id observer = (__bridge_transfer id)audio_interruption_observer_;
529 [center removeObserver:observer];
530 audio_interruption_observer_ = nullptr;
531 }
532 if (route_change_observer_ != nullptr) {
533 id observer = (__bridge_transfer id)route_change_observer_;
534 [center removeObserver:observer];
535 route_change_observer_ = nullptr;
536 }
537 }
538
407 void AudioDeviceIOS::SetupAudioBuffersForActiveAudioSession() { 539 void AudioDeviceIOS::SetupAudioBuffersForActiveAudioSession() {
408 LOGI() << "SetupAudioBuffersForActiveAudioSession"; 540 LOGI() << "SetupAudioBuffersForActiveAudioSession";
541 // Verify the current values once the audio session has been activated.
409 AVAudioSession* session = [AVAudioSession sharedInstance]; 542 AVAudioSession* session = [AVAudioSession sharedInstance];
410 // Verify the current values once the audio session has been activated.
411 LOG(LS_INFO) << " sample rate: " << session.sampleRate; 543 LOG(LS_INFO) << " sample rate: " << session.sampleRate;
412 LOG(LS_INFO) << " IO buffer duration: " << session.IOBufferDuration; 544 LOG(LS_INFO) << " IO buffer duration: " << session.IOBufferDuration;
413 LOG(LS_INFO) << " output channels: " << session.outputNumberOfChannels; 545 LOG(LS_INFO) << " output channels: " << session.outputNumberOfChannels;
414 LOG(LS_INFO) << " input channels: " << session.inputNumberOfChannels; 546 LOG(LS_INFO) << " input channels: " << session.inputNumberOfChannels;
415 LOG(LS_INFO) << " output latency: " << session.outputLatency; 547 LOG(LS_INFO) << " output latency: " << session.outputLatency;
416 LOG(LS_INFO) << " input latency: " << session.inputLatency; 548 LOG(LS_INFO) << " input latency: " << session.inputLatency;
549
417 // Log a warning message for the case when we are unable to set the preferred 550 // Log a warning message for the case when we are unable to set the preferred
418 // hardware sample rate but continue and use the non-ideal sample rate after 551 // hardware sample rate but continue and use the non-ideal sample rate after
419 // reinitializing the audio parameters. 552 // reinitializing the audio parameters. Most BT headsets only support 8kHz or
420 if (session.sampleRate != playout_parameters_.sample_rate()) { 553 // 16kHz.
421 LOG(LS_WARNING) 554 if (session.sampleRate != kPreferredSampleRate) {
422 << "Failed to enable an audio session with the preferred sample rate!"; 555 LOG(LS_WARNING) << "Unable to set the preferred sample rate";
423 } 556 }
424 557
425 // At this stage, we also know the exact IO buffer duration and can add 558 // At this stage, we also know the exact IO buffer duration and can add
426 // that info to the existing audio parameters where it is converted into 559 // that info to the existing audio parameters where it is converted into
427 // number of audio frames. 560 // number of audio frames.
428 // Example: IO buffer size = 0.008 seconds <=> 128 audio frames at 16kHz. 561 // Example: IO buffer size = 0.008 seconds <=> 128 audio frames at 16kHz.
429 // Hence, 128 is the size we expect to see in upcoming render callbacks. 562 // Hence, 128 is the size we expect to see in upcoming render callbacks.
430 playout_parameters_.reset(session.sampleRate, playout_parameters_.channels(), 563 playout_parameters_.reset(session.sampleRate, playout_parameters_.channels(),
431 session.IOBufferDuration); 564 session.IOBufferDuration);
432 RTC_DCHECK(playout_parameters_.is_complete()); 565 RTC_DCHECK(playout_parameters_.is_complete());
(...skipping 92 matching lines...) Expand 10 before | Expand all | Expand 10 after
525 RTC_DCHECK_EQ(1, kPreferredNumberOfChannels); 658 RTC_DCHECK_EQ(1, kPreferredNumberOfChannels);
526 application_format.mSampleRate = playout_parameters_.sample_rate(); 659 application_format.mSampleRate = playout_parameters_.sample_rate();
527 application_format.mFormatID = kAudioFormatLinearPCM; 660 application_format.mFormatID = kAudioFormatLinearPCM;
528 application_format.mFormatFlags = 661 application_format.mFormatFlags =
529 kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked; 662 kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
530 application_format.mBytesPerPacket = kBytesPerSample; 663 application_format.mBytesPerPacket = kBytesPerSample;
531 application_format.mFramesPerPacket = 1; // uncompressed 664 application_format.mFramesPerPacket = 1; // uncompressed
532 application_format.mBytesPerFrame = kBytesPerSample; 665 application_format.mBytesPerFrame = kBytesPerSample;
533 application_format.mChannelsPerFrame = kPreferredNumberOfChannels; 666 application_format.mChannelsPerFrame = kPreferredNumberOfChannels;
534 application_format.mBitsPerChannel = 8 * kBytesPerSample; 667 application_format.mBitsPerChannel = 8 * kBytesPerSample;
668 // Store the new format.
669 application_format_ = application_format;
535 #if !defined(NDEBUG) 670 #if !defined(NDEBUG)
536 LogABSD(application_format); 671 LogABSD(application_format_);
537 #endif 672 #endif
538 673
539 // Set the application format on the output scope of the input element/bus. 674 // Set the application format on the output scope of the input element/bus.
540 LOG_AND_RETURN_IF_ERROR( 675 LOG_AND_RETURN_IF_ERROR(
541 AudioUnitSetProperty(vpio_unit_, kAudioUnitProperty_StreamFormat, 676 AudioUnitSetProperty(vpio_unit_, kAudioUnitProperty_StreamFormat,
542 kAudioUnitScope_Output, input_bus, 677 kAudioUnitScope_Output, input_bus,
543 &application_format, size), 678 &application_format, size),
544 "Failed to set application format on output scope of input element"); 679 "Failed to set application format on output scope of input element");
545 680
546 // Set the application format on the input scope of the output element/bus. 681 // Set the application format on the input scope of the output element/bus.
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
582 kAudioUnitScope_Global, input_bus, &input_callback, 717 kAudioUnitScope_Global, input_bus, &input_callback,
583 sizeof(input_callback)), 718 sizeof(input_callback)),
584 "Failed to specify the input callback on the input element"); 719 "Failed to specify the input callback on the input element");
585 720
586 // Initialize the Voice-Processing I/O unit instance. 721 // Initialize the Voice-Processing I/O unit instance.
587 LOG_AND_RETURN_IF_ERROR(AudioUnitInitialize(vpio_unit_), 722 LOG_AND_RETURN_IF_ERROR(AudioUnitInitialize(vpio_unit_),
588 "Failed to initialize the Voice-Processing I/O unit"); 723 "Failed to initialize the Voice-Processing I/O unit");
589 return true; 724 return true;
590 } 725 }
591 726
727 bool AudioDeviceIOS::RestartAudioUnitWithNewFormat(float sample_rate) {
728 LOGI() << "RestartAudioUnitWithNewFormat(sample_rate=" << sample_rate << ")";
729 // Stop the active audio unit.
730 LOG_AND_RETURN_IF_ERROR(AudioOutputUnitStop(vpio_unit_),
731 "Failed to stop the the Voice-Processing I/O unit");
732
733 // The stream format is about to be changed and it requires that we first
734 // uninitialize it to deallocate its resources.
735 LOG_AND_RETURN_IF_ERROR(
736 AudioUnitUninitialize(vpio_unit_),
737 "Failed to uninitialize the the Voice-Processing I/O unit");
738
739 // Allocate new buffers given the new stream format.
740 SetupAudioBuffersForActiveAudioSession();
741
742 // Update the existing application format using the new sample rate.
743 application_format_.mSampleRate = playout_parameters_.sample_rate();
744 UInt32 size = sizeof(application_format_);
745 AudioUnitSetProperty(vpio_unit_, kAudioUnitProperty_StreamFormat,
746 kAudioUnitScope_Output, 1, &application_format_, size);
747 AudioUnitSetProperty(vpio_unit_, kAudioUnitProperty_StreamFormat,
748 kAudioUnitScope_Input, 0, &application_format_, size);
749
750 // Prepare the audio unit to render audio again.
751 LOG_AND_RETURN_IF_ERROR(AudioUnitInitialize(vpio_unit_),
752 "Failed to initialize the Voice-Processing I/O unit");
753
754 // Start rendering audio using the new format.
755 LOG_AND_RETURN_IF_ERROR(AudioOutputUnitStart(vpio_unit_),
756 "Failed to start the Voice-Processing I/O unit");
757 return true;
758 }
759
592 bool AudioDeviceIOS::InitPlayOrRecord() { 760 bool AudioDeviceIOS::InitPlayOrRecord() {
593 LOGI() << "InitPlayOrRecord"; 761 LOGI() << "InitPlayOrRecord";
594 AVAudioSession* session = [AVAudioSession sharedInstance]; 762 AVAudioSession* session = [AVAudioSession sharedInstance];
595 // Activate the audio session and ask for a set of preferred audio parameters. 763 // Activate the audio session and ask for a set of preferred audio parameters.
596 ActivateAudioSession(session, true); 764 ActivateAudioSession(session, true);
597 765
766 // Start observing audio session interruptions and route changes.
767 RegisterNotificationObservers();
768
598 // Ensure that we got what what we asked for in our active audio session. 769 // Ensure that we got what what we asked for in our active audio session.
599 SetupAudioBuffersForActiveAudioSession(); 770 SetupAudioBuffersForActiveAudioSession();
600 771
601 // Create, setup and initialize a new Voice-Processing I/O unit. 772 // Create, setup and initialize a new Voice-Processing I/O unit.
602 if (!SetupAndInitializeVoiceProcessingAudioUnit()) { 773 if (!SetupAndInitializeVoiceProcessingAudioUnit()) {
603 return false; 774 return false;
604 } 775 }
605
606 // Listen to audio interruptions.
607 // TODO(henrika): learn this area better.
608 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
609 id observer = [center
610 addObserverForName:AVAudioSessionInterruptionNotification
611 object:nil
612 queue:[NSOperationQueue mainQueue]
613 usingBlock:^(NSNotification* notification) {
614 NSNumber* typeNumber =
615 [notification userInfo][AVAudioSessionInterruptionTypeKey];
616 AVAudioSessionInterruptionType type =
617 (AVAudioSessionInterruptionType)[typeNumber
618 unsignedIntegerValue];
619 switch (type) {
620 case AVAudioSessionInterruptionTypeBegan:
621 // At this point our audio session has been deactivated and
622 // the audio unit render callbacks no longer occur.
623 // Nothing to do.
624 break;
625 case AVAudioSessionInterruptionTypeEnded: {
626 NSError* error = nil;
627 AVAudioSession* session = [AVAudioSession sharedInstance];
628 [session setActive:YES error:&error];
629 if (error != nil) {
630 LOG_F(LS_ERROR) << "Failed to active audio session";
631 }
632 // Post interruption the audio unit render callbacks don't
633 // automatically continue, so we restart the unit manually
634 // here.
635 AudioOutputUnitStop(vpio_unit_);
636 AudioOutputUnitStart(vpio_unit_);
637 break;
638 }
639 }
640 }];
641 // Increment refcount on observer using ARC bridge. Instance variable is a
642 // void* instead of an id because header is included in other pure C++
643 // files.
644 audio_interruption_observer_ = (__bridge_retained void*)observer;
645 return true; 776 return true;
646 } 777 }
647 778
648 bool AudioDeviceIOS::ShutdownPlayOrRecord() { 779 bool AudioDeviceIOS::ShutdownPlayOrRecord() {
649 LOGI() << "ShutdownPlayOrRecord"; 780 LOGI() << "ShutdownPlayOrRecord";
650 if (audio_interruption_observer_ != nullptr) { 781 // Remove audio session notification observers.
651 NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; 782 UnregisterNotificationObservers();
652 // Transfer ownership of observer back to ARC, which will dealloc the 783
653 // observer once it exits this scope.
654 id observer = (__bridge_transfer id)audio_interruption_observer_;
655 [center removeObserver:observer];
656 audio_interruption_observer_ = nullptr;
657 }
658 // Close and delete the voice-processing I/O unit. 784 // Close and delete the voice-processing I/O unit.
659 OSStatus result = -1; 785 OSStatus result = -1;
660 if (nullptr != vpio_unit_) { 786 if (nullptr != vpio_unit_) {
661 result = AudioOutputUnitStop(vpio_unit_); 787 result = AudioOutputUnitStop(vpio_unit_);
662 if (result != noErr) { 788 if (result != noErr) {
663 LOG_F(LS_ERROR) << "AudioOutputUnitStop failed: " << result; 789 LOG_F(LS_ERROR) << "AudioOutputUnitStop failed: " << result;
664 } 790 }
791 result = AudioUnitUninitialize(vpio_unit_);
tkchin_webrtc 2015/10/16 16:23:32 oh dear, were we really not doing this before? Thx
henrika_webrtc 2015/10/20 10:18:16 You are welcome ;-)
792 if (result != noErr) {
793 LOG_F(LS_ERROR) << "AudioUnitUninitialize failed: " << result;
794 }
665 result = AudioComponentInstanceDispose(vpio_unit_); 795 result = AudioComponentInstanceDispose(vpio_unit_);
666 if (result != noErr) { 796 if (result != noErr) {
667 LOG_F(LS_ERROR) << "AudioComponentInstanceDispose failed: " << result; 797 LOG_F(LS_ERROR) << "AudioComponentInstanceDispose failed: " << result;
668 } 798 }
669 vpio_unit_ = nullptr; 799 vpio_unit_ = nullptr;
670 } 800 }
801
671 // All I/O should be stopped or paused prior to deactivating the audio 802 // All I/O should be stopped or paused prior to deactivating the audio
672 // session, hence we deactivate as last action. 803 // session, hence we deactivate as last action.
673 AVAudioSession* session = [AVAudioSession sharedInstance]; 804 AVAudioSession* session = [AVAudioSession sharedInstance];
674 ActivateAudioSession(session, false); 805 ActivateAudioSession(session, false);
675 return true; 806 return true;
676 } 807 }
677 808
678 OSStatus AudioDeviceIOS::RecordedDataIsAvailable( 809 OSStatus AudioDeviceIOS::RecordedDataIsAvailable(
679 void* in_ref_con, 810 void* in_ref_con,
680 AudioUnitRenderActionFlags* io_action_flags, 811 AudioUnitRenderActionFlags* io_action_flags,
681 const AudioTimeStamp* in_time_stamp, 812 const AudioTimeStamp* in_time_stamp,
682 UInt32 in_bus_number, 813 UInt32 in_bus_number,
683 UInt32 in_number_frames, 814 UInt32 in_number_frames,
684 AudioBufferList* io_data) { 815 AudioBufferList* io_data) {
685 RTC_DCHECK_EQ(1u, in_bus_number); 816 RTC_DCHECK_EQ(1u, in_bus_number);
686 RTC_DCHECK( 817 RTC_DCHECK(
687 !io_data); // no buffer should be allocated for input at this stage 818 !io_data); // no buffer should be allocated for input at this stage
688 AudioDeviceIOS* audio_device_ios = static_cast<AudioDeviceIOS*>(in_ref_con); 819 AudioDeviceIOS* audio_device_ios = static_cast<AudioDeviceIOS*>(in_ref_con);
689 return audio_device_ios->OnRecordedDataIsAvailable( 820 return audio_device_ios->OnRecordedDataIsAvailable(
690 io_action_flags, in_time_stamp, in_bus_number, in_number_frames); 821 io_action_flags, in_time_stamp, in_bus_number, in_number_frames);
691 } 822 }
692 823
693 OSStatus AudioDeviceIOS::OnRecordedDataIsAvailable( 824 OSStatus AudioDeviceIOS::OnRecordedDataIsAvailable(
694 AudioUnitRenderActionFlags* io_action_flags, 825 AudioUnitRenderActionFlags* io_action_flags,
695 const AudioTimeStamp* in_time_stamp, 826 const AudioTimeStamp* in_time_stamp,
696 UInt32 in_bus_number, 827 UInt32 in_bus_number,
697 UInt32 in_number_frames) { 828 UInt32 in_number_frames) {
698 RTC_DCHECK_EQ(record_parameters_.frames_per_buffer(), in_number_frames);
699 OSStatus result = noErr; 829 OSStatus result = noErr;
700 // Simply return if recording is not enabled. 830 // Simply return if recording is not enabled.
701 if (!rtc::AtomicOps::AcquireLoad(&recording_)) 831 if (!rtc::AtomicOps::AcquireLoad(&recording_))
702 return result; 832 return result;
703 RTC_DCHECK_EQ(record_parameters_.frames_per_buffer(), in_number_frames); 833 RTC_DCHECK_EQ(record_parameters_.frames_per_buffer(), in_number_frames);
704 // Obtain the recorded audio samples by initiating a rendering cycle. 834 // Obtain the recorded audio samples by initiating a rendering cycle.
705 // Since it happens on the input bus, the |io_data| parameter is a reference 835 // Since it happens on the input bus, the |io_data| parameter is a reference
706 // to the preallocated audio buffer list that the audio unit renders into. 836 // to the preallocated audio buffer list that the audio unit renders into.
707 // TODO(henrika): should error handling be improved? 837 // TODO(henrika): should error handling be improved?
708 AudioBufferList* io_data = &audio_record_buffer_list_; 838 AudioBufferList* io_data = &audio_record_buffer_list_;
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
760 // Read decoded 16-bit PCM samples from WebRTC (using a size that matches 890 // Read decoded 16-bit PCM samples from WebRTC (using a size that matches
761 // the native I/O audio unit) to a preallocated intermediate buffer and 891 // the native I/O audio unit) to a preallocated intermediate buffer and
762 // copy the result to the audio buffer in the |io_data| destination. 892 // copy the result to the audio buffer in the |io_data| destination.
763 SInt8* source = playout_audio_buffer_.get(); 893 SInt8* source = playout_audio_buffer_.get();
764 fine_audio_buffer_->GetPlayoutData(source); 894 fine_audio_buffer_->GetPlayoutData(source);
765 memcpy(destination, source, dataSizeInBytes); 895 memcpy(destination, source, dataSizeInBytes);
766 return noErr; 896 return noErr;
767 } 897 }
768 898
769 } // namespace webrtc 899 } // namespace webrtc
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698