Separate Simple Backend creation from initialization.
[chromium-blink-merge.git] / media / audio / win / wavein_input_win.cc
blobe561ab4a5005bde874007459d37f15ced4974620
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/win/wavein_input_win.h"
7 #pragma comment(lib, "winmm.lib")
9 #include "base/logging.h"
10 #include "media/audio/audio_io.h"
11 #include "media/audio/audio_util.h"
12 #include "media/audio/win/audio_manager_win.h"
13 #include "media/audio/win/device_enumeration_win.h"
15 namespace media {
17 // Our sound buffers are allocated once and kept in a linked list using the
18 // the WAVEHDR::dwUser variable. The last buffer points to the first buffer.
19 static WAVEHDR* GetNextBuffer(WAVEHDR* current) {
20 return reinterpret_cast<WAVEHDR*>(current->dwUser);
23 PCMWaveInAudioInputStream::PCMWaveInAudioInputStream(
24 AudioManagerWin* manager, const AudioParameters& params, int num_buffers,
25 const std::string& device_id)
26 : state_(kStateEmpty),
27 manager_(manager),
28 device_id_(device_id),
29 wavein_(NULL),
30 callback_(NULL),
31 num_buffers_(num_buffers),
32 buffer_(NULL),
33 channels_(params.channels()) {
34 DCHECK_GT(num_buffers_, 0);
35 format_.wFormatTag = WAVE_FORMAT_PCM;
36 format_.nChannels = params.channels() > 2 ? 2 : params.channels();
37 format_.nSamplesPerSec = params.sample_rate();
38 format_.wBitsPerSample = params.bits_per_sample();
39 format_.cbSize = 0;
40 format_.nBlockAlign = (format_.nChannels * format_.wBitsPerSample) / 8;
41 format_.nAvgBytesPerSec = format_.nBlockAlign * format_.nSamplesPerSec;
42 buffer_size_ = params.frames_per_buffer() * format_.nBlockAlign;
43 // If we don't have a packet size we use 100ms.
44 if (!buffer_size_)
45 buffer_size_ = format_.nAvgBytesPerSec / 10;
46 // The event is auto-reset.
47 stopped_event_.Set(::CreateEventW(NULL, FALSE, FALSE, NULL));
50 PCMWaveInAudioInputStream::~PCMWaveInAudioInputStream() {
51 DCHECK(NULL == wavein_);
54 bool PCMWaveInAudioInputStream::Open() {
55 DCHECK(thread_checker_.CalledOnValidThread());
56 if (state_ != kStateEmpty)
57 return false;
58 if (num_buffers_ < 2 || num_buffers_ > 10)
59 return false;
61 // Convert the stored device id string into an unsigned integer
62 // corresponding to the selected device.
63 UINT device_id = WAVE_MAPPER;
64 if (!GetDeviceId(&device_id)) {
65 return false;
68 // Open the specified input device for recording.
69 MMRESULT result = MMSYSERR_NOERROR;
70 result = ::waveInOpen(&wavein_, device_id, &format_,
71 reinterpret_cast<DWORD_PTR>(WaveCallback),
72 reinterpret_cast<DWORD_PTR>(this),
73 CALLBACK_FUNCTION);
74 if (result != MMSYSERR_NOERROR)
75 return false;
77 SetupBuffers();
78 state_ = kStateReady;
79 return true;
82 void PCMWaveInAudioInputStream::SetupBuffers() {
83 WAVEHDR* last = NULL;
84 WAVEHDR* first = NULL;
85 for (int ix = 0; ix != num_buffers_; ++ix) {
86 uint32 sz = sizeof(WAVEHDR) + buffer_size_;
87 buffer_ = reinterpret_cast<WAVEHDR*>(new char[sz]);
88 buffer_->lpData = reinterpret_cast<char*>(buffer_) + sizeof(WAVEHDR);
89 buffer_->dwBufferLength = buffer_size_;
90 buffer_->dwBytesRecorded = 0;
91 buffer_->dwUser = reinterpret_cast<DWORD_PTR>(last);
92 buffer_->dwFlags = WHDR_DONE;
93 buffer_->dwLoops = 0;
94 if (ix == 0)
95 first = buffer_;
96 last = buffer_;
97 ::waveInPrepareHeader(wavein_, buffer_, sizeof(WAVEHDR));
99 // Fix the first buffer to point to the last one.
100 first->dwUser = reinterpret_cast<DWORD_PTR>(last);
103 void PCMWaveInAudioInputStream::FreeBuffers() {
104 WAVEHDR* current = buffer_;
105 for (int ix = 0; ix != num_buffers_; ++ix) {
106 WAVEHDR* next = GetNextBuffer(current);
107 if (current->dwFlags & WHDR_PREPARED)
108 ::waveInUnprepareHeader(wavein_, current, sizeof(WAVEHDR));
109 delete[] reinterpret_cast<char*>(current);
110 current = next;
112 buffer_ = NULL;
115 void PCMWaveInAudioInputStream::Start(AudioInputCallback* callback) {
116 DCHECK(thread_checker_.CalledOnValidThread());
117 if (state_ != kStateReady)
118 return;
120 DCHECK(!callback_);
121 callback_ = callback;
122 state_ = kStateRecording;
124 WAVEHDR* buffer = buffer_;
125 for (int ix = 0; ix != num_buffers_; ++ix) {
126 QueueNextPacket(buffer);
127 buffer = GetNextBuffer(buffer);
129 buffer = buffer_;
131 MMRESULT result = ::waveInStart(wavein_);
132 if (result != MMSYSERR_NOERROR) {
133 HandleError(result);
134 state_ = kStateReady;
135 callback_ = NULL;
136 } else {
137 manager_->IncreaseActiveInputStreamCount();
141 // Stopping is tricky. First, no buffer should be locked by the audio driver
142 // or else the waveInReset() will deadlock and secondly, the callback should
143 // not be inside the AudioInputCallback's OnData because waveInReset()
144 // forcefully kills the callback thread.
145 void PCMWaveInAudioInputStream::Stop() {
146 DVLOG(1) << "PCMWaveInAudioInputStream::Stop()";
147 DCHECK(thread_checker_.CalledOnValidThread());
148 if (state_ != kStateRecording)
149 return;
151 bool already_stopped = false;
153 // Tell the callback that we're stopping.
154 // As a result, |stopped_event_| will be signaled in callback method.
155 base::AutoLock auto_lock(lock_);
156 already_stopped = (callback_ == NULL);
157 callback_ = NULL;
160 if (already_stopped)
161 return;
163 // Wait for the callback to finish, it will signal us when ready to be reset.
164 DWORD wait = ::WaitForSingleObject(stopped_event_, INFINITE);
165 DCHECK_EQ(wait, WAIT_OBJECT_0);
167 // Stop input and reset the current position to zero for |wavein_|.
168 // All pending buffers are marked as done and returned to the application.
169 MMRESULT res = ::waveInReset(wavein_);
170 DCHECK_EQ(res, static_cast<MMRESULT>(MMSYSERR_NOERROR));
172 state_ = kStateReady;
173 manager_->DecreaseActiveInputStreamCount();
176 void PCMWaveInAudioInputStream::Close() {
177 DVLOG(1) << "PCMWaveInAudioInputStream::Close()";
178 DCHECK(thread_checker_.CalledOnValidThread());
180 // We should not call Close() while recording. Catch it with DCHECK and
181 // implement auto-stop just in case.
182 DCHECK_NE(state_, kStateRecording);
183 Stop();
185 if (wavein_) {
186 FreeBuffers();
188 // waveInClose() generates a WIM_CLOSE callback. In case Start() was never
189 // called, force a reset to ensure close succeeds.
190 MMRESULT res = ::waveInReset(wavein_);
191 DCHECK_EQ(res, static_cast<MMRESULT>(MMSYSERR_NOERROR));
192 res = ::waveInClose(wavein_);
193 DCHECK_EQ(res, static_cast<MMRESULT>(MMSYSERR_NOERROR));
194 state_ = kStateClosed;
195 wavein_ = NULL;
198 // Tell the audio manager that we have been released. This can result in
199 // the manager destroying us in-place so this needs to be the last thing
200 // we do on this function.
201 manager_->ReleaseInputStream(this);
204 double PCMWaveInAudioInputStream::GetMaxVolume() {
205 // TODO(henrika): Add volume support using the Audio Mixer API.
206 return 0.0;
209 void PCMWaveInAudioInputStream::SetVolume(double volume) {
210 // TODO(henrika): Add volume support using the Audio Mixer API.
213 double PCMWaveInAudioInputStream::GetVolume() {
214 // TODO(henrika): Add volume support using the Audio Mixer API.
215 return 0.0;
218 void PCMWaveInAudioInputStream::SetAutomaticGainControl(bool enabled) {
219 // TODO(henrika): Add AGC support when volume control has been added.
220 NOTIMPLEMENTED();
223 bool PCMWaveInAudioInputStream::GetAutomaticGainControl() {
224 // TODO(henrika): Add AGC support when volume control has been added.
225 NOTIMPLEMENTED();
226 return false;
229 void PCMWaveInAudioInputStream::HandleError(MMRESULT error) {
230 DLOG(WARNING) << "PCMWaveInAudio error " << error;
231 callback_->OnError(this);
234 void PCMWaveInAudioInputStream::QueueNextPacket(WAVEHDR *buffer) {
235 MMRESULT res = ::waveInAddBuffer(wavein_, buffer, sizeof(WAVEHDR));
236 if (res != MMSYSERR_NOERROR)
237 HandleError(res);
240 bool PCMWaveInAudioInputStream::GetDeviceId(UINT* device_index) {
241 // Deliver the default input device id (WAVE_MAPPER) if the default
242 // device has been selected.
243 if (device_id_ == AudioManagerBase::kDefaultDeviceId) {
244 *device_index = WAVE_MAPPER;
245 return true;
248 // Get list of all available and active devices.
249 AudioDeviceNames device_names;
250 if (!media::GetInputDeviceNamesWinXP(&device_names))
251 return false;
253 if (device_names.empty())
254 return false;
256 // Search the full list of devices and compare with the specified
257 // device id which was specified in the constructor. Stop comparing
258 // when a match is found and return the corresponding index.
259 UINT index = 0;
260 bool found_device = false;
261 AudioDeviceNames::const_iterator it = device_names.begin();
262 while (it != device_names.end()) {
263 if (it->unique_id.compare(device_id_) == 0) {
264 *device_index = index;
265 found_device = true;
266 break;
268 ++index;
269 ++it;
272 return found_device;
275 // Windows calls us back in this function when some events happen. Most notably
276 // when it has an audio buffer with recorded data.
277 void PCMWaveInAudioInputStream::WaveCallback(HWAVEIN hwi, UINT msg,
278 DWORD_PTR instance,
279 DWORD_PTR param1, DWORD_PTR) {
280 PCMWaveInAudioInputStream* obj =
281 reinterpret_cast<PCMWaveInAudioInputStream*>(instance);
283 // The lock ensures that Stop() can't be called during a callback.
284 base::AutoLock auto_lock(obj->lock_);
286 if (msg == WIM_DATA) {
287 // The WIM_DATA message is sent when waveform-audio data is present in
288 // the input buffer and the buffer is being returned to the application.
289 // The message can be sent when the buffer is full or after the
290 // waveInReset function is called.
291 if (obj->callback_) {
292 // TODO(henrika): the |volume| parameter is always set to zero since
293 // there is currently no support for controlling the microphone volume
294 // level.
295 WAVEHDR* buffer = reinterpret_cast<WAVEHDR*>(param1);
296 obj->callback_->OnData(obj,
297 reinterpret_cast<const uint8*>(buffer->lpData),
298 buffer->dwBytesRecorded,
299 buffer->dwBytesRecorded,
300 0.0);
302 // Queue the finished buffer back with the audio driver. Since we are
303 // reusing the same buffers we can get away without calling
304 // waveInPrepareHeader.
305 obj->QueueNextPacket(buffer);
306 } else {
307 // Main thread has called Stop() and set |callback_| to NULL and is
308 // now waiting to issue waveInReset which will kill this thread.
309 // We should not call AudioSourceCallback code anymore.
310 ::SetEvent(obj->stopped_event_);
312 } else if (msg == WIM_CLOSE) {
313 // Intentionaly no-op for now.
314 } else if (msg == WIM_OPEN) {
315 // Intentionaly no-op for now.
319 } // namespace media