change license verbiage to Xiph's
[platform/upstream/flac.git] / src / libFLAC / lpc.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2000,2001,2002,2003  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 #else
238                         if(sumo > 2147483647ll || sumo < -2147483648ll)
239 #endif
240                         {
241                                 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);
242                         }
243 #endif
244                 }
245                 *(residual++) = *(data++) - (sum >> lp_quantization);
246         }
247
248         /* Here's a slower but clearer version:
249         for(i = 0; i < data_len; i++) {
250                 sum = 0;
251                 for(j = 0; j < order; j++)
252                         sum += qlp_coeff[j] * data[i-j-1];
253                 residual[i] = data[i] - (sum >> lp_quantization);
254         }
255         */
256 }
257
258 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[])
259 {
260         unsigned i, j;
261         FLAC__int64 sum;
262         const FLAC__int32 *history;
263
264 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
265         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
266         for(i=0;i<order;i++)
267                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
268         fprintf(stderr,"\n");
269 #endif
270         FLAC__ASSERT(order > 0);
271
272         for(i = 0; i < data_len; i++) {
273                 sum = 0;
274                 history = data;
275                 for(j = 0; j < order; j++)
276                         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
277 #ifdef FLAC__OVERFLOW_DETECT
278                 if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
279                         fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, sum >> lp_quantization);
280                         break;
281                 }
282                 if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
283                         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));
284                         break;
285                 }
286 #endif
287                 *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
288         }
289 }
290
291 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[])
292 {
293 #ifdef FLAC__OVERFLOW_DETECT
294         FLAC__int64 sumo;
295 #endif
296         unsigned i, j;
297         FLAC__int32 sum;
298         const FLAC__int32 *history;
299
300 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
301         fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
302         for(i=0;i<order;i++)
303                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
304         fprintf(stderr,"\n");
305 #endif
306         FLAC__ASSERT(order > 0);
307
308         for(i = 0; i < data_len; i++) {
309 #ifdef FLAC__OVERFLOW_DETECT
310                 sumo = 0;
311 #endif
312                 sum = 0;
313                 history = data;
314                 for(j = 0; j < order; j++) {
315                         sum += qlp_coeff[j] * (*(--history));
316 #ifdef FLAC__OVERFLOW_DETECT
317                         sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
318 #if defined _MSC_VER
319                         if(sumo > 2147483647I64 || sumo < -2147483648I64)
320 #else
321                         if(sumo > 2147483647ll || sumo < -2147483648ll)
322 #endif
323                         {
324                                 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);
325                         }
326 #endif
327                 }
328                 *(data++) = *(residual++) + (sum >> lp_quantization);
329         }
330
331         /* Here's a slower but clearer version:
332         for(i = 0; i < data_len; i++) {
333                 sum = 0;
334                 for(j = 0; j < order; j++)
335                         sum += qlp_coeff[j] * data[i-j-1];
336                 data[i] = residual[i] + (sum >> lp_quantization);
337         }
338         */
339 }
340
341 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[])
342 {
343         unsigned i, j;
344         FLAC__int64 sum;
345         const FLAC__int32 *history;
346
347 #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
348         fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
349         for(i=0;i<order;i++)
350                 fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
351         fprintf(stderr,"\n");
352 #endif
353         FLAC__ASSERT(order > 0);
354
355         for(i = 0; i < data_len; i++) {
356                 sum = 0;
357                 history = data;
358                 for(j = 0; j < order; j++)
359                         sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
360 #ifdef FLAC__OVERFLOW_DETECT
361                 if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
362                         fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, sum >> lp_quantization);
363                         break;
364                 }
365                 if(FLAC__bitmath_silog2_wide((FLAC__int64)(*residual) + (sum >> lp_quantization)) > 32) {
366                         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));
367                         break;
368                 }
369 #endif
370                 *(data++) = *(residual++) + (FLAC__int32)(sum >> lp_quantization);
371         }
372 }
373
374 FLAC__real FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__real lpc_error, unsigned total_samples)
375 {
376         double error_scale;
377
378         FLAC__ASSERT(total_samples > 0);
379
380         error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__real)total_samples;
381
382         return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
383 }
384
385 FLAC__real FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__real lpc_error, double error_scale)
386 {
387         if(lpc_error > 0.0) {
388                 FLAC__real bps = (FLAC__real)((double)0.5 * log(error_scale * lpc_error) / M_LN2);
389                 if(bps >= 0.0)
390                         return bps;
391                 else
392                         return 0.0;
393         }
394         else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate float resolution */
395                 return (FLAC__real)1e32;
396         }
397         else {
398                 return 0.0;
399         }
400 }
401
402 unsigned FLAC__lpc_compute_best_order(const FLAC__real lpc_error[], unsigned max_order, unsigned total_samples, unsigned bits_per_signal_sample)
403 {
404         unsigned order, best_order;
405         FLAC__real best_bits, tmp_bits;
406         double error_scale;
407
408         FLAC__ASSERT(max_order > 0);
409         FLAC__ASSERT(total_samples > 0);
410
411         error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__real)total_samples;
412
413         best_order = 0;
414         best_bits = FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error[0], error_scale) * (FLAC__real)total_samples;
415
416         for(order = 1; order < max_order; order++) {
417                 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);
418                 if(tmp_bits < best_bits) {
419                         best_order = order;
420                         best_bits = tmp_bits;
421                 }
422         }
423
424         return best_order+1; /* +1 since index of lpc_error[] is order-1 */
425 }