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