xref: /aosp_15_r20/external/libopus/dnn/torch/osce/utils/silk_features.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 os
31
32import numpy as np
33import torch
34
35import scipy
36import scipy.signal
37
38from utils.pitch import hangover, calculate_acorr_window
39from utils.spec import create_filter_bank, cepstrum, log_spectrum, log_spectrum_from_lpc
40
41def spec_from_lpc(a, n_fft=128, eps=1e-9):
42    order = a.shape[-1]
43    assert order + 1 < n_fft
44
45    x = np.zeros((*a.shape[:-1], n_fft ))
46    x[..., 0] = 1
47    x[..., 1:1 + order] = -a
48
49    X = np.fft.fft(x, axis=-1)
50    X = np.abs(X[..., :n_fft//2 + 1]) ** 2
51
52    S = 1 / (X + eps)
53
54    return S
55
56def silk_feature_factory(no_pitch_value=256,
57                         acorr_radius=2,
58                         pitch_hangover=8,
59                         num_bands_clean_spec=64,
60                         num_bands_noisy_spec=18,
61                         noisy_spec_scale='opus',
62                         noisy_apply_dct=True,
63                         add_double_lag_acorr=False
64                         ):
65
66    w = scipy.signal.windows.cosine(320)
67    fb_clean_spec = create_filter_bank(num_bands_clean_spec, 320, scale='erb', round_center_bins=True, normalize=True)
68    fb_noisy_spec = create_filter_bank(num_bands_noisy_spec, 320, scale=noisy_spec_scale, round_center_bins=True, normalize=True)
69
70    def create_features(noisy, noisy_history, lpcs, gains, ltps, periods):
71
72        periods = periods.copy()
73
74        if pitch_hangover > 0:
75            periods = hangover(periods, num_frames=pitch_hangover)
76
77        periods[periods == 0] = no_pitch_value
78
79        clean_spectrum = 0.3 * log_spectrum_from_lpc(lpcs, fb=fb_clean_spec, n_fft=320)
80
81        if noisy_apply_dct:
82            noisy_cepstrum = np.repeat(
83                cepstrum(np.concatenate((noisy_history[-160:], noisy), dtype=np.float32), 320, fb_noisy_spec, w), 2, 0)
84        else:
85            noisy_cepstrum = np.repeat(
86                log_spectrum(np.concatenate((noisy_history[-160:], noisy), dtype=np.float32), 320, fb_noisy_spec, w), 2, 0)
87
88        log_gains = np.log(gains + 1e-9).reshape(-1, 1)
89
90        acorr, _ = calculate_acorr_window(noisy, 80, periods, noisy_history, radius=acorr_radius, add_double_lag_acorr=add_double_lag_acorr)
91
92        features = np.concatenate((clean_spectrum, noisy_cepstrum, acorr, ltps, log_gains), axis=-1, dtype=np.float32)
93
94        return features, periods.astype(np.int64)
95
96    return create_features
97
98
99
100def load_inference_data(path,
101                        no_pitch_value=256,
102                        skip=92,
103                        preemph=0.85,
104                        acorr_radius=2,
105                        pitch_hangover=8,
106                        num_bands_clean_spec=64,
107                        num_bands_noisy_spec=18,
108                        noisy_spec_scale='opus',
109                        noisy_apply_dct=True,
110                        add_double_lag_acorr=False,
111                        **kwargs):
112
113    print(f"[load_inference_data]: ignoring keyword arguments {kwargs.keys()}...")
114
115    lpcs    = np.fromfile(os.path.join(path, 'features_lpc.f32'), dtype=np.float32).reshape(-1, 16)
116    ltps    = np.fromfile(os.path.join(path, 'features_ltp.f32'), dtype=np.float32).reshape(-1, 5)
117    gains   = np.fromfile(os.path.join(path, 'features_gain.f32'), dtype=np.float32)
118    periods = np.fromfile(os.path.join(path, 'features_period.s16'), dtype=np.int16)
119    num_bits = np.fromfile(os.path.join(path, 'features_num_bits.s32'), dtype=np.int32).astype(np.float32).reshape(-1, 1)
120    num_bits_smooth = np.fromfile(os.path.join(path, 'features_num_bits_smooth.f32'), dtype=np.float32).reshape(-1, 1)
121
122    # load signal, add back delay and pre-emphasize
123    signal  = np.fromfile(os.path.join(path, 'noisy.s16'), dtype=np.int16).astype(np.float32) / (2 ** 15)
124    signal = np.concatenate((np.zeros(skip, dtype=np.float32), signal), dtype=np.float32)
125
126    create_features = silk_feature_factory(no_pitch_value, acorr_radius, pitch_hangover, num_bands_clean_spec, num_bands_noisy_spec, noisy_spec_scale, noisy_apply_dct, add_double_lag_acorr)
127
128    num_frames = min((len(signal) // 320) * 4, len(lpcs))
129    signal = signal[: num_frames * 80]
130    lpcs = lpcs[: num_frames]
131    ltps = ltps[: num_frames]
132    gains = gains[: num_frames]
133    periods = periods[: num_frames]
134    num_bits = num_bits[: num_frames // 4]
135    num_bits_smooth = num_bits[: num_frames // 4]
136
137    numbits = np.repeat(np.concatenate((num_bits, num_bits_smooth), axis=-1, dtype=np.float32), 4, axis=0)
138
139    features, periods = create_features(signal, np.zeros(350, dtype=signal.dtype), lpcs, gains, ltps, periods)
140
141    if preemph > 0:
142        signal[1:] -= preemph * signal[:-1]
143
144    return torch.from_numpy(signal), torch.from_numpy(features), torch.from_numpy(periods), torch.from_numpy(numbits)
145