Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions test-case/check-smart-amplifier.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
#!/bin/bash
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
# SPDX-License-Identifier: BSD-3-Clause
# Copyright(c) 2020 Intel Corporation. All rights reserved.
set -e

##
## Case Name: check-smart-amplifier
## Preconditions:
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
## require python3-numpy, python3-scipy and python3-matplotlib
## to be installed, or wavetool.py will not work
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
## Description:
## test smart amplifier with customized wavetool.py,
## this tool will do binary comparison of reference wave file
## and recorded wave file.
## Case step:
## 1. acquire playback & capture pipelines with smart_amp component
## 2. generate playback wave file (default 997Hz sine wave)
## 3. play reference wave file through smart_amp playback pipeline
## and record it back through smart_amp capture pipeline
## 4. compare channel 0/1, 2/3 of recorded wave with reference wave
## Expect result:
## 1. reference wave and recorded wave are binary same
## 2. delay in recorded wave less than 5ms
##

# source from the relative path of current folder
# shellcheck source=case-lib/lib.sh
source "$(dirname "${BASH_SOURCE[0]}")"/../case-lib/lib.sh
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved

# What we want here is the "$TPLG" string
# shellcheck disable=SC2016
OPT_OPT_lst['t']='tplg' OPT_DESC_lst['t']='tplg file, default value is env TPLG: $TPLG'
# $TPLG is assigned outside this script as env variable
# shellcheck disable=SC2153
OPT_PARM_lst['t']=1 OPT_VALUE_lst['t']="$TPLG"

OPT_OPT_lst['s']='sof-logger' OPT_DESC_lst['s']="Open sof-logger trace the data will store at $LOG_ROOT"
OPT_PARM_lst['s']=0 OPT_VALUE_lst['s']=1

OPT_OPT_lst['l']='loop' OPT_DESC_lst['l']='loop count'
OPT_PARM_lst['l']=1 OPT_VALUE_lst['l']=1

OPT_OPT_lst['d']='duration' OPT_DESC_lst['d']='playback/capture duration in second'
OPT_PARM_lst['d']=1 OPT_VALUE_lst['d']=6

# We need OPT_OPT_lst to tell what the command option is, and OPT_PARM_lst to tell
# how many arguments this option required, though they are not used.
# shellcheck disable=SC2034
OPT_OPT_lst['F']='fmts' OPT_DESC_lst['F']='Iterate all supported formats'
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
# shellcheck disable=SC2034
OPT_PARM_lst['F']=0 OPT_VALUE_lst['F']=0

func_opt_parse_option "$@"

duration=${OPT_VALUE_lst['d']}
loop_cnt=${OPT_VALUE_lst['l']}
tplg=${OPT_VALUE_lst['t']}

[[ ${OPT_VALUE_lst['s']} -eq 1 ]] && func_lib_start_log_collect

func_pipeline_export $tplg "smart_amp:any"
func_lib_setup_kernel_last_line

[ "$PIPELINE_COUNT" == "2" ] || die "Only detect $PIPELINE_COUNT pipeline(s) from topology, but two are needed"

for idx in $(seq 0 $((PIPELINE_COUNT - 1)))
do
type=$(func_pipeline_parse_value "$idx" type)
if [ "$type" == "playback" ]; then
pb_chan=$(func_pipeline_parse_value "$idx" ch_max)
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
pb_rate=$(func_pipeline_parse_value "$idx" rate)
pb_dev=$(func_pipeline_parse_value "$idx" dev)
else
cp_chan=$(func_pipeline_parse_value "$idx" ch_max)
cp_rate=$(func_pipeline_parse_value "$idx" rate)
cp_fmt=$(func_pipeline_parse_value "$idx" fmt)
cp_fmts=$(func_pipeline_parse_value "$idx" fmts)
Comment thread
marc-hb marked this conversation as resolved.
Resolved
cp_dev=$(func_pipeline_parse_value "$idx" dev)
fi
done

fmts="$cp_fmt"
if [ ${OPT_VALUE_lst['F']} = '1' ]; then
fmts="$cp_fmts"
fi

