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