blob: 05dcf47f999cfe7bd51d8728c3ef11181d031fa3 [file] [log] [blame]
kjellander8f8d1a02017-03-06 04:01:16 -08001#!/usr/bin/env python
2# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3#
4# Use of this source code is governed by a BSD-style license
5# that can be found in the LICENSE file in the root of the source
6# tree. An additional intellectual property rights grant can be found
7# in the file PATENTS. All contributing project authors may
8# be found in the AUTHORS file in the root of the source tree.
9
10"""
11This script is the wrapper that runs the low-bandwidth audio test.
12
13After running the test, post-process steps for calculating audio quality of the
14output files will be performed.
15"""
16
17import argparse
oprypinf2501002017-04-12 05:00:56 -070018import collections
kjellander8f8d1a02017-03-06 04:01:16 -080019import logging
20import os
oprypin92220ff2017-03-23 03:40:03 -070021import re
oprypin6d305ba2017-03-30 04:01:30 -070022import shutil
kjellander8f8d1a02017-03-06 04:01:16 -080023import subprocess
24import sys
25
26
27SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
Henrik Kjellander5a6aa4f2017-09-15 09:31:54 +020028SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
kjellander8f8d1a02017-03-06 04:01:16 -080029
Edward Lemurb0250f02017-10-04 14:41:17 +020030NO_TOOLS_ERROR_MESSAGE = (
31 'Could not find PESQ or POLQA at %s.\n'
32 '\n'
33 'To fix this run:\n'
34 ' python %s %s\n'
35 '\n'
36 'Note that these tools are Google-internal due to licensing, so in order to '
37 'use them you will have to get your own license and manually put them in the '
38 'right location.\n'
39 'See https://cs.chromium.org/chromium/src/third_party/webrtc/tools_webrtc/'
40 'download_tools.py?rcl=bbceb76f540159e2dba0701ac03c514f01624130&l=13')
41
kjellander8f8d1a02017-03-06 04:01:16 -080042
oprypin92220ff2017-03-23 03:40:03 -070043def _LogCommand(command):
44 logging.info('Running %r', command)
45 return command
kjellander8f8d1a02017-03-06 04:01:16 -080046
47
48def _ParseArgs():
49 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
50 parser.add_argument('build_dir',
51 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070052 parser.add_argument('--remove', action='store_true',
53 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070054 parser.add_argument('--android', action='store_true',
55 help='Perform the test on a connected Android device instead.')
56 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
Edward Lemur7e3b5692017-10-04 17:03:16 +020057
58 # Ignore Chromium-specific flags
59 parser.add_argument('--isolated-script-test-output',
60 type=str, default=None)
Edward Lemur88b23f62017-10-04 19:20:23 +020061 parser.add_argument('--isolated-script-test-perf-output',
Edward Lemur7e3b5692017-10-04 17:03:16 +020062 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080063 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020064
kjellander8f8d1a02017-03-06 04:01:16 -080065 return args
66
67
oprypin92220ff2017-03-23 03:40:03 -070068def _GetPlatform():
69 if sys.platform == 'win32':
70 return 'win'
71 elif sys.platform == 'darwin':
72 return 'mac'
73 elif sys.platform.startswith('linux'):
74 return 'linux'
75
76
Edward Lemurb0250f02017-10-04 14:41:17 +020077def _GetExtension():
78 return '.exe' if sys.platform == 'win32' else ''
79
80
81def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020082 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070083 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
84
Edward Lemurb0250f02017-10-04 14:41:17 +020085 platform = _GetPlatform()
86 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000087
Edward Lemurb0250f02017-10-04 14:41:17 +020088 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
89 if not os.path.isfile(pesq_path):
90 pesq_path = None
91
92 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
93 if not os.path.isfile(polqa_path):
94 polqa_path = None
95
96 if (platform != 'mac' and not polqa_path) or not pesq_path:
97 logging.error(NO_TOOLS_ERROR_MESSAGE,
98 toolchain_dir,
99 os.path.join(tools_dir, 'download_tools.py'),
100 toolchain_dir)
101
oprypinf2501002017-04-12 05:00:56 -0700102 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700103
104
oprypinabd101b2017-04-06 23:21:30 -0700105def ExtractTestRuns(lines, echo=False):
106 """Extracts information about tests from the output of a test runner.
107
108 Produces tuples (android_device, test_name, reference_file, degraded_file).
109 """
110 for line in lines:
111 if echo:
112 sys.stdout.write(line)
113
114 # Output from Android has a prefix with the device name.
115 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
116 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
117
118 match = re.search(test_re, line)
119 if match:
120 yield match.groups()
121
122
123def _GetFile(file_path, out_dir, move=False,
124 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700125 out_file_name = os.path.basename(file_path)
126 out_file_path = os.path.join(out_dir, out_file_name)
127
128 if android:
oprypinabd101b2017-04-06 23:21:30 -0700129 # Pull the file from the connected Android device.
130 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700131 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700132 if move:
133 # Remove that file.
134 adb_command = adb_prefix + ('shell', 'rm', file_path)
135 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700136 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700137 if move:
138 shutil.move(file_path, out_file_path)
139 else:
140 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700141
142 return out_file_path
143
144
oprypinf2501002017-04-12 05:00:56 -0700145def _RunPesq(executable_path, reference_file, degraded_file,
146 sample_rate_hz=16000):
147 directory = os.path.dirname(reference_file)
148 assert os.path.dirname(degraded_file) == directory
149
150 # Analyze audio.
151 command = [executable_path, '+%d' % sample_rate_hz,
152 os.path.basename(reference_file),
153 os.path.basename(degraded_file)]
154 # Need to provide paths in the current directory due to a bug in PESQ:
155 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
156 # 'path/to', PESQ crashes.
157 out = subprocess.check_output(_LogCommand(command),
158 cwd=directory, stderr=subprocess.STDOUT)
159
160 # Find the scores in stdout of PESQ.
161 match = re.search(
162 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
163 if match:
164 raw_mos, _ = match.groups()
165
166 return {'pesq_mos': (raw_mos, 'score')}
167 else:
168 logging.error('PESQ: %s', out.splitlines()[-1])
169 return {}
170
171
172def _RunPolqa(executable_path, reference_file, degraded_file):
173 # Analyze audio.
174 command = [executable_path, '-q', '-LC', 'NB',
175 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200176 process = subprocess.Popen(_LogCommand(command),
177 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700178 out, err = process.communicate()
179
180 # Find the scores in stdout of POLQA.
181 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
182
183 if process.returncode != 0 or not match:
184 if process.returncode == 2:
185 logging.warning('%s (2)', err.strip())
186 logging.warning('POLQA license error, skipping test.')
187 else:
188 logging.error('%s (%d)', err.strip(), process.returncode)
189 return {}
190
191 mos_lqo, = match.groups()
192 return {'polqa_mos_lqo': (mos_lqo, 'score')}
193
194
195Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
196 'sample_rate_hz'])
197
198
kjellander8f8d1a02017-03-06 04:01:16 -0800199def main():
200 # pylint: disable=W0101
201 logging.basicConfig(level=logging.INFO)
202
203 args = _ParseArgs()
204
Edward Lemurb0250f02017-10-04 14:41:17 +0200205 pesq_path, polqa_path = _GetPathToTools()
206 if pesq_path is None:
207 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800208
oprypin6d305ba2017-03-30 04:01:30 -0700209 out_dir = os.path.join(args.build_dir, '..')
210 if args.android:
211 test_command = [os.path.join(args.build_dir, 'bin',
212 'run_low_bandwidth_audio_test'), '-v']
213 else:
214 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700215
oprypinf2501002017-04-12 05:00:56 -0700216 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
217 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
218 example_path = os.path.join(SRC_DIR, 'resources',
219 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200220 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
oprypinf2501002017-04-12 05:00:56 -0700221 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700222
oprypinf2501002017-04-12 05:00:56 -0700223 for analyzer in analyzers:
224 # Start the test executable that produces audio files.
225 test_process = subprocess.Popen(
226 _LogCommand(test_command + ['--sample_rate_hz=%d' %
227 analyzer.sample_rate_hz]),
oprypin4f1f4582017-06-14 09:35:11 -0700228 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700229 try:
230 lines = iter(test_process.stdout.readline, '')
231 for result in ExtractTestRuns(lines, echo=True):
232 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700233
oprypinf2501002017-04-12 05:00:56 -0700234 adb_prefix = (args.adb_path,)
235 if android_device:
236 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700237
oprypinf2501002017-04-12 05:00:56 -0700238 reference_file = _GetFile(reference_file, out_dir,
239 android=args.android, adb_prefix=adb_prefix)
240 degraded_file = _GetFile(degraded_file, out_dir, move=True,
241 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700242
oprypinf2501002017-04-12 05:00:56 -0700243 analyzer_results = analyzer.func(analyzer.executable,
244 reference_file, degraded_file)
245 for metric, (value, units) in analyzer_results.items():
246 # Output a result for the perf dashboard.
247 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700248
oprypinf2501002017-04-12 05:00:56 -0700249 if args.remove:
250 os.remove(reference_file)
251 os.remove(degraded_file)
252 finally:
253 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700254
oprypin92220ff2017-03-23 03:40:03 -0700255 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800256
257
258if __name__ == '__main__':
259 sys.exit(main())