Merge branch 'master' into 0.11
[platform/upstream/gst-plugins-good.git] / gst / audiofx / audiocheblimit.c
1 /* 
2  * GStreamer
3  * Copyright (C) 2007-2009 Sebastian Dröge <sebastian.droege@collabora.co.uk>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library 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 GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /* 
22  * Chebyshev type 1 filter design based on
23  * "The Scientist and Engineer's Guide to DSP", Chapter 20.
24  * http://www.dspguide.com/
25  *
26  * For type 2 and Chebyshev filters in general read
27  * http://en.wikipedia.org/wiki/Chebyshev_filter
28  *
29  */
30
31 /**
32  * SECTION:element-audiocheblimit
33  *
34  * Attenuates all frequencies above the cutoff frequency (low-pass) or all frequencies below the
35  * cutoff frequency (high-pass). The number of poles and the ripple parameter control the rolloff.
36  *
37  * This element has the advantage over the windowed sinc lowpass and highpass filter that it is
38  * much faster and produces almost as good results. It's only disadvantages are the highly
39  * non-linear phase and the slower rolloff compared to a windowed sinc filter with a large kernel.
40  *
41  * For type 1 the ripple parameter specifies how much ripple in dB is allowed in the passband, i.e.
42  * some frequencies in the passband will be amplified by that value. A higher ripple value will allow
43  * a faster rolloff.
44  *
45  * For type 2 the ripple parameter specifies the stopband attenuation. In the stopband the gain will
46  * be at most this value. A lower ripple value will allow a faster rolloff.
47  *
48  * As a special case, a Chebyshev type 1 filter with no ripple is a Butterworth filter.
49  * </para>
50  * <note><para>
51  * Be warned that a too large number of poles can produce noise. The most poles are possible with
52  * a cutoff frequency at a quarter of the sampling rate.
53  * </para></note>
54  * <para>
55  * <refsect2>
56  * <title>Example launch line</title>
57  * |[
58  * gst-launch audiotestsrc freq=1500 ! audioconvert ! audiocheblimit mode=low-pass cutoff=1000 poles=4 ! audioconvert ! alsasink
59  * gst-launch filesrc location="melo1.ogg" ! oggdemux ! vorbisdec ! audioconvert ! audiocheblimit mode=high-pass cutoff=400 ripple=0.2 ! audioconvert ! alsasink
60  * gst-launch audiotestsrc wave=white-noise ! audioconvert ! audiocheblimit mode=low-pass cutoff=800 type=2 ! audioconvert ! alsasink
61  * ]|
62  * </refsect2>
63  */
64
65 #ifdef HAVE_CONFIG_H
66 #include "config.h"
67 #endif
68
69 #include <gst/gst.h>
70 #include <gst/base/gstbasetransform.h>
71 #include <gst/audio/audio.h>
72 #include <gst/audio/gstaudiofilter.h>
73
74 #include <math.h>
75
76 #include "math_compat.h"
77
78 #include "audiocheblimit.h"
79
80 #define GST_CAT_DEFAULT gst_audio_cheb_limit_debug
81 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
82
83 enum
84 {
85   PROP_0,
86   PROP_MODE,
87   PROP_TYPE,
88   PROP_CUTOFF,
89   PROP_RIPPLE,
90   PROP_POLES
91 };
92
93 #define gst_audio_cheb_limit_parent_class parent_class
94 G_DEFINE_TYPE (GstAudioChebLimit,
95     gst_audio_cheb_limit, GST_TYPE_AUDIO_FX_BASE_IIR_FILTER);
96
97 static void gst_audio_cheb_limit_set_property (GObject * object,
98     guint prop_id, const GValue * value, GParamSpec * pspec);
99 static void gst_audio_cheb_limit_get_property (GObject * object,
100     guint prop_id, GValue * value, GParamSpec * pspec);
101 static void gst_audio_cheb_limit_finalize (GObject * object);
102
103 static gboolean gst_audio_cheb_limit_setup (GstAudioFilter * filter,
104     const GstAudioInfo * info);
105
106 enum
107 {
108   MODE_LOW_PASS = 0,
109   MODE_HIGH_PASS
110 };
111
112 #define GST_TYPE_AUDIO_CHEBYSHEV_FREQ_LIMIT_MODE (gst_audio_cheb_limit_mode_get_type ())
113 static GType
114 gst_audio_cheb_limit_mode_get_type (void)
115 {
116   static GType gtype = 0;
117
118   if (gtype == 0) {
119     static const GEnumValue values[] = {
120       {MODE_LOW_PASS, "Low pass (default)",
121           "low-pass"},
122       {MODE_HIGH_PASS, "High pass",
123           "high-pass"},
124       {0, NULL, NULL}
125     };
126
127     gtype = g_enum_register_static ("GstAudioChebLimitMode", values);
128   }
129   return gtype;
130 }
131
132 /* GObject vmethod implementations */
133
134 static void
135 gst_audio_cheb_limit_class_init (GstAudioChebLimitClass * klass)
136 {
137   GObjectClass *gobject_class = (GObjectClass *) klass;
138   GstElementClass *gstelement_class = (GstElementClass *) klass;
139   GstAudioFilterClass *filter_class = (GstAudioFilterClass *) klass;
140
141   GST_DEBUG_CATEGORY_INIT (gst_audio_cheb_limit_debug, "audiocheblimit", 0,
142       "audiocheblimit element");
143
144   gobject_class->set_property = gst_audio_cheb_limit_set_property;
145   gobject_class->get_property = gst_audio_cheb_limit_get_property;
146   gobject_class->finalize = gst_audio_cheb_limit_finalize;
147
148   g_object_class_install_property (gobject_class, PROP_MODE,
149       g_param_spec_enum ("mode", "Mode",
150           "Low pass or high pass mode",
151           GST_TYPE_AUDIO_CHEBYSHEV_FREQ_LIMIT_MODE, MODE_LOW_PASS,
152           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
153   g_object_class_install_property (gobject_class, PROP_TYPE,
154       g_param_spec_int ("type", "Type", "Type of the chebychev filter", 1, 2, 1,
155           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
156
157   /* FIXME: Don't use the complete possible range but restrict the upper boundary
158    * so automatically generated UIs can use a slider without */
159   g_object_class_install_property (gobject_class, PROP_CUTOFF,
160       g_param_spec_float ("cutoff", "Cutoff", "Cut off frequency (Hz)", 0.0,
161           100000.0, 0.0,
162           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
163   g_object_class_install_property (gobject_class, PROP_RIPPLE,
164       g_param_spec_float ("ripple", "Ripple", "Amount of ripple (dB)", 0.0,
165           200.0, 0.25,
166           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
167
168   /* FIXME: What to do about this upper boundary? With a cutoff frequency of
169    * rate/4 32 poles are completely possible, with a cutoff frequency very low
170    * or very high 16 poles already produces only noise */
171   g_object_class_install_property (gobject_class, PROP_POLES,
172       g_param_spec_int ("poles", "Poles",
173           "Number of poles to use, will be rounded up to the next even number",
174           2, 32, 4,
175           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
176
177   gst_element_class_set_details_simple (gstelement_class,
178       "Low pass & high pass filter",
179       "Filter/Effect/Audio",
180       "Chebyshev low pass and high pass filter",
181       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
182
183   filter_class->setup = GST_DEBUG_FUNCPTR (gst_audio_cheb_limit_setup);
184 }
185
186 static void
187 gst_audio_cheb_limit_init (GstAudioChebLimit * filter)
188 {
189   filter->cutoff = 0.0;
190   filter->mode = MODE_LOW_PASS;
191   filter->type = 1;
192   filter->poles = 4;
193   filter->ripple = 0.25;
194
195   filter->lock = g_mutex_new ();
196 }
197
198 static void
199 generate_biquad_coefficients (GstAudioChebLimit * filter,
200     gint p, gdouble * a0, gdouble * a1, gdouble * a2,
201     gdouble * b1, gdouble * b2)
202 {
203   gint np = filter->poles;
204   gdouble ripple = filter->ripple;
205
206   /* pole location in s-plane */
207   gdouble rp, ip;
208
209   /* zero location in s-plane */
210   gdouble iz = 0.0;
211
212   /* transfer function coefficients for the z-plane */
213   gdouble x0, x1, x2, y1, y2;
214   gint type = filter->type;
215
216   /* Calculate pole location for lowpass at frequency 1 */
217   {
218     gdouble angle = (G_PI / 2.0) * (2.0 * p - 1) / np;
219
220     rp = -sin (angle);
221     ip = cos (angle);
222   }
223
224   /* If we allow ripple, move the pole from the unit
225    * circle to an ellipse and keep cutoff at frequency 1 */
226   if (ripple > 0 && type == 1) {
227     gdouble es, vx;
228
229     es = sqrt (pow (10.0, ripple / 10.0) - 1.0);
230
231     vx = (1.0 / np) * asinh (1.0 / es);
232     rp = rp * sinh (vx);
233     ip = ip * cosh (vx);
234   } else if (type == 2) {
235     gdouble es, vx;
236
237     es = sqrt (pow (10.0, ripple / 10.0) - 1.0);
238     vx = (1.0 / np) * asinh (es);
239     rp = rp * sinh (vx);
240     ip = ip * cosh (vx);
241   }
242
243   /* Calculate inverse of the pole location to convert from
244    * type I to type II */
245   if (type == 2) {
246     gdouble mag2 = rp * rp + ip * ip;
247
248     rp /= mag2;
249     ip /= mag2;
250   }
251
252   /* Calculate zero location for frequency 1 on the
253    * unit circle for type 2 */
254   if (type == 2) {
255     gdouble angle = G_PI / (np * 2.0) + ((p - 1) * G_PI) / (np);
256     gdouble mag2;
257
258     iz = cos (angle);
259     mag2 = iz * iz;
260     iz /= mag2;
261   }
262
263   /* Convert from s-domain to z-domain by
264    * using the bilinear Z-transform, i.e.
265    * substitute s by (2/t)*((z-1)/(z+1))
266    * with t = 2 * tan(0.5).
267    */
268   if (type == 1) {
269     gdouble t, m, d;
270
271     t = 2.0 * tan (0.5);
272     m = rp * rp + ip * ip;
273     d = 4.0 - 4.0 * rp * t + m * t * t;
274
275     x0 = (t * t) / d;
276     x1 = 2.0 * x0;
277     x2 = x0;
278     y1 = (8.0 - 2.0 * m * t * t) / d;
279     y2 = (-4.0 - 4.0 * rp * t - m * t * t) / d;
280   } else {
281     gdouble t, m, d;
282
283     t = 2.0 * tan (0.5);
284     m = rp * rp + ip * ip;
285     d = 4.0 - 4.0 * rp * t + m * t * t;
286
287     x0 = (t * t * iz * iz + 4.0) / d;
288     x1 = (-8.0 + 2.0 * iz * iz * t * t) / d;
289     x2 = x0;
290     y1 = (8.0 - 2.0 * m * t * t) / d;
291     y2 = (-4.0 - 4.0 * rp * t - m * t * t) / d;
292   }
293
294   /* Convert from lowpass at frequency 1 to either lowpass
295    * or highpass.
296    *
297    * For lowpass substitute z^(-1) with:
298    *  -1
299    * z   - k
300    * ------------
301    *          -1
302    * 1 - k * z
303    *
304    * k = sin((1-w)/2) / sin((1+w)/2)
305    *
306    * For highpass substitute z^(-1) with:
307    *
308    *   -1
309    * -z   - k
310    * ------------
311    *          -1
312    * 1 + k * z
313    *
314    * k = -cos((1+w)/2) / cos((1-w)/2)
315    *
316    */
317   {
318     gdouble k, d;
319     gdouble omega =
320         2.0 * G_PI * (filter->cutoff / GST_AUDIO_FILTER_RATE (filter));
321
322     if (filter->mode == MODE_LOW_PASS)
323       k = sin ((1.0 - omega) / 2.0) / sin ((1.0 + omega) / 2.0);
324     else
325       k = -cos ((omega + 1.0) / 2.0) / cos ((omega - 1.0) / 2.0);
326
327     d = 1.0 + y1 * k - y2 * k * k;
328     *a0 = (x0 + k * (-x1 + k * x2)) / d;
329     *a1 = (x1 + k * k * x1 - 2.0 * k * (x0 + x2)) / d;
330     *a2 = (x0 * k * k - x1 * k + x2) / d;
331     *b1 = (2.0 * k + y1 + y1 * k * k - 2.0 * y2 * k) / d;
332     *b2 = (-k * k - y1 * k + y2) / d;
333
334     if (filter->mode == MODE_HIGH_PASS) {
335       *a1 = -*a1;
336       *b1 = -*b1;
337     }
338   }
339 }
340
341 static void
342 generate_coefficients (GstAudioChebLimit * filter)
343 {
344   if (GST_AUDIO_FILTER_RATE (filter) == 0) {
345     gdouble *a = g_new0 (gdouble, 1);
346
347     a[0] = 1.0;
348     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
349         (filter), a, 1, NULL, 0);
350
351     GST_LOG_OBJECT (filter, "rate was not set yet");
352     return;
353   }
354
355   if (filter->cutoff >= GST_AUDIO_FILTER_RATE (filter) / 2.0) {
356     gdouble *a = g_new0 (gdouble, 1);
357
358     a[0] = (filter->mode == MODE_LOW_PASS) ? 1.0 : 0.0;
359     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
360         (filter), a, 1, NULL, 0);
361     GST_LOG_OBJECT (filter, "cutoff was higher than nyquist frequency");
362     return;
363   } else if (filter->cutoff <= 0.0) {
364     gdouble *a = g_new0 (gdouble, 1);
365
366     a[0] = (filter->mode == MODE_LOW_PASS) ? 0.0 : 1.0;
367     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
368         (filter), a, 1, NULL, 0);
369     GST_LOG_OBJECT (filter, "cutoff is lower than zero");
370     return;
371   }
372
373   /* Calculate coefficients for the chebyshev filter */
374   {
375     gint np = filter->poles;
376     gdouble *a, *b;
377     gint i, p;
378
379     a = g_new0 (gdouble, np + 3);
380     b = g_new0 (gdouble, np + 3);
381
382     /* Calculate transfer function coefficients */
383     a[2] = 1.0;
384     b[2] = 1.0;
385
386     for (p = 1; p <= np / 2; p++) {
387       gdouble a0, a1, a2, b1, b2;
388       gdouble *ta = g_new0 (gdouble, np + 3);
389       gdouble *tb = g_new0 (gdouble, np + 3);
390
391       generate_biquad_coefficients (filter, p, &a0, &a1, &a2, &b1, &b2);
392
393       memcpy (ta, a, sizeof (gdouble) * (np + 3));
394       memcpy (tb, b, sizeof (gdouble) * (np + 3));
395
396       /* add the new coefficients for the new two poles
397        * to the cascade by multiplication of the transfer
398        * functions */
399       for (i = 2; i < np + 3; i++) {
400         a[i] = a0 * ta[i] + a1 * ta[i - 1] + a2 * ta[i - 2];
401         b[i] = tb[i] - b1 * tb[i - 1] - b2 * tb[i - 2];
402       }
403       g_free (ta);
404       g_free (tb);
405     }
406
407     /* Move coefficients to the beginning of the array
408      * and multiply the b coefficients with -1 to move from
409      * the transfer function's coefficients to the difference
410      * equation's coefficients */
411     b[2] = 0.0;
412     for (i = 0; i <= np; i++) {
413       a[i] = a[i + 2];
414       b[i] = -b[i + 2];
415     }
416
417     /* Normalize to unity gain at frequency 0 for lowpass
418      * and frequency 0.5 for highpass */
419     {
420       gdouble gain;
421
422       if (filter->mode == MODE_LOW_PASS)
423         gain =
424             gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b, np + 1,
425             1.0, 0.0);
426       else
427         gain =
428             gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b, np + 1,
429             -1.0, 0.0);
430
431       for (i = 0; i <= np; i++) {
432         a[i] /= gain;
433       }
434     }
435
436     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
437         (filter), a, np + 1, b, np + 1);
438
439     GST_LOG_OBJECT (filter,
440         "Generated IIR coefficients for the Chebyshev filter");
441     GST_LOG_OBJECT (filter,
442         "mode: %s, type: %d, poles: %d, cutoff: %.2f Hz, ripple: %.2f dB",
443         (filter->mode == MODE_LOW_PASS) ? "low-pass" : "high-pass",
444         filter->type, filter->poles, filter->cutoff, filter->ripple);
445     GST_LOG_OBJECT (filter, "%.2f dB gain @ 0 Hz",
446         20.0 * log10 (gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b,
447                 np + 1, 1.0, 0.0)));
448
449 #ifndef GST_DISABLE_GST_DEBUG
450     {
451       gdouble wc =
452           2.0 * G_PI * (filter->cutoff / GST_AUDIO_FILTER_RATE (filter));
453       gdouble zr = cos (wc), zi = sin (wc);
454
455       GST_LOG_OBJECT (filter, "%.2f dB gain @ %d Hz",
456           20.0 * log10 (gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1,
457                   b, np + 1, zr, zi)), (int) filter->cutoff);
458     }
459 #endif
460
461     GST_LOG_OBJECT (filter, "%.2f dB gain @ %d Hz",
462         20.0 * log10 (gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b,
463                 np + 1, -1.0, 0.0)), GST_AUDIO_FILTER_RATE (filter) / 2);
464   }
465 }
466
467 static void
468 gst_audio_cheb_limit_finalize (GObject * object)
469 {
470   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
471
472   g_mutex_free (filter->lock);
473   filter->lock = NULL;
474
475   G_OBJECT_CLASS (parent_class)->finalize (object);
476 }
477
478 static void
479 gst_audio_cheb_limit_set_property (GObject * object, guint prop_id,
480     const GValue * value, GParamSpec * pspec)
481 {
482   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
483
484   switch (prop_id) {
485     case PROP_MODE:
486       g_mutex_lock (filter->lock);
487       filter->mode = g_value_get_enum (value);
488       generate_coefficients (filter);
489       g_mutex_unlock (filter->lock);
490       break;
491     case PROP_TYPE:
492       g_mutex_lock (filter->lock);
493       filter->type = g_value_get_int (value);
494       generate_coefficients (filter);
495       g_mutex_unlock (filter->lock);
496       break;
497     case PROP_CUTOFF:
498       g_mutex_lock (filter->lock);
499       filter->cutoff = g_value_get_float (value);
500       generate_coefficients (filter);
501       g_mutex_unlock (filter->lock);
502       break;
503     case PROP_RIPPLE:
504       g_mutex_lock (filter->lock);
505       filter->ripple = g_value_get_float (value);
506       generate_coefficients (filter);
507       g_mutex_unlock (filter->lock);
508       break;
509     case PROP_POLES:
510       g_mutex_lock (filter->lock);
511       filter->poles = GST_ROUND_UP_2 (g_value_get_int (value));
512       generate_coefficients (filter);
513       g_mutex_unlock (filter->lock);
514       break;
515     default:
516       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
517       break;
518   }
519 }
520
521 static void
522 gst_audio_cheb_limit_get_property (GObject * object, guint prop_id,
523     GValue * value, GParamSpec * pspec)
524 {
525   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
526
527   switch (prop_id) {
528     case PROP_MODE:
529       g_value_set_enum (value, filter->mode);
530       break;
531     case PROP_TYPE:
532       g_value_set_int (value, filter->type);
533       break;
534     case PROP_CUTOFF:
535       g_value_set_float (value, filter->cutoff);
536       break;
537     case PROP_RIPPLE:
538       g_value_set_float (value, filter->ripple);
539       break;
540     case PROP_POLES:
541       g_value_set_int (value, filter->poles);
542       break;
543     default:
544       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
545       break;
546   }
547 }
548
549 /* GstAudioFilter vmethod implementations */
550
551 static gboolean
552 gst_audio_cheb_limit_setup (GstAudioFilter * base, const GstAudioInfo * info)
553 {
554   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (base);
555
556   generate_coefficients (filter);
557
558   return GST_AUDIO_FILTER_CLASS (parent_class)->setup (base, info);
559 }