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