blob: 93da7db16f048abe7d3a42d1d62c66f198199934 [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
30
oprypin92220ff2017-03-23 03:40:03 -070031def _LogCommand(command):
32 logging.info('Running %r', command)
33 return command
kjellander8f8d1a02017-03-06 04:01:16 -080034
35
36def _ParseArgs():
37 parser = argparse.ArgumentParser(description='Run low-bandwidth audio tests.')
38 parser.add_argument('build_dir',
39 help='Path to the build directory (e.g. out/Release).')
oprypin92220ff2017-03-23 03:40:03 -070040 parser.add_argument('--remove', action='store_true',
41 help='Remove output audio files after testing.')
oprypin6d305ba2017-03-30 04:01:30 -070042 parser.add_argument('--android', action='store_true',
43 help='Perform the test on a connected Android device instead.')
44 parser.add_argument('--adb-path', help='Path to adb binary.', default='adb')
kjellander8f8d1a02017-03-06 04:01:16 -080045 args = parser.parse_args()
46 return args
47
48
oprypin92220ff2017-03-23 03:40:03 -070049def _GetPlatform():
50 if sys.platform == 'win32':
51 return 'win'
52 elif sys.platform == 'darwin':
53 return 'mac'
54 elif sys.platform.startswith('linux'):
55 return 'linux'
56
57
Edward Lemur45a0b362017-10-03 14:00:06 +000058def _DownloadTools():
Henrik Kjellander90fd7d82017-05-09 08:30:10 +020059 tools_dir = os.path.join(SRC_DIR, 'tools_webrtc')
oprypin92220ff2017-03-23 03:40:03 -070060 toolchain_dir = os.path.join(tools_dir, 'audio_quality')
61
Edward Lemur45a0b362017-10-03 14:00:06 +000062 # Download PESQ and POLQA.
63 download_script = os.path.join(tools_dir, 'download_tools.py')
64 command = [sys.executable, download_script, toolchain_dir]
65 subprocess.check_call(_LogCommand(command))
Edward Lemurbb1222f2017-10-03 12:33:38 +000066
Edward Lemur45a0b362017-10-03 14:00:06 +000067 pesq_path = os.path.join(toolchain_dir, _GetPlatform(), 'pesq')
68 polqa_path = os.path.join(toolchain_dir, _GetPlatform(), 'PolqaOem64')
oprypinf2501002017-04-12 05:00:56 -070069 return pesq_path, polqa_path
oprypin92220ff2017-03-23 03:40:03 -070070
71
oprypinabd101b2017-04-06 23:21:30 -070072def ExtractTestRuns(lines, echo=False):
73 """Extracts information about tests from the output of a test runner.
74
75 Produces tuples (android_device, test_name, reference_file, degraded_file).
76 """
77 for line in lines:
78 if echo:
79 sys.stdout.write(line)
80
81 # Output from Android has a prefix with the device name.
82 android_prefix_re = r'(?:I\b.+\brun_tests_on_device\((.+?)\)\s*)?'
83 test_re = r'^' + android_prefix_re + r'TEST (\w+) ([^ ]+?) ([^ ]+?)\s*$'
84
85 match = re.search(test_re, line)
86 if match:
87 yield match.groups()
88
89
90def _GetFile(file_path, out_dir, move=False,
91 android=False, adb_prefix=('adb',)):
oprypin6d305ba2017-03-30 04:01:30 -070092 out_file_name = os.path.basename(file_path)
93 out_file_path = os.path.join(out_dir, out_file_name)
94
95 if android:
oprypinabd101b2017-04-06 23:21:30 -070096 # Pull the file from the connected Android device.
97 adb_command = adb_prefix + ('pull', file_path, out_dir)
oprypin6d305ba2017-03-30 04:01:30 -070098 subprocess.check_call(_LogCommand(adb_command))
oprypinabd101b2017-04-06 23:21:30 -070099 if move:
100 # Remove that file.
101 adb_command = adb_prefix + ('shell', 'rm', file_path)
102 subprocess.check_call(_LogCommand(adb_command))
oprypin6d305ba2017-03-30 04:01:30 -0700103 elif os.path.abspath(file_path) != os.path.abspath(out_file_path):
oprypinabd101b2017-04-06 23:21:30 -0700104 if move:
105 shutil.move(file_path, out_file_path)
106 else:
107 shutil.copy(file_path, out_file_path)
oprypin6d305ba2017-03-30 04:01:30 -0700108
109 return out_file_path
110
111
oprypinf2501002017-04-12 05:00:56 -0700112def _RunPesq(executable_path, reference_file, degraded_file,
113 sample_rate_hz=16000):
114 directory = os.path.dirname(reference_file)
115 assert os.path.dirname(degraded_file) == directory
116
117 # Analyze audio.
118 command = [executable_path, '+%d' % sample_rate_hz,
119 os.path.basename(reference_file),
120 os.path.basename(degraded_file)]
121 # Need to provide paths in the current directory due to a bug in PESQ:
122 # On Mac, for some 'path/to/file.wav', if 'file.wav' is longer than
123 # 'path/to', PESQ crashes.
124 out = subprocess.check_output(_LogCommand(command),
125 cwd=directory, stderr=subprocess.STDOUT)
126
127 # Find the scores in stdout of PESQ.
128 match = re.search(
129 r'Prediction \(Raw MOS, MOS-LQO\):\s+=\s+([\d.]+)\s+([\d.]+)', out)
130 if match:
131 raw_mos, _ = match.groups()
132
133 return {'pesq_mos': (raw_mos, 'score')}
134 else:
135 logging.error('PESQ: %s', out.splitlines()[-1])
136 return {}
137
138
139def _RunPolqa(executable_path, reference_file, degraded_file):
140 # Analyze audio.
141 command = [executable_path, '-q', '-LC', 'NB',
142 '-Ref', reference_file, '-Test', degraded_file]
Edward Lemur45a0b362017-10-03 14:00:06 +0000143 try:
144 process = subprocess.Popen(_LogCommand(command),
145 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
146 except OSError as e:
147 if e.errno == os.errno.ENOENT:
148 logging.warning('POLQA executable missing, skipping test.')
149 return {}
150 else:
151 raise
oprypinf2501002017-04-12 05:00:56 -0700152 out, err = process.communicate()
153
154 # Find the scores in stdout of POLQA.
155 match = re.search(r'\bMOS-LQO:\s+([\d.]+)', out)
156
157 if process.returncode != 0 or not match:
158 if process.returncode == 2:
159 logging.warning('%s (2)', err.strip())
160 logging.warning('POLQA license error, skipping test.')
161 else:
162 logging.error('%s (%d)', err.strip(), process.returncode)
163 return {}
164
165 mos_lqo, = match.groups()
166 return {'polqa_mos_lqo': (mos_lqo, 'score')}
167
168
169Analyzer = collections.namedtuple('Analyzer', ['func', 'executable',
170 'sample_rate_hz'])
171
172
kjellander8f8d1a02017-03-06 04:01:16 -0800173def main():
174 # pylint: disable=W0101
175 logging.basicConfig(level=logging.INFO)
176
177 args = _ParseArgs()
178
Edward Lemur45a0b362017-10-03 14:00:06 +0000179 pesq_path, polqa_path = _DownloadTools()
kjellander8f8d1a02017-03-06 04:01:16 -0800180
oprypin6d305ba2017-03-30 04:01:30 -0700181 out_dir = os.path.join(args.build_dir, '..')
182 if args.android:
183 test_command = [os.path.join(args.build_dir, 'bin',
184 'run_low_bandwidth_audio_test'), '-v']
185 else:
186 test_command = [os.path.join(args.build_dir, 'low_bandwidth_audio_test')]
oprypin92220ff2017-03-23 03:40:03 -0700187
oprypinf2501002017-04-12 05:00:56 -0700188 analyzers = [Analyzer(_RunPesq, pesq_path, 16000)]
189 # Check if POLQA can run at all, or skip the 48 kHz tests entirely.
190 example_path = os.path.join(SRC_DIR, 'resources',
191 'voice_engine', 'audio_tiny48.wav')
Edward Lemur45a0b362017-10-03 14:00:06 +0000192 if _RunPolqa(polqa_path, example_path, example_path):
oprypinf2501002017-04-12 05:00:56 -0700193 analyzers.append(Analyzer(_RunPolqa, polqa_path, 48000))
oprypin92220ff2017-03-23 03:40:03 -0700194
oprypinf2501002017-04-12 05:00:56 -0700195 for analyzer in analyzers:
196 # Start the test executable that produces audio files.
197 test_process = subprocess.Popen(
198 _LogCommand(test_command + ['--sample_rate_hz=%d' %
199 analyzer.sample_rate_hz]),
oprypin4f1f4582017-06-14 09:35:11 -0700200 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
oprypinf2501002017-04-12 05:00:56 -0700201 try:
202 lines = iter(test_process.stdout.readline, '')
203 for result in ExtractTestRuns(lines, echo=True):
204 (android_device, test_name, reference_file, degraded_file) = result
oprypin92220ff2017-03-23 03:40:03 -0700205
oprypinf2501002017-04-12 05:00:56 -0700206 adb_prefix = (args.adb_path,)
207 if android_device:
208 adb_prefix += ('-s', android_device)
oprypin92220ff2017-03-23 03:40:03 -0700209
oprypinf2501002017-04-12 05:00:56 -0700210 reference_file = _GetFile(reference_file, out_dir,
211 android=args.android, adb_prefix=adb_prefix)
212 degraded_file = _GetFile(degraded_file, out_dir, move=True,
213 android=args.android, adb_prefix=adb_prefix)
oprypin92220ff2017-03-23 03:40:03 -0700214
oprypinf2501002017-04-12 05:00:56 -0700215 analyzer_results = analyzer.func(analyzer.executable,
216 reference_file, degraded_file)
217 for metric, (value, units) in analyzer_results.items():
218 # Output a result for the perf dashboard.
219 print 'RESULT %s: %s= %s %s' % (metric, test_name, value, units)
oprypin92220ff2017-03-23 03:40:03 -0700220
oprypinf2501002017-04-12 05:00:56 -0700221 if args.remove:
222 os.remove(reference_file)
223 os.remove(degraded_file)
224 finally:
225 test_process.terminate()
oprypin6d305ba2017-03-30 04:01:30 -0700226
oprypin92220ff2017-03-23 03:40:03 -0700227 return test_process.wait()
kjellander8f8d1a02017-03-06 04:01:16 -0800228
229
230if __name__ == '__main__':
231 sys.exit(main())