1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/audio/mac/audio_input_mac.h"
7 #include <CoreServices/CoreServices.h>
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "base/mac/mac_logging.h"
12 #include "media/audio/mac/audio_manager_mac.h"
13 #include "media/base/audio_bus.h"
17 PCMQueueInAudioInputStream::PCMQueueInAudioInputStream(
18 AudioManagerMac
* manager
,
19 const AudioParameters
& params
)
23 buffer_size_bytes_(0),
25 audio_bus_(media::AudioBus::Create(params
)) {
26 // We must have a manager.
28 // A frame is one sample across all channels. In interleaved audio the per
29 // frame fields identify the set of n |channels|. In uncompressed audio, a
30 // packet is always one frame.
31 format_
.mSampleRate
= params
.sample_rate();
32 format_
.mFormatID
= kAudioFormatLinearPCM
;
33 format_
.mFormatFlags
= kLinearPCMFormatFlagIsPacked
|
34 kLinearPCMFormatFlagIsSignedInteger
;
35 format_
.mBitsPerChannel
= params
.bits_per_sample();
36 format_
.mChannelsPerFrame
= params
.channels();
37 format_
.mFramesPerPacket
= 1;
38 format_
.mBytesPerPacket
= (params
.bits_per_sample() * params
.channels()) / 8;
39 format_
.mBytesPerFrame
= format_
.mBytesPerPacket
;
40 format_
.mReserved
= 0;
42 buffer_size_bytes_
= params
.GetBytesPerBuffer();
45 PCMQueueInAudioInputStream::~PCMQueueInAudioInputStream() {
47 DCHECK(!audio_queue_
);
50 bool PCMQueueInAudioInputStream::Open() {
51 OSStatus err
= AudioQueueNewInput(&format_
,
52 &HandleInputBufferStatic
,
54 NULL
, // Use OS CFRunLoop for |callback|
55 kCFRunLoopCommonModes
,
62 return SetupBuffers();
65 void PCMQueueInAudioInputStream::Start(AudioInputCallback
* callback
) {
67 DLOG_IF(ERROR
, !audio_queue_
) << "Open() has not been called successfully";
68 if (callback_
|| !audio_queue_
)
71 // Check if we should defer Start() for http://crbug.com/160920.
72 if (manager_
->ShouldDeferStreamStart()) {
73 // Use a cancellable closure so that if Stop() is called before Start()
74 // actually runs, we can cancel the pending start.
75 deferred_start_cb_
.Reset(base::Bind(
76 &PCMQueueInAudioInputStream::Start
, base::Unretained(this), callback
));
77 manager_
->GetTaskRunner()->PostDelayedTask(
79 deferred_start_cb_
.callback(),
80 base::TimeDelta::FromSeconds(
81 AudioManagerMac::kStartDelayInSecsForPowerEvents
));
86 OSStatus err
= AudioQueueStart(audio_queue_
, NULL
);
94 void PCMQueueInAudioInputStream::Stop() {
95 deferred_start_cb_
.Cancel();
96 if (!audio_queue_
|| !started_
)
99 // We request a synchronous stop, so the next call can take some time. In
100 // the windows implementation we block here as well.
101 OSStatus err
= AudioQueueStop(audio_queue_
, true);
109 void PCMQueueInAudioInputStream::Close() {
112 // It is valid to call Close() before calling Open() or Start(), thus
113 // |audio_queue_| and |callback_| might be NULL.
115 OSStatus err
= AudioQueueDispose(audio_queue_
, true);
121 manager_
->ReleaseInputStream(this);
122 // CARE: This object may now be destroyed.
125 double PCMQueueInAudioInputStream::GetMaxVolume() {
126 NOTREACHED() << "Only supported for low-latency mode.";
130 void PCMQueueInAudioInputStream::SetVolume(double volume
) {
131 NOTREACHED() << "Only supported for low-latency mode.";
134 double PCMQueueInAudioInputStream::GetVolume() {
135 NOTREACHED() << "Only supported for low-latency mode.";
139 bool PCMQueueInAudioInputStream::IsMuted() {
140 NOTREACHED() << "Only supported for low-latency mode.";
144 bool PCMQueueInAudioInputStream::SetAutomaticGainControl(bool enabled
) {
145 NOTREACHED() << "Only supported for low-latency mode.";
149 bool PCMQueueInAudioInputStream::GetAutomaticGainControl() {
150 NOTREACHED() << "Only supported for low-latency mode.";
154 void PCMQueueInAudioInputStream::HandleError(OSStatus err
) {
156 callback_
->OnError(this);
157 // This point should never be reached.
158 OSSTATUS_DCHECK(0, err
);
161 bool PCMQueueInAudioInputStream::SetupBuffers() {
162 DCHECK(buffer_size_bytes_
);
163 for (int i
= 0; i
< kNumberBuffers
; ++i
) {
164 AudioQueueBufferRef buffer
;
165 OSStatus err
= AudioQueueAllocateBuffer(audio_queue_
,
169 err
= QueueNextBuffer(buffer
);
174 // |buffer| will automatically be freed when |audio_queue_| is released.
179 OSStatus
PCMQueueInAudioInputStream::QueueNextBuffer(
180 AudioQueueBufferRef audio_buffer
) {
181 // Only the first 2 params are needed for recording.
182 return AudioQueueEnqueueBuffer(audio_queue_
, audio_buffer
, 0, NULL
);
186 void PCMQueueInAudioInputStream::HandleInputBufferStatic(
188 AudioQueueRef audio_queue
,
189 AudioQueueBufferRef audio_buffer
,
190 const AudioTimeStamp
* start_time
,
192 const AudioStreamPacketDescription
* desc
) {
193 reinterpret_cast<PCMQueueInAudioInputStream
*>(data
)->
194 HandleInputBuffer(audio_queue
, audio_buffer
, start_time
,
198 void PCMQueueInAudioInputStream::HandleInputBuffer(
199 AudioQueueRef audio_queue
,
200 AudioQueueBufferRef audio_buffer
,
201 const AudioTimeStamp
* start_time
,
203 const AudioStreamPacketDescription
* packet_desc
) {
204 DCHECK_EQ(audio_queue_
, audio_queue
);
205 DCHECK(audio_buffer
->mAudioData
);
207 // This can happen if Stop() was called without start.
208 DCHECK_EQ(0U, audio_buffer
->mAudioDataByteSize
);
212 if (audio_buffer
->mAudioDataByteSize
) {
213 // The AudioQueue API may use a large internal buffer and repeatedly call us
214 // back to back once that internal buffer is filled. When this happens the
215 // renderer client does not have enough time to read data back from the
216 // shared memory before the next write comes along. If HandleInputBuffer()
217 // is called too frequently, Sleep() at least 5ms to ensure the shared
218 // memory doesn't get trampled.
219 // TODO(dalecurtis): This is a HACK. Long term the AudioQueue path is going
220 // away in favor of the AudioUnit based AUAudioInputStream(). Tracked by
221 // http://crbug.com/161383.
222 base::TimeDelta elapsed
= base::TimeTicks::Now() - last_fill_
;
223 const base::TimeDelta kMinDelay
= base::TimeDelta::FromMilliseconds(5);
224 if (elapsed
< kMinDelay
)
225 base::PlatformThread::Sleep(kMinDelay
- elapsed
);
227 uint8
* audio_data
= reinterpret_cast<uint8
*>(audio_buffer
->mAudioData
);
228 audio_bus_
->FromInterleaved(
229 audio_data
, audio_bus_
->frames(), format_
.mBitsPerChannel
/ 8);
231 this, audio_bus_
.get(), audio_buffer
->mAudioDataByteSize
, 0.0);
233 last_fill_
= base::TimeTicks::Now();
235 // Recycle the buffer.
236 OSStatus err
= QueueNextBuffer(audio_buffer
);
238 if (err
== kAudioQueueErr_EnqueueDuringReset
) {
239 // This is the error you get if you try to enqueue a buffer and the
240 // queue has been closed. Not really a problem if indeed the queue
242 // TODO(joth): PCMQueueOutAudioOutputStream uses callback_ to provide an
243 // extra guard for this situation, but it seems to introduce more
244 // complications than it solves (memory barrier issues accessing it from
245 // multiple threads, looses the means to indicate OnClosed to client).
246 // Should determine if we need to do something equivalent here.