3 * Copyright (C) 2007 Sebastian Dröge <slomo@circular-chaos.org>
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.
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.
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.
22 * Chebyshev type 1 filter design based on
23 * "The Scientist and Engineer's Guide to DSP", Chapter 20.
24 * http://www.dspguide.com/
26 * For type 2 and Chebyshev filters in general read
27 * http://en.wikipedia.org/wiki/Chebyshev_filter
32 * SECTION:element-audiocheblimit
33 * @short_description: Chebyshev low pass and high pass filter
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.
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.
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
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.
55 * As a special case, a Chebyshev type 1 filter with no ripple is a Butterworth filter.
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.
61 * <title>Example launch line</title>
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
77 #include <gst/base/gstbasetransform.h>
78 #include <gst/audio/audio.h>
79 #include <gst/audio/gstaudiofilter.h>
80 #include <gst/controller/gstcontroller.h>
84 #include "math_compat.h"
86 #include "audiocheblimit.h"
88 #define GST_CAT_DEFAULT gst_audio_cheb_limit_debug
89 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
91 static const GstElementDetails element_details =
92 GST_ELEMENT_DETAILS ("Low pass & high pass filter",
93 "Filter/Effect/Audio",
94 "Chebyshev low pass and high pass filter",
95 "Sebastian Dröge <slomo@circular-chaos.org>");
97 /* Filter signals and args */
114 #define ALLOWED_CAPS \
115 "audio/x-raw-float," \
116 " width = (int) { 32, 64 }, " \
117 " endianness = (int) BYTE_ORDER," \
118 " rate = (int) [ 1, MAX ]," \
119 " channels = (int) [ 1, MAX ]"
121 #define DEBUG_INIT(bla) \
122 GST_DEBUG_CATEGORY_INIT (gst_audio_cheb_limit_debug, "audiocheblimit", 0, "audiocheblimit element");
124 GST_BOILERPLATE_FULL (GstAudioChebLimit,
125 gst_audio_cheb_limit, GstAudioFilter, GST_TYPE_AUDIO_FILTER, DEBUG_INIT);
127 static void gst_audio_cheb_limit_set_property (GObject * object,
128 guint prop_id, const GValue * value, GParamSpec * pspec);
129 static void gst_audio_cheb_limit_get_property (GObject * object,
130 guint prop_id, GValue * value, GParamSpec * pspec);
132 static gboolean gst_audio_cheb_limit_setup (GstAudioFilter * filter,
133 GstRingBufferSpec * format);
135 gst_audio_cheb_limit_transform_ip (GstBaseTransform * base, GstBuffer * buf);
136 static gboolean gst_audio_cheb_limit_start (GstBaseTransform * base);
138 static void process_64 (GstAudioChebLimit * filter,
139 gdouble * data, guint num_samples);
140 static void process_32 (GstAudioChebLimit * filter,
141 gfloat * data, guint num_samples);
149 #define GST_TYPE_AUDIO_CHEBYSHEV_FREQ_LIMIT_MODE (gst_audio_cheb_limit_mode_get_type ())
151 gst_audio_cheb_limit_mode_get_type (void)
153 static GType gtype = 0;
156 static const GEnumValue values[] = {
157 {MODE_LOW_PASS, "Low pass (default)",
159 {MODE_HIGH_PASS, "High pass",
164 gtype = g_enum_register_static ("GstAudioChebLimitMode", values);
169 /* GObject vmethod implementations */
172 gst_audio_cheb_limit_base_init (gpointer klass)
174 GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
177 gst_element_class_set_details (element_class, &element_details);
179 caps = gst_caps_from_string (ALLOWED_CAPS);
180 gst_audio_filter_class_add_pad_templates (GST_AUDIO_FILTER_CLASS (klass),
182 gst_caps_unref (caps);
186 gst_audio_cheb_limit_dispose (GObject * object)
188 GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
200 if (filter->channels) {
201 GstAudioChebLimitChannelCtx *ctx;
202 gint i, channels = GST_AUDIO_FILTER (filter)->format.channels;
204 for (i = 0; i < channels; i++) {
205 ctx = &filter->channels[i];
210 g_free (filter->channels);
211 filter->channels = NULL;
214 G_OBJECT_CLASS (parent_class)->dispose (object);
218 gst_audio_cheb_limit_class_init (GstAudioChebLimitClass * klass)
220 GObjectClass *gobject_class;
221 GstBaseTransformClass *trans_class;
222 GstAudioFilterClass *filter_class;
224 gobject_class = (GObjectClass *) klass;
225 trans_class = (GstBaseTransformClass *) klass;
226 filter_class = (GstAudioFilterClass *) klass;
228 gobject_class->set_property = gst_audio_cheb_limit_set_property;
229 gobject_class->get_property = gst_audio_cheb_limit_get_property;
230 gobject_class->dispose = gst_audio_cheb_limit_dispose;
232 g_object_class_install_property (gobject_class, PROP_MODE,
233 g_param_spec_enum ("mode", "Mode",
234 "Low pass or high pass mode",
235 GST_TYPE_AUDIO_CHEBYSHEV_FREQ_LIMIT_MODE, MODE_LOW_PASS,
236 G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
237 g_object_class_install_property (gobject_class, PROP_TYPE,
238 g_param_spec_int ("type", "Type", "Type of the chebychev filter", 1, 2, 1,
239 G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
241 /* FIXME: Don't use the complete possible range but restrict the upper boundary
242 * so automatically generated UIs can use a slider without */
243 g_object_class_install_property (gobject_class, PROP_CUTOFF,
244 g_param_spec_float ("cutoff", "Cutoff", "Cut off frequency (Hz)", 0.0,
245 100000.0, 0.0, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
246 g_object_class_install_property (gobject_class, PROP_RIPPLE,
247 g_param_spec_float ("ripple", "Ripple", "Amount of ripple (dB)", 0.0,
248 200.0, 0.25, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
250 /* FIXME: What to do about this upper boundary? With a cutoff frequency of
251 * rate/4 32 poles are completely possible, with a cutoff frequency very low
252 * or very high 16 poles already produces only noise */
253 g_object_class_install_property (gobject_class, PROP_POLES,
254 g_param_spec_int ("poles", "Poles",
255 "Number of poles to use, will be rounded up to the next even number",
256 2, 32, 4, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
258 filter_class->setup = GST_DEBUG_FUNCPTR (gst_audio_cheb_limit_setup);
259 trans_class->transform_ip =
260 GST_DEBUG_FUNCPTR (gst_audio_cheb_limit_transform_ip);
261 trans_class->start = GST_DEBUG_FUNCPTR (gst_audio_cheb_limit_start);
265 gst_audio_cheb_limit_init (GstAudioChebLimit * filter,
266 GstAudioChebLimitClass * klass)
268 filter->cutoff = 0.0;
269 filter->mode = MODE_LOW_PASS;
272 filter->ripple = 0.25;
273 gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), TRUE);
275 filter->have_coeffs = FALSE;
278 filter->channels = NULL;
282 generate_biquad_coefficients (GstAudioChebLimit * filter,
283 gint p, gdouble * a0, gdouble * a1, gdouble * a2,
284 gdouble * b1, gdouble * b2)
286 gint np = filter->poles;
287 gdouble ripple = filter->ripple;
289 /* pole location in s-plane */
292 /* zero location in s-plane */
293 gdouble rz = 0.0, iz = 0.0;
295 /* transfer function coefficients for the z-plane */
296 gdouble x0, x1, x2, y1, y2;
297 gint type = filter->type;
299 /* Calculate pole location for lowpass at frequency 1 */
301 gdouble angle = (M_PI / 2.0) * (2.0 * p - 1) / np;
307 /* If we allow ripple, move the pole from the unit
308 * circle to an ellipse and keep cutoff at frequency 1 */
309 if (ripple > 0 && type == 1) {
312 es = sqrt (pow (10.0, ripple / 10.0) - 1.0);
314 vx = (1.0 / np) * asinh (1.0 / es);
317 } else if (type == 2) {
320 es = sqrt (pow (10.0, ripple / 10.0) - 1.0);
321 vx = (1.0 / np) * asinh (es);
326 /* Calculate inverse of the pole location to convert from
327 * type I to type II */
329 gdouble mag2 = rp * rp + ip * ip;
335 /* Calculate zero location for frequency 1 on the
336 * unit circle for type 2 */
338 gdouble angle = M_PI / (np * 2.0) + ((p - 1) * M_PI) / (np);
343 mag2 = rz * rz + iz * iz;
348 /* Convert from s-domain to z-domain by
349 * using the bilinear Z-transform, i.e.
350 * substitute s by (2/t)*((z-1)/(z+1))
351 * with t = 2 * tan(0.5).
357 m = rp * rp + ip * ip;
358 d = 4.0 - 4.0 * rp * t + m * t * t;
363 y1 = (8.0 - 2.0 * m * t * t) / d;
364 y2 = (-4.0 - 4.0 * rp * t - m * t * t) / d;
369 m = rp * rp + ip * ip;
370 d = 4.0 - 4.0 * rp * t + m * t * t;
372 x0 = (t * t * iz * iz + 4.0) / d;
373 x1 = (-8.0 + 2.0 * iz * iz * t * t) / d;
375 y1 = (8.0 - 2.0 * m * t * t) / d;
376 y2 = (-4.0 - 4.0 * rp * t - m * t * t) / d;
379 /* Convert from lowpass at frequency 1 to either lowpass
382 * For lowpass substitute z^(-1) with:
389 * k = sin((1-w)/2) / sin((1+w)/2)
391 * For highpass substitute z^(-1) with:
399 * k = -cos((1+w)/2) / cos((1-w)/2)
405 2.0 * M_PI * (filter->cutoff / GST_AUDIO_FILTER (filter)->format.rate);
407 if (filter->mode == MODE_LOW_PASS)
408 k = sin ((1.0 - omega) / 2.0) / sin ((1.0 + omega) / 2.0);
410 k = -cos ((omega + 1.0) / 2.0) / cos ((omega - 1.0) / 2.0);
412 d = 1.0 + y1 * k - y2 * k * k;
413 *a0 = (x0 + k * (-x1 + k * x2)) / d;
414 *a1 = (x1 + k * k * x1 - 2.0 * k * (x0 + x2)) / d;
415 *a2 = (x0 * k * k - x1 * k + x2) / d;
416 *b1 = (2.0 * k + y1 + y1 * k * k - 2.0 * y2 * k) / d;
417 *b2 = (-k * k - y1 * k + y2) / d;
419 if (filter->mode == MODE_HIGH_PASS) {
426 /* Evaluate the transfer function that corresponds to the IIR
427 * coefficients at zr + zi*I and return the magnitude */
429 calculate_gain (gdouble * a, gdouble * b, gint num_a, gint num_b, gdouble zr,
432 gdouble sum_ar, sum_ai;
433 gdouble sum_br, sum_bi;
434 gdouble gain_r, gain_i;
443 for (i = num_a; i >= 0; i--) {
447 sum_ar = (sum_r_old * zr - sum_i_old * zi) + a[i];
448 sum_ai = (sum_r_old * zi + sum_i_old * zr) + 0.0;
453 for (i = num_b; i >= 0; i--) {
457 sum_br = (sum_r_old * zr - sum_i_old * zi) - b[i];
458 sum_bi = (sum_r_old * zi + sum_i_old * zr) - 0.0;
464 (sum_ar * sum_br + sum_ai * sum_bi) / (sum_br * sum_br + sum_bi * sum_bi);
466 (sum_ai * sum_br - sum_ar * sum_bi) / (sum_br * sum_br + sum_bi * sum_bi);
468 return (sqrt (gain_r * gain_r + gain_i * gain_i));
472 generate_coefficients (GstAudioChebLimit * filter)
474 gint channels = GST_AUDIO_FILTER (filter)->format.channels;
486 if (filter->channels) {
487 GstAudioChebLimitChannelCtx *ctx;
490 for (i = 0; i < channels; i++) {
491 ctx = &filter->channels[i];
496 g_free (filter->channels);
497 filter->channels = NULL;
500 if (GST_AUDIO_FILTER (filter)->format.rate == 0) {
502 filter->a = g_new0 (gdouble, 1);
505 filter->channels = g_new0 (GstAudioChebLimitChannelCtx, channels);
506 GST_LOG_OBJECT (filter, "rate was not set yet");
510 filter->have_coeffs = TRUE;
512 if (filter->cutoff >= GST_AUDIO_FILTER (filter)->format.rate / 2.0) {
514 filter->a = g_new0 (gdouble, 1);
515 filter->a[0] = (filter->mode == MODE_LOW_PASS) ? 1.0 : 0.0;
517 filter->channels = g_new0 (GstAudioChebLimitChannelCtx, channels);
518 GST_LOG_OBJECT (filter, "cutoff was higher than nyquist frequency");
520 } else if (filter->cutoff <= 0.0) {
522 filter->a = g_new0 (gdouble, 1);
523 filter->a[0] = (filter->mode == MODE_LOW_PASS) ? 0.0 : 1.0;
525 filter->channels = g_new0 (GstAudioChebLimitChannelCtx, channels);
526 GST_LOG_OBJECT (filter, "cutoff is lower than zero");
530 /* Calculate coefficients for the chebyshev filter */
532 gint np = filter->poles;
536 filter->num_a = np + 1;
537 filter->a = a = g_new0 (gdouble, np + 3);
538 filter->num_b = np + 1;
539 filter->b = b = g_new0 (gdouble, np + 3);
541 filter->channels = g_new0 (GstAudioChebLimitChannelCtx, channels);
542 for (i = 0; i < channels; i++) {
543 GstAudioChebLimitChannelCtx *ctx = &filter->channels[i];
545 ctx->x = g_new0 (gdouble, np + 1);
546 ctx->y = g_new0 (gdouble, np + 1);
549 /* Calculate transfer function coefficients */
553 for (p = 1; p <= np / 2; p++) {
554 gdouble a0, a1, a2, b1, b2;
555 gdouble *ta = g_new0 (gdouble, np + 3);
556 gdouble *tb = g_new0 (gdouble, np + 3);
558 generate_biquad_coefficients (filter, p, &a0, &a1, &a2, &b1, &b2);
560 memcpy (ta, a, sizeof (gdouble) * (np + 3));
561 memcpy (tb, b, sizeof (gdouble) * (np + 3));
563 /* add the new coefficients for the new two poles
564 * to the cascade by multiplication of the transfer
566 for (i = 2; i < np + 3; i++) {
567 a[i] = a0 * ta[i] + a1 * ta[i - 1] + a2 * ta[i - 2];
568 b[i] = tb[i] - b1 * tb[i - 1] - b2 * tb[i - 2];
574 /* Move coefficients to the beginning of the array
575 * and multiply the b coefficients with -1 to move from
576 * the transfer function's coefficients to the difference
577 * equation's coefficients */
579 for (i = 0; i <= np; i++) {
584 /* Normalize to unity gain at frequency 0 for lowpass
585 * and frequency 0.5 for highpass */
589 if (filter->mode == MODE_LOW_PASS)
590 gain = calculate_gain (a, b, np, np, 1.0, 0.0);
592 gain = calculate_gain (a, b, np, np, -1.0, 0.0);
594 for (i = 0; i <= np; i++) {
599 GST_LOG_OBJECT (filter,
600 "Generated IIR coefficients for the Chebyshev filter");
601 GST_LOG_OBJECT (filter,
602 "mode: %s, type: %d, poles: %d, cutoff: %.2f Hz, ripple: %.2f dB",
603 (filter->mode == MODE_LOW_PASS) ? "low-pass" : "high-pass",
604 filter->type, filter->poles, filter->cutoff, filter->ripple);
605 GST_LOG_OBJECT (filter, "%.2f dB gain @ 0 Hz",
606 20.0 * log10 (calculate_gain (a, b, np, np, 1.0, 0.0)));
609 2.0 * M_PI * (filter->cutoff /
610 GST_AUDIO_FILTER (filter)->format.rate);
611 gdouble zr = cos (wc), zi = sin (wc);
613 GST_LOG_OBJECT (filter, "%.2f dB gain @ %d Hz",
614 20.0 * log10 (calculate_gain (a, b, np, np, zr, zi)),
615 (int) filter->cutoff);
617 GST_LOG_OBJECT (filter, "%.2f dB gain @ %d Hz",
618 20.0 * log10 (calculate_gain (a, b, np, np, -1.0, 0.0)),
619 GST_AUDIO_FILTER (filter)->format.rate / 2);
624 gst_audio_cheb_limit_set_property (GObject * object, guint prop_id,
625 const GValue * value, GParamSpec * pspec)
627 GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
631 GST_BASE_TRANSFORM_LOCK (filter);
632 filter->mode = g_value_get_enum (value);
633 generate_coefficients (filter);
634 GST_BASE_TRANSFORM_UNLOCK (filter);
637 GST_BASE_TRANSFORM_LOCK (filter);
638 filter->type = g_value_get_int (value);
639 generate_coefficients (filter);
640 GST_BASE_TRANSFORM_UNLOCK (filter);
643 GST_BASE_TRANSFORM_LOCK (filter);
644 filter->cutoff = g_value_get_float (value);
645 generate_coefficients (filter);
646 GST_BASE_TRANSFORM_UNLOCK (filter);
649 GST_BASE_TRANSFORM_LOCK (filter);
650 filter->ripple = g_value_get_float (value);
651 generate_coefficients (filter);
652 GST_BASE_TRANSFORM_UNLOCK (filter);
655 GST_BASE_TRANSFORM_LOCK (filter);
656 filter->poles = GST_ROUND_UP_2 (g_value_get_int (value));
657 generate_coefficients (filter);
658 GST_BASE_TRANSFORM_UNLOCK (filter);
661 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
667 gst_audio_cheb_limit_get_property (GObject * object, guint prop_id,
668 GValue * value, GParamSpec * pspec)
670 GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (object);
674 g_value_set_enum (value, filter->mode);
677 g_value_set_int (value, filter->type);
680 g_value_set_float (value, filter->cutoff);
683 g_value_set_float (value, filter->ripple);
686 g_value_set_int (value, filter->poles);
689 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
694 /* GstAudioFilter vmethod implementations */
697 gst_audio_cheb_limit_setup (GstAudioFilter * base, GstRingBufferSpec * format)
699 GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (base);
702 if (format->width == 32)
703 filter->process = (GstAudioChebLimitProcessFunc)
705 else if (format->width == 64)
706 filter->process = (GstAudioChebLimitProcessFunc)
711 filter->have_coeffs = FALSE;
716 static inline gdouble
717 process (GstAudioChebLimit * filter,
718 GstAudioChebLimitChannelCtx * ctx, gdouble x0)
720 gdouble val = filter->a[0] * x0;
723 for (i = 1, j = ctx->x_pos; i < filter->num_a; i++) {
724 val += filter->a[i] * ctx->x[j];
727 j = filter->num_a - 1;
730 for (i = 1, j = ctx->y_pos; i < filter->num_b; i++) {
731 val += filter->b[i] * ctx->y[j];
734 j = filter->num_b - 1;
739 if (ctx->x_pos > filter->num_a - 1)
741 ctx->x[ctx->x_pos] = x0;
746 if (ctx->y_pos > filter->num_b - 1)
749 ctx->y[ctx->y_pos] = val;
755 #define DEFINE_PROCESS_FUNC(width,ctype) \
757 process_##width (GstAudioChebLimit * filter, \
758 g##ctype * data, guint num_samples) \
760 gint i, j, channels = GST_AUDIO_FILTER (filter)->format.channels; \
763 for (i = 0; i < num_samples / channels; i++) { \
764 for (j = 0; j < channels; j++) { \
765 val = process (filter, &filter->channels[j], *data); \
771 DEFINE_PROCESS_FUNC (32, float);
772 DEFINE_PROCESS_FUNC (64, double);
774 #undef DEFINE_PROCESS_FUNC
776 /* GstBaseTransform vmethod implementations */
778 gst_audio_cheb_limit_transform_ip (GstBaseTransform * base, GstBuffer * buf)
780 GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (base);
782 GST_BUFFER_SIZE (buf) / (GST_AUDIO_FILTER (filter)->format.width / 8);
784 if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (buf)))
785 gst_object_sync_values (G_OBJECT (filter), GST_BUFFER_TIMESTAMP (buf));
787 if (gst_base_transform_is_passthrough (base))
790 if (!filter->have_coeffs)
791 generate_coefficients (filter);
793 filter->process (filter, GST_BUFFER_DATA (buf), num_samples);
800 gst_audio_cheb_limit_start (GstBaseTransform * base)
802 GstAudioChebLimit *filter = GST_AUDIO_CHEB_LIMIT (base);
803 gint channels = GST_AUDIO_FILTER (filter)->format.channels;
804 GstAudioChebLimitChannelCtx *ctx;
807 /* Reset the history of input and output values if
808 * already existing */
809 if (channels && filter->channels) {
810 for (i = 0; i < channels; i++) {
811 ctx = &filter->channels[i];
813 memset (ctx->x, 0, (filter->poles + 1) * sizeof (gdouble));
815 memset (ctx->y, 0, (filter->poles + 1) * sizeof (gdouble));