Merge remote-tracking branch 'origin/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 <string.h>
70
71 #include <gst/gst.h>
72 #include <gst/base/gstbasetransform.h>
73 #include <gst/audio/audio.h>
74 #include <gst/audio/gstaudiofilter.h>
75
76 #include <math.h>
77
78 #include "math_compat.h"
79
80 #include "audiocheblimit.h"
81
82 #define GST_CAT_DEFAULT gst_audio_cheb_limit_debug
83 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
84
85 enum
86 {
87   PROP_0,
88   PROP_MODE,
89   PROP_TYPE,
90   PROP_CUTOFF,
91   PROP_RIPPLE,
92   PROP_POLES
93 };
94
95 #define gst_audio_cheb_limit_parent_class parent_class
96 G_DEFINE_TYPE (GstAudioChebLimit,
97     gst_audio_cheb_limit, GST_TYPE_AUDIO_FX_BASE_IIR_FILTER);
98
99 static void gst_audio_cheb_limit_set_property (GObject * object,
100     guint prop_id, const GValue * value, GParamSpec * pspec);
101 static void gst_audio_cheb_limit_get_property (GObject * object,
102     guint prop_id, GValue * value, GParamSpec * pspec);
103 static void gst_audio_cheb_limit_finalize (GObject * object);
104
105 static gboolean gst_audio_cheb_limit_setup (GstAudioFilter * filter,
106     const GstAudioInfo * info);
107
108 enum
109 {
110   MODE_LOW_PASS = 0,
111   MODE_HIGH_PASS
112 };
113
114 #define GST_TYPE_AUDIO_CHEBYSHEV_FREQ_LIMIT_MODE (gst_audio_cheb_limit_mode_get_type ())
115 static GType
116 gst_audio_cheb_limit_mode_get_type (void)
117 {
118   static GType gtype = 0;
119
120   if (gtype == 0) {
121     static const GEnumValue values[] = {
122       {MODE_LOW_PASS, "Low pass (default)",
123           "low-pass"},
124       {MODE_HIGH_PASS, "High pass",
125           "high-pass"},
126       {0, NULL, NULL}
127     };
128
129     gtype = g_enum_register_static ("GstAudioChebLimitMode", values);
130   }
131   return gtype;
132 }
133
134 /* GObject vmethod implementations */
135
136 static void
137 gst_audio_cheb_limit_class_init (GstAudioChebLimitClass * klass)
138 {
139   GObjectClass *gobject_class = (GObjectClass *) klass;
140   GstElementClass *gstelement_class = (GstElementClass *) klass;
141   GstAudioFilterClass *filter_class = (GstAudioFilterClass *) klass;
142
143   GST_DEBUG_CATEGORY_INIT (gst_audio_cheb_limit_debug, "audiocheblimit", 0,
144       "audiocheblimit element");
145
146   gobject_class->set_property = gst_audio_cheb_limit_set_property;
147   gobject_class->get_property = gst_audio_cheb_limit_get_property;
148   gobject_class->finalize = gst_audio_cheb_limit_finalize;
149
150   g_object_class_install_property (gobject_class, PROP_MODE,
151       g_param_spec_enum ("mode", "Mode",
152           "Low pass or high pass mode",
153           GST_TYPE_AUDIO_CHEBYSHEV_FREQ_LIMIT_MODE, MODE_LOW_PASS,
154           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
155   g_object_class_install_property (gobject_class, PROP_TYPE,
156       g_param_spec_int ("type", "Type", "Type of the chebychev filter", 1, 2, 1,
157           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
158
159   /* FIXME: Don't use the complete possible range but restrict the upper boundary
160    * so automatically generated UIs can use a slider without */
161   g_object_class_install_property (gobject_class, PROP_CUTOFF,
162       g_param_spec_float ("cutoff", "Cutoff", "Cut off frequency (Hz)", 0.0,
163           100000.0, 0.0,
164           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
165   g_object_class_install_property (gobject_class, PROP_RIPPLE,
166       g_param_spec_float ("ripple", "Ripple", "Amount of ripple (dB)", 0.0,
167           200.0, 0.25,
168           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
169
170   /* FIXME: What to do about this upper boundary? With a cutoff frequency of
171    * rate/4 32 poles are completely possible, with a cutoff frequency very low
172    * or very high 16 poles already produces only noise */
173   g_object_class_install_property (gobject_class, PROP_POLES,
174       g_param_spec_int ("poles", "Poles",
175           "Number of poles to use, will be rounded up to the next even number",
176           2, 32, 4,
177           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
178
179   gst_element_class_set_details_simple (gstelement_class,
180       "Low pass & high pass filter",
181       "Filter/Effect/Audio",
182       "Chebyshev low pass and high pass filter",
183       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
184
185   filter_class->setup = GST_DEBUG_FUNCPTR (gst_audio_cheb_limit_setup);
186 }
187
188 static void
189 gst_audio_cheb_limit_init (GstAudioChebLimit * filter)
190 {
191   filter->cutoff = 0.0;
192   filter->mode = MODE_LOW_PASS;
193   filter->type = 1;
194   filter->poles = 4;
195   filter->ripple = 0.25;
196
197   filter->lock = g_mutex_new ();
198 }
199
200 static void
201 generate_biquad_coefficients (GstAudioChebLimit * filter,
202     gint p, gdouble * a0, gdouble * a1, gdouble * a2,
203     gdouble * b1, gdouble * b2)
204 {
205   gint np = filter->poles;
206   gdouble ripple = filter->ripple;
207
208   /* pole location in s-plane */
209   gdouble rp, ip;
210
211   /* zero location in s-plane */
212   gdouble iz = 0.0;
213
214   /* transfer function coefficients for the z-plane */
215   gdouble x0, x1, x2, y1, y2;
216   gint type = filter->type;
217
218   /* Calculate pole location for lowpass at frequency 1 */
219   {
220     gdouble angle = (G_PI / 2.0) * (2.0 * p - 1) / np;
221
222     rp = -sin (angle);
223     ip = cos (angle);
224   }
225
226   /* If we allow ripple, move the pole from the unit
227    * circle to an ellipse and keep cutoff at frequency 1 */
228   if (ripple > 0 && type == 1) {
229     gdouble es, vx;
230
231     es = sqrt (pow (10.0, ripple / 10.0) - 1.0);
232
233     vx = (1.0 / np) * asinh (1.0 / es);
234     rp = rp * sinh (vx);
235     ip = ip * cosh (vx);
236   } else if (type == 2) {
237     gdouble es, vx;
238
239     es = sqrt (pow (10.0, ripple / 10.0) - 1.0);
240     vx = (1.0 / np) * asinh (es);
241     rp = rp * sinh (vx);
242     ip = ip * cosh (vx);
243   }
244
245   /* Calculate inverse of the pole location to convert from
246    * type I to type II */
247   if (type == 2) {
248     gdouble mag2 = rp * rp + ip * ip;
249
250     rp /= mag2;
251     ip /= mag2;
252   }
253
254   /* Calculate zero location for frequency 1 on the
255    * unit circle for type 2 */
256   if (type == 2) {
257     gdouble angle = G_PI / (np * 2.0) + ((p - 1) * G_PI) / (np);
258     gdouble mag2;
259
260     iz = cos (angle);
261     mag2 = iz * iz;
262     iz /= mag2;
263   }
264
265   /* Convert from s-domain to z-domain by
266    * using the bilinear Z-transform, i.e.
267    * substitute s by (2/t)*((z-1)/(z+1))
268    * with t = 2 * tan(0.5).
269    */
270   if (type == 1) {
271     gdouble t, m, d;
272
273     t = 2.0 * tan (0.5);
274     m = rp * rp + ip * ip;
275     d = 4.0 - 4.0 * rp * t + m * t * t;
276
277     x0 = (t * t) / d;
278     x1 = 2.0 * x0;
279     x2 = x0;
280     y1 = (8.0 - 2.0 * m * t * t) / d;
281     y2 = (-4.0 - 4.0 * rp * t - m * t * t) / d;
282   } else {
283     gdouble t, m, d;
284
285     t = 2.0 * tan (0.5);
286     m = rp * rp + ip * ip;
287     d = 4.0 - 4.0 * rp * t + m * t * t;
288
289     x0 = (t * t * iz * iz + 4.0) / d;
290     x1 = (-8.0 + 2.0 * iz * iz * t * t) / d;
291     x2 = x0;
292     y1 = (8.0 - 2.0 * m * t * t) / d;
293     y2 = (-4.0 - 4.0 * rp * t - m * t * t) / d;
294   }
295
296   /* Convert from lowpass at frequency 1 to either lowpass
297    * or highpass.
298    *
299    * For lowpass substitute z^(-1) with:
300    *  -1
301    * z   - k
302    * ------------
303    *          -1
304    * 1 - k * z
305    *
306    * k = sin((1-w)/2) / sin((1+w)/2)
307    *
308    * For highpass substitute z^(-1) with:
309    *
310    *   -1
311    * -z   - k
312    * ------------
313    *          -1
314    * 1 + k * z
315    *
316    * k = -cos((1+w)/2) / cos((1-w)/2)
317    *
318    */
319   {
320     gdouble k, d;
321     gdouble omega =
322         2.0 * G_PI * (filter->cutoff / GST_AUDIO_FILTER_RATE (filter));
323
324     if (filter->mode == MODE_LOW_PASS)
325       k = sin ((1.0 - omega) / 2.0) / sin ((1.0 + omega) / 2.0);
326     else
327       k = -cos ((omega + 1.0) / 2.0) / cos ((omega - 1.0) / 2.0);
328
329     d = 1.0 + y1 * k - y2 * k * k;
330     *a0 = (x0 + k * (-x1 + k * x2)) / d;
331     *a1 = (x1 + k * k * x1 - 2.0 * k * (x0 + x2)) / d;
332     *a2 = (x0 * k * k - x1 * k + x2) / d;
333     *b1 = (2.0 * k + y1 + y1 * k * k - 2.0 * y2 * k) / d;
334     *b2 = (-k * k - y1 * k + y2) / d;
335
336     if (filter->mode == MODE_HIGH_PASS) {
337       *a1 = -*a1;
338       *b1 = -*b1;
339     }
340   }
341 }
342
343 static void
344 generate_coefficients (GstAudioChebLimit * filter)
345 {
346   if (GST_AUDIO_FILTER_RATE (filter) == 0) {
347     gdouble *a = g_new0 (gdouble, 1);
348
349     a[0] = 1.0;
350     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
351         (filter), a, 1, NULL, 0);
352
353     GST_LOG_OBJECT (filter, "rate was not set yet");
354     return;
355   }
356
357   if (filter->cutoff >= GST_AUDIO_FILTER_RATE (filter) / 2.0) {
358     gdouble *a = g_new0 (gdouble, 1);
359
360     a[0] = (filter->mode == MODE_LOW_PASS) ? 1.0 : 0.0;
361     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
362         (filter), a, 1, NULL, 0);
363     GST_LOG_OBJECT (filter, "cutoff was higher than nyquist frequency");
364     return;
365   } else if (filter->cutoff <= 0.0) {
366     gdouble *a = g_new0 (gdouble, 1);
367
368     a[0] = (filter->mode == MODE_LOW_PASS) ? 0.0 : 1.0;
369     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
370         (filter), a, 1, NULL, 0);
371     GST_LOG_OBJECT (filter, "cutoff is lower than zero");
372     return;
373   }
374
375   /* Calculate coefficients for the chebyshev filter */
376   {
377     gint np = filter->poles;
378     gdouble *a, *b;
379     gint i, p;
380
381     a = g_new0 (gdouble, np + 3);
382     b = g_new0 (gdouble, np + 3);
383
384     /* Calculate transfer function coefficients */
385     a[2] = 1.0;
386     b[2] = 1.0;
387
388     for (p = 1; p <= np / 2; p++) {
389       gdouble a0, a1, a2, b1, b2;
390       gdouble *ta = g_new0 (gdouble, np + 3);
391       gdouble *tb = g_new0 (gdouble, np + 3);
392
393       generate_biquad_coefficients (filter, p, &a0, &a1, &a2, &b1, &b2);
394
395       memcpy (ta, a, sizeof (gdouble) * (np + 3));
396       memcpy (tb, b, sizeof (gdouble) * (np + 3));
397
398       /* add the new coefficients for the new two poles
399        * to the cascade by multiplication of the transfer
400        * functions */
401       for (i = 2; i < np + 3; i++) {
402         a[i] = a0 * ta[i] + a1 * ta[i - 1] + a2 * ta[i - 2];
403         b[i] = tb[i] - b1 * tb[i - 1] - b2 * tb[i - 2];
404       }
405       g_free (ta);
406       g_free (tb);
407     }
408
409     /* Move coefficients to the beginning of the array
410      * and multiply the b coefficients with -1 to move from
411      * the transfer function's coefficients to the difference
412      * equation's coefficients */
413     b[2] = 0.0;
414     for (i = 0; i <= np; i++) {
415       a[i] = a[i + 2];
416       b[i] = -b[i + 2];
417     }
418
419     /* Normalize to unity gain at frequency 0 for lowpass
420      * and frequency 0.5 for highpass */
421     {
422       gdouble gain;
423
424       if (filter->mode == MODE_LOW_PASS)
425         gain =
426             gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b, np + 1,
427             1.0, 0.0);
428       else
429         gain =
430             gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b, np + 1,
431             -1.0, 0.0);
432
433       for (i = 0; i <= np; i++) {
434         a[i] /= gain;
435       }
436     }
437
438     gst_audio_fx_base_iir_filter_set_coefficients (GST_AUDIO_FX_BASE_IIR_FILTER
439         (filter), a, np + 1, b, np + 1);
440
441     GST_LOG_OBJECT (filter,
442         "Generated IIR coefficients for the Chebyshev filter");
443     GST_LOG_OBJECT (filter,
444         "mode: %s, type: %d, poles: %d, cutoff: %.2f Hz, ripple: %.2f dB",
445         (filter->mode == MODE_LOW_PASS) ? "low-pass" : "high-pass",
446         filter->type, filter->poles, filter->cutoff, filter->ripple);
447     GST_LOG_OBJECT (filter, "%.2f dB gain @ 0 Hz",
448         20.0 * log10 (gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b,
449                 np + 1, 1.0, 0.0)));
450
451 #ifndef GST_DISABLE_GST_DEBUG
452     {
453       gdouble wc =
454           2.0 * G_PI * (filter->cutoff / GST_AUDIO_FILTER_RATE (filter));
455       gdouble zr = cos (wc), zi = sin (wc);
456
457       GST_LOG_OBJECT (filter, "%.2f dB gain @ %d Hz",
458           20.0 * log10 (gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1,
459                   b, np + 1, zr, zi)), (int) filter->cutoff);
460     }
461 #endif
462
463     GST_LOG_OBJECT (filter, "%.2f dB gain @ %d Hz",
464         20.0 * log10 (gst_audio_fx_base_iir_filter_calculate_gain (a, np + 1, b,
465                 np + 1, -1.0, 0.0)), GST_AUDIO_FILTER_RATE (filter) / 2);
466   }
467 }
468
469 static void
470 gst_audio_cheb_limit_finalize (GObject * object)
471 {
472   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
473
474   g_mutex_free (filter->lock);
475   filter->lock = NULL;
476
477   G_OBJECT_CLASS (parent_class)->finalize (object);
478 }
479
480 static void
481 gst_audio_cheb_limit_set_property (GObject * object, guint prop_id,
482     const GValue * value, GParamSpec * pspec)
483 {
484   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
485
486   switch (prop_id) {
487     case PROP_MODE:
488       g_mutex_lock (filter->lock);
489       filter->mode = g_value_get_enum (value);
490       generate_coefficients (filter);
491       g_mutex_unlock (filter->lock);
492       break;
493     case PROP_TYPE:
494       g_mutex_lock (filter->lock);
495       filter->type = g_value_get_int (value);
496       generate_coefficients (filter);
497       g_mutex_unlock (filter->lock);
498       break;
499     case PROP_CUTOFF:
500       g_mutex_lock (filter->lock);
501       filter->cutoff = g_value_get_float (value);
502       generate_coefficients (filter);
503       g_mutex_unlock (filter->lock);
504       break;
505     case PROP_RIPPLE:
506       g_mutex_lock (filter->lock);
507       filter->ripple = g_value_get_float (value);
508       generate_coefficients (filter);
509       g_mutex_unlock (filter->lock);
510       break;
511     case PROP_POLES:
512       g_mutex_lock (filter->lock);
513       filter->poles = GST_ROUND_UP_2 (g_value_get_int (value));
514       generate_coefficients (filter);
515       g_mutex_unlock (filter->lock);
516       break;
517     default:
518       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
519       break;
520   }
521 }
522
523 static void
524 gst_audio_cheb_limit_get_property (GObject * object, guint prop_id,
525     GValue * value, GParamSpec * pspec)
526 {
527   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
528
529   switch (prop_id) {
530     case PROP_MODE:
531       g_value_set_enum (value, filter->mode);
532       break;
533     case PROP_TYPE:
534       g_value_set_int (value, filter->type);
535       break;
536     case PROP_CUTOFF:
537       g_value_set_float (value, filter->cutoff);
538       break;
539     case PROP_RIPPLE:
540       g_value_set_float (value, filter->ripple);
541       break;
542     case PROP_POLES:
543       g_value_set_int (value, filter->poles);
544       break;
545     default:
546       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
547       break;
548   }
549 }
550
551 /* GstAudioFilter vmethod implementations */
552
553 static gboolean
554 gst_audio_cheb_limit_setup (GstAudioFilter * base, const GstAudioInfo * info)
555 {
556   GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (base);
557
558   generate_coefficients (filter);
559
560   return GST_AUDIO_FILTER_CLASS (parent_class)->setup (base, info);
561 }