blob: add4f2f72b81337946555e8953dca4eac2cb5aaf [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
Edward Lemurb4017712018-01-15 14:21:09 +010019import json
kjellander8f8d1a02017-03-06 04:01:16 -080020import logging
21import os
oprypin92220ff2017-03-23 03:40:03 -070022import re
oprypin6d305ba2017-03-30 04:01:30 -070023import shutil
kjellander8f8d1a02017-03-06 04:01:16 -080024import subprocess
25import sys
26
27
28SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
Henrik Kjellander5a6aa4f2017-09-15 09:31:54 +020029SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
kjellander8f8d1a02017-03-06 04:01:16 -080030
Edward Lemurb0250f02017-10-04 14:41:17 +020031NO_TOOLS_ERROR_MESSAGE = (
32 'Could not find PESQ or POLQA at %s.\n'
33 '\n'
34 'To fix this run:\n'
35 ' python %s %s\n'
36 '\n'
37 'Note that these tools are Google-internal due to licensing, so in order to '
38 'use them you will have to get your own license and manually put them in the '
39 'right location.\n'
40 'See https://cs.chromium.org/chromium/src/third_party/webrtc/tools_webrtc/'
41 'download_tools.py?rcl=bbceb76f540159e2dba0701ac03c514f01624130&l=13')
42
kjellander8f8d1a02017-03-06 04:01:16 -080043
oprypin92220ff2017-03-23 03:40:03 -070044def _LogCommand(command):
45 logging.info('Running %r', command)
46 return command
kjellander8f8d1a02017-03-06 04:01:16 -080047
48
49def _ParseArgs():
50 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
51 parser.add_argument('build_dir',
52 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070053 parser.add_argument('--remove', action='store_true',
54 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070055 parser.add_argument('--android', action='store_true',
56 help='Perform the test on a connected Android device instead.')
57 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
Edward Lesmes9599fd42018-03-12 16:43:05 -040058 parser.add_argument('--num-retries', default='0',
Edward Lesmes5b9c6842018-03-09 13:07:22 -050059 help='Number of times to retry the test on Android.')
Oleh Prypin637b0b52018-09-21 17:16:06 +020060 parser.add_argument('--isolated-script-test-perf-output', default=None,
61 help='Path to store perf results in chartjson format.')
62 parser.add_argument('--isolated-script-test-output', default=None,
63 help='Path to output an empty JSON file which Chromium infra requires.')
Edward Lemur7e3b5692017-10-04 17:03:16 +020064
65 # Ignore Chromium-specific flags
Edward Lemurd8b041c2018-01-16 14:30:28 +010066 parser.add_argument('--test-launcher-summary-output',
67 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080068 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020069
kjellander8f8d1a02017-03-06 04:01:16 -080070 return args
71
72
oprypin92220ff2017-03-23 03:40:03 -070073def _GetPlatform():
74 if sys.platform == 'win32':
75 return 'win'
76 elif sys.platform == 'darwin':
77 return 'mac'
78 elif sys.platform.startswith('linux'):
79 return 'linux'
80
81
Edward Lemurb0250f02017-10-04 14:41:17 +020082def _GetExtension():
83 return '.exe' if sys.platform == 'win32' else ''
84
85
86def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020087 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070088 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
89
Edward Lemurb0250f02017-10-04 14:41:17 +020090 platform = _GetPlatform()
91 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000092
Edward Lemurb0250f02017-10-04 14:41:17 +020093 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
94 if not os.path.isfile(pesq_path):
95 pesq_path = None
96
97 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
98 if not os.path.isfile(polqa_path):
99 polqa_path = None
100
101 if (platform != 'mac' and not polqa_path) or not pesq_path:
102 logging.error(NO_TOOLS_ERROR_MESSAGE,
103 toolchain_dir,
104 os.path.join(tools_dir, 'download_tools.py'),
105 toolchain_dir)
106
oprypinf2501002017-04-12 05:00:56 -0700107 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700108
109
oprypinabd101b2017-04-06 23:21:30 -0700110def ExtractTestRuns(lines, echo=False):
111 """Extracts information about tests from the output of a test runner.
112
113 Produces tuples (android_device, test_name, reference_file, degraded_file).
114 """
115 for line in lines:
116 if echo:
117 sys.stdout.write(line)
118
119 # Output from Android has a prefix with the device name.
120 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
121 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
122
123 match = re.search(test_re, line)
124 if match:
125 yield match.groups()
126
127
128def _GetFile(file_path, out_dir, move=False,
129 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700130 out_file_name = os.path.basename(file_path)
131 out_file_path = os.path.join(out_dir, out_file_name)
132
133 if android:
oprypinabd101b2017-04-06 23:21:30 -0700134 # Pull the file from the connected Android device.
135 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700136 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700137 if move:
138 # Remove that file.
139 adb_command = adb_prefix + ('shell', 'rm', file_path)
140 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700141 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700142 if move:
143 shutil.move(file_path, out_file_path)
144 else:
145 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700146
147 return out_file_path
148
149
oprypinf2501002017-04-12 05:00:56 -0700150def _RunPesq(executable_path, reference_file, degraded_file,
151 sample_rate_hz=16000):
152 directory = os.path.dirname(reference_file)
153 assert os.path.dirname(degraded_file) == directory
154
155 # Analyze audio.
156 command = [executable_path, '+%d' % sample_rate_hz,
157 os.path.basename(reference_file),
158 os.path.basename(degraded_file)]
159 # Need to provide paths in the current directory due to a bug in PESQ:
160 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
161 # 'path/to', PESQ crashes.
162 out = subprocess.check_output(_LogCommand(command),
163 cwd=directory, stderr=subprocess.STDOUT)
164
165 # Find the scores in stdout of PESQ.
166 match = re.search(
167 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
168 if match:
169 raw_mos, _ = match.groups()
170
171 return {'pesq_mos': (raw_mos, 'score')}
172 else:
173 logging.error('PESQ: %s', out.splitlines()[-1])
174 return {}
175
176
177def _RunPolqa(executable_path, reference_file, degraded_file):
178 # Analyze audio.
179 command = [executable_path, '-q', '-LC', 'NB',
180 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200181 process = subprocess.Popen(_LogCommand(command),
182 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700183 out, err = process.communicate()
184
185 # Find the scores in stdout of POLQA.
186 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
187
188 if process.returncode != 0 or not match:
189 if process.returncode == 2:
190 logging.warning('%s (2)', err.strip())
191 logging.warning('POLQA license error, skipping test.')
192 else:
193 logging.error('%s (%d)', err.strip(), process.returncode)
194 return {}
195
196 mos_lqo, = match.groups()
197 return {'polqa_mos_lqo': (mos_lqo, 'score')}
198
199
Edward Lemurb4017712018-01-15 14:21:09 +0100200def _AddChart(charts, metric, test_name, value, units):
201 chart = charts.setdefault(metric, {})
202 chart[test_name] = {
203 "type": "scalar",
204 "value": value,
205 "units": units,
206 }
207
208
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000209Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
oprypinf2501002017-04-12 05:00:56 -0700210 'sample_rate_hz'])
211
212
kjellander8f8d1a02017-03-06 04:01:16 -0800213def main():
214 # pylint: disable=W0101
215 logging.basicConfig(level=logging.INFO)
216
217 args = _ParseArgs()
218
Edward Lemurb0250f02017-10-04 14:41:17 +0200219 pesq_path, polqa_path = _GetPathToTools()
220 if pesq_path is None:
221 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800222
oprypin6d305ba2017-03-30 04:01:30 -0700223 out_dir = os.path.join(args.build_dir, '..')
224 if args.android:
225 test_command = [os.path.join(args.build_dir, 'bin',
Edward Lesmes5b9c6842018-03-09 13:07:22 -0500226 'run_low_bandwidth_audio_test'),
227 '-v', '--num-retries', args.num_retries]
oprypin6d305ba2017-03-30 04:01:30 -0700228 else:
229 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700230
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000231 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
oprypinf2501002017-04-12 05:00:56 -0700232 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
233 example_path = os.path.join(SRC_DIR, 'resources',
234 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200235 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000236 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700237
Edward Lemurb4017712018-01-15 14:21:09 +0100238 charts = {}
239
oprypinf2501002017-04-12 05:00:56 -0700240 for analyzer in analyzers:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000241 # Start the test executable that produces audio files.
242 test_process = subprocess.Popen(
243 _LogCommand(test_command + ['--sample_rate_hz=%d' %
244 analyzer.sample_rate_hz]),
245 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700246 try:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000247 lines = iter(test_process.stdout.readline, '')
248 for result in ExtractTestRuns(lines, echo=True):
249 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700250
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000251 adb_prefix = (args.adb_path,)
252 if android_device:
253 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700254
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000255 reference_file = _GetFile(reference_file, out_dir,
256 android=args.android, adb_prefix=adb_prefix)
257 degraded_file = _GetFile(degraded_file, out_dir, move=True,
258 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700259
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000260 analyzer_results = analyzer.func(analyzer.executable,
261 reference_file, degraded_file)
262 for metric, (value, units) in analyzer_results.items():
263 # Output a result for the perf dashboard.
264 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
265 _AddChart(charts, metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700266
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000267 if args.remove:
268 os.remove(reference_file)
269 os.remove(degraded_file)
oprypinf2501002017-04-12 05:00:56 -0700270 finally:
Mirko Bonadei4876cb22019-07-09 20:08:55 +0000271 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700272
Edward Lemured7b4ff2018-02-01 17:23:58 +0100273 if args.isolated_script_test_perf_output:
274 with open(args.isolated_script_test_perf_output, 'w') as f:
Edward Lemurb4017712018-01-15 14:21:09 +0100275 json.dump({"format_version": "1.0", "charts": charts}, f)
276
Oleh Prypin637b0b52018-09-21 17:16:06 +0200277 if args.isolated_script_test_output:
278 with open(args.isolated_script_test_output, 'w') as f:
279 json.dump({"version": 3}, f)
280
oprypin92220ff2017-03-23 03:40:03 -0700281 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800282
283
284if __name__ == '__main__':
285 sys.exit(main())