waveout_output_win.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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.
4
5#include "media/audio/win/waveout_output_win.h"
6
7#include <windows.h>
8#include <mmsystem.h>
9#pragma comment(lib, "winmm.lib")
10
11#include "base/basictypes.h"
12#include "base/debug/trace_event.h"
13#include "base/logging.h"
14#include "media/audio/audio_io.h"
15#include "media/audio/audio_util.h"
16#include "media/audio/win/audio_manager_win.h"
17
18namespace media {
19
20// Some general thoughts about the waveOut API which is badly documented :
21// - We use CALLBACK_EVENT mode in which XP signals events such as buffer
22//   releases.
23// - We use RegisterWaitForSingleObject() so one of threads in thread pool
24//   automatically calls our callback that feeds more data to Windows.
25// - Windows does not provide a way to query if the device is playing or paused
26//   thus it forces you to maintain state, which naturally is not exactly
27//   synchronized to the actual device state.
28
29// Sixty four MB is the maximum buffer size per AudioOutputStream.
30static const uint32 kMaxOpenBufferSize = 1024 * 1024 * 64;
31
32// See Also
33// http://www.thx.com/consumer/home-entertainment/home-theater/surround-sound-speaker-set-up/
34// http://en.wikipedia.org/wiki/Surround_sound
35
36static const int kMaxChannelsToMask = 8;
37static const unsigned int kChannelsToMask[kMaxChannelsToMask + 1] = {
38  0,
39  // 1 = Mono
40  SPEAKER_FRONT_CENTER,
41  // 2 = Stereo
42  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT,
43  // 3 = Stereo + Center
44  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER,
45  // 4 = Quad
46  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT |
47  SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT,
48  // 5 = 5.0
49  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER |
50  SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT,
51  // 6 = 5.1
52  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT |
53  SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |
54  SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT,
55  // 7 = 6.1
56  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT |
57  SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |
58  SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |
59  SPEAKER_BACK_CENTER,
60  // 8 = 7.1
61  SPEAKER_FRONT_LEFT  | SPEAKER_FRONT_RIGHT |
62  SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |
63  SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |
64  SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT
65  // TODO(fbarchard): Add additional masks for 7.2 and beyond.
66};
67
68inline size_t PCMWaveOutAudioOutputStream::BufferSize() const {
69  // Round size of buffer up to the nearest 16 bytes.
70  return (sizeof(WAVEHDR) + buffer_size_ + 15u) & static_cast<size_t>(~15);
71}
72
73inline WAVEHDR* PCMWaveOutAudioOutputStream::GetBuffer(int n) const {
74  DCHECK_GE(n, 0);
75  DCHECK_LT(n, num_buffers_);
76  return reinterpret_cast<WAVEHDR*>(&buffers_[n * BufferSize()]);
77}
78
79
80PCMWaveOutAudioOutputStream::PCMWaveOutAudioOutputStream(
81    AudioManagerWin* manager, const AudioParameters& params, int num_buffers,
82    UINT device_id)
83    : state_(PCMA_BRAND_NEW),
84      manager_(manager),
85      device_id_(device_id),
86      waveout_(NULL),
87      callback_(NULL),
88      num_buffers_(num_buffers),
89      buffer_size_(params.GetBytesPerBuffer()),
90      volume_(1),
91      channels_(params.channels()),
92      pending_bytes_(0),
93      waiting_handle_(NULL),
94      audio_bus_(AudioBus::Create(params)) {
95  format_.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
96  format_.Format.nChannels = params.channels();
97  format_.Format.nSamplesPerSec = params.sample_rate();
98  format_.Format.wBitsPerSample = params.bits_per_sample();
99  format_.Format.cbSize = sizeof(format_) - sizeof(WAVEFORMATEX);
100  // The next are computed from above.
101  format_.Format.nBlockAlign = (format_.Format.nChannels *
102                                format_.Format.wBitsPerSample) / 8;
103  format_.Format.nAvgBytesPerSec = format_.Format.nBlockAlign *
104                                   format_.Format.nSamplesPerSec;
105  if (params.channels() > kMaxChannelsToMask) {
106    format_.dwChannelMask = kChannelsToMask[kMaxChannelsToMask];
107  } else {
108    format_.dwChannelMask = kChannelsToMask[params.channels()];
109  }
110  format_.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
111  format_.Samples.wValidBitsPerSample = params.bits_per_sample();
112}
113
114PCMWaveOutAudioOutputStream::~PCMWaveOutAudioOutputStream() {
115  DCHECK(NULL == waveout_);
116}
117
118bool PCMWaveOutAudioOutputStream::Open() {
119  if (state_ != PCMA_BRAND_NEW)
120    return false;
121  if (BufferSize() * num_buffers_ > kMaxOpenBufferSize)
122    return false;
123  if (num_buffers_ < 2 || num_buffers_ > 5)
124    return false;
125
126  // Create buffer event.
127  buffer_event_.Set(::CreateEvent(NULL,    // Security attributes.
128                                  FALSE,   // It will auto-reset.
129                                  FALSE,   // Initial state.
130                                  NULL));  // No name.
131  if (!buffer_event_.Get())
132    return false;
133
134  // Open the device.
135  // We'll be getting buffer_event_ events when it's time to refill the buffer.
136  MMRESULT result = ::waveOutOpen(
137      &waveout_,
138      device_id_,
139      reinterpret_cast<LPCWAVEFORMATEX>(&format_),
140      reinterpret_cast<DWORD_PTR>(buffer_event_.Get()),
141      NULL,
142      CALLBACK_EVENT);
143  if (result != MMSYSERR_NOERROR)
144    return false;
145
146  SetupBuffers();
147  state_ = PCMA_READY;
148  return true;
149}
150
151void PCMWaveOutAudioOutputStream::SetupBuffers() {
152  buffers_.reset(new char[BufferSize() * num_buffers_]);
153  for (int ix = 0; ix != num_buffers_; ++ix) {
154    WAVEHDR* buffer = GetBuffer(ix);
155    buffer->lpData = reinterpret_cast<char*>(buffer) + sizeof(WAVEHDR);
156    buffer->dwBufferLength = buffer_size_;
157    buffer->dwBytesRecorded = 0;
158    buffer->dwFlags = WHDR_DONE;
159    buffer->dwLoops = 0;
160    // Tell windows sound drivers about our buffers. Not documented what
161    // this does but we can guess that causes the OS to keep a reference to
162    // the memory pages so the driver can use them without worries.
163    ::waveOutPrepareHeader(waveout_, buffer, sizeof(WAVEHDR));
164  }
165}
166
167void PCMWaveOutAudioOutputStream::FreeBuffers() {
168  for (int ix = 0; ix != num_buffers_; ++ix) {
169    ::waveOutUnprepareHeader(waveout_, GetBuffer(ix), sizeof(WAVEHDR));
170  }
171  buffers_.reset(NULL);
172}
173
174// Initially we ask the source to fill up all audio buffers. If we don't do
175// this then we would always get the driver callback when it is about to run
176// samples and that would leave too little time to react.
177void PCMWaveOutAudioOutputStream::Start(AudioSourceCallback* callback) {
178  if (state_ != PCMA_READY)
179    return;
180  callback_ = callback;
181
182  // Reset buffer event, it can be left in the arbitrary state if we
183  // previously stopped the stream. Can happen because we are stopping
184  // callbacks before stopping playback itself.
185  if (!::ResetEvent(buffer_event_.Get())) {
186    HandleError(MMSYSERR_ERROR);
187    return;
188  }
189
190  // Start watching for buffer events.
191  if (!::RegisterWaitForSingleObject(&waiting_handle_,
192                                     buffer_event_.Get(),
193                                     &BufferCallback,
194                                     this,
195                                     INFINITE,
196                                     WT_EXECUTEDEFAULT)) {
197    HandleError(MMSYSERR_ERROR);
198    waiting_handle_ = NULL;
199    return;
200  }
201
202  state_ = PCMA_PLAYING;
203
204  // Queue the buffers.
205  pending_bytes_ = 0;
206  for (int ix = 0; ix != num_buffers_; ++ix) {
207    WAVEHDR* buffer = GetBuffer(ix);
208    // Caller waits for 1st packet to become available, but not for others,
209    // so we wait for them here.
210    if (ix != 0)
211      callback_->WaitTillDataReady();
212    QueueNextPacket(buffer);  // Read more data.
213    pending_bytes_ += buffer->dwBufferLength;
214  }
215
216  // From now on |pending_bytes_| would be accessed by callback thread.
217  // Most likely waveOutPause() or waveOutRestart() has its own memory barrier,
218  // but issuing our own is safer.
219  MemoryBarrier();
220
221  MMRESULT result = ::waveOutPause(waveout_);
222  if (result != MMSYSERR_NOERROR) {
223    HandleError(result);
224    return;
225  }
226
227  // Send the buffers to the audio driver. Note that the device is paused
228  // so we avoid entering the callback method while still here.
229  for (int ix = 0; ix != num_buffers_; ++ix) {
230    result = ::waveOutWrite(waveout_, GetBuffer(ix), sizeof(WAVEHDR));
231    if (result != MMSYSERR_NOERROR) {
232      HandleError(result);
233      break;
234    }
235  }
236  result = ::waveOutRestart(waveout_);
237  if (result != MMSYSERR_NOERROR) {
238    HandleError(result);
239    return;
240  }
241}
242
243// Stopping is tricky if we want it be fast.
244// For now just do it synchronously and avoid all the complexities.
245// TODO(enal): if we want faster Stop() we can create singleton that keeps track
246//             of all currently playing streams. Then you don't have to wait
247//             till all callbacks are completed. Of course access to singleton
248//             should be under its own lock, and checking the liveness and
249//             acquiring the lock on stream should be done atomically.
250void PCMWaveOutAudioOutputStream::Stop() {
251  if (state_ != PCMA_PLAYING)
252    return;
253  state_ = PCMA_STOPPING;
254  MemoryBarrier();
255
256  // Stop watching for buffer event, wait till all the callbacks are complete.
257  // Should be done before ::waveOutReset() call to avoid race condition when
258  // callback that is currently active and already checked that stream is still
259  // being played calls ::waveOutWrite() after ::waveOutReset() returns, later
260  // causing ::waveOutClose() to fail with WAVERR_STILLPLAYING.
261  // TODO(enal): that delays actual stopping of playback. Alternative can be
262  //             to call ::waveOutReset() twice, once before
263  //             ::UnregisterWaitEx() and once after.
264  if (waiting_handle_) {
265    if (!::UnregisterWaitEx(waiting_handle_, INVALID_HANDLE_VALUE)) {
266      state_ = PCMA_PLAYING;
267      HandleError(MMSYSERR_ERROR);
268      return;
269    }
270    waiting_handle_ = NULL;
271  }
272
273  // Stop playback.
274  MMRESULT res = ::waveOutReset(waveout_);
275  if (res != MMSYSERR_NOERROR) {
276    state_ = PCMA_PLAYING;
277    HandleError(res);
278    return;
279  }
280
281  // waveOutReset() leaves buffers in the unpredictable state, causing
282  // problems if we want to close, release, or reuse them. Fix the states.
283  for (int ix = 0; ix != num_buffers_; ++ix) {
284    GetBuffer(ix)->dwFlags = WHDR_PREPARED;
285  }
286
287  // Don't use callback after Stop().
288  callback_ = NULL;
289
290  state_ = PCMA_READY;
291}
292
293// We can Close in any state except that trying to close a stream that is
294// playing Windows generates an error. We cannot propagate it to the source,
295// as callback_ is set to NULL. Just print it and hope somebody somehow
296// will find it...
297void PCMWaveOutAudioOutputStream::Close() {
298  Stop();  // Just to be sure. No-op if not playing.
299  if (waveout_) {
300    MMRESULT result = ::waveOutClose(waveout_);
301    // If ::waveOutClose() fails we cannot just delete the stream, callback
302    // may try to access it and would crash. Better to leak the stream.
303    if (result != MMSYSERR_NOERROR) {
304      HandleError(result);
305      state_ = PCMA_PLAYING;
306      return;
307    }
308    state_ = PCMA_CLOSED;
309    waveout_ = NULL;
310    FreeBuffers();
311  }
312  // Tell the audio manager that we have been released. This can result in
313  // the manager destroying us in-place so this needs to be the last thing
314  // we do on this function.
315  manager_->ReleaseOutputStream(this);
316}
317
318void PCMWaveOutAudioOutputStream::SetVolume(double volume) {
319  if (!waveout_)
320    return;
321  volume_ = static_cast<float>(volume);
322}
323
324void PCMWaveOutAudioOutputStream::GetVolume(double* volume) {
325  if (!waveout_)
326    return;
327  *volume = volume_;
328}
329
330void PCMWaveOutAudioOutputStream::HandleError(MMRESULT error) {
331  DLOG(WARNING) << "PCMWaveOutAudio error " << error;
332  if (callback_)
333    callback_->OnError(this, error);
334}
335
336void PCMWaveOutAudioOutputStream::QueueNextPacket(WAVEHDR *buffer) {
337  DCHECK_EQ(channels_, format_.Format.nChannels);
338  // Call the source which will fill our buffer with pleasant sounds and
339  // return to us how many bytes were used.
340  // TODO(fbarchard): Handle used 0 by queueing more.
341
342  // TODO(sergeyu): Specify correct hardware delay for AudioBuffersState.
343  int frames_filled = callback_->OnMoreData(
344      audio_bus_.get(), AudioBuffersState(pending_bytes_, 0));
345  uint32 used = frames_filled * audio_bus_->channels() *
346      format_.Format.wBitsPerSample / 8;
347
348  if (used <= buffer_size_) {
349    // Note: If this ever changes to output raw float the data must be clipped
350    // and sanitized since it may come from an untrusted source such as NaCl.
351    audio_bus_->ToInterleaved(
352        frames_filled, format_.Format.wBitsPerSample / 8, buffer->lpData);
353
354    buffer->dwBufferLength = used * format_.Format.nChannels / channels_;
355    media::AdjustVolume(buffer->lpData, used,
356                        format_.Format.nChannels,
357                        format_.Format.wBitsPerSample >> 3,
358                        volume_);
359  } else {
360    HandleError(0);
361    return;
362  }
363  buffer->dwFlags = WHDR_PREPARED;
364}
365
366// One of the threads in our thread pool asynchronously calls this function when
367// buffer_event_ is signalled. Search through all the buffers looking for freed
368// ones, fills them with data, and "feed" the Windows.
369// Note: by searching through all the buffers we guarantee that we fill all the
370//       buffers, even when "event loss" happens, i.e. if Windows signals event
371//       when it did not flip into unsignaled state from the previous signal.
372void NTAPI PCMWaveOutAudioOutputStream::BufferCallback(PVOID lpParameter,
373                                                       BOOLEAN timer_fired) {
374  TRACE_EVENT0("audio", "PCMWaveOutAudioOutputStream::BufferCallback");
375
376  DCHECK(!timer_fired);
377  PCMWaveOutAudioOutputStream* stream =
378      reinterpret_cast<PCMWaveOutAudioOutputStream*>(lpParameter);
379
380  // Lock the stream so callbacks do not interfere with each other.
381  // Several callbacks can be called simultaneously by different threads in the
382  // thread pool if some of the callbacks are slow, or system is very busy and
383  // scheduled callbacks are not called on time.
384  base::AutoLock auto_lock(stream->lock_);
385  if (stream->state_ != PCMA_PLAYING)
386    return;
387
388  for (int ix = 0; ix != stream->num_buffers_; ++ix) {
389    WAVEHDR* buffer = stream->GetBuffer(ix);
390    if (buffer->dwFlags & WHDR_DONE) {
391      // Before we queue the next packet, we need to adjust the number of
392      // pending bytes since the last write to hardware.
393      stream->pending_bytes_ -= buffer->dwBufferLength;
394      stream->QueueNextPacket(buffer);
395
396      // QueueNextPacket() can take a long time, especially if several of them
397      // were called back-to-back. Check if we are stopping now.
398      if (stream->state_ != PCMA_PLAYING)
399        return;
400
401      // Time to send the buffer to the audio driver. Since we are reusing
402      // the same buffers we can get away without calling waveOutPrepareHeader.
403      MMRESULT result = ::waveOutWrite(stream->waveout_,
404                                       buffer,
405                                       sizeof(WAVEHDR));
406      if (result != MMSYSERR_NOERROR)
407        stream->HandleError(result);
408      stream->pending_bytes_ += buffer->dwBufferLength;
409    }
410  }
411}
412
413}  // namespace media
414