minor comments
[platform/upstream/flac.git] / src / libFLAC / lpc.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003,2004,2005,2006  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 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #include <math.h>
37 #include "FLAC/assert.h"
38 #include "FLAC/format.h"
39 #include "private/bitmath.h"
40 #include "private/lpc.h"
41 #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
42 #include <stdio.h>
43 #endif
44
45 #ifndef FLAC__INTEGER_ONLY_LIBRARY
46
47 #ifndef M_LN2
48 /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
49 #define M_LN2 0.69314718055994530942
50 #endif
51
52 void FLAC__lpc_window_data(const FLAC__real in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
53 {
54         unsigned i;
55         for(i = 0; i < data_len; i++)
56                 out[i] = in[i] * window[i];
57 }
58
59 void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
60 {
61         /* a readable, but slower, version */
62 #if 0
63         FLAC__real d;
64         unsigned i;
65
66         FLAC__ASSERT(lag > 0);
67         FLAC__ASSERT(lag <= data_len);
68
69         /*
70          * Technically we should subtract the mean first like so:
71          *   for(i = 0; i < data_len; i++)
72          *     data[i] -= mean;
73          * but it appears not to make enough of a difference to matter, and
74          * most signals are already closely centered around zero
75          */
76         while(lag--) {
77                 for(i = lag, d = 0.0; i < data_len; i++)
78                         d += data[i] * data[i - lag];
79                 autoc[lag] = d;
80         }
81 #endif
82
83         /*
84          * this version tends to run faster because of better data locality
85          * ('data_len' is usually much larger than 'lag')
86          */
87         FLAC__real d;
88         unsigned sample, coeff;
89         const unsigned limit = data_len - lag;
90
91         FLAC__ASSERT(lag > 0);
92         FLAC__ASSERT(lag <= data_len);
93
94         for(coeff = 0; coeff < lag; coeff++)
95                 autoc[coeff] = 0.0;
96         for(sample = 0; sample <= limit; sample++) {
97                 d = data[sample];
98                 for(coeff = 0; coeff < lag; coeff++)
99                         autoc[coeff] += d * data[sample+coeff];
100         }
101         for(; sample < data_len; sample++) {
102                 d = data[sample];
103                 for(coeff = 0; coeff < data_len - sample; coeff++)
104                         autoc[coeff] += d * data[sample+coeff];
105         }
106 }
107
108 void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
109 {
110         unsigned i, j;
111         FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
112
113         FLAC__ASSERT(0 != max_order);
114         FLAC__ASSERT(0 < *max_order);
115         FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
116         FLAC__ASSERT(autoc[0] != 0.0);
117
118         err = autoc[0];
119
120         for(i = 0; i < *max_order; i++) {
121                 /* Sum up this iteration's reflection coefficient. */
122                 r = -autoc[i+1];
123                 for(j = 0; j < i; j++)
124                         r -= lpc[j] * autoc[i-j];
125                 ref[i] = (r/=err);
126
127                 /* Update LPC coefficients and total error. */
128                 lpc[i]=r;
129                 for(j = 0; j < (i>>1); j++) {
130                         FLAC__double tmp = lpc[j];
131                         lpc[j] += r * lpc[i-1-j];
132                         lpc[i-1-j] += r * tmp;
133                 }
134                 if(i & 1)
135                         lpc[j] += lpc[j] * r;
136
137                 err *= (1.0 - r * r);
138
139                 /* save this order */
140                 for(j = 0; j <= i; j++)
141                         lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
142                 error[i] = err;
143
144                 /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
145                 if(err == 0.0) {
146                         *max_order = i+1;
147                         return;
148                 }
149         }
150 }
151
152 int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
153 {
154         unsigned i;
155         FLAC__double d, cmax = -1e32;
156         FLAC__int32 qmax, qmin;
157         const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
158         const int min_shiftlimit = -max_shiftlimit - 1;
159
160         FLAC__ASSERT(precision > 0);
161         FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
162
163         /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
164         precision--;
165         qmax = 1 << precision;
166         qmin = -qmax;
167         qmax--;
168
169         for(i = 0; i < order; i++) {
170                 if(lp_coeff[i] == 0.0)
171                         continue;
172                 d = fabs(lp_coeff[i]);
173                 if(d > cmax)
174                         cmax = d;
175         }
176 redo_it:
177         if(cmax <= 0.0) {
178                 /* => coefficients are all 0, which means our constant-detect didn't work */
179                 return 2;
180         }
181         else {
182                 int log2cmax;
183
184                 (void)frexp(cmax, &log2cmax);
185                 log2cmax--;
186                 *shift = (int)precision - log2cmax - 1;
187
188                 if(*shift < min_shiftlimit || *shift > max_shiftlimit) {
189 #if 0
190                         /*@@@ this does not seem to help at all, but was not extensively tested either: */
191                         if(*shift > max_shiftlimit)
192                                 *shift = max_shiftlimit;
193                         else
194 #endif
195                                 return 1;
196                 }
197         }
198
199         if(*shift >= 0) {
200                 for(i = 0; i < order; i++) {
201                         qlp_coeff[i] = (FLAC__int32)floor((FLAC__double)lp_coeff[i] * (FLAC__double)(1 << *shift));
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 << *shift), floor((FLAC__double)lp_coeff[i] * (FLAC__double)(1 << *shift)));
207 #endif
208                                 cmax *= 2.0;
209                                 goto redo_it;
210                         }
211                 }
212         }
213         else { /* (*shift < 0) */
214                 const int nshift = -(*shift);
215 #ifdef DEBUG
216                 fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift = %d\n", *shift);
217 #endif
218                 for(i = 0; i < order; i++) {
219                         qlp_coeff[i] = (FLAC__int32)floor((FLAC__double)lp_coeff[i] / (FLAC__double)(1 << nshift));
220
221                         /* double-check the result */
222                         if(qlp_coeff[i] > qmax || qlp_coeff[i] < qmin) {
223 #ifdef FLAC__OVERFLOW_DETECT
224                                 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)));
225 #endif
226                                 cmax *= 2.0;
227                                 goto redo_it;
228                         }
229                 }
230         }
231
232         return 0;
233 }
234
235 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[])
236 {
237 #ifdef FLAC__OVERFLOW_DETECT
238         FLAC__int64 sumo;
239 #endif
240         unsigned i, j;
241         FLAC__int32 sum;
242         const FLAC__int32 *history;
243
244 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
245         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
246         for(i=0;i<order;i++)
247                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
248         fprintf(stderr,"\n");
249 #endif
250         FLAC__ASSERT(order > 0);
251
252         for(i = 0; i < data_len; i++) {
253 #ifdef FLAC__OVERFLOW_DETECT
254                 sumo = 0;
255 #endif
256                 sum = 0;
257                 history = data;
258                 for(j = 0; j < order; j++) {
259                         sum += qlp_coeff[j] * (*(--history));
260 #ifdef FLAC__OVERFLOW_DETECT
261                         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
262 #if defined _MSC_VER
263                         if(sumo > 2147483647I64 || sumo < -2147483648I64)
264                                 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);
265 #else
266                         if(sumo > 2147483647ll || sumo < -2147483648ll)
267                                 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,(long long)sumo);
268 #endif
269 #endif
270                 }
271                 *(residual++) = *(data++) - (sum >> lp_quantization);
272         }
273
274         /* Here's a slower but clearer version:
275         for(i = 0; i < data_len; i++) {
276                 sum = 0;
277                 for(j = 0; j < order; j++)
278                         sum += qlp_coeff[j] * data[i-j-1];
279                 residual[i] = data[i] - (sum >> lp_quantization);
280         }
281         */
282 }
283
284 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[])
285 {
286         unsigned i, j;
287         FLAC__int64 sum;
288         const FLAC__int32 *history;
289
290 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
291         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
292         for(i=0;i<order;i++)
293                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
294         fprintf(stderr,"\n");
295 #endif
296         FLAC__ASSERT(order > 0);
297
298         for(i = 0; i < data_len; i++) {
299                 sum = 0;
300                 history = data;
301                 for(j = 0; j < order; j++)
302                         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
303 #ifdef FLAC__OVERFLOW_DETECT
304                 if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
305                         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
306                         break;
307                 }
308                 if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
309                         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, data=%d, sum=%lld, residual=%lld\n", i, *data, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*data) - (sum >> lp_quantization)));
310                         break;
311                 }
312 #endif
313                 *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
314         }
315 }
316
317 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
318
319 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[])
320 {
321 #ifdef FLAC__OVERFLOW_DETECT
322         FLAC__int64 sumo;
323 #endif
324         unsigned i, j;
325         FLAC__int32 sum;
326         const FLAC__int32 *r = residual, *history;
327
328 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
329         fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
330         for(i=0;i<order;i++)
331                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
332         fprintf(stderr,"\n");
333 #endif
334         FLAC__ASSERT(order > 0);
335
336         for(i = 0; i < data_len; i++) {
337 #ifdef FLAC__OVERFLOW_DETECT
338                 sumo = 0;
339 #endif
340                 sum = 0;
341                 history = data;
342                 for(j = 0; j < order; j++) {
343                         sum += qlp_coeff[j] * (*(--history));
344 #ifdef FLAC__OVERFLOW_DETECT
345                         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
346 #if defined _MSC_VER
347                         if(sumo > 2147483647I64 || sumo < -2147483648I64)
348                                 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);
349 #else
350                         if(sumo > 2147483647ll || sumo < -2147483648ll)
351                                 fprintf(stderr,"FLAC__lpc_restore_signal: OVERFLOW, i=%u, j=%u, c=%d, d=%d, sumo=%lld\n",i,j,qlp_coeff[j],*history,(long long)sumo);
352 #endif
353 #endif
354                 }
355                 *(data++) = *(r++) + (sum >> lp_quantization);
356         }
357
358         /* Here's a slower but clearer version:
359         for(i = 0; i < data_len; i++) {
360                 sum = 0;
361                 for(j = 0; j < order; j++)
362                         sum += qlp_coeff[j] * data[i-j-1];
363                 data[i] = residual[i] + (sum >> lp_quantization);
364         }
365         */
366 }
367
368 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[])
369 {
370         unsigned i, j;
371         FLAC__int64 sum;
372         const FLAC__int32 *r = residual, *history;
373
374 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
375         fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
376         for(i=0;i<order;i++)
377                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
378         fprintf(stderr,"\n");
379 #endif
380         FLAC__ASSERT(order > 0);
381
382         for(i = 0; i < data_len; i++) {
383                 sum = 0;
384                 history = data;
385                 for(j = 0; j < order; j++)
386                         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
387 #ifdef FLAC__OVERFLOW_DETECT
388                 if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
389                         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
390                         break;
391                 }
392                 if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
393                         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, residual=%d, sum=%lld, data=%lld\n", i, *r, (long long)(sum >> lp_quantization), (long long)((FLAC__int64)(*r) + (sum >> lp_quantization)));
394                         break;
395                 }
396 #endif
397                 *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
398         }
399 }
400
401 #ifndef FLAC__INTEGER_ONLY_LIBRARY
402
403 FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
404 {
405         FLAC__double error_scale;
406
407         FLAC__ASSERT(total_samples > 0);
408
409         error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
410
411         return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
412 }
413
414 FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
415 {
416         if(lpc_error > 0.0) {
417                 FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
418                 if(bps >= 0.0)
419                         return bps;
420                 else
421                         return 0.0;
422         }
423         else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
424                 return 1e32;
425         }
426         else {
427                 return 0.0;
428         }
429 }
430
431 unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
432 {
433         unsigned order, index, best_index; /* 'index' the index into lpc_error; index==order-1 since lpc_error[0] is for order==1, lpc_error[1] is for order==2, etc */
434         FLAC__double bits, best_bits, error_scale;
435
436         FLAC__ASSERT(max_order > 0);
437         FLAC__ASSERT(total_samples > 0);
438
439         error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
440
441         best_index = 0;
442         best_bits = (unsigned)(-1);
443
444         for(index = 0, order = 1; index < max_order; index++, order++) {
445                 bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[index], error_scale) * (FLAC__double)(total_samples - order) + (FLAC__double)(order * overhead_bits_per_order);
446                 if(bits < best_bits) {
447                         best_index = index;
448                         best_bits = bits;
449                 }
450         }
451
452         return best_index+1; /* +1 since index of lpc_error[] is order-1 */
453 }
454
455 #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */