1 // Copyright 2007 "Gilles Degottex"
3 // This file is part of "Music"
5 // "Music" is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU Lesser General Public License as published by
7 // the Free Software Foundation; either version 2.1 of the License, or
8 // (at your option) any later version.
10 // "Music" is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 // #include <iostream>
23 #include <CppAddons/CAMath.h>
32 // b = fir1(32,[0.00001 0.23]);
33 vector<double> Music::fir1_lowpass(int n, double cutoff)
39 for(size_t i=0; i<b.size(); i++)
40 b[i] = cutoff*sinc(cutoff*(i-d));
46 vector<double> Music::fir1_highpass(int n, double cutoff)
53 for(size_t i=0; i<b.size(); i++)
55 b[i] = cutoff*sinc(cutoff*(i-d));
59 for(size_t i=0; i<b.size(); i++)
66 // cutoff in ]0;0.5[ where 0.5 is the Nyquist frequency
67 vector<double> Music::fir1_bandpass(int n, double low_cutoff, double high_cutoff)
69 double *weights, *desired, *bands;
73 bands = (double *)malloc(6 * sizeof(double));
74 weights = (double *)malloc(3 * sizeof(double));
75 desired = (double *)malloc(3 * sizeof(double));
76 h = (double *)malloc(1000 * sizeof(double));
93 // bands[1] = low_cutoff/2;
94 // bands[2] = low_cutoff;
95 // bands[3] = high_cutoff;
96 // bands[4] = 0.5*(high_cutoff+0.5);
99 remez(h, n, 3, bands, desired, weights, BANDPASS);
101 vector<double> hv(n);
106 // printf("%23.20f %23.20f\n", h[i], hv[i]);
117 Music::FIRRTFilter::FIRRTFilter(std::vector<double>& imp_res)
119 assert(imp_res.size()>0);
122 // m_to_filter.reserve(imp_res.size());
125 double Music::FIRRTFilter::operator()(double v)
129 m_to_filter.push_front(v);
131 if(m_to_filter.size()>=m_imp_res.size())
134 for(size_t i=0; i<m_imp_res.size(); i++)
135 value += m_imp_res[i]*m_to_filter[i];
138 // m_queue.push_front(value);
141 m_to_filter.pop_back();
147 Music::RectangularHighPassRTFilter::RectangularHighPassRTFilter(int N)
151 void Music::RectangularHighPassRTFilter::reset(int N)
157 m_summed_values.clear();
159 double Music::RectangularHighPassRTFilter::operator()(double v)
161 m_summed_values.push_front(v);
163 while(int(m_summed_values.size())>m_N)
165 m_sum -= m_summed_values.back();
167 m_summed_values.pop_back();
171 fv = m_summed_values[m_summed_values.size()/2] - m_sum/m_summed_values.size();
176 double Music::RectangularLowPassRTFilter::operator()(double v)
181 double Music::RectangularBandPassRTFilter::operator()(double v)
188 Type : biquad, tweaked butterworthReferences : Posted by Patrice TarrabiaCode : www.musicdsp.org
189 r = rez amount, from sqrt(2) to ~ 0.1
191 (from ~0 Hz to SampleRate/2 - though many
192 synths seem to filter only up to SampleRate/4)
195 out(n) = a1 * in + a2 * in(n-1) + a3 * in(n-2) - b1*out(n-1) - b2*out(n-2)
198 c = 1.0 / tan(pi * f / sample_rate);
200 a1 = 1.0 / ( 1.0 + r * c + c * c);
203 b1 = 2.0 * ( 1.0 - c*c) * a1;
204 b2 = ( 1.0 - r * c + c * c) * a1;
207 c = tan(pi * f / sample_rate);
209 a1 = 1.0 / ( 1.0 + r * c + c * c);
212 b1 = 2.0 * ( c*c - 1.0) * a1;
213 b2 = ( 1.0 - r * c + c * c) * a1;
216 /**************************************************************************
217 * Parks-McClellan algorithm for FIR filter design (C version)
218 *-------------------------------------------------
219 * Copyright (c) 1995,1998 Jake Janovetz (janovetz@uiuc.edu)
221 * This library is free software; you can redistribute it and/or
222 * modify it under the terms of the GNU Library General Public
223 * License as published by the Free Software Foundation; either
224 * version 2 of the License, or (at your option) any later version.
226 * This library is distributed in the hope that it will be useful,
227 * but WITHOUT ANY WARRANTY; without even the implied warranty of
228 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
229 * Library General Public License for more details.
231 * You should have received a copy of the GNU Library General Public
232 * License along with this library; if not, write to the Free
233 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
235 *************************************************************************/
241 * Creates the dense grid of frequencies from the specified bands.
242 * Also creates the Desired Frequency Response function (D[]) and
243 * the Weight function (W[]) on that dense grid
248 * int r - 1/2 the number of filter coefficients
249 * int numtaps - Number of taps in the resulting filter
250 * int numband - Number of bands in user specification
251 * double bands[] - User-specified band edges [2*numband]
252 * double des[] - Desired response per band [numband]
253 * double weight[] - Weight per band [numband]
254 * int symmetry - Symmetry of filter - used for grid check
258 * int gridsize - Number of elements in the dense frequency grid
259 * double Grid[] - Frequencies (0 to 0.5) on the dense grid [gridsize]
260 * double D[] - Desired response on the dense grid [gridsize]
261 * double W[] - Weight function on the dense grid [gridsize]
264 void CreateDenseGrid(int r, int numtaps, int numband, double bands[],
265 double des[], double weight[], int *gridsize,
266 double Grid[], double D[], double W[],
270 double delf, lowf, highf;
272 delf = 0.5/(GRIDDENSITY*r);
275 * For differentiator, hilbert,
276 * symmetry is odd and Grid[0] = max(delf, band[0])
279 if ((symmetry == NEGATIVE) && (delf > bands[0]))
283 for (band=0; band < numband; band++)
285 Grid[j] = bands[2*band];
286 lowf = bands[2*band];
287 highf = bands[2*band + 1];
288 k = (int)((highf - lowf)/delf + 0.5); /* .5 for rounding */
301 * Similar to above, if odd symmetry, last grid point can't be .5
302 * - but, if there are even taps, leave the last grid point at .5
304 if ((symmetry == NEGATIVE) &&
305 (Grid[*gridsize-1] > (0.5 - delf)) &&
308 Grid[*gridsize-1] = 0.5-delf;
313 /********************
316 * Places Extremal Frequencies evenly throughout the dense grid.
321 * int r - 1/2 the number of filter coefficients
322 * int gridsize - Number of elements in the dense frequency grid
326 * int Ext[] - Extremal indexes to dense frequency grid [r+1]
327 ********************/
329 void InitialGuess(int r, int Ext[], int gridsize)
334 Ext[i] = i * (gridsize-1) / r;
338 /***********************
345 * int r - 1/2 the number of filter coefficients
346 * int Ext[] - Extremal indexes to dense frequency grid [r+1]
347 * double Grid[] - Frequencies (0 to 0.5) on the dense grid [gridsize]
348 * double D[] - Desired response on the dense grid [gridsize]
349 * double W[] - Weight function on the dense grid [gridsize]
353 * double ad[] - 'b' in Oppenheim & Schafer [r+1]
355 * double y[] - 'C' in Oppenheim & Schafer [r+1]
356 ***********************/
358 void CalcParms(int r, int Ext[], double Grid[], double D[], double W[],
359 double ad[], double x[], double y[])
362 double sign, xi, delta, denom, numer;
368 x[i] = cos(Pi2 * Grid[Ext[i]]);
371 * Calculate ad[] - Oppenheim & Schafer eq 7.132
373 ld = (r-1)/15 + 1; /* Skips around to avoid round errors */
380 for (k=j; k<=r; k+=ld)
382 denom *= 2.0*(xi - x[k]);
384 if (fabs(denom)<0.00001)
390 * Calculate delta - Oppenheim & Schafer eq 7.131
396 numer += ad[i] * D[Ext[i]];
397 denom += sign * ad[i]/W[Ext[i]];
404 * Calculate y[] - Oppenheim & Schafer eq 7.133b
408 y[i] = D[Ext[i]] - sign * delta/W[Ext[i]];
414 /*********************
417 * Using values calculated in CalcParms, ComputeA calculates the
418 * actual filter response at a given frequency (freq). Uses
419 * eq 7.133a from Oppenheim & Schafer.
424 * double freq - Frequency (0 to 0.5) at which to calculate A
425 * int r - 1/2 the number of filter coefficients
426 * double ad[] - 'b' in Oppenheim & Schafer [r+1]
428 * double y[] - 'C' in Oppenheim & Schafer [r+1]
432 * Returns double value of A[freq]
433 *********************/
435 double ComputeA(double freq, int r, double ad[], double x[], double y[])
438 double xc, c, denom, numer;
441 xc = cos(Pi2 * freq);
445 if (fabs(c) < 1.0e-7)
459 /************************
462 * Calculates the Error function from the desired frequency response
463 * on the dense grid (D[]), the weight function on the dense grid (W[]),
464 * and the present response calculation (A[])
469 * int r - 1/2 the number of filter coefficients
470 * double ad[] - [r+1]
473 * int gridsize - Number of elements in the dense frequency grid
474 * double Grid[] - Frequencies on the dense grid [gridsize]
475 * double D[] - Desired response on the dense grid [gridsize]
476 * double W[] - Weight function on the desnse grid [gridsize]
480 * double E[] - Error function on dense grid [gridsize]
481 ************************/
483 void CalcError(int r, double ad[], double x[], double y[],
484 int gridsize, double Grid[],
485 double D[], double W[], double E[])
490 for (i=0; i<gridsize; i++)
492 A = ComputeA(Grid[i], r, ad, x, y);
493 E[i] = W[i] * (D[i] - A);
497 /************************
500 * Searches for the maxima/minima of the error curve. If more than
501 * r+1 extrema are found, it uses the following heuristic (thanks
503 * 1) Adjacent non-alternating extrema deleted first.
504 * 2) If there are more than one excess extrema, delete the
505 * one with the smallest error. This will create a non-alternation
506 * condition that is fixed by 1).
507 * 3) If there is exactly one excess extremum, delete the smaller
508 * of the first/last extremum
513 * int r - 1/2 the number of filter coefficients
514 * int Ext[] - Indexes to Grid[] of extremal frequencies [r+1]
515 * int gridsize - Number of elements in the dense frequency grid
516 * double E[] - Array of error values. [gridsize]
519 * int Ext[] - New indexes to extremal frequencies [r+1]
520 ************************/
522 void Search(int r, int Ext[],
523 int gridsize, double E[])
525 int i, j, k, l, extra; /* Counters */
527 int *foundExt; /* Array of found extremals */
530 * Allocate enough space for found extremals.
532 foundExt = (int *)malloc((2*r) * sizeof(int));
536 * Check for extremum at 0.
538 if (((E[0]>0.0) && (E[0]>E[1])) ||
539 ((E[0]<0.0) && (E[0]<E[1])))
543 * Check for extrema inside dense grid
545 for (i=1; i<gridsize-1; i++)
547 if (((E[i]>=E[i-1]) && (E[i]>E[i+1]) && (E[i]>0.0)) ||
548 ((E[i]<=E[i-1]) && (E[i]<E[i+1]) && (E[i]<0.0)))
553 * Check for extremum at 0.5
556 if (((E[j]>0.0) && (E[j]>E[j-1])) ||
557 ((E[j]<0.0) && (E[j]<E[j-1])))
562 * Remove extra extremals
568 if (E[foundExt[0]] > 0.0)
569 up = 1; /* first one is a maxima */
571 up = 0; /* first one is a minima */
577 if (fabs(E[foundExt[j]]) < fabs(E[foundExt[l]]))
578 l = j; /* new smallest error. */
579 if ((up) && (E[foundExt[j]] < 0.0))
580 up = 0; /* switch to a minima */
581 else if ((!up) && (E[foundExt[j]] > 0.0))
582 up = 1; /* switch to a maxima */
586 break; /* Ooops, found two non-alternating */
587 } /* extrema. Delete smallest of them */
588 } /* if the loop finishes, all extrema are alternating */
591 * If there's only one extremal and all are alternating,
592 * delete the smallest of the first/last extremals.
594 if ((alt) && (extra == 1))
596 if (fabs(E[foundExt[k-1]]) < fabs(E[foundExt[0]]))
597 l = foundExt[k-1]; /* Delete last extremal */
599 l = foundExt[0]; /* Delete first extremal */
602 for (j=l; j<k; j++) /* Loop that does the deletion */
604 foundExt[j] = foundExt[j+1];
612 Ext[i] = foundExt[i]; /* Copy found extremals to Ext[] */
619 /*********************
622 * Simple frequency sampling algorithm to determine the impulse
623 * response h[] from A's found in ComputeA
628 * int N - Number of filter coefficients
629 * double A[] - Sample points of desired response [N/2]
630 * int symmetry - Symmetry of desired filter
634 * double h[] - Impulse Response of final filter [N]
635 *********************/
636 void FreqSample(int N, double A[], double h[], int symm)
642 if (symm == POSITIVE)
651 val += 2.0 * A[k] * cos(x*k);
661 for (k=1; k<=(N/2-1); k++)
662 val += 2.0 * A[k] * cos(x*k);
676 val += 2.0 * A[k] * sin(x*k);
684 val = A[N/2] * sin(Pi * (n - M));
686 for (k=1; k<=(N/2-1); k++)
687 val += 2.0 * A[k] * sin(x*k);
697 * Checks to see if the error function is small enough to consider
698 * the result to have converged.
702 * int r - 1/2 the number of filter coeffiecients
703 * int Ext[] - Indexes to extremal frequencies [r+1]
704 * double E[] - Error function on the dense grid [gridsize]
708 * Returns 1 if the result converged
709 * Returns 0 if the result has not converged
710 ********************/
712 short isDone(int r, int Ext[], double E[])
715 double min, max, current;
717 min = max = fabs(E[Ext[0]]);
720 current = fabs(E[Ext[i]]);
726 if (((max-min)/max) < 0.0001)
731 /********************
734 * Calculates the optimal (in the Chebyshev/minimax sense)
735 * FIR filter impulse response given a set of band edges,
736 * the desired reponse on those bands, and the weight given to
737 * the error in those bands.
741 * int numtaps - Number of filter coefficients
742 * int numband - Number of bands in filter specification
743 * double bands[] - User-specified band edges [2 * numband]
744 * double des[] - User-specified band responses [numband]
745 * double weight[] - User-specified error weights [numband]
746 * int type - Type of filter
750 * double h[] - Impulse response of final filter [numtaps]
751 ********************/
753 void Music::remez(double h[], int numtaps,
754 int numband, double bands[], double des[], double weight[],
757 double *Grid, *W, *D, *E;
758 int i, iter, gridsize, r, *Ext;
763 if (type == BANDPASS)
768 r = numtaps/2; /* number of extrema */
769 if ((numtaps%2) && (symmetry == POSITIVE))
773 * Predict dense grid size in advance for memory allocation
774 * .5 is so we round up, not truncate
777 for (i=0; i<numband; i++)
779 gridsize += (int)(2*r*GRIDDENSITY*(bands[2*i+1] - bands[2*i]) + .5);
781 if (symmetry == NEGATIVE)
787 * Dynamically allocate memory for arrays with proper sizes
789 Grid = (double *)malloc(gridsize * sizeof(double));
790 D = (double *)malloc(gridsize * sizeof(double));
791 W = (double *)malloc(gridsize * sizeof(double));
792 E = (double *)malloc(gridsize * sizeof(double));
793 Ext = (int *)malloc((r+1) * sizeof(int));
794 taps = (double *)malloc((r+1) * sizeof(double));
795 x = (double *)malloc((r+1) * sizeof(double));
796 y = (double *)malloc((r+1) * sizeof(double));
797 ad = (double *)malloc((r+1) * sizeof(double));
800 * Create dense frequency grid
802 CreateDenseGrid(r, numtaps, numband, bands, des, weight,
803 &gridsize, Grid, D, W, symmetry);
804 InitialGuess(r, Ext, gridsize);
807 * For Differentiator: (fix grid)
809 if (type == DIFFERENTIATOR)
811 for (i=0; i<gridsize; i++)
813 /* D[i] = D[i]*Grid[i]; */
820 * For odd or Negative symmetry filters, alter the
821 * D[] and W[] according to Parks McClellan
823 if (symmetry == POSITIVE)
825 if (numtaps % 2 == 0)
827 for (i=0; i<gridsize; i++)
829 c = cos(Pi * Grid[i]);
839 for (i=0; i<gridsize; i++)
841 c = sin(Pi2 * Grid[i]);
848 for (i=0; i<gridsize; i++)
850 c = sin(Pi * Grid[i]);
858 * Perform the Remez Exchange algorithm
860 for (iter=0; iter<MAXITERATIONS; iter++)
862 CalcParms(r, Ext, Grid, D, W, ad, x, y);
863 CalcError(r, ad, x, y, gridsize, Grid, D, W, E);
864 Search(r, Ext, gridsize, E);
865 if (isDone(r, Ext, E))
868 if (iter == MAXITERATIONS)
870 printf("Reached maximum iteration count.\nResults may be bad.\n");
873 CalcParms(r, Ext, Grid, D, W, ad, x, y);
876 * Find the 'taps' of the filter for use with Frequency
877 * Sampling. If odd or Negative symmetry, fix the taps
878 * according to Parks McClellan
880 for (i=0; i<=numtaps/2; i++)
882 if (symmetry == POSITIVE)
887 c = cos(Pi * (double)i/numtaps);
892 c = sin(Pi2 * (double)i/numtaps);
894 c = sin(Pi * (double)i/numtaps);
896 taps[i] = ComputeA((double)i/numtaps, r, ad, x, y)*c;
900 * Frequency sampling design with calculated taps
902 FreqSample(numtaps, taps, h, symmetry);
905 * Delete allocated memory