summaryrefslogtreecommitdiffstats
path: root/media/audio/win/wavein_input_win.cc
blob: f4055dbb6d83482b4ef099ab1ce41e5bec72d977 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/audio/win/wavein_input_win.h"

#pragma comment(lib, "winmm.lib")

#include "base/logging.h"
#include "media/audio/audio_io.h"
#include "media/audio/audio_util.h"
#include "media/audio/win/audio_manager_win.h"
#include "media/audio/win/device_enumeration_win.h"

namespace {
const int kStopInputStreamCallbackTimeout = 3000;  // Three seconds.
}

using media::AudioDeviceNames;

// Our sound buffers are allocated once and kept in a linked list using the
// the WAVEHDR::dwUser variable. The last buffer points to the first buffer.
static WAVEHDR* GetNextBuffer(WAVEHDR* current) {
  return reinterpret_cast<WAVEHDR*>(current->dwUser);
}

PCMWaveInAudioInputStream::PCMWaveInAudioInputStream(
    AudioManagerWin* manager, const AudioParameters& params, int num_buffers,
    const std::string& device_id)
    : state_(kStateEmpty),
      manager_(manager),
      device_id_(device_id),
      wavein_(NULL),
      callback_(NULL),
      num_buffers_(num_buffers),
      buffer_(NULL),
      channels_(params.channels()) {
  format_.wFormatTag = WAVE_FORMAT_PCM;
  format_.nChannels = params.channels() > 2 ? 2 : params.channels();
  format_.nSamplesPerSec = params.sample_rate();
  format_.wBitsPerSample = params.bits_per_sample();
  format_.cbSize = 0;
  format_.nBlockAlign = (format_.nChannels * format_.wBitsPerSample) / 8;
  format_.nAvgBytesPerSec = format_.nBlockAlign * format_.nSamplesPerSec;
  buffer_size_ = params.frames_per_buffer() * format_.nBlockAlign;
  // If we don't have a packet size we use 100ms.
  if (!buffer_size_)
    buffer_size_ = format_.nAvgBytesPerSec / 10;
  // The event is auto-reset.
  stopped_event_.Set(::CreateEventW(NULL, FALSE, FALSE, NULL));
}

PCMWaveInAudioInputStream::~PCMWaveInAudioInputStream() {
  DCHECK(NULL == wavein_);
}

bool PCMWaveInAudioInputStream::Open() {
  if (state_ != kStateEmpty)
    return false;
  if (num_buffers_ < 2 || num_buffers_ > 10)
    return false;

  // Convert the stored device id string into an unsigned integer
  // corresponding to the selected device.
  UINT device_id = WAVE_MAPPER;
  if (!GetDeviceId(&device_id)) {
    return false;
  }

  // Open the specified input device for recording.
  MMRESULT result = MMSYSERR_NOERROR;
  result = ::waveInOpen(&wavein_, device_id, &format_,
                        reinterpret_cast<DWORD_PTR>(WaveCallback),
                        reinterpret_cast<DWORD_PTR>(this),
                        CALLBACK_FUNCTION);
  if (result != MMSYSERR_NOERROR)
    return false;

  SetupBuffers();
  state_ = kStateReady;
  return true;
}

void PCMWaveInAudioInputStream::SetupBuffers() {
  WAVEHDR* last = NULL;
  WAVEHDR* first = NULL;
  for (int ix = 0; ix != num_buffers_; ++ix) {
    uint32 sz = sizeof(WAVEHDR) + buffer_size_;
    buffer_ =  reinterpret_cast<WAVEHDR*>(new char[sz]);
    buffer_->lpData = reinterpret_cast<char*>(buffer_) + sizeof(WAVEHDR);
    buffer_->dwBufferLength = buffer_size_;
    buffer_->dwBytesRecorded = 0;
    buffer_->dwUser = reinterpret_cast<DWORD_PTR>(last);
    buffer_->dwFlags = WHDR_DONE;
    buffer_->dwLoops = 0;
    if (ix == 0)
      first = buffer_;
    last = buffer_;
    ::waveInPrepareHeader(wavein_, buffer_, sizeof(WAVEHDR));
  }
  // Fix the first buffer to point to the last one.
  first->dwUser = reinterpret_cast<DWORD_PTR>(last);
}

void PCMWaveInAudioInputStream::FreeBuffers() {
  WAVEHDR* current = buffer_;
  for (int ix = 0; ix != num_buffers_; ++ix) {
    WAVEHDR* next = GetNextBuffer(current);
    if (current->dwFlags & WHDR_PREPARED)
      ::waveInUnprepareHeader(wavein_, current, sizeof(WAVEHDR));
    delete[] reinterpret_cast<char*>(current);
    current = next;
  }
  buffer_ = NULL;
}

void PCMWaveInAudioInputStream::Start(AudioInputCallback* callback) {
  if (state_ != kStateReady)
    return;

  callback_ = callback;
  state_ = kStateRecording;

  WAVEHDR* buffer = buffer_;
  for (int ix = 0; ix != num_buffers_; ++ix) {
    QueueNextPacket(buffer);
    buffer = GetNextBuffer(buffer);
  }
  buffer = buffer_;

  MMRESULT result = ::waveInStart(wavein_);
  if (result != MMSYSERR_NOERROR) {
    HandleError(result);
    state_ = kStateReady;
  } else {
    manager_->IncreaseActiveInputStreamCount();
  }
}

