File: pitchtracker.C

package info (click to toggle)
mixviews 1.10-3
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 2,440 kB
  • ctags: 6,314
  • sloc: cpp: 31,647; ansic: 2,100; makefile: 1,782; sh: 17
file content (381 lines) | stat: -rw-r--r-- 9,655 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// pitchtracker.C

/******************************************************************************
 *
 *  MiXViews - an X window system based sound & data editor/processor
 *
 *  Copyright (c) 1993, 1994 Regents of the University of California
 *
 *  Author:     Douglas Scott
 *  Date:       December 13, 1994
 *
 *  Permission to use, copy and modify this software and its documentation
 *  for research and/or educational purposes and without fee is hereby granted,
 *  provided that the above copyright notice appear in all copies and that
 *  both that copyright notice and this permission notice appear in
 *  supporting documentation. The author reserves the right to distribute this
 *  software and its documentation.  The University of California and the author
 *  make no representations about the suitability of this software for any 
 *  purpose, and in no event shall University of California be liable for any
 *  damage, loss of data, or profits resulting from its use.
 *  It is provided "as is" without express or implied warranty.
 *
 ******************************************************************************/

#ifdef __GNUG_
#pragma implementation
#endif

#include "application.h"
#include "ellipfilt.h"
#include "pitchtracker.h"
#include "pchdata.h"
#include "request.h"
#include "requester.h"

class PitchTrackRequester : public TitledRequester {
public:
	PitchTrackRequester(PitchTracker *);
protected:
	redefined void configureRequest(Request *);
	redefined boolean confirmValues();
private:
	PitchTracker* client;
	int fsize;
	int foffset;
	double frate;
	double lowFreq;
	double hiFreq;
};

PitchTrackRequester::PitchTrackRequester(PitchTracker* p)
	: TitledRequester("Pitch Track Analysis of Selected Region:"),
	  client(p), fsize(350), foffset(200), frate(0.0), lowFreq(100.0), hiFreq(1000.0) {}

void
PitchTrackRequester::configureRequest(Request* request) {
	request->appendLabel("(Set framesize to 0 to have it auto-sized.)");
	request->appendValue("Frame size (samples):", &fsize,
			    NonNegativeIntegers);
	request->appendValue("Frame offset (samples):", &foffset,
			    Range(1, client->target()->length() / 2));
	request->appendValue("Frame rate (frames/sec):", &frate,
			    PositiveNumbers);
	Range allFreqs(0.0, client->sampRate()/2.0);
	request->appendValue("High Freq. Boundry (Hz):", &hiFreq, allFreqs);
	request->appendValue("Low Freq. Boundry (Hz):", &lowFreq, allFreqs);
	request->appendChoice("Filter Mode:",
			     "|BandPass (Best)|LowPass (Faster)|",
			     &client->filterType, true);
}

boolean
PitchTrackRequester::confirmValues() {
	boolean status = true;
	// If frame auto-sized, make sure it is at least one larger than offset
	fsize = (fsize == 0) ?
		max(foffset + 1, round(client->sampRate() / lowFreq)) : fsize;
	if(foffset >= fsize) {	// only true for pitch tracking
		char msg[128];
		sprintf(msg, "Frame offset (%d) must be less than framesize (%d).",
			foffset, fsize);
		Application::alert(msg);
		return false;
	}	
	if((status = client->setBaseValues(fsize, frate, foffset)) == true)
		client->freqRange.set(lowFreq, hiFreq).check();
	else return status;
	
	int neededFrameSize = round(1.0 / client->freqRange.min() * client->sampRate());
	if(client->framesize() < neededFrameSize) {
		char msg[128];
		sprintf(msg,
			"To track frequencies down to %0.0f hz, a frame size of %d is needed.",
			client->freqRange.min(), neededFrameSize);
		status = Application::confirm("For Your Information:", msg, "Continue anyway?");
	}
	return status;
}

//********

PitchTracker::PitchTracker(Data* output, const Range &freqs, int framesize,
		int frameoffset) : ArrayFunction(output, framesize, frameoffset),
		freqRange(freqs),
		filterType(BandPass) {
	initialize();
}

PitchTracker::PitchTracker(Data* data)
	: ArrayFunction(data), filterType(BandPass) {}

Requester *
PitchTracker::createRequester() {
	return new PitchTrackRequester(this);
}

