blob: 58fda4a9d35c71d3979d76fa216f8081baae2e1a [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 Lemur20196982017-10-03 11:14:35 +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 Lemur20196982017-10-03 11:14:35 +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
oprypin6d305ba2017-03-30 04:01:30 -070074 pesq_path = os.path.join(toolchain_dir, _GetPlatform(), 'pesq')
oprypinf2501002017-04-12 05:00:56 -070075 polqa_path = os.path.join(toolchain_dir, _GetPlatform(), 'PolqaOem64')
Edward Lemur20196982017-10-03 11:14:35 +020076
77 if not os.path.isfile(pesq_path) or not os.path.isfile(polqa_path):
78 logging.error(NO_TOOLS_ERROR_MESSAGE,
79 toolchain_dir,
80 os.path.join(tools_dir, 'download_tools.py'),
81 toolchain_dir)
82 return None, None
83
oprypinf2501002017-04-12 05:00:56 -070084 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -070085
86
oprypinabd101b2017-04-06 23:21:30 -070087def ExtractTestRuns(lines, echo=False):
88 """Extracts information about tests from the output of a test runner.
89
90 Produces tuples (android_device, test_name, reference_file, degraded_file).
91 """
92 for line in lines:
93 if echo:
94 sys.stdout.write(line)
95
96 # Output from Android has a prefix with the device name.
97 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
98 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
99
100 match = re.search(test_re, line)
101 if match:
102 yield match.groups()
103
104
105def _GetFile(file_path, out_dir, move=False,
106 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -0700107 out_file_name = os.path.basename(file_path)
108 out_file_path = os.path.join(out_dir, out_file_name)
109
110 if android:
oprypinabd101b2017-04-06 23:21:30 -0700111 # Pull the file from the connected Android device.
112 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -0700113 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -0700114 if move:
115 # Remove that file.
116 adb_command = adb_prefix + ('shell', 'rm', file_path)
117 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700118 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700119 if move:
120 shutil.move(file_path, out_file_path)
121 else:
122 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700123
124 return out_file_path
125
126
oprypinf2501002017-04-12 05:00:56 -0700127def _RunPesq(executable_path, reference_file, degraded_file,
128 sample_rate_hz=16000):
129 directory = os.path.dirname(reference_file)
130 assert os.path.dirname(degraded_file) == directory
131
132 # Analyze audio.
133 command = [executable_path, '+%d' % sample_rate_hz,
134 os.path.basename(reference_file),
135 os.path.basename(degraded_file)]
136 # Need to provide paths in the current directory due to a bug in PESQ:
137 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
138 # 'path/to', PESQ crashes.
139 out = subprocess.check_output(_LogCommand(command),
140 cwd=directory, stderr=subprocess.STDOUT)
141
142 # Find the scores in stdout of PESQ.
143 match = re.search(
144 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
145 if match:
146 raw_mos, _ = match.groups()
147
148 return {'pesq_mos': (raw_mos, 'score')}
149 else:
150 logging.error('PESQ: %s', out.splitlines()[-1])
151 return {}
152
153
154def _RunPolqa(executable_path, reference_file, degraded_file):
155 # Analyze audio.
156 command = [executable_path, '-q', '-LC', 'NB',
157 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemur20196982017-10-03 11:14:35 +0200158 process = subprocess.Popen(_LogCommand(command),
159 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
oprypinf2501002017-04-12 05:00:56 -0700160 out, err = process.communicate()
161
162 # Find the scores in stdout of POLQA.
163 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
164
165 if process.returncode != 0 or not match:
166 if process.returncode == 2:
167 logging.warning('%s (2)', err.strip())
168 logging.warning('POLQA license error, skipping test.')
169 else:
170 logging.error('%s (%d)', err.strip(), process.returncode)
171 return {}
172
173 mos_lqo, = match.groups()
174 return {'polqa_mos_lqo': (mos_lqo, 'score')}
175
176
177Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
178 'sample_rate_hz'])
179
180
kjellander8f8d1a02017-03-06 04:01:16 -0800181def main():
182 # pylint: disable=W0101
183 logging.basicConfig(level=logging.INFO)
184
185 args = _ParseArgs()
186
Edward Lemur20196982017-10-03 11:14:35 +0200187 pesq_path, polqa_path = _GetPathToTools()
188 if pesq_path is None:
189 return 1
kjellander8f8d1a02017-03-06 04:01:16 -0800190
oprypin6d305ba2017-03-30 04:01:30 -0700191 out_dir = os.path.join(args.build_dir, '..')
192 if args.android:
193 test_command = [os.path.join(args.build_dir, 'bin',
194 'run_low_bandwidth_audio_test'), '-v']
195 else:
196 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700197
oprypinf2501002017-04-12 05:00:56 -0700198 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
199 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
200 example_path = os.path.join(SRC_DIR, 'resources',
201 'voice_engine', 'audio_tiny48.wav')
202 if _RunPolqa(polqa_path, example_path, example_path):
203 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700204
oprypinf2501002017-04-12 05:00:56 -0700205 for analyzer in analyzers:
206 # Start the test executable that produces audio files.
207 test_process = subprocess.Popen(
208 _LogCommand(test_command + ['--sample_rate_hz=%d' %
209 analyzer.sample_rate_hz]),
oprypin4f1f4582017-06-14 09:35:11 -0700210 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700211 try:
212 lines = iter(test_process.stdout.readline, '')
213 for result in ExtractTestRuns(lines, echo=True):
214 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700215
oprypinf2501002017-04-12 05:00:56 -0700216 adb_prefix = (args.adb_path,)
217 if android_device:
218 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700219
oprypinf2501002017-04-12 05:00:56 -0700220 reference_file = _GetFile(reference_file, out_dir,
221 android=args.android, adb_prefix=adb_prefix)
222 degraded_file = _GetFile(degraded_file, out_dir, move=True,
223 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700224
oprypinf2501002017-04-12 05:00:56 -0700225 analyzer_results = analyzer.func(analyzer.executable,
226 reference_file, degraded_file)
227 for metric, (value, units) in analyzer_results.items():
228 # Output a result for the perf dashboard.
229 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700230
oprypinf2501002017-04-12 05:00:56 -0700231 if args.remove:
232 os.remove(reference_file)
233 os.remove(degraded_file)
234 finally:
235 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700236
oprypin92220ff2017-03-23 03:40:03 -0700237 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800238
239
240if __name__ == '__main__':
241 sys.exit(main())