Move the lpwsinc and bpwsinc elements from gst-plugins-bad into the audiofx plugin...
[platform/upstream/gst-plugins-good.git] / gst / audiofx / audiowsincband.c
1 /* -*- c-basic-offset: 2 -*-
2  * 
3  * GStreamer
4  * Copyright (C) 1999-2001 Erik Walthinsen <omega@cse.ogi.edu>
5  *               2006 Dreamlab Technologies Ltd. <mathis.hofer@dreamlab.net>
6  *               2007 Sebastian Dröge <slomo@circular-chaos.org>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  * 
23  * 
24  * this windowed sinc filter is taken from the freely downloadable DSP book,
25  * "The Scientist and Engineer's Guide to Digital Signal Processing",
26  * chapter 16
27  * available at http://www.dspguide.com/
28  *
29  * TODO:  - Implement the convolution in place, probably only makes sense
30  *          when using FFT convolution as currently the convolution itself
31  *          is probably the bottleneck
32  *        - Maybe allow cascading the filter to get a better stopband attenuation.
33  *          Can be done by convolving a filter kernel with itself
34  *        - Drop the first kernel_length/2 samples and append the same number of
35  *          samples on EOS as the first few samples are essentialy zero.
36  */
37
38 /**
39  * SECTION:element-audiowsincband
40  * @short_description: Windowed Sinc band pass and band reject filter
41  *
42  * <refsect2>
43  * <para>
44  * Attenuates all frequencies outside (bandpass) or inside (bandreject) of a frequency
45  * band. The length parameter controls the rolloff, the window parameter
46  * controls rolloff and stopband attenuation. The Hamming window provides a faster rolloff but a bit
47  * worse stopband attenuation, the other way around for the Blackman window.
48  * </para>
49  * <para>
50  * This element has the advantage over the Chebyshev bandpass and bandreject filter that it has
51  * a much better rolloff when using a larger kernel size and almost linear phase. The only
52  * disadvantage is the much slower execution time with larger kernels.
53  * </para>
54  * <title>Example launch line</title>
55  * <para>
56  * <programlisting>
57  * gst-launch audiotestsrc freq=1500 ! audioconvert ! audiosincband mode=band-pass lower-frequency=3000 upper-frequency=10000 length=501 window=blackman ! audioconvert ! alsasink
58  * gst-launch filesrc location="melo1.ogg" ! oggdemux ! vorbisdec ! audioconvert ! audiowsincband mode=band-reject lower-frequency=59 upper-frequency=61 length=10001 window=hamming ! audioconvert ! alsasink
59  * gst-launch audiotestsrc wave=white-noise ! audioconvert ! audiowsincband mode=band-pass lower-frequency=1000 upper-frequency=2000 length=31 ! audioconvert ! alsasink
60  * </programlisting>
61  * </para>
62  * </refsect2>
63  */
64
65 #ifdef HAVE_CONFIG_H
66 #include "config.h"
67 #endif
68
69 #include <string.h>
70 #include <math.h>
71 #include <gst/gst.h>
72 #include <gst/audio/gstaudiofilter.h>
73 #include <gst/controller/gstcontroller.h>
74
75 #include "audiowsincband.h"
76
77 #define GST_CAT_DEFAULT gst_audio_wsincband_debug
78 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
79
80 static const GstElementDetails audio_wsincband_details =
81 GST_ELEMENT_DETAILS ("Band-pass and Band-reject Windowed sinc filter",
82     "Filter/Effect/Audio",
83     "Band-pass Windowed sinc filter",
84     "Thomas <thomas@apestaart.org>, "
85     "Steven W. Smith, "
86     "Dreamlab Technologies Ltd. <mathis.hofer@dreamlab.net>, "
87     "Sebastian Dröge <slomo@circular-chaos.org>");
88
89 /* Filter signals and args */
90 enum
91 {
92   /* FILL ME */
93   LAST_SIGNAL
94 };
95
96 enum
97 {
98   PROP_0,
99   PROP_LENGTH,
100   PROP_LOWER_FREQUENCY,
101   PROP_UPPER_FREQUENCY,
102   PROP_MODE,
103   PROP_WINDOW
104 };
105
106 enum
107 {
108   MODE_BAND_PASS = 0,
109   MODE_BAND_REJECT
110 };
111
112 #define GST_TYPE_AUDIO_WSINC_BAND_MODE (gst_audio_wsincband_mode_get_type ())
113 static GType
114 gst_audio_wsincband_mode_get_type (void)
115 {
116   static GType gtype = 0;
117
118   if (gtype == 0) {
119     static const GEnumValue values[] = {
120       {MODE_BAND_PASS, "Band pass (default)",
121           "band-pass"},
122       {MODE_BAND_REJECT, "Band reject",
123           "band-reject"},
124       {0, NULL, NULL}
125     };
126
127     gtype = g_enum_register_static ("GstAudioWSincBandMode", values);
128   }
129   return gtype;
130 }
131
132 enum
133 {
134   WINDOW_HAMMING = 0,
135   WINDOW_BLACKMAN
136 };
137
138 #define GST_TYPE_AUDIO_WSINC_BAND_WINDOW (gst_audio_wsincband_window_get_type ())
139 static GType
140 gst_audio_wsincband_window_get_type (void)
141 {
142   static GType gtype = 0;
143
144   if (gtype == 0) {
145     static const GEnumValue values[] = {
146       {WINDOW_HAMMING, "Hamming window (default)",
147           "hamming"},
148       {WINDOW_BLACKMAN, "Blackman window",
149           "blackman"},
150       {0, NULL, NULL}
151     };
152
153     gtype = g_enum_register_static ("GstAudioWSincBandWindow", values);
154   }
155   return gtype;
156 }
157
158 #define ALLOWED_CAPS \
159     "audio/x-raw-float, "                                             \
160     " width = (int) { 32, 64 }, "                                     \
161     " endianness = (int) BYTE_ORDER, "                                \
162     " rate = (int) [ 1, MAX ], "                                      \
163     " channels = (int) [ 1, MAX ] "
164
165 #define DEBUG_INIT(bla) \
166   GST_DEBUG_CATEGORY_INIT (gst_audio_wsincband_debug, "audiowsincband", 0, \
167       "Band-pass and Band-reject Windowed sinc filter plugin");
168
169 GST_BOILERPLATE_FULL (GstAudioWSincBand, audio_wsincband, GstAudioFilter,
170     GST_TYPE_AUDIO_FILTER, DEBUG_INIT);
171
172 static void audio_wsincband_set_property (GObject * object, guint prop_id,
173     const GValue * value, GParamSpec * pspec);
174 static void audio_wsincband_get_property (GObject * object, guint prop_id,
175     GValue * value, GParamSpec * pspec);
176
177 static GstFlowReturn audio_wsincband_transform (GstBaseTransform * base,
178     GstBuffer * inbuf, GstBuffer * outbuf);
179 static gboolean audio_wsincband_start (GstBaseTransform * base);
180 static gboolean audio_wsincband_event (GstBaseTransform * base,
181     GstEvent * event);
182
183 static gboolean audio_wsincband_setup (GstAudioFilter * base,
184     GstRingBufferSpec * format);
185
186 static gboolean audio_wsincband_query (GstPad * pad, GstQuery * query);
187 static const GstQueryType *audio_wsincband_query_type (GstPad * pad);
188
189 /* Element class */
190
191 static void
192 audio_wsincband_dispose (GObject * object)
193 {
194   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (object);
195
196   if (self->residue) {
197     g_free (self->residue);
198     self->residue = NULL;
199   }
200
201   if (self->kernel) {
202     g_free (self->kernel);
203     self->kernel = NULL;
204   }
205
206   G_OBJECT_CLASS (parent_class)->dispose (object);
207 }
208
209 static void
210 audio_wsincband_base_init (gpointer g_class)
211 {
212   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
213   GstCaps *caps;
214
215   gst_element_class_set_details (element_class, &audio_wsincband_details);
216
217   caps = gst_caps_from_string (ALLOWED_CAPS);
218   gst_audio_filter_class_add_pad_templates (GST_AUDIO_FILTER_CLASS (g_class),
219       caps);
220   gst_caps_unref (caps);
221 }
222
223 static void
224 audio_wsincband_class_init (GstAudioWSincBandClass * klass)
225 {
226   GObjectClass *gobject_class;
227   GstBaseTransformClass *trans_class;
228   GstAudioFilterClass *filter_class;
229
230   gobject_class = (GObjectClass *) klass;
231   trans_class = (GstBaseTransformClass *) klass;
232   filter_class = (GstAudioFilterClass *) klass;
233
234   gobject_class->set_property = audio_wsincband_set_property;
235   gobject_class->get_property = audio_wsincband_get_property;
236   gobject_class->dispose = audio_wsincband_dispose;
237
238   /* FIXME: Don't use the complete possible range but restrict the upper boundary
239    * so automatically generated UIs can use a slider */
240   g_object_class_install_property (gobject_class, PROP_LOWER_FREQUENCY,
241       g_param_spec_float ("lower-frequency", "Lower Frequency",
242           "Cut-off lower frequency (Hz)", 0.0, 100000.0, 0, G_PARAM_READWRITE));
243   g_object_class_install_property (gobject_class, PROP_UPPER_FREQUENCY,
244       g_param_spec_float ("upper-frequency", "Upper Frequency",
245           "Cut-off upper frequency (Hz)", 0.0, 100000.0, 0, G_PARAM_READWRITE));
246   g_object_class_install_property (gobject_class, PROP_LENGTH,
247       g_param_spec_int ("length", "Length",
248           "Filter kernel length, will be rounded to the next odd number",
249           3, 50000, 101, G_PARAM_READWRITE));
250
251   g_object_class_install_property (gobject_class, PROP_MODE,
252       g_param_spec_enum ("mode", "Mode",
253           "Band pass or band reject mode", GST_TYPE_AUDIO_WSINC_BAND_MODE,
254           MODE_BAND_PASS, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
255
256   g_object_class_install_property (gobject_class, PROP_WINDOW,
257       g_param_spec_enum ("window", "Window",
258           "Window function to use", GST_TYPE_AUDIO_WSINC_BAND_WINDOW,
259           WINDOW_HAMMING, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
260
261   trans_class->transform = GST_DEBUG_FUNCPTR (audio_wsincband_transform);
262   trans_class->start = GST_DEBUG_FUNCPTR (audio_wsincband_start);
263   trans_class->event = GST_DEBUG_FUNCPTR (audio_wsincband_event);
264   filter_class->setup = GST_DEBUG_FUNCPTR (audio_wsincband_setup);
265 }
266
267 static void
268 audio_wsincband_init (GstAudioWSincBand * self,
269     GstAudioWSincBandClass * g_class)
270 {
271   self->kernel_length = 101;
272   self->latency = 50;
273   self->lower_frequency = 0.0;
274   self->upper_frequency = 0.0;
275   self->mode = MODE_BAND_PASS;
276   self->window = WINDOW_HAMMING;
277   self->kernel = NULL;
278   self->have_kernel = FALSE;
279   self->residue = NULL;
280
281   self->residue_length = 0;
282   self->next_ts = GST_CLOCK_TIME_NONE;
283   self->next_off = GST_BUFFER_OFFSET_NONE;
284
285   gst_pad_set_query_function (GST_BASE_TRANSFORM (self)->srcpad,
286       audio_wsincband_query);
287   gst_pad_set_query_type_function (GST_BASE_TRANSFORM (self)->srcpad,
288       audio_wsincband_query_type);
289 }
290
291 #define DEFINE_PROCESS_FUNC(width,ctype) \
292 static void \
293 process_##width (GstAudioWSincBand * self, g##ctype * src, g##ctype * dst, guint input_samples) \
294 { \
295   gint kernel_length = self->kernel_length; \
296   gint i, j, k, l; \
297   gint channels = GST_AUDIO_FILTER (self)->format.channels; \
298   gint res_start; \
299   \
300   /* convolution */ \
301   for (i = 0; i < input_samples; i++) { \
302     dst[i] = 0.0; \
303     k = i % channels; \
304     l = i / channels; \
305     for (j = 0; j < kernel_length; j++) \
306       if (l < j) \
307         dst[i] += \
308             self->residue[(kernel_length + l - j) * channels + \
309             k] * self->kernel[j]; \
310       else \
311         dst[i] += src[(l - j) * channels + k] * self->kernel[j]; \
312   } \
313   \
314   /* copy the tail of the current input buffer to the residue, while \
315    * keeping parts of the residue if the input buffer is smaller than \
316    * the kernel length */ \
317   if (input_samples < kernel_length * channels) \
318     res_start = kernel_length * channels - input_samples; \
319   else \
320     res_start = 0; \
321   \
322   for (i = 0; i < res_start; i++) \
323     self->residue[i] = self->residue[i + input_samples]; \
324   for (i = res_start; i < kernel_length * channels; i++) \
325     self->residue[i] = src[input_samples - kernel_length * channels + i]; \
326   \
327   self->residue_length += kernel_length * channels - res_start; \
328   if (self->residue_length > kernel_length * channels) \
329     self->residue_length = kernel_length * channels; \
330 }
331
332 DEFINE_PROCESS_FUNC (32, float);
333 DEFINE_PROCESS_FUNC (64, double);
334
335 #undef DEFINE_PROCESS_FUNC
336
337 static void
338 audio_wsincband_build_kernel (GstAudioWSincBand * self)
339 {
340   gint i = 0;
341   gdouble sum = 0.0;
342   gint len = 0;
343   gdouble *kernel_lp, *kernel_hp;
344   gdouble w;
345
346   len = self->kernel_length;
347
348   if (GST_AUDIO_FILTER (self)->format.rate == 0) {
349     GST_DEBUG ("rate not set yet");
350     return;
351   }
352
353   if (GST_AUDIO_FILTER (self)->format.channels == 0) {
354     GST_DEBUG ("channels not set yet");
355     return;
356   }
357
358   /* Clamp frequencies */
359   self->lower_frequency =
360       CLAMP (self->lower_frequency, 0.0,
361       GST_AUDIO_FILTER (self)->format.rate / 2);
362   self->upper_frequency =
363       CLAMP (self->upper_frequency, 0.0,
364       GST_AUDIO_FILTER (self)->format.rate / 2);
365   if (self->lower_frequency > self->upper_frequency) {
366     gint tmp = self->lower_frequency;
367
368     self->lower_frequency = self->upper_frequency;
369     self->upper_frequency = tmp;
370   }
371
372   GST_DEBUG ("audio_wsincband: initializing filter kernel of length %d "
373       "with lower frequency %.2lf Hz "
374       ", upper frequency %.2lf Hz for mode %s",
375       len, self->lower_frequency, self->upper_frequency,
376       (self->mode == MODE_BAND_PASS) ? "band-pass" : "band-reject");
377
378   /* fill the lp kernel */
379   w = 2 * M_PI * (self->lower_frequency / GST_AUDIO_FILTER (self)->format.rate);
380   kernel_lp = g_new (gdouble, len);
381   for (i = 0; i < len; ++i) {
382     if (i == len / 2)
383       kernel_lp[i] = w;
384     else
385       kernel_lp[i] = sin (w * (i - len / 2))
386           / (i - len / 2);
387     /* Windowing */
388     if (self->window == WINDOW_HAMMING)
389       kernel_lp[i] *= (0.54 - 0.46 * cos (2 * M_PI * i / len));
390     else
391       kernel_lp[i] *=
392           (0.42 - 0.5 * cos (2 * M_PI * i / len) +
393           0.08 * cos (4 * M_PI * i / len));
394   }
395
396   /* normalize for unity gain at DC */
397   sum = 0.0;
398   for (i = 0; i < len; ++i)
399     sum += kernel_lp[i];
400   for (i = 0; i < len; ++i)
401     kernel_lp[i] /= sum;
402
403   /* fill the hp kernel */
404   w = 2 * M_PI * (self->upper_frequency / GST_AUDIO_FILTER (self)->format.rate);
405   kernel_hp = g_new (gdouble, len);
406   for (i = 0; i < len; ++i) {
407     if (i == len / 2)
408       kernel_hp[i] = w;
409     else
410       kernel_hp[i] = sin (w * (i - len / 2))
411           / (i - len / 2);
412     /* Windowing */
413     if (self->window == WINDOW_HAMMING)
414       kernel_hp[i] *= (0.54 - 0.46 * cos (2 * M_PI * i / len));
415     else
416       kernel_hp[i] *=
417           (0.42 - 0.5 * cos (2 * M_PI * i / len) +
418           0.08 * cos (4 * M_PI * i / len));
419   }
420
421   /* normalize for unity gain at DC */
422   sum = 0.0;
423   for (i = 0; i < len; ++i)
424     sum += kernel_hp[i];
425   for (i = 0; i < len; ++i)
426     kernel_hp[i] /= sum;
427
428   /* do spectral inversion to go from lowpass to highpass */
429   for (i = 0; i < len; ++i)
430     kernel_hp[i] = -kernel_hp[i];
431   kernel_hp[len / 2] += 1;
432
433   /* combine the two kernels */
434   if (self->kernel)
435     g_free (self->kernel);
436   self->kernel = g_new (gdouble, len);
437
438   for (i = 0; i < len; ++i)
439     self->kernel[i] = kernel_lp[i] + kernel_hp[i];
440
441   /* free the helper kernels */
442   g_free (kernel_lp);
443   g_free (kernel_hp);
444
445   /* do spectral inversion to go from bandreject to bandpass
446    * if specified */
447   if (self->mode == MODE_BAND_PASS) {
448     for (i = 0; i < len; ++i)
449       self->kernel[i] = -self->kernel[i];
450     self->kernel[len / 2] += 1;
451   }
452
453   /* set up the residue memory space */
454   if (!self->residue) {
455     self->residue =
456         g_new0 (gdouble, len * GST_AUDIO_FILTER (self)->format.channels);
457     self->residue_length = 0;
458   }
459
460   self->have_kernel = TRUE;
461 }
462
463 static void
464 audio_wsincband_push_residue (GstAudioWSincBand * self)
465 {
466   GstBuffer *outbuf;
467   GstFlowReturn res;
468   gint rate = GST_AUDIO_FILTER (self)->format.rate;
469   gint channels = GST_AUDIO_FILTER (self)->format.channels;
470   gint outsize, outsamples;
471   gint diffsize, diffsamples;
472   guint8 *in, *out;
473
474   /* Calculate the number of samples and their memory size that
475    * should be pushed from the residue */
476   outsamples = MIN (self->latency, self->residue_length / channels);
477   outsize = outsamples * channels * (GST_AUDIO_FILTER (self)->format.width / 8);
478   if (outsize == 0)
479     return;
480
481   /* Process the difference between latency and residue_length samples
482    * to start at the actual data instead of starting at the zeros before
483    * when we only got one buffer smaller than latency */
484   diffsamples = self->latency - self->residue_length / channels;
485   diffsize =
486       diffsamples * channels * (GST_AUDIO_FILTER (self)->format.width / 8);
487   if (diffsize > 0) {
488     in = g_new0 (guint8, diffsize);
489     out = g_new0 (guint8, diffsize);
490     self->process (self, in, out, diffsamples * channels);
491     g_free (in);
492     g_free (out);
493   }
494
495   res = gst_pad_alloc_buffer (GST_BASE_TRANSFORM (self)->srcpad,
496       GST_BUFFER_OFFSET_NONE, outsize,
497       GST_PAD_CAPS (GST_BASE_TRANSFORM (self)->srcpad), &outbuf);
498
499   if (G_UNLIKELY (res != GST_FLOW_OK)) {
500     GST_WARNING_OBJECT (self, "failed allocating buffer of %d bytes", outsize);
501     return;
502   }
503
504   /* Convolve the residue with zeros to get the actual remaining data */
505   in = g_new0 (guint8, outsize);
506   self->process (self, in, GST_BUFFER_DATA (outbuf), outsamples * channels);
507   g_free (in);
508
509   /* Set timestamp, offset, etc from the values we
510    * saved when processing the regular buffers */
511   if (GST_CLOCK_TIME_IS_VALID (self->next_ts))
512     GST_BUFFER_TIMESTAMP (outbuf) = self->next_ts;
513   else
514     GST_BUFFER_TIMESTAMP (outbuf) = 0;
515   GST_BUFFER_DURATION (outbuf) =
516       gst_util_uint64_scale (outsamples, GST_SECOND, rate);
517   self->next_ts += gst_util_uint64_scale (outsamples, GST_SECOND, rate);
518
519   if (self->next_off != GST_BUFFER_OFFSET_NONE) {
520     GST_BUFFER_OFFSET (outbuf) = self->next_off;
521     GST_BUFFER_OFFSET_END (outbuf) = self->next_off + outsamples;
522   }
523
524   GST_DEBUG_OBJECT (self, "Pushing residue buffer of size %d with timestamp: %"
525       GST_TIME_FORMAT ", duration: %" GST_TIME_FORMAT ", offset: %lld,"
526       " offset_end: %lld, nsamples: %d", GST_BUFFER_SIZE (outbuf),
527       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
528       GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf),
529       GST_BUFFER_OFFSET_END (outbuf), outsamples);
530
531   res = gst_pad_push (GST_BASE_TRANSFORM (self)->srcpad, outbuf);
532
533   if (G_UNLIKELY (res != GST_FLOW_OK)) {
534     GST_WARNING_OBJECT (self, "failed to push residue");
535   }
536
537 }
538
539 /* GstAudioFilter vmethod implementations */
540
541 /* get notified of caps and plug in the correct process function */
542 static gboolean
543 audio_wsincband_setup (GstAudioFilter * base, GstRingBufferSpec * format)
544 {
545   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (base);
546
547   gboolean ret = TRUE;
548
549   if (format->width == 32)
550     self->process = (GstAudioWSincBandProcessFunc) process_32;
551   else if (format->width == 64)
552     self->process = (GstAudioWSincBandProcessFunc) process_64;
553   else
554     ret = FALSE;
555
556   self->have_kernel = FALSE;
557
558   return TRUE;
559 }
560
561 /* GstBaseTransform vmethod implementations */
562
563 static GstFlowReturn
564 audio_wsincband_transform (GstBaseTransform * base, GstBuffer * inbuf,
565     GstBuffer * outbuf)
566 {
567   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (base);
568   GstClockTime timestamp;
569   gint channels = GST_AUDIO_FILTER (self)->format.channels;
570   gint rate = GST_AUDIO_FILTER (self)->format.rate;
571   gint input_samples =
572       GST_BUFFER_SIZE (outbuf) / (GST_AUDIO_FILTER (self)->format.width / 8);
573   gint output_samples = input_samples;
574   gint diff;
575
576   /* FIXME: subdivide GST_BUFFER_SIZE into small chunks for smooth fades */
577   timestamp = GST_BUFFER_TIMESTAMP (outbuf);
578   if (GST_CLOCK_TIME_IS_VALID (timestamp))
579     gst_object_sync_values (G_OBJECT (self), timestamp);
580
581   if (!self->have_kernel)
582     audio_wsincband_build_kernel (self);
583
584   /* Reset the residue if already existing on discont buffers */
585   if (GST_BUFFER_IS_DISCONT (inbuf)) {
586     if (channels && self->residue)
587       memset (self->residue, 0, channels *
588           self->kernel_length * sizeof (gdouble));
589     self->residue_length = 0;
590     self->next_ts = GST_CLOCK_TIME_NONE;
591     self->next_off = GST_BUFFER_OFFSET_NONE;
592   }
593
594   /* Calculate the number of samples we can push out now without outputting
595    * kernel_length/2 zeros in the beginning */
596   diff = (self->kernel_length / 2) * channels - self->residue_length;
597   if (diff > 0)
598     output_samples -= diff;
599
600   self->process (self, GST_BUFFER_DATA (inbuf), GST_BUFFER_DATA (outbuf),
601       input_samples);
602
603   if (output_samples <= 0) {
604     /* Drop buffer and save original timestamp/offset for later use */
605     if (!GST_CLOCK_TIME_IS_VALID (self->next_ts)
606         && GST_BUFFER_TIMESTAMP_IS_VALID (outbuf))
607       self->next_ts = GST_BUFFER_TIMESTAMP (outbuf);
608     if (self->next_off == GST_BUFFER_OFFSET_NONE
609         && GST_BUFFER_OFFSET_IS_VALID (outbuf))
610       self->next_off = GST_BUFFER_OFFSET (outbuf);
611     return GST_BASE_TRANSFORM_FLOW_DROPPED;
612   } else if (output_samples < input_samples) {
613     /* First (probably partial) buffer after starting from
614      * a clean residue. Use stored timestamp/offset here */
615     if (GST_CLOCK_TIME_IS_VALID (self->next_ts))
616       GST_BUFFER_TIMESTAMP (outbuf) = self->next_ts;
617
618     if (self->next_off != GST_BUFFER_OFFSET_NONE) {
619       GST_BUFFER_OFFSET (outbuf) = self->next_off;
620       if (GST_BUFFER_OFFSET_END_IS_VALID (outbuf))
621         GST_BUFFER_OFFSET_END (outbuf) =
622             self->next_off + output_samples / channels;
623     } else {
624       /* We dropped no buffer, offset is valid, offset_end must be adjusted by diff */
625       if (GST_BUFFER_OFFSET_END_IS_VALID (outbuf))
626         GST_BUFFER_OFFSET_END (outbuf) -= diff / channels;
627     }
628
629     if (GST_BUFFER_DURATION_IS_VALID (outbuf))
630       GST_BUFFER_DURATION (outbuf) -=
631           gst_util_uint64_scale (diff, GST_SECOND, channels * rate);
632
633     GST_BUFFER_DATA (outbuf) +=
634         diff * (GST_AUDIO_FILTER (self)->format.width / 8);
635     GST_BUFFER_SIZE (outbuf) -=
636         diff * (GST_AUDIO_FILTER (self)->format.width / 8);
637   } else {
638     GstClockTime ts_latency =
639         gst_util_uint64_scale (self->latency, GST_SECOND, rate);
640
641     /* Normal buffer, adjust timestamp/offset/etc by latency */
642     if (GST_BUFFER_TIMESTAMP (outbuf) < ts_latency) {
643       GST_WARNING_OBJECT (self, "GST_BUFFER_TIMESTAMP (outbuf) < latency");
644       GST_BUFFER_TIMESTAMP (outbuf) = 0;
645     } else {
646       GST_BUFFER_TIMESTAMP (outbuf) -= ts_latency;
647     }
648
649     if (GST_BUFFER_OFFSET_IS_VALID (outbuf)) {
650       if (GST_BUFFER_OFFSET (outbuf) > self->latency) {
651         GST_BUFFER_OFFSET (outbuf) -= self->latency;
652       } else {
653         GST_WARNING_OBJECT (self, "GST_BUFFER_OFFSET (outbuf) < latency");
654         GST_BUFFER_OFFSET (outbuf) = 0;
655       }
656     }
657
658     if (GST_BUFFER_OFFSET_END_IS_VALID (outbuf)) {
659       if (GST_BUFFER_OFFSET_END (outbuf) > self->latency) {
660         GST_BUFFER_OFFSET_END (outbuf) -= self->latency;
661       } else {
662         GST_WARNING_OBJECT (self, "GST_BUFFER_OFFSET_END (outbuf) < latency");
663         GST_BUFFER_OFFSET_END (outbuf) = 0;
664       }
665     }
666   }
667
668   GST_DEBUG_OBJECT (self, "Pushing buffer of size %d with timestamp: %"
669       GST_TIME_FORMAT ", duration: %" GST_TIME_FORMAT ", offset: %lld,"
670       " offset_end: %lld, nsamples: %d", GST_BUFFER_SIZE (outbuf),
671       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
672       GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf),
673       GST_BUFFER_OFFSET_END (outbuf), output_samples / channels);
674
675   self->next_ts = GST_BUFFER_TIMESTAMP (outbuf) + GST_BUFFER_DURATION (outbuf);
676   self->next_off = GST_BUFFER_OFFSET_END (outbuf);
677
678   return GST_FLOW_OK;
679 }
680
681 static gboolean
682 audio_wsincband_start (GstBaseTransform * base)
683 {
684   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (base);
685   gint channels = GST_AUDIO_FILTER (self)->format.channels;
686
687   /* Reset the residue if already existing */
688   if (channels && self->residue)
689     memset (self->residue, 0, channels *
690         self->kernel_length * sizeof (gdouble));
691
692   self->residue_length = 0;
693   self->next_ts = GST_CLOCK_TIME_NONE;
694   self->next_off = GST_BUFFER_OFFSET_NONE;
695
696   return TRUE;
697 }
698
699 static gboolean
700 audio_wsincband_query (GstPad * pad, GstQuery * query)
701 {
702   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (gst_pad_get_parent (pad));
703   gboolean res = TRUE;
704
705   switch (GST_QUERY_TYPE (query)) {
706     case GST_QUERY_LATENCY:
707     {
708       GstClockTime min, max;
709       gboolean live;
710       guint64 latency;
711       GstPad *peer;
712       gint rate = GST_AUDIO_FILTER (self)->format.rate;
713
714       if ((peer = gst_pad_get_peer (GST_BASE_TRANSFORM (self)->sinkpad))) {
715         if ((res = gst_pad_query (peer, query))) {
716           gst_query_parse_latency (query, &live, &min, &max);
717
718           GST_DEBUG_OBJECT (self, "Peer latency: min %"
719               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
720               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
721
722           /* add our own latency */
723           latency =
724               (rate != 0) ? gst_util_uint64_scale (self->latency, GST_SECOND,
725               rate) : 0;
726
727           GST_DEBUG_OBJECT (self, "Our latency: %"
728               GST_TIME_FORMAT, GST_TIME_ARGS (latency));
729
730           min += latency;
731           if (max != GST_CLOCK_TIME_NONE)
732             max += latency;
733
734           GST_DEBUG_OBJECT (self, "Calculated total latency : min %"
735               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
736               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
737
738           gst_query_set_latency (query, live, min, max);
739         }
740         gst_object_unref (peer);
741       }
742       break;
743     }
744     default:
745       res = gst_pad_query_default (pad, query);
746       break;
747   }
748   gst_object_unref (self);
749   return res;
750 }
751
752 static const GstQueryType *
753 audio_wsincband_query_type (GstPad * pad)
754 {
755   static const GstQueryType types[] = {
756     GST_QUERY_LATENCY,
757     0
758   };
759
760   return types;
761 }
762
763 static gboolean
764 audio_wsincband_event (GstBaseTransform * base, GstEvent * event)
765 {
766   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (base);
767
768   switch (GST_EVENT_TYPE (event)) {
769     case GST_EVENT_EOS:
770       audio_wsincband_push_residue (self);
771       break;
772     default:
773       break;
774   }
775
776   return GST_BASE_TRANSFORM_CLASS (parent_class)->event (base, event);
777 }
778
779 static void
780 audio_wsincband_set_property (GObject * object, guint prop_id,
781     const GValue * value, GParamSpec * pspec)
782 {
783   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (object);
784
785   g_return_if_fail (GST_IS_AUDIO_WSINC_BAND (self));
786
787   switch (prop_id) {
788     case PROP_LENGTH:{
789       gint val;
790
791       GST_BASE_TRANSFORM_LOCK (self);
792       val = g_value_get_int (value);
793       if (val % 2 == 0)
794         val++;
795
796       if (val != self->kernel_length) {
797         if (self->residue) {
798           audio_wsincband_push_residue (self);
799           g_free (self->residue);
800           self->residue = NULL;
801         }
802         self->kernel_length = val;
803         self->latency = val / 2;
804         audio_wsincband_build_kernel (self);
805         gst_element_post_message (GST_ELEMENT (self),
806             gst_message_new_latency (GST_OBJECT (self)));
807       }
808       GST_BASE_TRANSFORM_UNLOCK (self);
809       break;
810     }
811     case PROP_LOWER_FREQUENCY:
812       GST_BASE_TRANSFORM_LOCK (self);
813       self->lower_frequency = g_value_get_float (value);
814       audio_wsincband_build_kernel (self);
815       GST_BASE_TRANSFORM_UNLOCK (self);
816       break;
817     case PROP_UPPER_FREQUENCY:
818       GST_BASE_TRANSFORM_LOCK (self);
819       self->upper_frequency = g_value_get_float (value);
820       audio_wsincband_build_kernel (self);
821       GST_BASE_TRANSFORM_UNLOCK (self);
822       break;
823     case PROP_MODE:
824       GST_BASE_TRANSFORM_LOCK (self);
825       self->mode = g_value_get_enum (value);
826       audio_wsincband_build_kernel (self);
827       GST_BASE_TRANSFORM_UNLOCK (self);
828       break;
829     case PROP_WINDOW:
830       GST_BASE_TRANSFORM_LOCK (self);
831       self->window = g_value_get_enum (value);
832       audio_wsincband_build_kernel (self);
833       GST_BASE_TRANSFORM_UNLOCK (self);
834       break;
835     default:
836       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
837       break;
838   }
839 }
840
841 static void
842 audio_wsincband_get_property (GObject * object, guint prop_id, GValue * value,
843     GParamSpec * pspec)
844 {
845   GstAudioWSincBand *self = GST_AUDIO_WSINC_BAND (object);
846
847   switch (prop_id) {
848     case PROP_LENGTH:
849       g_value_set_int (value, self->kernel_length);
850       break;
851     case PROP_LOWER_FREQUENCY:
852       g_value_set_float (value, self->lower_frequency);
853       break;
854     case PROP_UPPER_FREQUENCY:
855       g_value_set_float (value, self->upper_frequency);
856       break;
857     case PROP_MODE:
858       g_value_set_enum (value, self->mode);
859       break;
860     case PROP_WINDOW:
861       g_value_set_enum (value, self->window);
862       break;
863     default:
864       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
865       break;
866   }
867 }