void
PitchTracker::initialize() {
	JMAX = framesize()/10;
	MM = (JMAX+1)/2;
	for(int i=0; i<50; ++i) {
		freq[i] = freqRange.min() + i * freqRange.spread()/50.;
		int nt = int(nyquist() / (10.0 * freq[i]));
		int n = (nt < 5 ? nt : 5);
		double omega = (freq[i]*TWO_PI) / (sampRate()/10.0);
		trigpo(omega,tphi[i],tpsi[i],tgamps[i],tgamph[i],n);
	}
	Super::initialize();
	setAnalysis(
		new PCHData(analysisLength(), sampRate(), framerate(),  framesize())
	);
}

int
PitchTracker::doApply(Data *data) {
	int status = true;
	boolean was = Data::deferRescan(true);	// no need to do updating on copy
	Application::inform("Preparing sound for analysis...");
	Data* copy = data->copyOf();
	copy->ref();
	if((status = (copy->length() > 0)) == true) {	// until Exceptions enabled
		Modifier* filter = createFilter(copy);
		filter->apply();
		delete filter;
		status = Super::doApply(copy);
	}
	Resource::unref(copy);
	Data::deferRescan(was);
	return status;
}

Modifier *
PitchTracker::createFilter(Data* input) {
	Modifier* filter = nil;
	switch(filterType) {
	case BandPass:
		filter = new EllipticalFilter(input, freqRange.min(), freqRange.max(),
			freqRange.min() * 0.9, 3.0, 60, 1);
		break;
	case LowPass:
		filter = new PitchTrackFilter(input);
		break;
	default:
		break;
	};
	return filter;
}

int
PitchTracker::operator () (double *input, Data *frame) {
	frame->set(getPitch(input), 0, 0);
	frame->set(getRMS(input), 0, 1);
	return true;
}

double 
PitchTracker::getRMS(double *sig) {
	int frameSize = framesize();
	double rms = 0.0 ;
	register double *s = sig;
	for (int step = 0; step < frameSize; ++step) {
		rms += (*s) * (*s);
		s++;
	}
	return (sqrt (rms / double(frameSize)));
}

double 
PitchTracker::getPitch(double *array) {
	float s[maxFrameSize/10], g[MAXMM], h[MAXMM];
	for(int j=0; j < JMAX; ++j)
		s[j] = array[10*(j+1)-1];
	double qsum = 0.0;
	for(int i=0; i < MM; ++i) {
		float gval = g[i] = .5 * ( s[MM+i-1] - s[MM-i-1] );
		float hval = h[i] = .5 * ( s[MM+i-1] + s[MM-i-1] );
		qsum += (gval*gval) + (hval*hval);
	}
	return search(qsum, g, h);
}

void
PitchTracker::trigpo(double omega, PA5MAX phi, PA6MAX psi,
		float *gampsi, float *gamphi, int n) {
	int j=0;
	int k,np;
	double alpha,beta,gamma;
	double wcos[MAXMM],wsin[MAXMM];
	double p,z,a,b,yy;

	np=n+1;
	for (k=0 ; k<MM ; ++k) {
		yy = omega* float(k);
		wcos[k]=cos(yy);
		wsin[k]=sin(yy);
	}
	beta=gamma= 0.0;
	for (k=0 ; k<MM ; ++k) {
		p=wsin[k];
		z=p*p;
		beta+=z*wcos[k];
		gamma+=z;
		phi[0][k]=p;
	}
	gamphi[0]=gamma;
	a=2.0 * beta/gamma;
	alpha=beta=gamma=0.0;
	for (k=0 ; k<MM ; ++k) {
		p= (2.0 * wcos[k]-a) * phi[0][k];
		alpha += wcos[k] * p * phi[0][k];
		beta += wcos[k]* ( p * p ) ;
		gamma += ( p * p );
		phi[1][k] = p ;
	}
	gamphi[1]=gamma;
	a = 2.0 * beta/gamma;
	b = 2.0 *alpha/gamphi[0];
	for (j=2; j<n; ++j) {
		alpha=beta=gamma = 0.0;
		for (k=0 ; k< MM ; ++k) {
			p = (2.0 * wcos[k] - a) * phi[j-1][k] - b * phi[j-2][k];
			alpha += wcos[k] * p * phi[j-1][k];
			beta += wcos[k] * (p * p);
			gamma += (p * p) ;
			phi[j][k] = p ;
		}
		gamphi[j] = gamma;
		a = 2.0 * beta/gamma;
		b = 2.0 *alpha/gamphi[j-1];
	}
	beta = 0.0 ;
	gamma = double(MM);
	for ( k=0; k < MM ; ++k) {
		beta += wcos[k];
		psi[0][k]= 1.0;
	}
	gampsi[0]=gamma;
	a=beta/gamma;
	alpha=beta=gamma= 0.0;
	for ( k=0 ; k < MM ; ++k) {
		p = wcos[k]-a;
		alpha += wcos[k] * p*psi[0][k];
		beta += wcos[k] * (p * p);
		gamma += (p * p);
		psi[1][k] = p ;
	}
	gampsi[1] = gamma ;
	a = 2.0 * beta / gamma ;
	b = 2.0 * alpha / gampsi[0];
	for (j=2 ; j<np ;++j) {
		alpha=beta=gamma= 0.0;
		for ( k=0; k < MM ; ++k) {
			p=(2.0 * wcos[k]-a)* psi[j-1][k]-b*psi[j-2][k];
			alpha += wcos[k]*p*psi[j-1][k];
			beta += wcos[k]* (p*p);
			gamma += (p*p);
			psi[j][k] = p;
		}
		gampsi[j]=gamma;
		a=2.0*beta/gamma;
		b=2.0*alpha/gampsi[j-1];
	}
}