for i in $(seq 1 $loop_cnt)
do
for fmt in $fmts
do
dlogi "Testing: iteration $i of $loop_cnt with $fmt format"
# S24_LE format is not supported
if [ "$fmt" == "S24_LE" ]; then
continue
fi
# generate wave file
tmp_dir="/tmp"
file="$tmp_dir/tmp_wave_${fmt%_*}.wav"
recorded_file="$tmp_dir/recorded_tmp_wave_${fmt%_*}.wav"
wavetool.py -gsine -A0.8 -B"${fmt%_*}" -o"$file"
dlogc "aplay -D$pb_dev -r $pb_rate -c $pb_chan -f $fmt -d $duration -q $file &"
aplay -D"$pb_dev" -r "$pb_rate" -c "$pb_chan" -f "$fmt" -d "$duration" -v -q "$file" &
dlogc "arecord -D$cp_dev -r $cp_rate -c $cp_chan -f $fmt -d $duration -q $recorded_file"
arecord -D"$cp_dev" -r "$cp_rate" -c "$cp_chan" -f "$fmt" -d "$duration" -v -q "$recorded_file"
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
dlogi "Comparing recorded wave and reference wave"
wavetool.py -a"smart_amp" -R"$recorded_file" -r"$file" || die "wavetool.py exit with $?"
# clean up generated wave files
rm -rf "$file" "$recorded_file"
done
done

sof-kernel-log-check.sh "$KERNEL_LAST_LINE"
160 changes: 160 additions & 0 deletions tools/wavetool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
#! /usr/bin/python3
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
# SPDX-License-Identifier: BSD-3-Clause
# Copyright(c) 2020 Intel Corporation. All rights reserved.

"""
A Tool to Generate and Manipulate Wave Files
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved

Supported features:
- generate sinusoids
- give verdict in check-smart-amplifier test case by binay wave comparison
"""

import os
import sys
import argparse
import numpy as np
import scipy.signal as signal
import scipy.io.wavfile as wavefile

# The acceptable threshold of smart amplifier delay, unit: ms.
# If the dealy is longer, then DSP is overloaded or something
# is wrong with firmware scheduler.
SMART_AMP_DELAY_THRESHOLD = 5

def generate_sinusoids(**p):
"""
Generate sine or cosine wave.

``y(t) = A * sin(2 * pi * f * t + phi)``

``y(t) = A * cos(2 * pi * f * t + phi)``

Parameters
----------
dict of sinusiod parameters:
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
p['type']: Wave type, ``sine`` or ``cosine``
p['amp']: Amplitude, range: 0.0 ~ 1.0
p['freq']: Frequency, unit: Herz
p['phase']: Phase, unit: Radian
p['chan']: Channels
p['sample_rate']: Sample rate, unit: Herz
p['duration']: Duration, unit: Second

Returns
----------
Real n-D Array with shape ``(duration * sample_rate, channel)``
"""
func = np.sin if p['type'] == 'sine' else np.cos
time = np.arange(0, p['duration'], 1.0 / p['sample_rate'], dtype=np.float32)
data = p['amp'] * func(2 * np.pi * p['freq'] * time + p['phase'])
return np.reshape(np.repeat(data, p['chan']),[len(data), p['chan']])

def generate_wav(**cmd):
if cmd['generate'] in ['sine', 'cosine']:
wave_param = {
'type': cmd['generate'], 'amp': cmd['amp'][0], 'freq': cmd['freq'][0],
'phase': cmd['phase'][0], 'chan': cmd['channel'], 'sample_rate': cmd['sample_rate'],
'duration': cmd['duration'][0]
}
wave_data = generate_sinusoids(**wave_param)
else:
raise Exception('invalid generate function, will generate nothing')
return wave_data

def save_wave(wave_data, **cmd):
wave_path = cmd['output']
if wave_path == '.' or not wave_path.endswith('wav'):
wave_path = wave_path + '/tmp.wav'
sample_bits = cmd['bits']
np_types = {'S8': np.int8, 'S16': np.int16, 'S32': np.int32}
if sample_bits in np_types.keys():
# range of wave_data is floating point [-1.0, 1.0]. When saving to any integer format use its full range.
wave_data = (np.iinfo(np_types[sample_bits]).max * wave_data).astype(np_types[sample_bits])
Comment thread
marc-hb marked this conversation as resolved.
Resolved
wavefile.write(wave_path, cmd['sample_rate'], wave_data)

def do_wave_analysis(**cmd):
fs_wav, wave = wavefile.read(cmd['recorded_wave'])
fs_ref, ref_wave = wavefile.read(cmd['reference_wave'])
if fs_wav != fs_ref:
print('Can not compare wave with different sample rate')
sys.exit(1)
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
if cmd['analyze'] == 'smart_amp':
analyze_wav_smart_amp(wave, ref_wave, fs_wav, cmd['zero_threshold'])

