blob: 412b267f56ec586751a42b13a69a6173fa021031 [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 Lemurf4898a62017-10-03 14:36:48 +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')
kjellander8f8d1a02017-03-06 04:01:16 -080057 args = parser.parse_args()
58 return args
59
60
oprypin92220ff2017-03-23 03:40:03 -070061def _GetPlatform():
62 if sys.platform == 'win32':
63 return 'win'
64 elif sys.platform == 'darwin':
65 return 'mac'
66 elif sys.platform.startswith('linux'):
67 return 'linux'
68
69
Edward Lemurf4898a62017-10-03 14:36:48 +020070def _GetPathToTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020071 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070072 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
73
Edward Lemurf4898a62017-10-03 14:36:48 +020074 platform = _GetPlatform()
Edward Lemurbb1222f2017-10-03 12:33:38 +000075
Edward Lemurf4898a62017-10-03 14:36:48 +020076 pesq_path = os.path.join(toolchain_dir, platform, 'pesq')
77 if not os.path.isfile(pesq_path):
78 pesq_path = None
79
80 polqa_path = os.path.join(toolchain_dir, platform, 'PolqaOem64')
81 if not os.path.isfile(polqa_path):
82 polqa_path = None
83
84 if (platform != 'mac' and not polqa_path) or not pesq_path:
85 logging.error(NO_TOOLS_ERROR_MESSAGE,
86 toolchain_dir,
87 os.path.join(tools_dir, 'download_tools.py'),
88 toolchain_dir)
89
oprypinf2501002017-04-12 05:00:56 -070090 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -070091
92
oprypinabd101b2017-04-06 23:21:30 -070093def ExtractTestRuns(lines, echo=False):
94 """Extracts information about tests from the output of a test runner.
95
96 Produces tuples (android_device, test_name, reference_file, degraded_file).
97 """
98 for line in lines:
99 if echo:
100 sys.stdout.write(line)
101
102 # Output from Android has a prefix with the device name.
103 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
104 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
105
106 match = re.search(test_re, line)
107 if match:
108 yield match.groups()
109
110
111def _GetFile(file_path, out_dir, move=False,
112 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700113 out_file_name = os.path.basename(file_path)
114 out_file_path = os.path.join(out_dir, out_file_name)
115
116 if android:
oprypinabd101b2017-04-06 23:21:30 -0700117 # Pull the file from the connected Android device.
118 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700119 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700120 if move:
121 # Remove that file.
122 adb_command = adb_prefix + ('shell', 'rm', file_path)
123 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700124 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700125 if move:
126 shutil.move(file_path, out_file_path)
127 else:
128 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700129
130 return out_file_path
131
132
oprypinf2501002017-04-12 05:00:56 -0700133def _RunPesq(executable_path, reference_file, degraded_file,
134 sample_rate_hz=16000):
135 directory = os.path.dirname(reference_file)
136 assert os.path.dirname(degraded_file) == directory
137
138 # Analyze audio.
139 command = [executable_path, '+%d' % sample_rate_hz,
140 os.path.basename(reference_file),
141 os.path.basename(degraded_file)]
142 # Need to provide paths in the current directory due to a bug in PESQ:
143 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
144 # 'path/to', PESQ crashes.
145 out = subprocess.check_output(_LogCommand(command),
146 cwd=directory, stderr=subprocess.STDOUT)
147
148 # Find the scores in stdout of PESQ.
149 match = re.search(
150 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
151 if match:
152 raw_mos, _ = match.groups()
153
154 return {'pesq_mos': (raw_mos, 'score')}
155 else:
156 logging.error('PESQ: %s', out.splitlines()[-1])
157 return {}
158
159
160def _RunPolqa(executable_path, reference_file, degraded_file):
161 # Analyze audio.
162 command = [executable_path, '-q', '-LC', 'NB',
163 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemurf4898a62017-10-03 14:36:48 +0200164 process = subprocess.Popen(_LogCommand(command),
165 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700166 out, err = process.communicate()
167
168 # Find the scores in stdout of POLQA.
169 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
170
171 if process.returncode != 0 or not match:
172 if process.returncode == 2:
173 logging.warning('%s (2)', err.strip())
174 logging.warning('POLQA license error, skipping test.')
175 else:
176 logging.error('%s (%d)', err.strip(), process.returncode)
177 return {}
178
179 mos_lqo, = match.groups()
180 return {'polqa_mos_lqo': (mos_lqo, 'score')}
181
182
183Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
184 'sample_rate_hz'])
185
186
kjellander8f8d1a02017-03-06 04:01:16 -0800187def main():
188 # pylint: disable=W0101
189 logging.basicConfig(level=logging.INFO)
190
191 args = _ParseArgs()
192
Edward Lemurf4898a62017-10-03 14:36:48 +0200193 pesq_path, polqa_path = _GetPathToTools()
194 if pesq_path is None:
195 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800196
oprypin6d305ba2017-03-30 04:01:30 -0700197 out_dir = os.path.join(args.build_dir, '..')
198 if args.android:
199 test_command = [os.path.join(args.build_dir, 'bin',
200 'run_low_bandwidth_audio_test'), '-v']
201 else:
202 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700203
oprypinf2501002017-04-12 05:00:56 -0700204 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
205 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
206 example_path = os.path.join(SRC_DIR, 'resources',
207 'voice_engine', 'audio_tiny48.wav')
Edward Lemurf4898a62017-10-03 14:36:48 +0200208 if polqa_path and _RunPolqa(polqa_path, example_path, example_path):
oprypinf2501002017-04-12 05:00:56 -0700209 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700210
oprypinf2501002017-04-12 05:00:56 -0700211 for analyzer in analyzers:
212 # Start the test executable that produces audio files.
213 test_process = subprocess.Popen(
214 _LogCommand(test_command + ['--sample_rate_hz=%d' %
215 analyzer.sample_rate_hz]),
oprypin4f1f4582017-06-14 09:35:11 -0700216 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700217 try:
218 lines = iter(test_process.stdout.readline, '')
219 for result in ExtractTestRuns(lines, echo=True):
220 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700221
oprypinf2501002017-04-12 05:00:56 -0700222 adb_prefix = (args.adb_path,)
223 if android_device:
224 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700225
oprypinf2501002017-04-12 05:00:56 -0700226 reference_file = _GetFile(reference_file, out_dir,
227 android=args.android, adb_prefix=adb_prefix)
228 degraded_file = _GetFile(degraded_file, out_dir, move=True,
229 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700230
oprypinf2501002017-04-12 05:00:56 -0700231 analyzer_results = analyzer.func(analyzer.executable,
232 reference_file, degraded_file)
233 for metric, (value, units) in analyzer_results.items():
234 # Output a result for the perf dashboard.
235 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700236
oprypinf2501002017-04-12 05:00:56 -0700237 if args.remove:
238 os.remove(reference_file)
239 os.remove(degraded_file)
240 finally:
241 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700242
oprypin92220ff2017-03-23 03:40:03 -0700243 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800244
245
246if __name__ == '__main__':
247 sys.exit(main())