fixed an SBR bug/cheat using a bunch of ugly hacks
[ghost.git] / libghost / pitch.c
blob4b41c68ae6e5df88845bc9fefcf6458fb694cdd9
1 /**
2 @file pitch.c
3 @brief Pitch analysis
4 */
6 /* Copyright (C) 2005
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24 #include <stdio.h>
25 #include <math.h>
26 #include "fftwrap.h"
28 float inner_prod(float *x, float *y, int len)
30 float sum=0;
31 int i;
32 for (i=0;i<len;i++)
34 sum += x[i]*y[i];
36 return sum;
39 void find_pitch(float *x, float *gain, float *pitch, int start, int end, int len)
41 int i;
42 float max_score = -1;
43 float sc[end+1];
44 int p=0;
45 for (i=start;i<=end;i++)
47 float corr, score, E;
48 corr = inner_prod(x,x-i,len);
49 E = inner_prod(x-i,x-i,len);
50 //E = inner_prod(x,x,len);
51 //printf ("%f ", E);
52 score = corr*fabs(corr)/(1e4+E);
53 sc[i] = score;
54 if (score > max_score || i==start)
56 p = i;
57 max_score = score;
58 *gain = corr/(1+E);
61 if (p == start || p == end)
63 *pitch = p;
64 } else {
65 *pitch = p+.5*(sc[p+1]-sc[p-1])/(2*sc[p]-sc[p-1]-sc[p+1]);
70 void find_spectral_pitch(float *x, float *y, int lag, int len, int *pitch, float *curve)
72 //FIXME: Yuck!!!
73 static void *fft;
75 if (!fft)
76 fft = spx_fft_init(lag);
78 float xx[lag];
79 float X[lag];
80 float Y[lag];
81 int i;
83 for (i=0;i<lag;i++)
84 xx[i] = 0;
85 for (i=0;i<len;i++)
86 xx[i] = x[i];
88 spx_fft(fft, xx, X);
89 spx_fft(fft, y, Y);
90 X[0] = X[0]*Y[0];
91 for (i=1;i<lag/2;i++)
93 float n = 1.f/(1e1+sqrt((X[2*i-1]*X[2*i-1] + X[2*i ]*X[2*i ])*(Y[2*i-1]*Y[2*i-1] + Y[2*i ]*Y[2*i ])));
94 //n = 1;
95 n = 1.f/(1+curve[i]);
96 /*if (i>10)
97 n *= .5;
98 if (i>20)
99 n *= .5;*/
100 float tmp = X[2*i-1];
101 X[2*i-1] = (X[2*i-1]*Y[2*i-1] + X[2*i ]*Y[2*i ])*n;
102 X[2*i ] = (- X[2*i ]*Y[2*i-1] + tmp*Y[2*i ])*n;
104 X[len-1] = 0;
105 X[0] = X[len-1] = 0;
106 spx_ifft(fft, X, xx);
108 float max_corr=-1;
109 //int pitch;
110 *pitch = -1;
111 for (i=0;i<lag-len;i++)
113 //printf ("%f ", xx[i]);
114 if (xx[i] > max_corr)
116 *pitch = i;
117 max_corr = xx[i];
120 //printf ("%d\n", *pitch);