xref: /aosp_15_r20/external/libopus/dnn/torch/testsuite/utils/pitch.py (revision a58d3d2adb790c104798cd88c8a3aff4fa8b82cc)
1"""
2/* Copyright (c) 2023 Amazon
3   Written by Jan Buethe */
4/*
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   - Redistributions of source code must retain the above copyright
10   notice, this list of conditions and the following disclaimer.
11
12   - Redistributions in binary form must reproduce the above copyright
13   notice, this list of conditions and the following disclaimer in the
14   documentation and/or other materials provided with the distribution.
15
16   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28"""
29
30import numpy as np
31from scipy.io import wavfile
32import amfm_decompy.pYAAPT as pYAAPT
33import amfm_decompy.basic_tools as basic
34
35def get_voicing_info(x, sr=16000):
36
37    signal = basic.SignalObj(x, sr)
38    pitch = pYAAPT.yaapt(signal, **{'frame_length' : 20.0, 'tda_frame_length' : 20.0})
39
40    pitch_values = pitch.samp_values
41    voiced_flags = pitch.vuv.astype('float')
42
43    return pitch_values, voiced_flags
44
45def compute_pitch_error(ref_path, test_path, fs=16000):
46    fs_orig, x_orig = wavfile.read(ref_path)
47    fs_test, x_test = wavfile.read(test_path)
48
49    min_length = min(len(x_orig), len(x_test))
50    x_orig = x_orig[:min_length]
51    x_test = x_test[:min_length]
52
53    assert fs_orig == fs_test == fs
54
55    pitch_contour_orig, voicing_orig = get_voicing_info(x_orig.astype(np.float32))
56    pitch_contour_test, voicing_test = get_voicing_info(x_test.astype(np.float32))
57
58    return {
59        'pitch_error' : np.mean(np.abs(pitch_contour_orig - pitch_contour_test)).item(),
60        'voicing_error' : np.sum(np.abs(voicing_orig - voicing_test)).item() / len(voicing_orig)
61        }