1 /******************************************************************************
2 *
3 * Copyright 2022 Google LLC
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 #include "energy.h"
20 #include "tables.h"
21
22
23 /**
24 * Energy estimation per band
25 */
lc3_energy_compute(enum lc3_dt dt,enum lc3_srate sr,const float * x,float * e)26 bool lc3_energy_compute(
27 enum lc3_dt dt, enum lc3_srate sr, const float *x, float *e)
28 {
29 static const int n1_table[LC3_NUM_DT][LC3_NUM_SRATE] = {
30 [LC3_DT_7M5] = { 56, 34, 27, 24, 22 },
31 [LC3_DT_10M] = { 49, 28, 23, 20, 18 },
32 };
33
34 /* First bands are 1 coefficient width */
35
36 int n1 = n1_table[dt][sr];
37 float e_sum[2] = { 0, 0 };
38 int iband;
39
40 for (iband = 0; iband < n1; iband++) {
41 *e = x[iband] * x[iband];
42 e_sum[0] += *(e++);
43 }
44
45 /* Mean the square of coefficients within each band,
46 * note that 7.5ms 8KHz frame has more bands than samples */
47
48 int nb = LC3_MIN(LC3_NUM_BANDS, LC3_NS(dt, sr));
49 int iband_h = nb - 2*(2 - dt);
50 const int *lim = lc3_band_lim[dt][sr];
51
52 for (int i = lim[iband]; iband < nb; iband++) {
53 int ie = lim[iband+1];
54 int n = ie - i;
55
56 float sx2 = x[i] * x[i];
57 for (i++; i < ie; i++)
58 sx2 += x[i] * x[i];
59
60 *e = sx2 / n;
61 e_sum[iband >= iband_h] += *(e++);
62 }
63
64 for (; iband < LC3_NUM_BANDS; iband++)
65 *(e++) = 0;
66
67 /* Return the near nyquist flag */
68
69 return e_sum[1] > 30 * e_sum[0];
70 }
71