// Stopping is tricky. First, no buffer should be locked by the audio driver
// or else the waveInReset() will deadlock and secondly, the callback should
// not be inside the AudioInputCallback's OnData because waveInReset()
// forcefully kills the callback thread.
void PCMWaveInAudioInputStream::Stop() {
  if (state_ != kStateRecording)
    return;
  state_ = kStateStopping;
  // Wait for the callback to finish, it will signal us when ready to be reset.
  if (WAIT_OBJECT_0 !=
      ::WaitForSingleObject(stopped_event_, kStopInputStreamCallbackTimeout)) {
    HandleError(::GetLastError());
    return;
  }
  // Stop is always called before Close. In case of error, this will be
  // also called when closing the input controller.
  manager_->DecreaseActiveInputStreamCount();

  state_ = kStateStopped;
  MMRESULT res = ::waveInReset(wavein_);
  if (res != MMSYSERR_NOERROR) {
    state_ = kStateRecording;
    HandleError(res);
    return;
  }
  state_ = kStateReady;
}

// We can Close in any state except that when trying to close a stream that is
// recording Windows generates an error, which we propagate to the source.
void PCMWaveInAudioInputStream::Close() {
  if (wavein_) {
    // waveInClose generates a callback with WIM_CLOSE id in the same thread.
    MMRESULT res = ::waveInClose(wavein_);
    if (res != MMSYSERR_NOERROR) {
      HandleError(res);
      return;
    }
    state_ = kStateClosed;
    wavein_ = NULL;
    FreeBuffers();
  }
  // Tell the audio manager that we have been released. This can result in
  // the manager destroying us in-place so this needs to be the last thing
  // we do on this function.
  manager_->ReleaseInputStream(this);
}

double PCMWaveInAudioInputStream::GetMaxVolume() {
  // TODO(henrika): Add volume support using the Audio Mixer API.
  return 0.0;
}

void PCMWaveInAudioInputStream::SetVolume(double volume) {
  // TODO(henrika): Add volume support using the Audio Mixer API.
}

double PCMWaveInAudioInputStream::GetVolume() {
  // TODO(henrika): Add volume support using the Audio Mixer API.
  return 0.0;
}

void PCMWaveInAudioInputStream::SetAutomaticGainControl(bool enabled) {
  // TODO(henrika): Add AGC support when volume control has been added.
  NOTIMPLEMENTED();
}

bool PCMWaveInAudioInputStream::GetAutomaticGainControl() {
  // TODO(henrika): Add AGC support when volume control has been added.
  NOTIMPLEMENTED();
  return false;
}

void PCMWaveInAudioInputStream::HandleError(MMRESULT error) {
  DLOG(WARNING) << "PCMWaveInAudio error " << error;
  callback_->OnError(this, error);
}

void PCMWaveInAudioInputStream::QueueNextPacket(WAVEHDR *buffer) {
  MMRESULT res = ::waveInAddBuffer(wavein_, buffer, sizeof(WAVEHDR));
  if (res != MMSYSERR_NOERROR)
    HandleError(res);
}

bool PCMWaveInAudioInputStream::GetDeviceId(UINT* device_index) {
  // Deliver the default input device id (WAVE_MAPPER) if the default
  // device has been selected.
  if (device_id_ == AudioManagerBase::kDefaultDeviceId) {
    *device_index = WAVE_MAPPER;
    return true;
  }

  // Get list of all available and active devices.
  AudioDeviceNames device_names;
  if (!media::GetInputDeviceNamesWinXP(&device_names))
    return false;

  if (device_names.empty())
    return false;

  // Search the full list of devices and compare with the specified
  // device id which was specified in the constructor. Stop comparing
  // when a match is found and return the corresponding index.
  UINT index = 0;
  bool found_device = false;
  AudioDeviceNames::const_iterator it = device_names.begin();
  while (it != device_names.end()) {
    if (it->unique_id.compare(device_id_) == 0) {
      *device_index = index;
      found_device = true;
      break;
    }
    ++index;
    ++it;
  }

  return found_device;
}

// Windows calls us back in this function when some events happen. Most notably
// when it has an audio buffer with recorded data.
void PCMWaveInAudioInputStream::WaveCallback(HWAVEIN hwi, UINT msg,
                                             DWORD_PTR instance,
                                             DWORD_PTR param1, DWORD_PTR) {
  PCMWaveInAudioInputStream* obj =
      reinterpret_cast<PCMWaveInAudioInputStream*>(instance);

  if (msg == WIM_DATA) {
    // WIM_DONE indicates that the driver is done with our buffer. We pass it
    // to the callback and check if we need to stop playing.
    // It should be OK to assume the data in the buffer is what has been
    // recorded in the soundcard.
    // TODO(henrika): the |volume| parameter is always set to zero since there
    // is currently no support for controlling the microphone volume level.
    WAVEHDR* buffer = reinterpret_cast<WAVEHDR*>(param1);
    obj->callback_->OnData(obj, reinterpret_cast<const uint8*>(buffer->lpData),
                           buffer->dwBytesRecorded,
                           buffer->dwBytesRecorded,
                           0.0);

    if (obj->state_ == kStateStopping) {
      // The main thread has called Stop() and is waiting to issue waveOutReset
      // which will kill this thread. We should not enter AudioSourceCallback
      // code anymore.
      ::SetEvent(obj->stopped_event_);
    } else if (obj->state_ == kStateStopped) {
      // Not sure if ever hit this but just in case.
    } else {
      // Queue the finished buffer back with the audio driver. Since we are
      // reusing the same buffers we can get away without calling
      // waveInPrepareHeader.
      obj->QueueNextPacket(buffer);
    }
  } else if (msg == WIM_CLOSE) {
    // We can be closed before calling Start, so it is possible to have a
    // null callback at this point.
    if (obj->callback_)
      obj->callback_->OnClose(obj);
  }
}