add support for specifying which apodization functions to use to window data before...
[platform/upstream/flac.git] / src / libFLAC / lpc.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <math.h>
33 #include "FLAC/assert.h"
34 #include "FLAC/format.h"
35 #include "private/bitmath.h"
36 #include "private/lpc.h"
37 #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
38 #include <stdio.h>
39 #endif
40
41 #ifndef FLAC__INTEGER_ONLY_LIBRARY
42
43 #ifndef M_LN2
44 /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
45 #define M_LN2 0.69314718055994530942
46 #endif
47
48 void FLAC__lpc_window_data(const FLAC__real in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
49 {
50         unsigned i;
51         for(i = 0; i < data_len; i++)
52                 out[i] = in[i] * window[i];
53 }
54
55 void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
56 {
57         /* a readable, but slower, version */
58 #if 0
59         FLAC__real d;
60         unsigned i;
61
62         FLAC__ASSERT(lag > 0);
63         FLAC__ASSERT(lag <= data_len);
64
65         while(lag--) {
66                 for(i = lag, d = 0.0; i < data_len; i++)
67                         d += data[i] * data[i - lag];
68                 autoc[lag] = d;
69         }
70 #endif
71
72         /*
73          * this version tends to run faster because of better data locality
74          * ('data_len' is usually much larger than 'lag')
75          */
76         FLAC__real d;
77         unsigned sample, coeff;
78         const unsigned limit = data_len - lag;
79
80         FLAC__ASSERT(lag > 0);
81         FLAC__ASSERT(lag <= data_len);
82
83         for(coeff = 0; coeff < lag; coeff++)
84                 autoc[coeff] = 0.0;
85         for(sample = 0; sample <= limit; sample++) {
86                 d = data[sample];
87                 for(coeff = 0; coeff < lag; coeff++)
88                         autoc[coeff] += d * data[sample+coeff];
89         }
90         for(; sample < data_len; sample++) {
91                 d = data[sample];
92                 for(coeff = 0; coeff < data_len - sample; coeff++)
93                         autoc[coeff] += d * data[sample+coeff];
94         }
95 }
96
97 void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
98 {
99         unsigned i, j;
100         FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
101
102         FLAC__ASSERT(0 < max_order);
103         FLAC__ASSERT(max_order <= FLAC__MAX_LPC_ORDER);
104         FLAC__ASSERT(autoc[0] != 0.0);
105
106         err = autoc[0];
107
108         for(i = 0; i < max_order; i++) {
109                 /* Sum up this iteration's reflection coefficient. */
110                 r = -autoc[i+1];
111                 for(j = 0; j < i; j++)
112                         r -= lpc[j] * autoc[i-j];
113                 ref[i] = (r/=err);
114
115                 /* Update LPC coefficients and total error. */
116                 lpc[i]=r;
117                 for(j = 0; j < (i>>1); j++) {
118                         FLAC__double tmp = lpc[j];
119                         lpc[j] += r * lpc[i-1-j];
120                         lpc[i-1-j] += r * tmp;
121                 }
122                 if(i & 1)
123                         lpc[j] += lpc[j] * r;
124
125                 err *= (1.0 - r * r);
126
127                 /* save this order */
128                 for(j = 0; j <= i; j++)
129                         lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
130                 error[i] = err;
131         }
132 }
133
134 int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
135 {
136         unsigned i;
137         FLAC__double d, cmax = -1e32;
138         FLAC__int32 qmax, qmin;
139         const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
140         const int min_shiftlimit = -max_shiftlimit - 1;
141
142         FLAC__ASSERT(precision > 0);
143         FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
144
145         /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
146         precision--;
147         qmax = 1 << precision;
148         qmin = -qmax;
149         qmax--;
150
151         for(i = 0; i < order; i++) {
152                 if(lp_coeff[i] == 0.0)
153                         continue;
154                 d = fabs(lp_coeff[i]);
155                 if(d > cmax)
156                         cmax = d;
157         }
158 redo_it:
159         if(cmax <= 0.0) {
160                 /* => coefficients are all 0, which means our constant-detect didn't work */
161                 return 2;
162         }
163         else {
164                 int log2cmax;
165
166                 (void)frexp(cmax, &log2cmax);
167                 log2cmax--;
168                 *shift = (int)precision - log2cmax - 1;
169
170                 if(*shift < min_shiftlimit || *shift > max_shiftlimit) {
171 #if 0
172                         /*@@@ this does not seem to help at all, but was not extensively tested either: */
173                         if(*shift > max_shiftlimit)
174                                 *shift = max_shiftlimit;
175                         else
176 #endif
177                                 return 1;
178                 }
179         }
180
181         if(*shift >= 0) {
182                 for(i = 0; i < order; i++) {
183                         qlp_coeff[i] = (FLAC__int32)floor((FLAC__double)lp_coeff[i] * (FLAC__double)(1 << *shift));
184
185                         /* double-check the result */
186                         if(qlp_coeff[i] > qmax || qlp_coeff[i] < qmin) {
187 #ifdef FLAC__OVERFLOW_DETECT
188                                 fprintf(stderr,"FLAC__lpc_quantize_coefficients: compensating for overflow, qlp_coeff[%u]=%d, lp_coeff[%u]=%f, cmax=%f, precision=%u, shift=%d, q=%f, f(q)=%f\n", i, qlp_coeff[i], i, lp_coeff[i], cmax, precision, *shift, (FLAC__double)lp_coeff[i] * (FLAC__double)(1 << *shift), floor((FLAC__double)lp_coeff[i] * (FLAC__double)(1 << *shift)));
189 #endif
190                                 cmax *= 2.0;
191                                 goto redo_it;
192                         }
193                 }
194         }
195         else { /* (*shift < 0) */
196                 const int nshift = -(*shift);
197 #ifdef DEBUG
198                 fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift = %d\n", *shift);
199 #endif
200                 for(i = 0; i < order; i++) {
201                         qlp_coeff[i] = (FLAC__int32)floor((FLAC__double)lp_coeff[i] / (FLAC__double)(1 << nshift));
202
203                         /* double-check the result */
204                         if(qlp_coeff[i] > qmax || qlp_coeff[i] < qmin) {
205 #ifdef FLAC__OVERFLOW_DETECT
206                                 fprintf(stderr,"FLAC__lpc_quantize_coefficients: compensating for overflow, qlp_coeff[%u]=%d, lp_coeff[%u]=%f, cmax=%f, precision=%u, shift=%d, q=%f, f(q)=%f\n", i, qlp_coeff[i], i, lp_coeff[i], cmax, precision, *shift, (FLAC__double)lp_coeff[i] / (FLAC__double)(1 << nshift), floor((FLAC__double)lp_coeff[i] / (FLAC__double)(1 << nshift)));
207 #endif
208                                 cmax *= 2.0;
209                                 goto redo_it;
210                         }
211                 }
212         }
213
214         return 0;
215 }
216
217 void FLAC__lpc_compute_residual_from_qlp_coefficients(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
218 {
219 #ifdef FLAC__OVERFLOW_DETECT
220         FLAC__int64 sumo;
221 #endif
222         unsigned i, j;
223         FLAC__int32 sum;
224         const FLAC__int32 *history;
225
226 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
227         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
228         for(i=0;i<order;i++)
229                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
230         fprintf(stderr,"\n");
231 #endif
232         FLAC__ASSERT(order > 0);
233
234         for(i = 0; i < data_len; i++) {
235 #ifdef FLAC__OVERFLOW_DETECT
236                 sumo = 0;
237 #endif
238                 sum = 0;
239                 history = data;
240                 for(j = 0; j < order; j++) {
241                         sum += qlp_coeff[j] * (*(--history));
242 #ifdef FLAC__OVERFLOW_DETECT
243                         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
244 #if defined _MSC_VER
245                         if(sumo > 2147483647I64 || sumo < -2147483648I64)
246                                 fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
247 #else
248                         if(sumo > 2147483647ll || sumo < -2147483648ll)
249                                 fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,sumo);
250 #endif
251 #endif
252                 }
253                 *(residual++) = *(data++) - (sum >> lp_quantization);
254         }
255
256         /* Here's a slower but clearer version:
257         for(i = 0; i < data_len; i++) {
258                 sum = 0;
259                 for(j = 0; j < order; j++)
260                         sum += qlp_coeff[j] * data[i-j-1];
261                 residual[i] = data[i] - (sum >> lp_quantization);
262         }
263         */
264 }
265
266 void FLAC__lpc_compute_residual_from_qlp_coefficients_wide(const FLAC__int32 *data, unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 residual[])
267 {
268         unsigned i, j;
269         FLAC__int64 sum;
270         const FLAC__int32 *history;
271
272 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
273         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
274         for(i=0;i<order;i++)
275                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
276         fprintf(stderr,"\n");
277 #endif
278         FLAC__ASSERT(order > 0);
279
280         for(i = 0; i < data_len; i++) {
281                 sum = 0;
282                 history = data;
283                 for(j = 0; j < order; j++)
284                         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
285 #ifdef FLAC__OVERFLOW_DETECT
286                 if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
287                         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, sum >> lp_quantization);
288                         break;
289                 }
290                 if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
291                         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, sum >> lp_quantization, (FLAC__int64)(*data) - (sum >> lp_quantization));
292                         break;
293                 }
294 #endif
295                 *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
296         }
297 }
298
299 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
300
301 void FLAC__lpc_restore_signal(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
302 {
303 #ifdef FLAC__OVERFLOW_DETECT
304         FLAC__int64 sumo;
305 #endif
306         unsigned i, j;
307         FLAC__int32 sum;
308         const FLAC__int32 *history;
309
310 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
311         fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
312         for(i=0;i<order;i++)
313                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
314         fprintf(stderr,"\n");
315 #endif
316         FLAC__ASSERT(order > 0);
317
318         for(i = 0; i < data_len; i++) {
319 #ifdef FLAC__OVERFLOW_DETECT
320                 sumo = 0;
321 #endif
322                 sum = 0;
323                 history = data;
324                 for(j = 0; j < order; j++) {
325                         sum += qlp_coeff[j] * (*(--history));
326 #ifdef FLAC__OVERFLOW_DETECT
327                         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
328 #if defined _MSC_VER
329                         if(sumo > 2147483647I64 || sumo < -2147483648I64)
330                                 fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%I64d\n",i,j,qlp_coeff[j],*history,sumo);
331 #else
332                         if(sumo > 2147483647ll || sumo < -2147483648ll)
333                                 fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,sumo);
334 #endif
335 #endif
336                 }
337                 *(data++) = *(residual++) + (sum >> lp_quantization);
338         }
339
340         /* Here's a slower but clearer version:
341         for(i = 0; i < data_len; i++) {
342                 sum = 0;
343                 for(j = 0; j < order; j++)
344                         sum += qlp_coeff[j] * data[i-j-1];
345                 data[i] = residual[i] + (sum >> lp_quantization);
346         }
347         */
348 }
349
350 void FLAC__lpc_restore_signal_wide(const FLAC__int32 residual[], unsigned data_len, const FLAC__int32 qlp_coeff[], unsigned order, int lp_quantization, FLAC__int32 data[])
351 {
352         unsigned i, j;
353         FLAC__int64 sum;
354         const FLAC__int32 *history;
355
356 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
357         fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
358         for(i=0;i<order;i++)
359                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
360         fprintf(stderr,"\n");
361 #endif
362         FLAC__ASSERT(order > 0);
363
364         for(i = 0; i < data_len; i++) {
365                 sum = 0;
366                 history = data;
367                 for(j = 0; j < order; j++)
368                         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
369 #ifdef FLAC__OVERFLOW_DETECT
370                 if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
371                         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, sum >> lp_quantization);
372                         break;
373                 }
374                 if(FLAC__bitmath_silog2_wide((FLAC__int64)(*residual) + (sum >> lp_quantization)) > 32) {
375                         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *residual, sum >> lp_quantization, (FLAC__int64)(*residual) + (sum >> lp_quantization));
376                         break;
377                 }
378 #endif
379                 *(data++) = *(residual++) + (FLAC__int32)(sum >> lp_quantization);
380         }
381 }
382
383 #ifndef FLAC__INTEGER_ONLY_LIBRARY
384
385 FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
386 {
387         FLAC__double error_scale;
388
389         FLAC__ASSERT(total_samples > 0);
390
391         error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
392
393         return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
394 }
395
396 FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
397 {
398         if(lpc_error > 0.0) {
399                 FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
400                 if(bps >= 0.0)
401                         return bps;
402                 else
403                         return 0.0;
404         }
405         else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
406                 return 1e32;
407         }
408         else {
409                 return 0.0;
410         }
411 }
412
413 unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned bits_per_signal_sample)
414 {
415         unsigned order, best_order;
416         FLAC__double best_bits, tmp_bits, error_scale;
417
418         FLAC__ASSERT(max_order > 0);
419         FLAC__ASSERT(total_samples > 0);
420
421         error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
422
423         best_order = 0;
424         best_bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[0], error_scale) * (FLAC__double)total_samples;
425
426         for(order = 1; order < max_order; order++) {
427                 tmp_bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[order], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * bits_per_signal_sample);
428                 if(tmp_bits < best_bits) {
429                         best_order = order;
430                         best_bits = tmp_bits;
431                 }
432         }
433
434         return best_order+1; /* +1 since index of lpc_error[] is order-1 */
435 }
436
437 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */