Commit for general psychoacoustics debugging/improvement.
[platform/upstream/libvorbis.git] / lib / lpc.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE Ogg Vorbis SOFTWARE CODEC SOURCE CODE.  *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
5  * THE GNU PUBLIC LICENSE 2, WHICH IS INCLUDED WITH THIS SOURCE.    *
6  * PLEASE READ THESE TERMS DISTRIBUTING.                            *
7  *                                                                  *
8  * THE OggSQUISH SOURCE CODE IS (C) COPYRIGHT 1994-1999             *
9  * by 1999 Monty <monty@xiph.org> and The XIPHOPHORUS Company       *
10  * http://www.xiph.org/                                             *
11  *                                                                  *
12  ********************************************************************
13
14   function: LPC low level routines
15   author: Monty <monty@xiph.org>
16   modifications by: Monty
17   last modification date: Oct 18 1999
18
19  ********************************************************************/
20
21 /* Some of these routines (autocorrelator, LPC coefficient estimator)
22    are derived from code written by Jutta Degener and Carsten Bormann;
23    thus we include their copyright below.  The entirety of this file
24    is freely redistributable on the condition that both of these
25    copyright notices are preserved without modification.  */
26
27 /* Preserved Copyright: *********************************************/
28
29 /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
30 Technische Universita"t Berlin
31
32 Any use of this software is permitted provided that this notice is not
33 removed and that neither the authors nor the Technische Universita"t
34 Berlin are deemed to have made any representations as to the
35 suitability of this software for any purpose nor are held responsible
36 for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
37 THIS SOFTWARE.
38
39 As a matter of courtesy, the authors request to be informed about uses
40 this software has found, about bugs in this software, and about any
41 improvements that may be of general interest.
42
43 Berlin, 28.11.1994
44 Jutta Degener
45 Carsten Bormann
46
47 *********************************************************************/
48
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <math.h>
53 #include "smallft.h"
54 #include "lpc.h"
55 #include "xlogmap.h"
56
57 /* This is pared down for Vorbis. Autocorrelation LPC coeff generation
58    algorithm invented by N. Levinson in 1947, modified by J. Durbin in
59    1959. */
60
61 /* Input : n elements of time doamin data
62    Output: m lpc coefficients, excitation energy */
63
64
65 double vorbis_lpc_from_data(double *data,double *lpc,int n,int m){
66   double aut[m+1],error;
67   int i,j;
68
69   /* autocorrelation, p+1 lag coefficients */
70
71   j=m+1;
72   while(j--){
73     double d=0;
74     for(i=j;i<n;i++)d+=data[i]*data[i-j];
75     aut[j]=d;
76   }
77   
78   /* Generate lpc coefficients from autocorr values */
79
80   error=aut[0];
81   if(error==0){
82     memset(lpc,0,m*sizeof(double));
83     return 0;
84   }
85   
86   for(i=0;i<m;i++){
87     double r=-aut[i+1];
88
89     /* Sum up this iteration's reflection coefficient; note that in
90        Vorbis we don't save it.  If anyone wants to recycle this code
91        and needs reflection coefficients, save the results of 'r' from
92        each iteration. */
93
94     for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
95     r/=error; 
96
97     /* Update LPC coefficients and total error */
98     
99     lpc[i]=r;
100     for(j=0;j<i/2;j++){
101       double tmp=lpc[j];
102       lpc[j]+=r*lpc[i-1-j];
103       lpc[i-1-j]+=r*tmp;
104     }
105     if(i%2)lpc[j]+=lpc[j]*r;
106     
107     error*=1.0-r*r;
108   }
109   
110   /* we need the error value to know how big an impulse to hit the
111      filter with later */
112   
113   return error;
114 }
115
116 /* Input : n element envelope spectral curve
117    Output: m lpc coefficients, excitation energy */
118
119 double vorbis_lpc_from_spectrum(double *curve,double *lpc,lpc_lookup *l){
120   int n=l->ln;
121   int m=l->m;
122   double work[n+n];
123   double fscale=.5/n;
124   int i,j;
125   
126   /* input is a real curve. make it complex-real */
127   /* This mixes phase, but the LPC generation doesn't care. */
128   for(i=0;i<n;i++){
129     work[i*2]=curve[i]*fscale;
130     work[i*2+1]=0;
131   }
132   
133   n*=2;
134   drft_backward(&l->fft,work);
135   
136   /* The autocorrelation will not be circular.  Shift, else we lose
137      most of the power in the edges. */
138   
139   for(i=0,j=n/2;i<n/2;){
140     double temp=work[i];
141     work[i++]=work[j];
142     work[j++]=temp;
143   }
144   
145   return(vorbis_lpc_from_data(work,lpc,n,m));
146 }
147
148 /* On top of this basic LPC infrastructure we introduce two modifications:
149
150    1) Filter generation is limited in the resolution of features it
151    can represent (this is more obvious when the filter is looked at as
152    a set of LSP coefficients).  Human perception of the audio spectrum
153    is logarithmic not only in amplitude, but also frequency.  Because
154    the high frequency features we'll need to encode will be broader
155    than the low frequency features, filter generation will be
156    dominated by higher frequencies (when most of the energy is in the
157    lowest frequencies, and greatest perceived resolution is in the
158    midrange).  To avoid this effect, Vorbis encodes the frequency
159    spectrum with a biased log frequency scale. The intent is to
160    roughly equalize the sizes of the octaves (see xlogmap.h)
161
162    2) When we change the frequency scale, we also change the
163    (apparent) relative energies of the bands; that is, on a log scale
164    covering 5 octaves, the highest octave goes from being represented
165    in half the bins, to only 1/32 of the bins.  If the amplitudes
166    remain the same, we have divided the energy represented by the
167    highest octave by 16 (as far as Levinson-Durbin is concerned).
168    This will seriously skew filter generation, which bases calculation
169    on the mean square error with respect to energy.  Thus, Vorbis
170    normalizes the amplitudes of the log spectrum frequencies to keep
171    the relative octave energies correct. */
172
173 /* n == size of vector to be used for filter, m == order of filter,
174    oct == octaves in normalized scale, encode_p == encode (1) or
175    decode (0) */
176
177 void lpc_init(lpc_lookup *l,int n, int mapped, int m, int oct, int encode_p){
178   double bias=LOG_BIAS(n,oct);
179   double scale=(float)mapped/(float)oct; /* where n==mapped */    
180   int i;
181
182   memset(l,0,sizeof(lpc_lookup));
183
184   l->n=n;
185   l->ln=mapped;
186   l->m=m;
187   l->iscale=malloc(n*sizeof(int));
188   l->ifrac=malloc(n*sizeof(double));
189   l->norm=malloc(n*sizeof(double));
190
191   for(i=0;i<n;i++){
192     /* how much 'real estate' in the log domain does the bin in the
193        linear domain represent? */
194     double logA=LOG_X(i,bias);
195     double logB=LOG_X(i+1.,bias);
196     l->norm[i]=logB-logA;  /* this much */
197   }
198
199   /* the scale is encode/decode specific for algebraic simplicity */
200
201   if(encode_p){
202     /* encode */
203     l->escale=malloc(mapped*sizeof(double));
204     l->uscale=malloc(n*sizeof(int));
205     
206     /* undersample guard */
207     for(i=0;i<n;i++){
208       l->uscale[i]=rint(LOG_X(i,bias)/oct*mapped);
209     }   
210
211     for(i=0;i<mapped;i++){
212       l->escale[i]=LINEAR_X(i/scale,bias);
213       l->uscale[(int)(floor(l->escale[i]))]=-1;
214       l->uscale[(int)(ceil(l->escale[i]))]=-1;
215     }   
216
217
218   }
219   /* decode; encode may use this too */
220   
221   drft_init(&l->fft,mapped*2);
222   for(i=0;i<n;i++){
223     double is=LOG_X(i,bias)/oct*mapped;
224     if(is<0.)is=0.;
225
226     l->iscale[i]=floor(is);
227     if(l->iscale[i]>=l->ln-1)l->iscale[i]=l->ln-2;
228
229     l->ifrac[i]=is-floor(is);
230     if(l->ifrac[i]>1.)l->ifrac[i]=1.;
231     
232   }
233 }
234
235 void lpc_clear(lpc_lookup *l){
236   if(l){
237     if(l->escale)free(l->escale);
238     drft_clear(&l->fft);
239     free(l->iscale);
240     free(l->ifrac);
241     free(l->norm);
242   }
243 }
244
245
246 /* less efficient than the decode side (written for clarity).  We're
247    not bottlenecked here anyway */
248
249 double vorbis_curve_to_lpc(double *curve,double *lpc,lpc_lookup *l){
250   /* map the input curve to a log curve for encoding */
251
252   /* for clarity, mapped and n are both represented although setting
253      'em equal is a decent rule of thumb. The below must be reworked
254      slightly if mapped != n */
255   
256   int mapped=l->ln;
257   double work[mapped];
258   int i;
259
260   /* fairly correct for low frequencies, naieve for high frequencies
261      (suffers from undersampling) */
262   for(i=0;i<mapped;i++){
263     double lin=l->escale[i];
264     int a=floor(lin);
265     int b=ceil(lin);
266     double del=lin-floor(lin);
267
268     work[i]=(curve[a]/l->norm[a]*(1.-del)+
269              curve[b]/l->norm[b]*del);      
270
271   }
272
273   /*  for(i=0;i<l->n;i++)
274     if(l->uscale[i]>0)
275     if(work[l->uscale[i]]<curve[i])work[l->uscale[i]]=curve[i];*/
276
277 #ifdef ANALYSIS
278   {
279     int j;
280     FILE *out;
281     char buffer[80];
282     static int frameno=0;
283     
284     sprintf(buffer,"preloglpc%d.m",frameno++);
285     out=fopen(buffer,"w+");
286     for(j=0;j<l->ln;j++)
287       fprintf(out,"%g\n",work[j]);
288     fclose(out);
289   }
290 #endif
291
292   return vorbis_lpc_from_spectrum(work,lpc,l);
293 }
294
295
296 /* One can do this the long way by generating the transfer function in
297    the time domain and taking the forward FFT of the result.  The
298    results from direct calculation are cleaner and faster. If one
299    looks at the below in the context of the calling function, there's
300    lots of redundant trig, but at least it's clear */
301
302 /* This version does a linear curve generation and then later
303    interpolates the log curve from the linear curve.  This could stand
304    optimization; it could both be more precise as well as not compute
305    quite a few unused values */
306
307 void _vlpc_de_helper(double *curve,double *lpc,double amp,
308                             lpc_lookup *l){
309   int i;
310   memset(curve,0,sizeof(double)*l->ln*2);
311   if(amp==0)return;
312
313   for(i=0;i<l->m;i++){
314     curve[i*2+1]=lpc[i]/4/amp;
315     curve[i*2+2]=-lpc[i]/4/amp;
316   }
317
318   drft_backward(&l->fft,curve); /* reappropriated ;-) */
319
320   {
321     int l2=l->ln*2;
322     double unit=1./amp;
323     curve[0]=(1./(curve[0]*2+unit));
324     for(i=1;i<l->ln;i++){
325       double real=(curve[i]+curve[l2-i]);
326       double imag=(curve[i]-curve[l2-i]);
327       curve[i]=(1./hypot(real+unit,imag));
328     }
329   }
330 }
331   
332
333 /* generate the whole freq response curve on an LPC IIR filter */
334
335 void vorbis_lpc_to_curve(double *curve,double *lpc,double amp,lpc_lookup *l){
336   double lcurve[l->ln*2];
337   int i;
338
339   _vlpc_de_helper(lcurve,lpc,amp,l);
340
341 #ifdef ANALYSIS
342   {
343     int j;
344     FILE *out;
345     char buffer[80];
346     static int frameno=0;
347     
348     sprintf(buffer,"loglpc%d.m",frameno++);
349     out=fopen(buffer,"w+");
350     for(j=0;j<l->ln;j++)
351       fprintf(out,"%g\n",lcurve[j]);
352     fclose(out);
353   }
354 #endif
355
356   if(amp==0)return;
357
358   for(i=0;i<l->n;i++){
359     int ii=l->iscale[i];
360     curve[i]=((1.-l->ifrac[i])*lcurve[ii]+
361               l->ifrac[i]*lcurve[ii+1])*l->norm[i];
362   }
363
364 }
365
366 void vorbis_lpc_apply(double *residue,double *lpc,double amp,lpc_lookup *l){
367   double lcurve[l->ln*2];
368   int i;
369
370   if(amp==0){
371     memset(residue,0,l->n*sizeof(double));
372   }else{
373     
374     _vlpc_de_helper(lcurve,lpc,amp,l);
375
376     for(i=0;i<l->n;i++){
377       if(residue[i]!=0){
378         int ii=l->iscale[i];
379         residue[i]*=((1.-l->ifrac[i])*lcurve[ii]+
380                      l->ifrac[i]*lcurve[ii+1])*l->norm[i];
381       }
382     }
383   }
384 }
385
386 /* subtract or add an lpc filter to data */
387
388 void vorbis_lpc_residue(double *coeff,double *prime,int m,
389                         double *data,long n){
390
391   /* in: coeff[0...m-1] LPC coefficients 
392          prime[0...m-1] initial values 
393          data[0...n-1] data samples 
394     out: data[0...n-1] residuals from LPC prediction */
395
396   long i,j;
397   double work[m+n],y;
398
399   if(!prime)
400     for(i=0;i<m;i++)
401       work[i]=0;
402   else
403     for(i=0;i<m;i++)
404       work[i]=prime[i];
405
406   for(i=0;i<n;i++){
407     y=0;
408     for(j=0;j<m;j++)
409       y-=work[i+j]*coeff[m-j-1];
410     
411     work[i+m]=data[i];
412     data[i]-=y;
413   }
414 }
415
416
417 void vorbis_lpc_predict(double *coeff,double *prime,int m,
418                      double *data,long n){
419
420   /* in: coeff[0...m-1] LPC coefficients 
421          prime[0...m-1] initial values (allocated size of n+m-1)
422          data[0...n-1] residuals from LPC prediction   
423     out: data[0...n-1] data samples */
424
425   long i,j,o,p;
426   double y;
427   double work[n+m];
428
429   if(!prime)
430     for(i=0;i<m;i++)
431       work[i]=0.;
432   else
433     for(i=0;i<m;i++)
434       work[i]=prime[i];
435
436   for(i=0;i<n;i++){
437     y=data[i];
438     o=i;
439     p=m;
440     for(j=0;j<m;j++)
441       y-=work[o++]*coeff[--p];
442     
443     data[i]=work[o]=y;
444   }
445 }
446
447