gst/filter/: Don't implement get_unit_size() ourselves, the GstAudioFilter base class...
[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-bpwsinc
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 ! bpwsinc 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 ! bpwsinc mode=band-reject lower-frequency=59 upper-frequency=61 length=10001 window=hamming ! audioconvert ! alsasink
59  * gst-launch audiotestsrc wave=white-noise ! audioconvert ! bpwsinc 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 "gstbpwsinc.h"
76
77 #define GST_CAT_DEFAULT gst_bpwsinc_debug
78 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
79
80 static const GstElementDetails bpwsinc_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_BPWSINC_MODE (gst_bpwsinc_mode_get_type ())
113 static GType
114 gst_bpwsinc_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 ("GstBPWSincMode", values);
128   }
129   return gtype;
130 }
131
132 enum
133 {
134   WINDOW_HAMMING = 0,
135   WINDOW_BLACKMAN
136 };
137
138 #define GST_TYPE_BPWSINC_WINDOW (gst_bpwsinc_window_get_type ())
139 static GType
140 gst_bpwsinc_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 ("GstBPWSincWindow", 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_bpwsinc_debug, "bpwsinc", 0, "Band-pass and Band-reject Windowed sinc filter plugin");
167
168 GST_BOILERPLATE_FULL (GstBPWSinc, gst_bpwsinc, GstAudioFilter,
169     GST_TYPE_AUDIO_FILTER, DEBUG_INIT);
170
171 static void bpwsinc_set_property (GObject * object, guint prop_id,
172     const GValue * value, GParamSpec * pspec);
173 static void bpwsinc_get_property (GObject * object, guint prop_id,
174     GValue * value, GParamSpec * pspec);
175
176 static GstFlowReturn bpwsinc_transform (GstBaseTransform * base,
177     GstBuffer * inbuf, GstBuffer * outbuf);
178 static gboolean bpwsinc_start (GstBaseTransform * base);
179 static gboolean bpwsinc_event (GstBaseTransform * base, GstEvent * event);
180
181 static gboolean bpwsinc_setup (GstAudioFilter * base,
182     GstRingBufferSpec * format);
183
184 static gboolean bpwsinc_query (GstPad * pad, GstQuery * query);
185 static const GstQueryType *bpwsinc_query_type (GstPad * pad);
186
187 /* Element class */
188
189 static void
190 gst_bpwsinc_dispose (GObject * object)
191 {
192   GstBPWSinc *self = GST_BPWSINC (object);
193
194   if (self->residue) {
195     g_free (self->residue);
196     self->residue = NULL;
197   }
198
199   if (self->kernel) {
200     g_free (self->kernel);
201     self->kernel = NULL;
202   }
203
204   G_OBJECT_CLASS (parent_class)->dispose (object);
205 }
206
207 static void
208 gst_bpwsinc_base_init (gpointer g_class)
209 {
210   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
211   GstCaps *caps;
212
213   gst_element_class_set_details (element_class, &bpwsinc_details);
214
215   caps = gst_caps_from_string (ALLOWED_CAPS);
216   gst_audio_filter_class_add_pad_templates (GST_AUDIO_FILTER_CLASS (g_class),
217       caps);
218   gst_caps_unref (caps);
219 }
220
221 static void
222 gst_bpwsinc_class_init (GstBPWSincClass * klass)
223 {
224   GObjectClass *gobject_class;
225   GstBaseTransformClass *trans_class;
226   GstAudioFilterClass *filter_class;
227
228   gobject_class = (GObjectClass *) klass;
229   trans_class = (GstBaseTransformClass *) klass;
230   filter_class = (GstAudioFilterClass *) klass;
231
232   gobject_class->set_property = bpwsinc_set_property;
233   gobject_class->get_property = bpwsinc_get_property;
234   gobject_class->dispose = gst_bpwsinc_dispose;
235
236   /* FIXME: Don't use the complete possible range but restrict the upper boundary
237    * so automatically generated UIs can use a slider */
238   g_object_class_install_property (gobject_class, PROP_LOWER_FREQUENCY,
239       g_param_spec_float ("lower-frequency", "Lower Frequency",
240           "Cut-off lower frequency (Hz)", 0.0, 100000.0, 0, G_PARAM_READWRITE));
241   g_object_class_install_property (gobject_class, PROP_UPPER_FREQUENCY,
242       g_param_spec_float ("upper-frequency", "Upper Frequency",
243           "Cut-off upper frequency (Hz)", 0.0, 100000.0, 0, G_PARAM_READWRITE));
244   g_object_class_install_property (gobject_class, PROP_LENGTH,
245       g_param_spec_int ("length", "Length",
246           "Filter kernel length, will be rounded to the next odd number",
247           3, 50000, 101, G_PARAM_READWRITE));
248
249   g_object_class_install_property (gobject_class, PROP_MODE,
250       g_param_spec_enum ("mode", "Mode",
251           "Band pass or band reject mode", GST_TYPE_BPWSINC_MODE,
252           MODE_BAND_PASS, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
253
254   g_object_class_install_property (gobject_class, PROP_WINDOW,
255       g_param_spec_enum ("window", "Window",
256           "Window function to use", GST_TYPE_BPWSINC_WINDOW,
257           WINDOW_HAMMING, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
258
259   trans_class->transform = GST_DEBUG_FUNCPTR (bpwsinc_transform);
260   trans_class->start = GST_DEBUG_FUNCPTR (bpwsinc_start);
261   trans_class->event = GST_DEBUG_FUNCPTR (bpwsinc_event);
262   filter_class->setup = GST_DEBUG_FUNCPTR (bpwsinc_setup);
263 }
264
265 static void
266 gst_bpwsinc_init (GstBPWSinc * self, GstBPWSincClass * g_class)
267 {
268   self->kernel_length = 101;
269   self->latency = 50;
270   self->lower_frequency = 0.0;
271   self->upper_frequency = 0.0;
272   self->mode = MODE_BAND_PASS;
273   self->window = WINDOW_HAMMING;
274   self->kernel = NULL;
275   self->have_kernel = FALSE;
276   self->residue = NULL;
277
278   self->residue_length = 0;
279   self->next_ts = GST_CLOCK_TIME_NONE;
280   self->next_off = GST_BUFFER_OFFSET_NONE;
281
282   gst_pad_set_query_function (GST_BASE_TRANSFORM (self)->srcpad, bpwsinc_query);
283   gst_pad_set_query_type_function (GST_BASE_TRANSFORM (self)->srcpad,
284       bpwsinc_query_type);
285 }
286
287 #define DEFINE_PROCESS_FUNC(width,ctype) \
288 static void \
289 process_##width (GstBPWSinc * self, g##ctype * src, g##ctype * dst, guint input_samples) \
290 { \
291   gint kernel_length = self->kernel_length; \
292   gint i, j, k, l; \
293   gint channels = GST_AUDIO_FILTER (self)->format.channels; \
294   gint res_start; \
295   \
296   /* convolution */ \
297   for (i = 0; i < input_samples; i++) { \
298     dst[i] = 0.0; \
299     k = i % channels; \
300     l = i / channels; \
301     for (j = 0; j < kernel_length; j++) \
302       if (l < j) \
303         dst[i] += \
304             self->residue[(kernel_length + l - j) * channels + \
305             k] * self->kernel[j]; \
306       else \
307         dst[i] += src[(l - j) * channels + k] * self->kernel[j]; \
308   } \
309   \
310   /* copy the tail of the current input buffer to the residue, while \
311    * keeping parts of the residue if the input buffer is smaller than \
312    * the kernel length */ \
313   if (input_samples < kernel_length * channels) \
314     res_start = kernel_length * channels - input_samples; \
315   else \
316     res_start = 0; \
317   \
318   for (i = 0; i < res_start; i++) \
319     self->residue[i] = self->residue[i + input_samples]; \
320   for (i = res_start; i < kernel_length * channels; i++) \
321     self->residue[i] = src[input_samples - kernel_length * channels + i]; \
322   \
323   self->residue_length += kernel_length * channels - res_start; \
324   if (self->residue_length > kernel_length * channels) \
325     self->residue_length = kernel_length * channels; \
326 }
327
328 DEFINE_PROCESS_FUNC (32, float);
329 DEFINE_PROCESS_FUNC (64, double);
330
331 #undef DEFINE_PROCESS_FUNC
332
333 static void
334 bpwsinc_build_kernel (GstBPWSinc * self)
335 {
336   gint i = 0;
337   gdouble sum = 0.0;
338   gint len = 0;
339   gdouble *kernel_lp, *kernel_hp;
340   gdouble w;
341
342   len = self->kernel_length;
343
344   if (GST_AUDIO_FILTER (self)->format.rate == 0) {
345     GST_DEBUG ("rate not set yet");
346     return;
347   }
348
349   if (GST_AUDIO_FILTER (self)->format.channels == 0) {
350     GST_DEBUG ("channels not set yet");
351     return;
352   }
353
354   /* Clamp frequencies */
355   self->lower_frequency =
356       CLAMP (self->lower_frequency, 0.0,
357       GST_AUDIO_FILTER (self)->format.rate / 2);
358   self->upper_frequency =
359       CLAMP (self->upper_frequency, 0.0,
360       GST_AUDIO_FILTER (self)->format.rate / 2);
361   if (self->lower_frequency > self->upper_frequency) {
362     gint tmp = self->lower_frequency;
363
364     self->lower_frequency = self->upper_frequency;
365     self->upper_frequency = tmp;
366   }
367
368   GST_DEBUG ("bpwsinc: initializing filter kernel of length %d "
369       "with lower frequency %.2lf Hz "
370       ", upper frequency %.2lf Hz for mode %s",
371       len, self->lower_frequency, self->upper_frequency,
372       (self->mode == MODE_BAND_PASS) ? "band-pass" : "band-reject");
373
374   /* fill the lp kernel */
375   w = 2 * M_PI * (self->lower_frequency / GST_AUDIO_FILTER (self)->format.rate);
376   kernel_lp = g_new (gdouble, len);
377   for (i = 0; i < len; ++i) {
378     if (i == len / 2)
379       kernel_lp[i] = w;
380     else
381       kernel_lp[i] = sin (w * (i - len / 2))
382           / (i - len / 2);
383     /* Windowing */
384     if (self->window == WINDOW_HAMMING)
385       kernel_lp[i] *= (0.54 - 0.46 * cos (2 * M_PI * i / len));
386     else
387       kernel_lp[i] *=
388           (0.42 - 0.5 * cos (2 * M_PI * i / len) +
389           0.08 * cos (4 * M_PI * i / len));
390   }
391
392   /* normalize for unity gain at DC */
393   sum = 0.0;
394   for (i = 0; i < len; ++i)
395     sum += kernel_lp[i];
396   for (i = 0; i < len; ++i)
397     kernel_lp[i] /= sum;
398
399   /* fill the hp kernel */
400   w = 2 * M_PI * (self->upper_frequency / GST_AUDIO_FILTER (self)->format.rate);
401   kernel_hp = g_new (gdouble, len);
402   for (i = 0; i < len; ++i) {
403     if (i == len / 2)
404       kernel_hp[i] = w;
405     else
406       kernel_hp[i] = sin (w * (i - len / 2))
407           / (i - len / 2);
408     /* Windowing */
409     if (self->window == WINDOW_HAMMING)
410       kernel_hp[i] *= (0.54 - 0.46 * cos (2 * M_PI * i / len));
411     else
412       kernel_hp[i] *=
413           (0.42 - 0.5 * cos (2 * M_PI * i / len) +
414           0.08 * cos (4 * M_PI * i / len));
415   }
416
417   /* normalize for unity gain at DC */
418   sum = 0.0;
419   for (i = 0; i < len; ++i)
420     sum += kernel_hp[i];
421   for (i = 0; i < len; ++i)
422     kernel_hp[i] /= sum;
423
424   /* do spectral inversion to go from lowpass to highpass */
425   for (i = 0; i < len; ++i)
426     kernel_hp[i] = -kernel_hp[i];
427   kernel_hp[len / 2] += 1;
428
429   /* combine the two kernels */
430   if (self->kernel)
431     g_free (self->kernel);
432   self->kernel = g_new (gdouble, len);
433
434   for (i = 0; i < len; ++i)
435     self->kernel[i] = kernel_lp[i] + kernel_hp[i];
436
437   /* free the helper kernels */
438   g_free (kernel_lp);
439   g_free (kernel_hp);
440
441   /* do spectral inversion to go from bandreject to bandpass
442    * if specified */
443   if (self->mode == MODE_BAND_PASS) {
444     for (i = 0; i < len; ++i)
445       self->kernel[i] = -self->kernel[i];
446     self->kernel[len / 2] += 1;
447   }
448
449   /* set up the residue memory space */
450   if (!self->residue) {
451     self->residue =
452         g_new0 (gdouble, len * GST_AUDIO_FILTER (self)->format.channels);
453     self->residue_length = 0;
454   }
455
456   self->have_kernel = TRUE;
457 }
458
459 static void
460 bpwsinc_push_residue (GstBPWSinc * self)
461 {
462   GstBuffer *outbuf;
463   GstFlowReturn res;
464   gint rate = GST_AUDIO_FILTER (self)->format.rate;
465   gint channels = GST_AUDIO_FILTER (self)->format.channels;
466   gint outsize, outsamples;
467   gint diffsize, diffsamples;
468   guint8 *in, *out;
469
470   /* Calculate the number of samples and their memory size that
471    * should be pushed from the residue */
472   outsamples = MIN (self->latency, self->residue_length / channels);
473   outsize = outsamples * channels * (GST_AUDIO_FILTER (self)->format.width / 8);
474   if (outsize == 0)
475     return;
476
477   /* Process the difference between latency and residue_length samples
478    * to start at the actual data instead of starting at the zeros before
479    * when we only got one buffer smaller than latency */
480   diffsamples = self->latency - self->residue_length / channels;
481   diffsize =
482       diffsamples * channels * (GST_AUDIO_FILTER (self)->format.width / 8);
483   if (diffsize > 0) {
484     in = g_new0 (guint8, diffsize);
485     out = g_new0 (guint8, diffsize);
486     self->process (self, in, out, diffsamples * channels);
487     g_free (in);
488     g_free (out);
489   }
490
491   res = gst_pad_alloc_buffer (GST_BASE_TRANSFORM (self)->srcpad,
492       GST_BUFFER_OFFSET_NONE, outsize,
493       GST_PAD_CAPS (GST_BASE_TRANSFORM (self)->srcpad), &outbuf);
494
495   if (G_UNLIKELY (res != GST_FLOW_OK)) {
496     GST_WARNING_OBJECT (self, "failed allocating buffer of %d bytes", outsize);
497     return;
498   }
499
500   /* Convolve the residue with zeros to get the actual remaining data */
501   in = g_new0 (guint8, outsize);
502   self->process (self, in, GST_BUFFER_DATA (outbuf), outsamples * channels);
503   g_free (in);
504
505   /* Set timestamp, offset, etc from the values we
506    * saved when processing the regular buffers */
507   if (GST_CLOCK_TIME_IS_VALID (self->next_ts))
508     GST_BUFFER_TIMESTAMP (outbuf) = self->next_ts;
509   else
510     GST_BUFFER_TIMESTAMP (outbuf) = 0;
511   GST_BUFFER_DURATION (outbuf) =
512       gst_util_uint64_scale (outsamples, GST_SECOND, rate);
513   self->next_ts += gst_util_uint64_scale (outsamples, GST_SECOND, rate);
514
515   if (self->next_off != GST_BUFFER_OFFSET_NONE) {
516     GST_BUFFER_OFFSET (outbuf) = self->next_off;
517     GST_BUFFER_OFFSET_END (outbuf) = self->next_off + outsamples;
518   }
519
520   GST_DEBUG_OBJECT (self, "Pushing residue buffer of size %d with timestamp: %"
521       GST_TIME_FORMAT ", duration: %" GST_TIME_FORMAT ", offset: %lld,"
522       " offset_end: %lld, nsamples: %d", GST_BUFFER_SIZE (outbuf),
523       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
524       GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf),
525       GST_BUFFER_OFFSET_END (outbuf), outsamples);
526
527   res = gst_pad_push (GST_BASE_TRANSFORM (self)->srcpad, outbuf);
528
529   if (G_UNLIKELY (res != GST_FLOW_OK)) {
530     GST_WARNING_OBJECT (self, "failed to push residue");
531   }
532
533 }
534
535 /* GstAudioFilter vmethod implementations */
536
537 /* get notified of caps and plug in the correct process function */
538 static gboolean
539 bpwsinc_setup (GstAudioFilter * base, GstRingBufferSpec * format)
540 {
541   GstBPWSinc *self = GST_BPWSINC (base);
542
543   gboolean ret = TRUE;
544
545   if (format->width == 32)
546     self->process = (GstBPWSincProcessFunc) process_32;
547   else if (format->width == 64)
548     self->process = (GstBPWSincProcessFunc) process_64;
549   else
550     ret = FALSE;
551
552   self->have_kernel = FALSE;
553
554   return TRUE;
555 }
556
557 /* GstBaseTransform vmethod implementations */
558
559 static GstFlowReturn
560 bpwsinc_transform (GstBaseTransform * base, GstBuffer * inbuf,
561     GstBuffer * outbuf)
562 {
563   GstBPWSinc *self = GST_BPWSINC (base);
564   GstClockTime timestamp;
565   gint channels = GST_AUDIO_FILTER (self)->format.channels;
566   gint rate = GST_AUDIO_FILTER (self)->format.rate;
567   gint input_samples =
568       GST_BUFFER_SIZE (outbuf) / (GST_AUDIO_FILTER (self)->format.width / 8);
569   gint output_samples = input_samples;
570   gint diff;
571
572   /* FIXME: subdivide GST_BUFFER_SIZE into small chunks for smooth fades */
573   timestamp = GST_BUFFER_TIMESTAMP (outbuf);
574   if (GST_CLOCK_TIME_IS_VALID (timestamp))
575     gst_object_sync_values (G_OBJECT (self), timestamp);
576
577   if (!self->have_kernel)
578     bpwsinc_build_kernel (self);
579
580   /* Reset the residue if already existing on discont buffers */
581   if (GST_BUFFER_IS_DISCONT (inbuf)) {
582     if (channels && self->residue)
583       memset (self->residue, 0, channels *
584           self->kernel_length * sizeof (gdouble));
585     self->residue_length = 0;
586     self->next_ts = GST_CLOCK_TIME_NONE;
587     self->next_off = GST_BUFFER_OFFSET_NONE;
588   }
589
590   /* Calculate the number of samples we can push out now without outputting
591    * kernel_length/2 zeros in the beginning */
592   diff = (self->kernel_length / 2) * channels - self->residue_length;
593   if (diff > 0)
594     output_samples -= diff;
595
596   self->process (self, GST_BUFFER_DATA (inbuf), GST_BUFFER_DATA (outbuf),
597       input_samples);
598
599   if (output_samples <= 0) {
600     /* Drop buffer and save original timestamp/offset for later use */
601     if (!GST_CLOCK_TIME_IS_VALID (self->next_ts)
602         && GST_BUFFER_TIMESTAMP_IS_VALID (outbuf))
603       self->next_ts = GST_BUFFER_TIMESTAMP (outbuf);
604     if (self->next_off == GST_BUFFER_OFFSET_NONE
605         && GST_BUFFER_OFFSET_IS_VALID (outbuf))
606       self->next_off = GST_BUFFER_OFFSET (outbuf);
607     return GST_BASE_TRANSFORM_FLOW_DROPPED;
608   } else if (output_samples < input_samples) {
609     /* First (probably partial) buffer after starting from
610      * a clean residue. Use stored timestamp/offset here */
611     if (GST_CLOCK_TIME_IS_VALID (self->next_ts))
612       GST_BUFFER_TIMESTAMP (outbuf) = self->next_ts;
613
614     if (self->next_off != GST_BUFFER_OFFSET_NONE) {
615       GST_BUFFER_OFFSET (outbuf) = self->next_off;
616       if (GST_BUFFER_OFFSET_END_IS_VALID (outbuf))
617         GST_BUFFER_OFFSET_END (outbuf) =
618             self->next_off + output_samples / channels;
619     } else {
620       /* We dropped no buffer, offset is valid, offset_end must be adjusted by diff */
621       if (GST_BUFFER_OFFSET_END_IS_VALID (outbuf))
622         GST_BUFFER_OFFSET_END (outbuf) -= diff / channels;
623     }
624
625     if (GST_BUFFER_DURATION_IS_VALID (outbuf))
626       GST_BUFFER_DURATION (outbuf) -=
627           gst_util_uint64_scale (diff, GST_SECOND, channels * rate);
628
629     GST_BUFFER_DATA (outbuf) +=
630         diff * (GST_AUDIO_FILTER (self)->format.width / 8);
631     GST_BUFFER_SIZE (outbuf) -=
632         diff * (GST_AUDIO_FILTER (self)->format.width / 8);
633   } else {
634     GstClockTime ts_latency =
635         gst_util_uint64_scale (self->latency, GST_SECOND, rate);
636
637     /* Normal buffer, adjust timestamp/offset/etc by latency */
638     if (GST_BUFFER_TIMESTAMP (outbuf) < ts_latency) {
639       GST_WARNING_OBJECT (self, "GST_BUFFER_TIMESTAMP (outbuf) < latency");
640       GST_BUFFER_TIMESTAMP (outbuf) = 0;
641     } else {
642       GST_BUFFER_TIMESTAMP (outbuf) -= ts_latency;
643     }
644
645     if (GST_BUFFER_OFFSET_IS_VALID (outbuf)) {
646       if (GST_BUFFER_OFFSET (outbuf) > self->latency) {
647         GST_BUFFER_OFFSET (outbuf) -= self->latency;
648       } else {
649         GST_WARNING_OBJECT (self, "GST_BUFFER_OFFSET (outbuf) < latency");
650         GST_BUFFER_OFFSET (outbuf) = 0;
651       }
652     }
653
654     if (GST_BUFFER_OFFSET_END_IS_VALID (outbuf)) {
655       if (GST_BUFFER_OFFSET_END (outbuf) > self->latency) {
656         GST_BUFFER_OFFSET_END (outbuf) -= self->latency;
657       } else {
658         GST_WARNING_OBJECT (self, "GST_BUFFER_OFFSET_END (outbuf) < latency");
659         GST_BUFFER_OFFSET_END (outbuf) = 0;
660       }
661     }
662   }
663
664   GST_DEBUG_OBJECT (self, "Pushing buffer of size %d with timestamp: %"
665       GST_TIME_FORMAT ", duration: %" GST_TIME_FORMAT ", offset: %lld,"
666       " offset_end: %lld, nsamples: %d", GST_BUFFER_SIZE (outbuf),
667       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
668       GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)), GST_BUFFER_OFFSET (outbuf),
669       GST_BUFFER_OFFSET_END (outbuf), output_samples / channels);
670
671   self->next_ts = GST_BUFFER_TIMESTAMP (outbuf) + GST_BUFFER_DURATION (outbuf);
672   self->next_off = GST_BUFFER_OFFSET_END (outbuf);
673
674   return GST_FLOW_OK;
675 }
676
677 static gboolean
678 bpwsinc_start (GstBaseTransform * base)
679 {
680   GstBPWSinc *self = GST_BPWSINC (base);
681   gint channels = GST_AUDIO_FILTER (self)->format.channels;
682
683   /* Reset the residue if already existing */
684   if (channels && self->residue)
685     memset (self->residue, 0, channels *
686         self->kernel_length * sizeof (gdouble));
687
688   self->residue_length = 0;
689   self->next_ts = GST_CLOCK_TIME_NONE;
690   self->next_off = GST_BUFFER_OFFSET_NONE;
691
692   return TRUE;
693 }
694
695 static gboolean
696 bpwsinc_query (GstPad * pad, GstQuery * query)
697 {
698   GstBPWSinc *self = GST_BPWSINC (gst_pad_get_parent (pad));
699   gboolean res = TRUE;
700
701   switch (GST_QUERY_TYPE (query)) {
702     case GST_QUERY_LATENCY:
703     {
704       GstClockTime min, max;
705       gboolean live;
706       guint64 latency;
707       GstPad *peer;
708       gint rate = GST_AUDIO_FILTER (self)->format.rate;
709
710       if ((peer = gst_pad_get_peer (GST_BASE_TRANSFORM (self)->sinkpad))) {
711         if ((res = gst_pad_query (peer, query))) {
712           gst_query_parse_latency (query, &live, &min, &max);
713
714           GST_DEBUG_OBJECT (self, "Peer latency: min %"
715               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
716               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
717
718           /* add our own latency */
719           latency =
720               (rate != 0) ? gst_util_uint64_scale (self->latency, GST_SECOND,
721               rate) : 0;
722
723           GST_DEBUG_OBJECT (self, "Our latency: %"
724               GST_TIME_FORMAT, GST_TIME_ARGS (latency));
725
726           min += latency;
727           if (max != GST_CLOCK_TIME_NONE)
728             max += latency;
729
730           GST_DEBUG_OBJECT (self, "Calculated total latency : min %"
731               GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
732               GST_TIME_ARGS (min), GST_TIME_ARGS (max));
733
734           gst_query_set_latency (query, live, min, max);
735         }
736         gst_object_unref (peer);
737       }
738       break;
739     }
740     default:
741       res = gst_pad_query_default (pad, query);
742       break;
743   }
744   gst_object_unref (self);
745   return res;
746 }
747
748 static const GstQueryType *
749 bpwsinc_query_type (GstPad * pad)
750 {
751   static const GstQueryType types[] = {
752     GST_QUERY_LATENCY,
753     0
754   };
755
756   return types;
757 }
758
759 static gboolean
760 bpwsinc_event (GstBaseTransform * base, GstEvent * event)
761 {
762   GstBPWSinc *self = GST_BPWSINC (base);
763
764   switch (GST_EVENT_TYPE (event)) {
765     case GST_EVENT_EOS:
766       bpwsinc_push_residue (self);
767       break;
768     default:
769       break;
770   }
771
772   return GST_BASE_TRANSFORM_CLASS (parent_class)->event (base, event);
773 }
774
775 static void
776 bpwsinc_set_property (GObject * object, guint prop_id, const GValue * value,
777     GParamSpec * pspec)
778 {
779   GstBPWSinc *self = GST_BPWSINC (object);
780
781   g_return_if_fail (GST_IS_BPWSINC (self));
782
783   switch (prop_id) {
784     case PROP_LENGTH:{
785       gint val;
786
787       GST_BASE_TRANSFORM_LOCK (self);
788       val = g_value_get_int (value);
789       if (val % 2 == 0)
790         val++;
791
792       if (val != self->kernel_length) {
793         if (self->residue) {
794           bpwsinc_push_residue (self);
795           g_free (self->residue);
796           self->residue = NULL;
797         }
798         self->kernel_length = val;
799         self->latency = val / 2;
800         bpwsinc_build_kernel (self);
801         gst_element_post_message (GST_ELEMENT (self),
802             gst_message_new_latency (GST_OBJECT (self)));
803       }
804       GST_BASE_TRANSFORM_UNLOCK (self);
805       break;
806     }
807     case PROP_LOWER_FREQUENCY:
808       GST_BASE_TRANSFORM_LOCK (self);
809       self->lower_frequency = g_value_get_float (value);
810       bpwsinc_build_kernel (self);
811       GST_BASE_TRANSFORM_UNLOCK (self);
812       break;
813     case PROP_UPPER_FREQUENCY:
814       GST_BASE_TRANSFORM_LOCK (self);
815       self->upper_frequency = g_value_get_float (value);
816       bpwsinc_build_kernel (self);
817       GST_BASE_TRANSFORM_UNLOCK (self);
818       break;
819     case PROP_MODE:
820       GST_BASE_TRANSFORM_LOCK (self);
821       self->mode = g_value_get_enum (value);
822       bpwsinc_build_kernel (self);
823       GST_BASE_TRANSFORM_UNLOCK (self);
824       break;
825     case PROP_WINDOW:
826       GST_BASE_TRANSFORM_LOCK (self);
827       self->window = g_value_get_enum (value);
828       bpwsinc_build_kernel (self);
829       GST_BASE_TRANSFORM_UNLOCK (self);
830       break;
831     default:
832       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
833       break;
834   }
835 }
836
837 static void
838 bpwsinc_get_property (GObject * object, guint prop_id, GValue * value,
839     GParamSpec * pspec)
840 {
841   GstBPWSinc *self = GST_BPWSINC (object);
842
843   switch (prop_id) {
844     case PROP_LENGTH:
845       g_value_set_int (value, self->kernel_length);
846       break;
847     case PROP_LOWER_FREQUENCY:
848       g_value_set_float (value, self->lower_frequency);
849       break;
850     case PROP_UPPER_FREQUENCY:
851       g_value_set_float (value, self->upper_frequency);
852       break;
853     case PROP_MODE:
854       g_value_set_enum (value, self->mode);
855       break;
856     case PROP_WINDOW:
857       g_value_set_enum (value, self->window);
858       break;
859     default:
860       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
861       break;
862   }
863 }