Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(251)

Side by Side Diff: media/audio/win/audio_low_latency_output_win_unittest.cc

Issue 8440002: Low-latency AudioOutputStream implementation based on WASAPI for Windows. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: rebased Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « media/audio/win/audio_low_latency_output_win.cc ('k') | media/audio/win/audio_manager_win.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2011 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 <windows.h>
6 #include <mmsystem.h>
7
8 #include "base/basictypes.h"
9 #include "base/environment.h"
10 #include "base/file_util.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop.h"
13 #include "base/test/test_timeouts.h"
14 #include "base/time.h"
15 #include "base/path_service.h"
16 #include "base/win/scoped_com_initializer.h"
17 #include "media/audio/audio_io.h"
18 #include "media/audio/audio_manager.h"
19 #include "media/audio/win/audio_low_latency_output_win.h"
20 #include "media/base/seekable_buffer.h"
21 #include "media/base/test_data_util.h"
22 #include "testing/gmock_mutant.h"
23 #include "testing/gmock/include/gmock/gmock.h"
24 #include "testing/gtest/include/gtest/gtest.h"
25
26 using ::testing::_;
27 using ::testing::AnyNumber;
28 using ::testing::Between;
29 using ::testing::CreateFunctor;
30 using ::testing::DoAll;
31 using ::testing::Gt;
32 using ::testing::InvokeWithoutArgs;
33 using ::testing::NotNull;
34 using ::testing::Return;
35 using base::win::ScopedCOMInitializer;
36
37 namespace media {
38
39 static const char kSpeechFile_16b_s_48k[] = "speech_16b_stereo_48kHz.raw";
40 static const char kSpeechFile_16b_s_44k[] = "speech_16b_stereo_44kHz.raw";
41 static const size_t kFileDurationMs = 20000;
42
43 static const size_t kMaxDeltaSamples = 1000;
44 static const char* kDeltaTimeMsFileName = "delta_times_ms.txt";
45
46 MATCHER_P(HasValidDelay, value, "") {
47 // It is difficult to come up with a perfect test condition for the delay
48 // estimation. For now, verify that the produced output delay is always
49 // larger than the selected buffer size.
50 return arg.hardware_delay_bytes > value.hardware_delay_bytes;
51 }
52
53 class MockAudioSourceCallback : public AudioOutputStream::AudioSourceCallback {
54 public:
55 MOCK_METHOD4(OnMoreData, uint32(AudioOutputStream* stream,
56 uint8* dest,
57 uint32 max_size,
58 AudioBuffersState buffers_state));
59 MOCK_METHOD2(OnError, void(AudioOutputStream* stream, int code));
60 };
61
62 // This audio source implementation should be used for manual tests only since
63 // it takes about 20 seconds to play out a file.
64 class ReadFromFileAudioSource : public AudioOutputStream::AudioSourceCallback {
65 public:
66 explicit ReadFromFileAudioSource(const std::string& name)
67 : pos_(0),
68 previous_call_time_(base::Time::Now()),
69 text_file_(NULL),
70 elements_to_write_(0) {
71 // Reads a test file from media/test/data directory and stores it in
72 // a scoped_array.
73 ReadTestDataFile(name, &file_, &file_size_);
74 file_size_ = file_size_;
75
76 // Creates an array that will store delta times between callbacks.
77 // The content of this array will be written to a text file at
78 // destruction and can then be used for off-line analysis of the exact
79 // timing of callbacks. The text file will be stored in media/test/data.
80 delta_times_.reset(new int[kMaxDeltaSamples]);
81 }
82
83 virtual ~ReadFromFileAudioSource() {
84 // Get complete file path to output file in directory containing
85 // media_unittests.exe.
86 FilePath file_name;
87 EXPECT_TRUE(PathService::Get(base::DIR_EXE, &file_name));
88 file_name = file_name.AppendASCII(kDeltaTimeMsFileName);
89
90 EXPECT_TRUE(!text_file_);
91 text_file_ = file_util::OpenFile(file_name, "wt");
92 DLOG_IF(ERROR, !text_file_) << "Failed to open log file.";
93
94 // Write the array which contains delta times to a text file.
95 size_t elements_written = 0;
96 while (elements_written < elements_to_write_) {
97 fprintf(text_file_, "%d\n", delta_times_[elements_written]);
98 ++elements_written;
99 }
100
101 file_util::CloseFile(text_file_);
102 }
103
104 // AudioOutputStream::AudioSourceCallback implementation.
105 virtual uint32 OnMoreData(AudioOutputStream* stream,
106 uint8* dest,
107 uint32 max_size,
108 AudioBuffersState buffers_state) {
109 // Store time difference between two successive callbacks in an array.
110 // These values will be written to a file in the destructor.
111 int diff = (base::Time::Now() - previous_call_time_).InMilliseconds();
112 previous_call_time_ = base::Time::Now();
113 if (elements_to_write_ < kMaxDeltaSamples) {
114 delta_times_[elements_to_write_] = diff;
115 ++elements_to_write_;
116 }
117
118 // Use samples read from a data file and fill up the audio buffer
119 // provided to us in the callback.
120 if (pos_ + static_cast<int>(max_size) > file_size_)
121 max_size = file_size_ - pos_;
122 if (max_size) {
123 memcpy(dest, &file_[pos_], max_size);
124 pos_ += max_size;
125 }
126 return max_size;
127 }
128
129 virtual void OnError(AudioOutputStream* stream, int code) {}
130
131 int file_size() { return file_size_; }
132
133 private:
134 scoped_array<uint8> file_;
135 scoped_array<int> delta_times_;
136 int file_size_;
137 int pos_;
138 base::Time previous_call_time_;
139 FILE* text_file_;
140 size_t elements_to_write_;
141 };
142
143 // Convenience method which ensures that we are not running on the build
144 // bots and that at least one valid output device can be found.
145 static bool CanRunAudioTests() {
146 scoped_ptr<base::Environment> env(base::Environment::Create());
147 if (env->HasVar("CHROME_HEADLESS"))
148 return false;
149 AudioManager* audio_man = AudioManager::GetAudioManager();
150 if (NULL == audio_man)
151 return false;
152 // TODO(henrika): note that we use Wave today to query the number of
153 // existing output devices.
154 return audio_man->HasAudioOutputDevices();
155 }
156
157 // Convenience method which creates a default AudioOutputStream object but
158 // also allows the user to modify the default settings.
159 class AudioOutputStreamWrapper {
160 public:
161 AudioOutputStreamWrapper()
162 : com_init_(ScopedCOMInitializer::kMTA),
163 audio_man_(AudioManager::GetAudioManager()),
164 format_(AudioParameters::AUDIO_PCM_LOW_LATENCY),
165 channel_layout_(CHANNEL_LAYOUT_STEREO),
166 bits_per_sample_(16) {
167 // Use native/mixing sample rate and 10ms frame size as default.
168 sample_rate_ = static_cast<int>(
169 WASAPIAudioOutputStream::HardwareSampleRate(eConsole));
170 samples_per_packet_ = sample_rate_ / 100;
171 DCHECK(sample_rate_);
172 }
173
174 ~AudioOutputStreamWrapper() {}
175
176 // Creates AudioOutputStream object using default parameters.
177 AudioOutputStream* Create() {
178 return CreateOutputStream();
179 }
180
181 // Creates AudioOutputStream object using non-default parameters where the
182 // frame size is modified.
183 AudioOutputStream* Create(int samples_per_packet) {
184 samples_per_packet_ = samples_per_packet;
185 return CreateOutputStream();
186 }
187
188 // Creates AudioOutputStream object using non-default parameters where the
189 // channel layout is modified.
190 AudioOutputStream* Create(ChannelLayout channel_layout) {
191 channel_layout_ = channel_layout;
192 return CreateOutputStream();
193 }
194
195 AudioParameters::Format format() const { return format_; }
196 int channels() const { return ChannelLayoutToChannelCount(channel_layout_); }
197 int bits_per_sample() const { return bits_per_sample_; }
198 int sample_rate() const { return sample_rate_; }
199 int samples_per_packet() const { return samples_per_packet_; }
200
201 private:
202 AudioOutputStream* CreateOutputStream() {
203 AudioOutputStream* aos = audio_man_->MakeAudioOutputStream(
204 AudioParameters(format_, channel_layout_, sample_rate_,
205 bits_per_sample_, samples_per_packet_));
206 EXPECT_TRUE(aos);
207 return aos;
208 }
209
210 ScopedCOMInitializer com_init_;
211 AudioManager* audio_man_;
212 AudioParameters::Format format_;
213 ChannelLayout channel_layout_;
214 int bits_per_sample_;
215 int sample_rate_;
216 int samples_per_packet_;
217 };
218
219 // Convenience method which creates a default AudioOutputStream object.
220 static AudioOutputStream* CreateDefaultAudioOutputStream() {
221 AudioOutputStreamWrapper aosw;
222 AudioOutputStream* aos = aosw.Create();
223 return aos;
224 }
225
226 static void QuitMessageLoop(base::MessageLoopProxy* proxy) {
227 proxy->PostTask(FROM_HERE, new MessageLoop::QuitTask());
228 }
229
230 // Verify that we can retrieve the current hardware/mixing sample rate
231 // for all supported device roles. The ERole enumeration defines constants
232 // that indicate the role that the system/user has assigned to an audio
233 // endpoint device.
234 // TODO(henrika): modify this test when we support full device enumeration.
235 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestHardwareSampleRate) {
236 if (!CanRunAudioTests())
237 return;
238
239 ScopedCOMInitializer com_init(ScopedCOMInitializer::kMTA);
240
241 // Default device intended for games, system notification sounds,
242 // and voice commands.
243 int fs = static_cast<int>(
244 WASAPIAudioOutputStream::HardwareSampleRate(eConsole));
245 EXPECT_GE(fs, 0);
246
247 // Default communication device intended for e.g. VoIP communication.
248 fs = static_cast<int>(
249 WASAPIAudioOutputStream::HardwareSampleRate(eCommunications));
250 EXPECT_GE(fs, 0);
251
252 // Multimedia device for music, movies and live music recording.
253 fs = static_cast<int>(
254 WASAPIAudioOutputStream::HardwareSampleRate(eMultimedia));
255 EXPECT_GE(fs, 0);
256 }
257
258 // Test Create(), Close() calling sequence.
259 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestCreateAndClose) {
260 if (!CanRunAudioTests())
261 return;
262 AudioOutputStream* aos = CreateDefaultAudioOutputStream();
263 aos->Close();
264 }
265
266 // Test Open(), Close() calling sequence.
267 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestOpenAndClose) {
268 if (!CanRunAudioTests())
269 return;
270 AudioOutputStream* aos = CreateDefaultAudioOutputStream();
271 EXPECT_TRUE(aos->Open());
272 aos->Close();
273 }
274
275 // Test Open(), Start(), Close() calling sequence.
276 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestOpenStartAndClose) {
277 if (!CanRunAudioTests())
278 return;
279 AudioOutputStream* aos = CreateDefaultAudioOutputStream();
280 EXPECT_TRUE(aos->Open());
281 MockAudioSourceCallback source;
282 EXPECT_CALL(source, OnError(aos, _))
283 .Times(0);
284 aos->Start(&source);
285 aos->Close();
286 }
287
288 // Test Open(), Start(), Stop(), Close() calling sequence.
289 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestOpenStartStopAndClose) {
290 if (!CanRunAudioTests())
291 return;
292 AudioOutputStream* aos = CreateDefaultAudioOutputStream();
293 EXPECT_TRUE(aos->Open());
294 MockAudioSourceCallback source;
295 EXPECT_CALL(source, OnError(aos, _))
296 .Times(0);
297 aos->Start(&source);
298 aos->Stop();
299 aos->Close();
300 }
301
302 // Test SetVolume(), GetVolume()
303 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestVolume) {
304 if (!CanRunAudioTests())
305 return;
306 AudioOutputStream* aos = CreateDefaultAudioOutputStream();
307
308 // Initial volume should be full volume (1.0).
309 double volume = 0.0;
310 aos->GetVolume(&volume);
311 EXPECT_EQ(1.0, volume);
312
313 // Verify some valid volume settings.
314 aos->SetVolume(0.0);
315 aos->GetVolume(&volume);
316 EXPECT_EQ(0.0, volume);
317
318 aos->SetVolume(0.5);
319 aos->GetVolume(&volume);
320 EXPECT_EQ(0.5, volume);
321
322 aos->SetVolume(1.0);
323 aos->GetVolume(&volume);
324 EXPECT_EQ(1.0, volume);
325
326 // Ensure that invalid volume setting have no effect.
327 aos->SetVolume(1.5);
328 aos->GetVolume(&volume);
329 EXPECT_EQ(1.0, volume);
330
331 aos->SetVolume(-0.5);
332 aos->GetVolume(&volume);
333 EXPECT_EQ(1.0, volume);
334
335 aos->Close();
336 }
337
338 // Test some additional calling sequences.
339 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestMiscCallingSequences) {
340 if (!CanRunAudioTests())
341 return;
342 AudioOutputStream* aos = CreateDefaultAudioOutputStream();
343 WASAPIAudioOutputStream* waos = static_cast<WASAPIAudioOutputStream*>(aos);
344
345 // Open(), Open() is a valid calling sequence (second call does nothing).
346 EXPECT_TRUE(aos->Open());
347 EXPECT_TRUE(aos->Open());
348
349 MockAudioSourceCallback source;
350
351 // Start(), Start() is a valid calling sequence (second call does nothing).
352 aos->Start(&source);
353 EXPECT_TRUE(waos->started());
354 aos->Start(&source);
355 EXPECT_TRUE(waos->started());
356
357 // Stop(), Stop() is a valid calling sequence (second call does nothing).
358 aos->Stop();
359 EXPECT_FALSE(waos->started());
360 aos->Stop();
361 EXPECT_FALSE(waos->started());
362
363 aos->Close();
364 }
365
366 // Use default packet size (10ms) and verify that rendering starts.
367 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestPacketSizeInMilliseconds) {
368 if (!CanRunAudioTests())
369 return;
370
371 MessageLoopForUI loop;
372 scoped_refptr<base::MessageLoopProxy> proxy(loop.message_loop_proxy());
373
374 MockAudioSourceCallback source;
375
376 // Create default WASAPI output stream which plays out in stereo using
377 // the shared mixing rate. The default buffer size is 10ms.
378 AudioOutputStreamWrapper aosw;
379 AudioOutputStream* aos = aosw.Create();
380 EXPECT_TRUE(aos->Open());
381
382 // Derive the expected size in bytes of each packet.
383 uint32 bytes_per_packet = aosw.channels() * aosw.samples_per_packet() *
384 (aosw.bits_per_sample() / 8);
385
386 // Set up expected minimum delay estimation.
387 AudioBuffersState state(0, bytes_per_packet);
388
389 // Wait for the first callback and verify its parameters.
390 EXPECT_CALL(source, OnMoreData(aos, NotNull(), bytes_per_packet,
391 HasValidDelay(state)))
392 .WillOnce(
393 DoAll(
394 InvokeWithoutArgs(
395 CreateFunctor(&QuitMessageLoop, proxy.get())),
396 Return(bytes_per_packet)));
397
398 aos->Start(&source);
399 loop.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask(),
400 TestTimeouts::action_timeout_ms());
401 loop.Run();
402 aos->Stop();
403 aos->Close();
404 }
405
406 // Use a fixed packets size (independent of sample rate) and verify
407 // that rendering starts.
408 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestPacketSizeInSamples) {
409 if (!CanRunAudioTests())
410 return;
411
412 MessageLoopForUI loop;
413 scoped_refptr<base::MessageLoopProxy> proxy(loop.message_loop_proxy());
414
415 MockAudioSourceCallback source;
416
417 // Create default WASAPI output stream which plays out in stereo using
418 // the shared mixing rate. The buffer size is set to 1024 samples.
419 AudioOutputStreamWrapper aosw;
420 AudioOutputStream* aos = aosw.Create(1024);
421 EXPECT_TRUE(aos->Open());
422
423 // Derive the expected size in bytes of each packet.
424 uint32 bytes_per_packet = aosw.channels() * aosw.samples_per_packet() *
425 (aosw.bits_per_sample() / 8);
426
427 // Set up expected minimum delay estimation.
428 AudioBuffersState state(0, bytes_per_packet);
429
430 // Wait for the first callback and verify its parameters.
431 EXPECT_CALL(source, OnMoreData(aos, NotNull(), bytes_per_packet,
432 HasValidDelay(state)))
433 .WillOnce(
434 DoAll(
435 InvokeWithoutArgs(
436 CreateFunctor(&QuitMessageLoop, proxy.get())),
437 Return(bytes_per_packet)));
438
439 aos->Start(&source);
440 loop.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask(),
441 TestTimeouts::action_timeout_ms());
442 loop.Run();
443 aos->Stop();
444 aos->Close();
445 }
446
447 TEST(WinAudioOutputTest, WASAPIAudioOutputStreamTestMono) {
448 if (!CanRunAudioTests())
449 return;
450
451 MessageLoopForUI loop;
452 scoped_refptr<base::MessageLoopProxy> proxy(loop.message_loop_proxy());
453
454 MockAudioSourceCallback source;
455
456 // Create default WASAPI output stream which plays out in *mono* using
457 // the shared mixing rate. The default buffer size is 10ms.
458 AudioOutputStreamWrapper aosw;
459 AudioOutputStream* aos = aosw.Create(CHANNEL_LAYOUT_MONO);
460 EXPECT_TRUE(aos->Open());
461
462 // Derive the expected size in bytes of each packet.
463 uint32 bytes_per_packet = aosw.channels() * aosw.samples_per_packet() *
464 (aosw.bits_per_sample() / 8);
465
466 // Set up expected minimum delay estimation.
467 AudioBuffersState state(0, bytes_per_packet);
468
469 EXPECT_CALL(source, OnMoreData(aos, NotNull(), bytes_per_packet,
470 HasValidDelay(state)))
471 .WillOnce(
472 DoAll(
473 InvokeWithoutArgs(
474 CreateFunctor(&QuitMessageLoop, proxy.get())),
475 Return(bytes_per_packet)));
476
477 aos->Start(&source);
478 loop.PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask(),
479 TestTimeouts::action_timeout_ms());
480 loop.Run();
481 aos->Stop();
482 aos->Close();
483 }
484
485 // This test is intended for manual tests and should only be enabled
486 // when it is required to store the captured data on a local file.
487 // By default, GTest will print out YOU HAVE 1 DISABLED TEST.
488 // To include disabled tests in test execution, just invoke the test program
489 // with --gtest_also_run_disabled_tests or set the GTEST_ALSO_RUN_DISABLED_TESTS
490 // environment variable to a value greater than 0.
491 // The test files are approximately 20 seconds long.
492 TEST(WinAudioOutputTest, DISABLE_WASAPIAudioOutputStreamReadFromFile) {
493 if (!CanRunAudioTests())
494 return;
495
496 AudioOutputStreamWrapper aosw;
497 AudioOutputStream* aos = aosw.Create();
498 EXPECT_TRUE(aos->Open());
499
500 std::string file_name;
501 if (aosw.sample_rate() == 48000) {
502 file_name = kSpeechFile_16b_s_48k;
503 } else if (aosw.sample_rate() == 44100) {
504 file_name = kSpeechFile_16b_s_44k;
505 } else if (aosw.sample_rate() == 96000) {
506 // Use 48kHz file at 96kHz as well. Will sound like Donald Duck.
507 file_name = kSpeechFile_16b_s_48k;
508 } else {
509 FAIL() << "This test supports 44.1, 48kHz and 96kHz only.";
510 return;
511 }
512 ReadFromFileAudioSource file_source(file_name);
513 int file_duration_ms = kFileDurationMs;
514
515 LOG(INFO) << "File name : " << file_name.c_str();
516 LOG(INFO) << "Sample rate: " << aosw.sample_rate();
517 LOG(INFO) << "File size : " << file_source.file_size();
518 LOG(INFO) << ">> Listen to the file while playing...";
519
520 aos->Start(&file_source);
521 base::PlatformThread::Sleep(file_duration_ms);
522 aos->Stop();
523
524 LOG(INFO) << ">> File playout has stopped.";
525 aos->Close();
526 }
527
528 } // namespace media
OLDNEW
« no previous file with comments | « media/audio/win/audio_low_latency_output_win.cc ('k') | media/audio/win/audio_manager_win.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698