# remove digital zeros in two sides
def trim_wave(wave, zero_threshold):
# once waves go through DAC/ADC, zero will become small value close to zero,
# here we set the digital zero threshold to 100, and cut samples below 100
# of two sides, this has no negative impact to processing.
ZERO_THRESHOLD_LEVEL = np.power(10, zero_threshold / 20.) * np.iinfo(wave.dtype).max
wave_mono = wave[:,0]
left_idx = 0
right_idx = wave_mono.shape[0] - 1
while True:
if abs(wave_mono[left_idx]) > ZERO_THRESHOLD_LEVEL:
break
left_idx = left_idx + 1
while True:
if abs(wave_mono[right_idx]) > ZERO_THRESHOLD_LEVEL:
break
right_idx = right_idx - 1
return wave[left_idx:right_idx,:], left_idx

# float point binary comparison is not supported, and will not be supported
# check recorded wave through smart amplifier component
def analyze_wav_smart_amp(wave, ref_wave, fs, zero_threshold):
trimed_ref_wave, _ = trim_wave(ref_wave, zero_threshold)
# compare the first two channel
trimed_wave_ch_0_1, delay1 = trim_wave(wave[:,0:2], zero_threshold)
trimed_ref_wave = trimed_ref_wave[0:trimed_wave_ch_0_1.shape[0],:]
compare_result0_1 = np.array_equal(trimed_ref_wave, trimed_wave_ch_0_1)
# compare the second two channel
trimed_wave_ch_2_3, delay2 = trim_wave(wave[:,2:4], zero_threshold)
trimed_ref_wave = trimed_ref_wave[0:trimed_wave_ch_2_3.shape[0],:]
compare_result2_3 = np.array_equal(trimed_ref_wave, trimed_wave_ch_2_3)

smart_amp_delay = ((delay2 - delay1) / fs * 1000)
print('Delay of smart amplifier is %0.3fms' % smart_amp_delay)
if compare_result0_1 and compare_result2_3 and smart_amp_delay < SMART_AMP_DELAY_THRESHOLD:
print('Recorded wave is binary same as reference wave')
print('Wave comparison result: PASSED')
else:
print('Recorded wave is not binary same as reference wave')
print('Wave comparison result: FAILED')
sys.exit(1001)

def parse_cmdline():
parser = argparse.ArgumentParser(add_help=True, formatter_class=argparse.RawTextHelpFormatter,
description='A Tool to Generate and Manipulate Wave Files.')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
# wave parameters
parser.add_argument('-g', '--generate', type=str, choices=['sine','cosine'], help='generate specified types of wave')
parser.add_argument('-A', '--amp', type=float, nargs='+', default=[1.0], help='amplitude of generated wave')
parser.add_argument('-F', '--freq', type=float, nargs='+', default=[997.0], help='frequency of generated wave')
parser.add_argument('-P', '--phase', type=float, nargs='+', default=[0.0], help='phase of generated wave')
parser.add_argument('-D', '--duration', type=float, nargs='+', default=[10.], help='duration of generated wave')
parser.add_argument('-S', '--sample_rate', type=int, default=48000, help='sample rate of generated wave')
parser.add_argument('-C', '--channel', type=int, default=2, help='channels of generated wave')
parser.add_argument('-B', '--bits', type=str, choices=['S8', 'S16', 'S32', 'F32'], default='S16',
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved
help='sample bits of generated wave')
parser.add_argument('-o', '--output', type=str, help='path to store generated files', default='.')
# wave comparison arguments
parser.add_argument('-a', '--analyze', type=str, choices=['smart_amp'], help='analyze reocrded wave to give case verdict')
parser.add_argument('-R', '--recorded_wave', type=str, help='path of recorded wave')
parser.add_argument('-r', '--reference_wave', type=str, help='path of reference wave')
parser.add_argument('-Z', '--zero_threshold', type=float, default=-50.3, help='zero threshold in dBFS')
return vars(parser.parse_args())
Comment thread
aiChaoSONG marked this conversation as resolved.
Resolved

def main():
cmd_args = parse_cmdline()

if cmd_args['generate'] is not None:
wave_data = generate_wav(**cmd_args)
save_wave(wave_data, **cmd_args)

if cmd_args['analyze'] is not None:
do_wave_analysis(**cmd_args)

if __name__ == '__main__':
main()