double
PitchTracker::search(double qsum, float *g, float *h) {
	float funmin; 
	float fun[50];
	float f1,f2,f3,x1,x2,x3,a,b,c,ftemp;
	int istar=0,i;

	filfun(qsum, fun, g, h);
	funmin = fun[istar];
	for (i = 1; i < 50; ++i) {
		ftemp = fun[i];
		if(ftemp < funmin) {
			funmin = ftemp;
			istar = i;
		}
	}
	if(istar == 0 || istar == 49) {
		return freq[istar];
	}
	else {
		x1 = freq[istar-1];
		f1 = fun[istar-1];
		x2 = freq[istar];
		f2 = fun[istar];
		x3 = freq[istar+1];
		f3 = fun[istar+1];
		a = f3/((x3-x1)*(x3-x2));
		b = f2/((x2-x1)*(x2-x3));
		c = f1/((x1-x2)*(x1-x3));
		return .5*(a*(x1+x2)+b*(x1+x3)+c*(x2+x3))/(a+b+c);
	}
}

void 
PitchTracker::filfun(double qsum, float *fun, float *g, float *h) {
	float c,sum;
	int i,n,np,j,k;

	for(i=0 ; i < 50 ;++i) {
		n = int((nyquist()/10.)/freq[i]);
		n = (n < 5) ? n : 5;
		np = n+1;
		sum = 0.0;
		for(j=0 ; j < n ; ++j) {
			c = 0.0;
			for(k=0 ; k< MM ; ++k)  
				c += g[k] * tphi[i][j][k];
			sum += (c*c)/tgamph[i][j];
		}
		for (j=0; j < np; ++j) {
			c = 0.0;
			for (k=0; k < MM; ++k) 
				c += h[k] * tpsi[i][j][k];
			sum += (c*c)/tgamps[i][j];
		}
		fun[i] = qsum -sum;
	}
}

PitchTrackFilter::PitchTrackFilter(Data *d) : SimpleFunction(d) {
	initialize();
}

void
PitchTrackFilter::initialize() {
	w1 = w11 = w12 = w2 = w21 = w22 = w3 = w31 = w32 = w4 = w41
		= w42 = 0.0;
}

double 
PitchTrackFilter::operator () (double x) {
	static const double c= .00048175311, a1= -1.89919924, c1= -1.923248041,
			d1= .985720370, a2= -1.86607670, c2= -1.90075003,
			d2= .948444690, a3= -1.66423461, c3= -1.87516686,
			d3= .896241023, c4= -.930449120;
	double temp,y;
	
	w1=c*x-c1*w11-d1*w12;
	temp=w1+a1*w11+w12;
	w12=w11;
	w11=w1;
	w2=temp-c2*w21-d2*w22;
	temp=w2+a2*w21+w22;
	w22=w21;
	w21=w2;
	w3=temp-c3*w31-d3*w32;
	temp=w3+a3*w31+w32;
	w32=w31;
	w31=w3;
	w4=temp-c4*w41;
	y=w4+w41;
	/* w42 set but not used in lowpass */
	w42=w41;
	w41=w4;
	return y;
}