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/waveout_output_win.h"
9 #pragma comment(lib, "winmm.lib")
11 #include "base/atomicops.h"
12 #include "base/basictypes.h"
13 #include "base/debug/trace_event.h"
14 #include "base/logging.h"
15 #include "media/audio/audio_io.h"
16 #include "media/audio/win/audio_manager_win.h"
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
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.
29 // Sixty four MB is the maximum buffer size per AudioOutputStream.
30 static const uint32 kMaxOpenBufferSize
= 1024 * 1024 * 64;
33 // http://www.thx.com/consumer/home-entertainment/home-theater/surround-sound-speaker-set-up/
34 // http://en.wikipedia.org/wiki/Surround_sound
36 static const int kMaxChannelsToMask
= 8;
37 static const unsigned int kChannelsToMask
[kMaxChannelsToMask
+ 1] = {
42 SPEAKER_FRONT_LEFT
| SPEAKER_FRONT_RIGHT
,
43 // 3 = Stereo + Center
44 SPEAKER_FRONT_LEFT
| SPEAKER_FRONT_RIGHT
| SPEAKER_FRONT_CENTER
,
46 SPEAKER_FRONT_LEFT
| SPEAKER_FRONT_RIGHT
|
47 SPEAKER_BACK_LEFT
| SPEAKER_BACK_RIGHT
,
49 SPEAKER_FRONT_LEFT
| SPEAKER_FRONT_RIGHT
| SPEAKER_FRONT_CENTER
|
50 SPEAKER_BACK_LEFT
| SPEAKER_BACK_RIGHT
,
52 SPEAKER_FRONT_LEFT
| SPEAKER_FRONT_RIGHT
|
53 SPEAKER_FRONT_CENTER
| SPEAKER_LOW_FREQUENCY
|
54 SPEAKER_BACK_LEFT
| SPEAKER_BACK_RIGHT
,
56 SPEAKER_FRONT_LEFT
| SPEAKER_FRONT_RIGHT
|
57 SPEAKER_FRONT_CENTER
| SPEAKER_LOW_FREQUENCY
|
58 SPEAKER_BACK_LEFT
| SPEAKER_BACK_RIGHT
|
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.
68 inline 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);
73 inline WAVEHDR
* PCMWaveOutAudioOutputStream::GetBuffer(int n
) const {
75 DCHECK_LT(n
, num_buffers_
);
76 return reinterpret_cast<WAVEHDR
*>(&buffers_
[n
* BufferSize()]);
79 PCMWaveOutAudioOutputStream::PCMWaveOutAudioOutputStream(
80 AudioManagerWin
* manager
, const AudioParameters
& params
, int num_buffers
,
82 : state_(PCMA_BRAND_NEW
),
84 device_id_(device_id
),
87 num_buffers_(num_buffers
),
88 buffer_size_(params
.GetBytesPerBuffer()),
90 channels_(params
.channels()),
92 waiting_handle_(NULL
),
93 audio_bus_(AudioBus::Create(params
)) {
94 format_
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
95 format_
.Format
.nChannels
= params
.channels();
96 format_
.Format
.nSamplesPerSec
= params
.sample_rate();
97 format_
.Format
.wBitsPerSample
= params
.bits_per_sample();
98 format_
.Format
.cbSize
= sizeof(format_
) - sizeof(WAVEFORMATEX
);
99 // The next are computed from above.
100 format_
.Format
.nBlockAlign
= (format_
.Format
.nChannels
*
101 format_
.Format
.wBitsPerSample
) / 8;
102 format_
.Format
.nAvgBytesPerSec
= format_
.Format
.nBlockAlign
*
103 format_
.Format
.nSamplesPerSec
;
104 if (params
.channels() > kMaxChannelsToMask
) {
105 format_
.dwChannelMask
= kChannelsToMask
[kMaxChannelsToMask
];
107 format_
.dwChannelMask
= kChannelsToMask
[params
.channels()];
109 format_
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
110 format_
.Samples
.wValidBitsPerSample
= params
.bits_per_sample();
113 PCMWaveOutAudioOutputStream::~PCMWaveOutAudioOutputStream() {
114 DCHECK(NULL
== waveout_
);
117 bool PCMWaveOutAudioOutputStream::Open() {
118 if (state_
!= PCMA_BRAND_NEW
)
120 if (BufferSize() * num_buffers_
> kMaxOpenBufferSize
)
122 if (num_buffers_
< 2 || num_buffers_
> 5)
125 // Create buffer event.
126 buffer_event_
.Set(::CreateEvent(NULL
, // Security attributes.
127 FALSE
, // It will auto-reset.
128 FALSE
, // Initial state.
130 if (!buffer_event_
.Get())
134 // We'll be getting buffer_event_ events when it's time to refill the buffer.
135 MMRESULT result
= ::waveOutOpen(
138 reinterpret_cast<LPCWAVEFORMATEX
>(&format_
),
139 reinterpret_cast<DWORD_PTR
>(buffer_event_
.Get()),
142 if (result
!= MMSYSERR_NOERROR
)
150 void PCMWaveOutAudioOutputStream::SetupBuffers() {
151 buffers_
.reset(new char[BufferSize() * num_buffers_
]);
152 for (int ix
= 0; ix
!= num_buffers_
; ++ix
) {
153 WAVEHDR
* buffer
= GetBuffer(ix
);
154 buffer
->lpData
= reinterpret_cast<char*>(buffer
) + sizeof(WAVEHDR
);
155 buffer
->dwBufferLength
= buffer_size_
;
156 buffer
->dwBytesRecorded
= 0;
157 buffer
->dwFlags
= WHDR_DONE
;
159 // Tell windows sound drivers about our buffers. Not documented what
160 // this does but we can guess that causes the OS to keep a reference to
161 // the memory pages so the driver can use them without worries.
162 ::waveOutPrepareHeader(waveout_
, buffer
, sizeof(WAVEHDR
));
166 void PCMWaveOutAudioOutputStream::FreeBuffers() {
167 for (int ix
= 0; ix
!= num_buffers_
; ++ix
) {
168 ::waveOutUnprepareHeader(waveout_
, GetBuffer(ix
), sizeof(WAVEHDR
));
173 // Initially we ask the source to fill up all audio buffers. If we don't do
174 // this then we would always get the driver callback when it is about to run
175 // samples and that would leave too little time to react.
176 void PCMWaveOutAudioOutputStream::Start(AudioSourceCallback
* callback
) {
177 if (state_
!= PCMA_READY
)
179 callback_
= callback
;
181 // Reset buffer event, it can be left in the arbitrary state if we
182 // previously stopped the stream. Can happen because we are stopping
183 // callbacks before stopping playback itself.
184 if (!::ResetEvent(buffer_event_
.Get())) {
185 HandleError(MMSYSERR_ERROR
);
189 // Start watching for buffer events.
190 if (!::RegisterWaitForSingleObject(&waiting_handle_
,
195 WT_EXECUTEDEFAULT
)) {
196 HandleError(MMSYSERR_ERROR
);
197 waiting_handle_
= NULL
;
201 state_
= PCMA_PLAYING
;
203 // Queue the buffers.
205 for (int ix
= 0; ix
!= num_buffers_
; ++ix
) {
206 WAVEHDR
* buffer
= GetBuffer(ix
);
207 // Caller waits for 1st packet to become available, but not for others,
208 // so we wait for them here.
210 callback_
->WaitTillDataReady();
211 QueueNextPacket(buffer
); // Read more data.
212 pending_bytes_
+= buffer
->dwBufferLength
;
215 // From now on |pending_bytes_| would be accessed by callback thread.
216 // Most likely waveOutPause() or waveOutRestart() has its own memory barrier,
217 // but issuing our own is safer.
218 base::subtle::MemoryBarrier();
220 MMRESULT result
= ::waveOutPause(waveout_
);
221 if (result
!= MMSYSERR_NOERROR
) {
226 // Send the buffers to the audio driver. Note that the device is paused
227 // so we avoid entering the callback method while still here.
228 for (int ix
= 0; ix
!= num_buffers_
; ++ix
) {
229 result
= ::waveOutWrite(waveout_
, GetBuffer(ix
), sizeof(WAVEHDR
));
230 if (result
!= MMSYSERR_NOERROR
) {
235 result
= ::waveOutRestart(waveout_
);
236 if (result
!= MMSYSERR_NOERROR
) {
242 // Stopping is tricky if we want it be fast.
243 // For now just do it synchronously and avoid all the complexities.
244 // TODO(enal): if we want faster Stop() we can create singleton that keeps track
245 // of all currently playing streams. Then you don't have to wait
246 // till all callbacks are completed. Of course access to singleton
247 // should be under its own lock, and checking the liveness and
248 // acquiring the lock on stream should be done atomically.
249 void PCMWaveOutAudioOutputStream::Stop() {
250 if (state_
!= PCMA_PLAYING
)
252 state_
= PCMA_STOPPING
;
253 base::subtle::MemoryBarrier();
255 // Stop watching for buffer event, wait till all the callbacks are complete.
256 // Should be done before ::waveOutReset() call to avoid race condition when
257 // callback that is currently active and already checked that stream is still
258 // being played calls ::waveOutWrite() after ::waveOutReset() returns, later
259 // causing ::waveOutClose() to fail with WAVERR_STILLPLAYING.
260 // TODO(enal): that delays actual stopping of playback. Alternative can be
261 // to call ::waveOutReset() twice, once before
262 // ::UnregisterWaitEx() and once after.
263 if (waiting_handle_
) {
264 if (!::UnregisterWaitEx(waiting_handle_
, INVALID_HANDLE_VALUE
)) {
265 state_
= PCMA_PLAYING
;
266 HandleError(MMSYSERR_ERROR
);
269 waiting_handle_
= NULL
;
273 MMRESULT res
= ::waveOutReset(waveout_
);
274 if (res
!= MMSYSERR_NOERROR
) {
275 state_
= PCMA_PLAYING
;
280 // Wait for lock to ensure all outstanding callbacks have completed.
281 base::AutoLock
auto_lock(lock_
);
283 // waveOutReset() leaves buffers in the unpredictable state, causing
284 // problems if we want to close, release, or reuse them. Fix the states.
285 for (int ix
= 0; ix
!= num_buffers_
; ++ix
) {
286 GetBuffer(ix
)->dwFlags
= WHDR_PREPARED
;
289 // Don't use callback after Stop().
295 // We can Close in any state except that trying to close a stream that is
296 // playing Windows generates an error. We cannot propagate it to the source,
297 // as callback_ is set to NULL. Just print it and hope somebody somehow
299 void PCMWaveOutAudioOutputStream::Close() {
300 // Force Stop() to ensure it's safe to release buffers and free the stream.
306 // waveOutClose() generates a WIM_CLOSE callback. In case Start() was never
307 // called, force a reset to ensure close succeeds.
308 MMRESULT res
= ::waveOutReset(waveout_
);
309 DCHECK_EQ(res
, static_cast<MMRESULT
>(MMSYSERR_NOERROR
));
310 res
= ::waveOutClose(waveout_
);
311 DCHECK_EQ(res
, static_cast<MMRESULT
>(MMSYSERR_NOERROR
));
312 state_
= PCMA_CLOSED
;
316 // Tell the audio manager that we have been released. This can result in
317 // the manager destroying us in-place so this needs to be the last thing
318 // we do on this function.
319 manager_
->ReleaseOutputStream(this);
322 void PCMWaveOutAudioOutputStream::SetVolume(double volume
) {
325 volume_
= static_cast<float>(volume
);
328 void PCMWaveOutAudioOutputStream::GetVolume(double* volume
) {
334 void PCMWaveOutAudioOutputStream::HandleError(MMRESULT error
) {
335 DLOG(WARNING
) << "PCMWaveOutAudio error " << error
;
337 callback_
->OnError(this);
340 void PCMWaveOutAudioOutputStream::QueueNextPacket(WAVEHDR
*buffer
) {
341 DCHECK_EQ(channels_
, format_
.Format
.nChannels
);
342 // Call the source which will fill our buffer with pleasant sounds and
343 // return to us how many bytes were used.
344 // TODO(fbarchard): Handle used 0 by queueing more.
346 // HACK: Yield if Read() is called too often. On older platforms which are
347 // still using the WaveOut backend, we run into synchronization issues where
348 // the renderer has not finished filling the shared memory when Read() is
349 // called. Reading too early will lead to clicks and pops. See issues:
350 // http://crbug.com/161307 and http://crbug.com/61022
351 callback_
->WaitTillDataReady();
353 // TODO(sergeyu): Specify correct hardware delay for AudioBuffersState.
354 int frames_filled
= callback_
->OnMoreData(
355 audio_bus_
.get(), AudioBuffersState(pending_bytes_
, 0));
356 uint32 used
= frames_filled
* audio_bus_
->channels() *
357 format_
.Format
.wBitsPerSample
/ 8;
359 if (used
<= buffer_size_
) {
360 // Note: If this ever changes to output raw float the data must be clipped
361 // and sanitized since it may come from an untrusted source such as NaCl.
362 audio_bus_
->Scale(volume_
);
363 audio_bus_
->ToInterleaved(
364 frames_filled
, format_
.Format
.wBitsPerSample
/ 8, buffer
->lpData
);
366 buffer
->dwBufferLength
= used
* format_
.Format
.nChannels
/ channels_
;
371 buffer
->dwFlags
= WHDR_PREPARED
;
374 // One of the threads in our thread pool asynchronously calls this function when
375 // buffer_event_ is signalled. Search through all the buffers looking for freed
376 // ones, fills them with data, and "feed" the Windows.
377 // Note: by searching through all the buffers we guarantee that we fill all the
378 // buffers, even when "event loss" happens, i.e. if Windows signals event
379 // when it did not flip into unsignaled state from the previous signal.
380 void NTAPI
PCMWaveOutAudioOutputStream::BufferCallback(PVOID lpParameter
,
381 BOOLEAN timer_fired
) {
382 TRACE_EVENT0("audio", "PCMWaveOutAudioOutputStream::BufferCallback");
384 DCHECK(!timer_fired
);
385 PCMWaveOutAudioOutputStream
* stream
=
386 reinterpret_cast<PCMWaveOutAudioOutputStream
*>(lpParameter
);
388 // Lock the stream so callbacks do not interfere with each other.
389 // Several callbacks can be called simultaneously by different threads in the
390 // thread pool if some of the callbacks are slow, or system is very busy and
391 // scheduled callbacks are not called on time.
392 base::AutoLock
auto_lock(stream
->lock_
);
393 if (stream
->state_
!= PCMA_PLAYING
)
396 for (int ix
= 0; ix
!= stream
->num_buffers_
; ++ix
) {
397 WAVEHDR
* buffer
= stream
->GetBuffer(ix
);
398 if (buffer
->dwFlags
& WHDR_DONE
) {
399 // Before we queue the next packet, we need to adjust the number of
400 // pending bytes since the last write to hardware.
401 stream
->pending_bytes_
-= buffer
->dwBufferLength
;
402 stream
->QueueNextPacket(buffer
);
404 // QueueNextPacket() can take a long time, especially if several of them
405 // were called back-to-back. Check if we are stopping now.
406 if (stream
->state_
!= PCMA_PLAYING
)
409 // Time to send the buffer to the audio driver. Since we are reusing
410 // the same buffers we can get away without calling waveOutPrepareHeader.
411 MMRESULT result
= ::waveOutWrite(stream
->waveout_
,
414 if (result
!= MMSYSERR_NOERROR
)
415 stream
->HandleError(result
);
416 stream
->pending_bytes_
+= buffer
->dwBufferLength
;