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     int nb = lc3_num_bands[dt][sr];
30     const int *lim = lc3_band_lim[dt][sr];
31 
32     /* Mean the square of coefficients within each band */
33 
34     float e_sum[2] = { 0, 0 };
35     int iband_h = nb - (const int []){
36         [LC3_DT_2M5] = 2, [LC3_DT_5M ] = 3,
37         [LC3_DT_7M5] = 4, [LC3_DT_10M] = 2 }[dt];
38 
39     for (int iband = 0, i = lim[iband]; iband < nb; iband++) {
40         int ie = lim[iband+1];
41         int n = ie - i;
42 
43         float sx2 = x[i] * x[i];
44         for (i++; i < ie; i++)
45             sx2 += x[i] * x[i];
46 
47         *e = sx2 / n;
48         e_sum[iband >= iband_h] += *(e++);
49     }
50 
51     /* Return the near nyquist flag */
52 
53     return e_sum[1] > 30 * e_sum[0];
54 }
55