blob: 9e2597741b93359982e26f15396ce0e904bb1619 [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 Lemurb4017712018-01-15 14:21:09 +010058 parser.add_argument('--chartjson-result-file',
59 help='Where to store perf results in chartjson format.', default=None)
Edward Lemur7e3b5692017-10-04 17:03:16 +020060
61 # Ignore Chromium-specific flags
62 parser.add_argument('--isolated-script-test-output',
63 type=str, default=None)
Edward Lemur88b23f62017-10-04 19:20:23 +020064 parser.add_argument('--isolated-script-test-perf-output',
Edward Lemur7e3b5692017-10-04 17:03:16 +020065 type=str, default=None)
kjellander8f8d1a02017-03-06 04:01:16 -080066 args = parser.parse_args()
Edward Lemur7e3b5692017-10-04 17:03:16 +020067
kjellander8f8d1a02017-03-06 04:01:16 -080068 return args
69
70
oprypin92220ff2017-03-23 03:40:03 -070071def _GetPlatform():
72 if sys.platform == 'win32':
73 return 'win'
74 elif sys.platform == 'darwin':
75 return 'mac'
76 elif sys.platform.startswith('linux'):
77 return 'linux'
78
79
Edward Lemurb0250f02017-10-04 14:41:17 +020080def _GetExtension():
81 return '.exe' if sys.platform == 'win32' else ''
82
83
84def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020085 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070086 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
87
Edward Lemurb0250f02017-10-04 14:41:17 +020088 platform = _GetPlatform()
89 ext = _GetExtension()
Edward Lemurbb1222f2017-10-03 12:33:38 +000090
Edward Lemurb0250f02017-10-04 14:41:17 +020091 pesq_path = os.path.join(toolchain_dir, platform, 'pesq' + ext)
92 if not os.path.isfile(pesq_path):
93 pesq_path = None
94
95 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64' + ext)
96 if not os.path.isfile(polqa_path):
97 polqa_path = None
98
99 if (platform != 'mac' and not polqa_path) or not pesq_path:
100 logging.error(NO_TOOLS_ERROR_MESSAGE,
101 toolchain_dir,
102 os.path.join(tools_dir, 'download_tools.py'),
103 toolchain_dir)
104
oprypinf2501002017-04-12 05:00:56 -0700105 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -0700106
107
oprypinabd101b2017-04-06 23:21:30 -0700108def ExtractTestRuns(lines, echo=False):
109 """Extracts information about tests from the output of a test runner.
110
111 Produces tuples (android_device, test_name, reference_file, degraded_file).
112 """
113 for line in lines:
114 if echo:
115 sys.stdout.write(line)
116
117 # Output from Android has a prefix with the device name.
118 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
119 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
120
121 match = re.search(test_re, line)
122 if match:
123 yield match.groups()
124
125
126def _GetFile(file_path, out_dir, move=False,
127 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700128 out_file_name = os.path.basename(file_path)
129 out_file_path = os.path.join(out_dir, out_file_name)
130
131 if android:
oprypinabd101b2017-04-06 23:21:30 -0700132 # Pull the file from the connected Android device.
133 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700134 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700135 if move:
136 # Remove that file.
137 adb_command = adb_prefix + ('shell', 'rm', file_path)
138 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700139 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700140 if move:
141 shutil.move(file_path, out_file_path)
142 else:
143 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700144
145 return out_file_path
146
147
oprypinf2501002017-04-12 05:00:56 -0700148def _RunPesq(executable_path, reference_file, degraded_file,
149 sample_rate_hz=16000):
150 directory = os.path.dirname(reference_file)
151 assert os.path.dirname(degraded_file) == directory
152
153 # Analyze audio.
154 command = [executable_path, '+%d' % sample_rate_hz,
155 os.path.basename(reference_file),
156 os.path.basename(degraded_file)]
157 # Need to provide paths in the current directory due to a bug in PESQ:
158 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
159 # 'path/to', PESQ crashes.
160 out = subprocess.check_output(_LogCommand(command),
161 cwd=directory, stderr=subprocess.STDOUT)
162
163 # Find the scores in stdout of PESQ.
164 match = re.search(
165 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
166 if match:
167 raw_mos, _ = match.groups()
168
169 return {'pesq_mos': (raw_mos, 'score')}
170 else:
171 logging.error('PESQ: %s', out.splitlines()[-1])
172 return {}
173
174
175def _RunPolqa(executable_path, reference_file, degraded_file):
176 # Analyze audio.
177 command = [executable_path, '-q', '-LC', 'NB',
178 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurb0250f02017-10-04 14:41:17 +0200179 process = subprocess.Popen(_LogCommand(command),
180 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700181 out, err = process.communicate()
182
183 # Find the scores in stdout of POLQA.
184 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
185
186 if process.returncode != 0 or not match:
187 if process.returncode == 2:
188 logging.warning('%s (2)', err.strip())
189 logging.warning('POLQA license error, skipping test.')
190 else:
191 logging.error('%s (%d)', err.strip(), process.returncode)
192 return {}
193
194 mos_lqo, = match.groups()
195 return {'polqa_mos_lqo': (mos_lqo, 'score')}
196
197
Edward Lemurb4017712018-01-15 14:21:09 +0100198def _AddChart(charts, metric, test_name, value, units):
199 chart = charts.setdefault(metric, {})
200 chart[test_name] = {
201 "type": "scalar",
202 "value": value,
203 "units": units,
204 }
205
206
oprypinf2501002017-04-12 05:00:56 -0700207Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
208 'sample_rate_hz'])
209
210
kjellander8f8d1a02017-03-06 04:01:16 -0800211def main():
212 # pylint: disable=W0101
213 logging.basicConfig(level=logging.INFO)
214
215 args = _ParseArgs()
216
Edward Lemurb0250f02017-10-04 14:41:17 +0200217 pesq_path, polqa_path = _GetPathToTools()
218 if pesq_path is None:
219 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800220
oprypin6d305ba2017-03-30 04:01:30 -0700221 out_dir = os.path.join(args.build_dir, '..')
222 if args.android:
223 test_command = [os.path.join(args.build_dir, 'bin',
224 'run_low_bandwidth_audio_test'), '-v']
225 else:
226 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700227
oprypinf2501002017-04-12 05:00:56 -0700228 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
229 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
230 example_path = os.path.join(SRC_DIR, 'resources',
231 'voice_engine', 'audio_tiny48.wav')
Edward Lemurb0250f02017-10-04 14:41:17 +0200232 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
oprypinf2501002017-04-12 05:00:56 -0700233 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700234
Edward Lemurb4017712018-01-15 14:21:09 +0100235 charts = {}
236
oprypinf2501002017-04-12 05:00:56 -0700237 for analyzer in analyzers:
238 # Start the test executable that produces audio files.
239 test_process = subprocess.Popen(
240 _LogCommand(test_command + ['--sample_rate_hz=%d' %
241 analyzer.sample_rate_hz]),
oprypin4f1f4582017-06-14 09:35:11 -0700242 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700243 try:
244 lines = iter(test_process.stdout.readline, '')
245 for result in ExtractTestRuns(lines, echo=True):
246 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700247
oprypinf2501002017-04-12 05:00:56 -0700248 adb_prefix = (args.adb_path,)
249 if android_device:
250 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700251
oprypinf2501002017-04-12 05:00:56 -0700252 reference_file = _GetFile(reference_file, out_dir,
253 android=args.android, adb_prefix=adb_prefix)
254 degraded_file = _GetFile(degraded_file, out_dir, move=True,
255 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700256
oprypinf2501002017-04-12 05:00:56 -0700257 analyzer_results = analyzer.func(analyzer.executable,
258 reference_file, degraded_file)
259 for metric, (value, units) in analyzer_results.items():
260 # Output a result for the perf dashboard.
261 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
Edward Lemurb4017712018-01-15 14:21:09 +0100262 _AddChart(charts, metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700263
oprypinf2501002017-04-12 05:00:56 -0700264 if args.remove:
265 os.remove(reference_file)
266 os.remove(degraded_file)
267 finally:
268 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700269
Edward Lemurb4017712018-01-15 14:21:09 +0100270 if args.chartjson_result_file:
271 with open(args.chartjson_result_file, 'w') as f:
272 json.dump({"format_version": "1.0", "charts": charts}, f)
273
oprypin92220ff2017-03-23 03:40:03 -0700274 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800275
276
277if __name__ == '__main__':
278 sys.exit(main())