1 // Copyright 2013 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.
7 #include "base/command_line.h"
8 #include "base/file_util.h"
9 #include "base/path_service.h"
10 #include "base/process/launch.h"
11 #include "base/scoped_native_library.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/win/windows_version.h"
14 #include "chrome/browser/media/webrtc_browsertest_base.h"
15 #include "chrome/browser/media/webrtc_browsertest_common.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/ui/browser.h"
18 #include "chrome/browser/ui/browser_tabstrip.h"
19 #include "chrome/browser/ui/tabs/tab_strip_model.h"
20 #include "chrome/common/chrome_paths.h"
21 #include "chrome/common/chrome_switches.h"
22 #include "chrome/test/base/ui_test_utils.h"
23 #include "content/public/test/browser_test_utils.h"
24 #include "net/test/embedded_test_server/embedded_test_server.h"
25 #include "testing/perf/perf_test.h"
27 // These are relative to the reference file dir defined by
28 // webrtc_browsertest_common.h (i.e. chrome/test/data/webrtc/resources).
29 static const base::FilePath::CharType kReferenceFile
[] =
31 FILE_PATH_LITERAL("human-voice-win.wav");
33 FILE_PATH_LITERAL("human-voice-linux.wav");
36 // The javascript will load the reference file relative to its location,
37 // which is in /webrtc on the web server. The files we are looking for are in
38 // webrtc/resources in the chrome/test/data folder.
39 static const char kReferenceFileRelativeUrl
[] =
41 "resources/human-voice-win.wav";
43 "resources/human-voice-linux.wav";
46 static const char kMainWebrtcTestHtmlPage
[] =
47 "/webrtc/webrtc_audio_quality_test.html";
49 // Test we can set up a WebRTC call and play audio through it.
51 // You must have the src-internal solution in your .gclient to put the required
52 // pyauto_private directory into chrome/test/data/.
54 // This test will only work on machines that have been configured to record
58 // 1. # sudo apt-get install pavucontrol
59 // 2. For the user who will run the test: # pavucontrol
60 // 3. In a separate terminal, # arecord dummy
61 // 4. In pavucontrol, go to the recording tab.
62 // 5. For the ALSA plug-in [aplay]: ALSA Capture from, change from <x> to
63 // <Monitor of x>, where x is whatever your primary sound device is called.
64 // 6. Try launching chrome as the target user on the target machine, try
65 // playing, say, a YouTube video, and record with # arecord -f dat tmp.dat.
66 // Verify the recording with aplay (should have recorded what you played
69 // Note: the volume for ALL your input devices will be forced to 100% by
70 // running this test on Linux.
73 // 1. Control panel > Sound > Manage audio devices.
74 // 2. In the recording tab, right-click in an empty space in the pane with the
75 // devices. Tick 'show disabled devices'.
76 // 3. You should see a 'stero mix' device - this is what your speakers output.
77 // Right click > Properties.
78 // 4. In the Listen tab for the mix device, check the 'listen to this device'
79 // checkbox. Ensure the mix device is the default recording device.
80 // 5. Launch chrome and try playing a video with sound. You should see
81 // in the volume meter for the mix device. Configure the mix device to have
82 // 50 / 100 in level. Also go into the playback tab, right-click Speakers,
83 // and set that level to 50 / 100. Otherwise you will get distortion in
85 class WebRtcAudioQualityBrowserTest
: public WebRtcTestBase
,
86 public testing::WithParamInterface
<bool> {
88 WebRtcAudioQualityBrowserTest() {}
89 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE
{
90 test::PeerConnectionServerRunner::KillAllPeerConnectionServers();
91 DetectErrorsInJavaScript(); // Look for errors in our rather complex js.
94 virtual void SetUpCommandLine(CommandLine
* command_line
) OVERRIDE
{
95 // This test expects real device handling and requires a real webcam / audio
96 // device; it will not work with fake devices.
97 EXPECT_FALSE(command_line
->HasSwitch(
98 switches::kUseFakeDeviceForMediaStream
));
99 EXPECT_FALSE(command_line
->HasSwitch(
100 switches::kUseFakeUIForMediaStream
));
102 bool enable_audio_track_processing
= GetParam();
103 if (enable_audio_track_processing
)
104 command_line
->AppendSwitch(switches::kEnableAudioTrackProcessing
);
107 void AddAudioFile(const std::string
& input_file_relative_url
,
108 content::WebContents
* tab_contents
) {
109 EXPECT_EQ("ok-added", ExecuteJavascript(
110 "addAudioFile('" + input_file_relative_url
+ "')", tab_contents
));
113 void PlayAudioFile(content::WebContents
* tab_contents
) {
114 EXPECT_EQ("ok-playing", ExecuteJavascript("playAudioFile()", tab_contents
));
117 void EstablishCall(content::WebContents
* from_tab
,
118 content::WebContents
* to_tab
) {
119 EXPECT_EQ("ok-negotiating",
120 ExecuteJavascript("negotiateCall()", from_tab
));
122 // Ensure the call gets up on both sides.
123 EXPECT_TRUE(test::PollingWaitUntil("getPeerConnectionReadyState()",
124 "active", from_tab
));
125 EXPECT_TRUE(test::PollingWaitUntil("getPeerConnectionReadyState()",
129 base::FilePath
CreateTemporaryWaveFile() {
130 base::FilePath filename
;
131 EXPECT_TRUE(base::CreateTemporaryFile(&filename
));
132 base::FilePath wav_filename
=
133 filename
.AddExtension(FILE_PATH_LITERAL(".wav"));
134 EXPECT_TRUE(base::Move(filename
, wav_filename
));
138 test::PeerConnectionServerRunner peerconnection_server_
;
141 class AudioRecorder
{
143 AudioRecorder(): recording_application_(base::kNullProcessHandle
) {}
146 // Starts the recording program for the specified duration. Returns true
148 bool StartRecording(int duration_sec
, const base::FilePath
& output_file
,
150 EXPECT_EQ(base::kNullProcessHandle
, recording_application_
)
151 << "Tried to record, but is already recording.";
153 CommandLine
command_line(CommandLine::NO_PROGRAM
);
155 // This disable is required to run SoundRecorder.exe on 64-bit Windows
156 // from a 32-bit binary. We need to load the wow64 disable function from
157 // the DLL since it doesn't exist on Windows XP.
158 // TODO(phoglund): find some cleaner solution than using SoundRecorder.exe.
159 base::ScopedNativeLibrary
kernel32_lib(base::FilePath(L
"kernel32"));
160 if (kernel32_lib
.is_valid()) {
161 typedef BOOL (WINAPI
* Wow64DisableWow64FSRedirection
)(PVOID
*);
162 Wow64DisableWow64FSRedirection wow_64_disable_wow_64_fs_redirection
;
163 wow_64_disable_wow_64_fs_redirection
=
164 reinterpret_cast<Wow64DisableWow64FSRedirection
>(
165 kernel32_lib
.GetFunctionPointer(
166 "Wow64DisableWow64FsRedirection"));
167 if (wow_64_disable_wow_64_fs_redirection
!= NULL
) {
168 PVOID
* ignored
= NULL
;
169 wow_64_disable_wow_64_fs_redirection(ignored
);
173 char duration_in_hms
[128] = {0};
174 struct tm duration_tm
= {0};
175 duration_tm
.tm_sec
= duration_sec
;
176 EXPECT_NE(0u, strftime(duration_in_hms
, arraysize(duration_in_hms
),
177 "%H:%M:%S", &duration_tm
));
179 command_line
.SetProgram(
180 base::FilePath(FILE_PATH_LITERAL("SoundRecorder.exe")));
181 command_line
.AppendArg("/FILE");
182 command_line
.AppendArgPath(output_file
);
183 command_line
.AppendArg("/DURATION");
184 command_line
.AppendArg(duration_in_hms
);
186 int num_channels
= mono
? 1 : 2;
187 command_line
.SetProgram(base::FilePath("arecord"));
188 command_line
.AppendArg("-d");
189 command_line
.AppendArg(base::StringPrintf("%d", duration_sec
));
190 command_line
.AppendArg("-f");
191 command_line
.AppendArg("dat");
192 command_line
.AppendArg("-c");
193 command_line
.AppendArg(base::StringPrintf("%d", num_channels
));
194 command_line
.AppendArgPath(output_file
);
197 VLOG(0) << "Running " << command_line
.GetCommandLineString();
198 return base::LaunchProcess(command_line
, base::LaunchOptions(),
199 &recording_application_
);
202 // Joins the recording program. Returns true on success.
203 bool WaitForRecordingToEnd() {
205 base::WaitForExitCode(recording_application_
, &exit_code
);
206 return exit_code
== 0;
209 base::ProcessHandle recording_application_
;
212 bool ForceMicrophoneVolumeTo100Percent() {
214 CommandLine
command_line(test::GetReferenceFilesDir().Append(
215 FILE_PATH_LITERAL("force_mic_volume_max.exe")));
216 VLOG(0) << "Running " << command_line
.GetCommandLineString();
218 if (!base::GetAppOutput(command_line
, &result
)) {
219 LOG(ERROR
) << "Failed to set source volume: output was " << result
;
223 // Just force the volume of, say the first 5 devices. A machine will rarely
224 // have more input sources than that. This is way easier than finding the
225 // input device we happen to be using.
226 for (int device_index
= 0; device_index
< 5; ++device_index
) {
228 const std::string kHundredPercentVolume
= "65536";
229 CommandLine
command_line(base::FilePath(FILE_PATH_LITERAL("pacmd")));
230 command_line
.AppendArg("set-source-volume");
231 command_line
.AppendArg(base::StringPrintf("%d", device_index
));
232 command_line
.AppendArg(kHundredPercentVolume
);
233 VLOG(0) << "Running " << command_line
.GetCommandLineString();
234 if (!base::GetAppOutput(command_line
, &result
)) {
235 LOG(ERROR
) << "Failed to set source volume: output was " << result
;
243 // Removes silence from beginning and end of the |input_audio_file| and writes
244 // the result to the |output_audio_file|. Returns true on success.
245 bool RemoveSilence(const base::FilePath
& input_file
,
246 const base::FilePath
& output_file
) {
247 // SOX documentation for silence command: http://sox.sourceforge.net/sox.html
248 // To remove the silence from both beginning and end of the audio file, we
249 // call sox silence command twice: once on normal file and again on its
250 // reverse, then we reverse the final output.
251 // Silence parameters are (in sequence):
252 // ABOVE_PERIODS: The period for which silence occurs. Value 1 is used for
253 // silence at beginning of audio.
254 // DURATION: the amount of time in seconds that non-silence must be detected
255 // before sox stops trimming audio.
256 // THRESHOLD: value used to indicate what sample value is treates as silence.
257 const char* kAbovePeriods
= "1";
258 const char* kDuration
= "2";
259 const char* kTreshold
= "5%";
262 CommandLine
command_line(test::GetReferenceFilesDir().Append(
263 FILE_PATH_LITERAL("sox.exe")));
265 CommandLine
command_line(base::FilePath(FILE_PATH_LITERAL("sox")));
267 command_line
.AppendArgPath(input_file
);
268 command_line
.AppendArgPath(output_file
);
269 command_line
.AppendArg("silence");
270 command_line
.AppendArg(kAbovePeriods
);
271 command_line
.AppendArg(kDuration
);
272 command_line
.AppendArg(kTreshold
);
273 command_line
.AppendArg("reverse");
274 command_line
.AppendArg("silence");
275 command_line
.AppendArg(kAbovePeriods
);
276 command_line
.AppendArg(kDuration
);
277 command_line
.AppendArg(kTreshold
);
278 command_line
.AppendArg("reverse");
280 VLOG(0) << "Running " << command_line
.GetCommandLineString();
282 bool ok
= base::GetAppOutput(command_line
, &result
);
283 VLOG(0) << "Output was:\n\n" << result
;
287 bool CanParseAsFloat(const std::string
& value
) {
288 return atof(value
.c_str()) != 0 || value
== "0";
291 // Runs PESQ to compare |reference_file| to a |actual_file|. The |sample_rate|
292 // can be either 16000 or 8000.
294 // PESQ is only mono-aware, so the files should preferably be recorded in mono.
295 // Furthermore it expects the file to be 16 rather than 32 bits, even though
296 // 32 bits might work. The audio bandwidth of the two files should be the same
297 // e.g. don't compare a 32 kHz file to a 8 kHz file.
299 // The raw score in MOS is written to |raw_mos|, whereas the MOS-LQO score is
300 // written to mos_lqo. The scores are returned as floats in string form (e.g.
301 // "3.145", etc). Returns true on success.
302 bool RunPesq(const base::FilePath
& reference_file
,
303 const base::FilePath
& actual_file
,
304 int sample_rate
, std::string
* raw_mos
, std::string
* mos_lqo
) {
305 // PESQ will break if the paths are too long (!).
306 EXPECT_LT(reference_file
.value().length(), 128u);
307 EXPECT_LT(actual_file
.value().length(), 128u);
310 base::FilePath pesq_path
=
311 test::GetReferenceFilesDir().Append(FILE_PATH_LITERAL("pesq.exe"));
313 base::FilePath pesq_path
=
314 test::GetReferenceFilesDir().Append(FILE_PATH_LITERAL("pesq"));
317 if (!base::PathExists(pesq_path
)) {
318 LOG(ERROR
) << "Missing PESQ binary in " << pesq_path
.value();
322 CommandLine
command_line(pesq_path
);
323 command_line
.AppendArg(base::StringPrintf("+%d", sample_rate
));
324 command_line
.AppendArgPath(reference_file
);
325 command_line
.AppendArgPath(actual_file
);
327 VLOG(0) << "Running " << command_line
.GetCommandLineString();
329 if (!base::GetAppOutput(command_line
, &result
)) {
330 LOG(ERROR
) << "Failed to run PESQ.";
333 VLOG(0) << "Output was:\n\n" << result
;
335 const std::string result_anchor
= "Prediction (Raw MOS, MOS-LQO): = ";
336 std::size_t anchor_pos
= result
.find(result_anchor
);
337 if (anchor_pos
== std::string::npos
) {
338 LOG(ERROR
) << "PESQ was not able to compute a score; we probably recorded "
343 // There are two tab-separated numbers on the format x.xxx, e.g. 5 chars each.
344 std::size_t first_number_pos
= anchor_pos
+ result_anchor
.length();
345 *raw_mos
= result
.substr(first_number_pos
, 5);
346 EXPECT_TRUE(CanParseAsFloat(*raw_mos
)) << "Failed to parse raw MOS number.";
347 *mos_lqo
= result
.substr(first_number_pos
+ 5 + 1, 5);
348 EXPECT_TRUE(CanParseAsFloat(*mos_lqo
)) << "Failed to parse MOS LQO number.";
353 static const bool kRunTestsWithFlag
[] = { false, true };
354 INSTANTIATE_TEST_CASE_P(WebRtcAudioQualityBrowserTests
,
355 WebRtcAudioQualityBrowserTest
,
356 testing::ValuesIn(kRunTestsWithFlag
));
358 #if defined(OS_LINUX) || defined(OS_WIN)
359 // Only implemented on Linux and Windows for now.
360 #define MAYBE_MANUAL_TestAudioQuality MANUAL_TestAudioQuality
362 #define MAYBE_MANUAL_TestAudioQuality DISABLED_MANUAL_TestAudioQuality
365 IN_PROC_BROWSER_TEST_P(WebRtcAudioQualityBrowserTest
,
366 MAYBE_MANUAL_TestAudioQuality
) {
368 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
369 // It would take work to implement this on XP; not prioritized right now.
370 LOG(ERROR
) << "This test is not implemented for Windows XP.";
374 ASSERT_TRUE(test::HasReferenceFilesInCheckout());
375 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
376 ASSERT_TRUE(peerconnection_server_
.Start());
378 ASSERT_TRUE(ForceMicrophoneVolumeTo100Percent());
380 ui_test_utils::NavigateToURL(
381 browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage
));
382 content::WebContents
* left_tab
=
383 browser()->tab_strip_model()->GetActiveWebContents();
385 chrome::AddTabAt(browser(), GURL(), -1, true);
386 content::WebContents
* right_tab
=
387 browser()->tab_strip_model()->GetActiveWebContents();
388 ui_test_utils::NavigateToURL(
389 browser(), embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage
));
391 ConnectToPeerConnectionServer("peer 1", left_tab
);
392 ConnectToPeerConnectionServer("peer 2", right_tab
);
394 EXPECT_EQ("ok-peerconnection-created",
395 ExecuteJavascript("preparePeerConnection()", left_tab
));
397 AddAudioFile(kReferenceFileRelativeUrl
, left_tab
);
399 EstablishCall(left_tab
, right_tab
);
401 // Note: the media flow isn't necessarily established on the connection just
402 // because the ready state is ok on both sides. We sleep a bit between call
403 // establishment and playing to avoid cutting of the beginning of the audio
405 test::SleepInJavascript(left_tab
, 2000);
407 base::FilePath recording
= CreateTemporaryWaveFile();
409 // Note: the sound clip is about 10 seconds: record for 15 seconds to get some
410 // safety margins on each side.
411 AudioRecorder recorder
;
412 static int kRecordingTimeSeconds
= 15;
413 ASSERT_TRUE(recorder
.StartRecording(kRecordingTimeSeconds
, recording
, true));
415 PlayAudioFile(left_tab
);
417 ASSERT_TRUE(recorder
.WaitForRecordingToEnd());
418 VLOG(0) << "Done recording to " << recording
.value() << std::endl
;
421 WaitUntilHangupVerified(left_tab
);
422 WaitUntilHangupVerified(right_tab
);
424 base::FilePath trimmed_recording
= CreateTemporaryWaveFile();
426 ASSERT_TRUE(RemoveSilence(recording
, trimmed_recording
));
427 VLOG(0) << "Trimmed silence: " << trimmed_recording
.value() << std::endl
;
431 base::FilePath reference_file_in_test_dir
=
432 test::GetReferenceFilesDir().Append(kReferenceFile
);
433 ASSERT_TRUE(RunPesq(reference_file_in_test_dir
, trimmed_recording
, 16000,
434 &raw_mos
, &mos_lqo
));
436 perf_test::PrintResult("audio_pesq", "", "raw_mos", raw_mos
, "score", true);
437 perf_test::PrintResult("audio_pesq", "", "mos_lqo", mos_lqo
, "score", true);
439 EXPECT_TRUE(base::DeleteFile(recording
, false));
440 EXPECT_TRUE(base::DeleteFile(trimmed_recording
, false));
442 ASSERT_TRUE(peerconnection_server_
.Stop());