Merge remote-tracking branch 'origin/master' into 0.11
[platform/upstream/gst-plugins-good.git] / gst / wavparse / gstwavparse.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: t; c-basic-offset: 2 -*- */
2 /* GStreamer
3  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
4  * Copyright (C) <2006> Nokia Corporation, Stefan Kost <stefan.kost@nokia.com>.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:element-wavparse
24  *
25  * Parse a .wav file into raw or compressed audio.
26  *
27  * Wavparse supports both push and pull mode operations, making it possible to
28  * stream from a network source.
29  *
30  * <refsect2>
31  * <title>Example launch line</title>
32  * |[
33  * gst-launch filesrc location=sine.wav ! wavparse ! audioconvert ! alsasink
34  * ]| Read a wav file and output to the soundcard using the ALSA element. The
35  * wav file is assumed to contain raw uncompressed samples.
36  * |[
37  * gst-launch gnomevfssrc location=http://www.example.org/sine.wav ! queue ! wavparse ! audioconvert ! alsasink
38  * ]| Stream data from a network url.
39  * </refsect2>
40  *
41  * Last reviewed on 2007-02-14 (0.10.6)
42  */
43
44 /*
45  * TODO:
46  * http://replaygain.hydrogenaudio.org/file_format_wav.html
47  */
48
49 #ifdef HAVE_CONFIG_H
50 #include "config.h"
51 #endif
52 #include <string.h>
53 #include <math.h>
54
55 #include "gstwavparse.h"
56 #include "gst/riff/riff-ids.h"
57 #include "gst/riff/riff-media.h"
58 #include <gst/base/gsttypefindhelper.h>
59 #include <gst/gst-i18n-plugin.h>
60
61 GST_DEBUG_CATEGORY_STATIC (wavparse_debug);
62 #define GST_CAT_DEFAULT (wavparse_debug)
63
64 static void gst_wavparse_dispose (GObject * object);
65
66 static gboolean gst_wavparse_sink_activate (GstPad * sinkpad,
67     GstObject * parent);
68 static gboolean gst_wavparse_sink_activate_mode (GstPad * sinkpad,
69     GstObject * parent, GstPadMode mode, gboolean active);
70 static gboolean gst_wavparse_send_event (GstElement * element,
71     GstEvent * event);
72 static GstStateChangeReturn gst_wavparse_change_state (GstElement * element,
73     GstStateChange transition);
74
75 static gboolean gst_wavparse_pad_query (GstPad * pad, GstObject * parent,
76     GstQuery * query);
77 static gboolean gst_wavparse_pad_convert (GstPad * pad, GstFormat src_format,
78     gint64 src_value, GstFormat * dest_format, gint64 * dest_value);
79
80 static GstFlowReturn gst_wavparse_chain (GstPad * pad, GstObject * parent,
81     GstBuffer * buf);
82 static gboolean gst_wavparse_sink_event (GstPad * pad, GstObject * parent,
83     GstEvent * event);
84 static void gst_wavparse_loop (GstPad * pad);
85 static gboolean gst_wavparse_srcpad_event (GstPad * pad, GstObject * parent,
86     GstEvent * event);
87
88 static GstStaticPadTemplate sink_template_factory =
89 GST_STATIC_PAD_TEMPLATE ("sink",
90     GST_PAD_SINK,
91     GST_PAD_ALWAYS,
92     GST_STATIC_CAPS ("audio/x-wav")
93     );
94
95 #define DEBUG_INIT \
96   GST_DEBUG_CATEGORY_INIT (wavparse_debug, "wavparse", 0, "WAV parser");
97
98 #define gst_wavparse_parent_class parent_class
99 G_DEFINE_TYPE_WITH_CODE (GstWavParse, gst_wavparse, GST_TYPE_ELEMENT,
100     DEBUG_INIT);
101
102 static void
103 gst_wavparse_class_init (GstWavParseClass * klass)
104 {
105   GstElementClass *gstelement_class;
106   GObjectClass *object_class;
107   GstPadTemplate *src_template;
108
109   gstelement_class = (GstElementClass *) klass;
110   object_class = (GObjectClass *) klass;
111
112   parent_class = g_type_class_peek_parent (klass);
113
114   object_class->dispose = gst_wavparse_dispose;
115
116   gstelement_class->change_state = gst_wavparse_change_state;
117   gstelement_class->send_event = gst_wavparse_send_event;
118
119   /* register pads */
120   gst_element_class_add_pad_template (gstelement_class,
121       gst_static_pad_template_get (&sink_template_factory));
122
123   src_template = gst_pad_template_new ("src", GST_PAD_SRC,
124       GST_PAD_ALWAYS, gst_riff_create_audio_template_caps ());
125   gst_element_class_add_pad_template (gstelement_class, src_template);
126
127   gst_element_class_set_details_simple (gstelement_class, "WAV audio demuxer",
128       "Codec/Demuxer/Audio",
129       "Parse a .wav file into raw audio",
130       "Erik Walthinsen <omega@cse.ogi.edu>");
131 }
132
133 static void
134 gst_wavparse_reset (GstWavParse * wav)
135 {
136   wav->state = GST_WAVPARSE_START;
137
138   /* These will all be set correctly in the fmt chunk */
139   wav->depth = 0;
140   wav->rate = 0;
141   wav->width = 0;
142   wav->channels = 0;
143   wav->blockalign = 0;
144   wav->bps = 0;
145   wav->fact = 0;
146   wav->offset = 0;
147   wav->end_offset = 0;
148   wav->dataleft = 0;
149   wav->datasize = 0;
150   wav->datastart = 0;
151   wav->duration = 0;
152   wav->got_fmt = FALSE;
153   wav->first = TRUE;
154
155   if (wav->seek_event)
156     gst_event_unref (wav->seek_event);
157   wav->seek_event = NULL;
158   if (wav->adapter) {
159     gst_adapter_clear (wav->adapter);
160     g_object_unref (wav->adapter);
161     wav->adapter = NULL;
162   }
163   if (wav->tags)
164     gst_tag_list_free (wav->tags);
165   wav->tags = NULL;
166   if (wav->caps)
167     gst_caps_unref (wav->caps);
168   wav->caps = NULL;
169   if (wav->start_segment)
170     gst_event_unref (wav->start_segment);
171   wav->start_segment = NULL;
172 }
173
174 static void
175 gst_wavparse_dispose (GObject * object)
176 {
177   GstWavParse *wav = GST_WAVPARSE (object);
178
179   GST_DEBUG_OBJECT (wav, "WAV: Dispose");
180   gst_wavparse_reset (wav);
181
182   G_OBJECT_CLASS (parent_class)->dispose (object);
183 }
184
185 static void
186 gst_wavparse_init (GstWavParse * wavparse)
187 {
188   gst_wavparse_reset (wavparse);
189
190   /* sink */
191   wavparse->sinkpad =
192       gst_pad_new_from_static_template (&sink_template_factory, "sink");
193   gst_pad_set_activate_function (wavparse->sinkpad,
194       GST_DEBUG_FUNCPTR (gst_wavparse_sink_activate));
195   gst_pad_set_activatemode_function (wavparse->sinkpad,
196       GST_DEBUG_FUNCPTR (gst_wavparse_sink_activate_mode));
197   gst_pad_set_chain_function (wavparse->sinkpad,
198       GST_DEBUG_FUNCPTR (gst_wavparse_chain));
199   gst_pad_set_event_function (wavparse->sinkpad,
200       GST_DEBUG_FUNCPTR (gst_wavparse_sink_event));
201   gst_element_add_pad (GST_ELEMENT_CAST (wavparse), wavparse->sinkpad);
202
203   /* src */
204   wavparse->srcpad =
205       gst_pad_new_from_template (gst_element_class_get_pad_template
206       (GST_ELEMENT_GET_CLASS (wavparse), "src"), "src");
207   gst_pad_use_fixed_caps (wavparse->srcpad);
208   gst_pad_set_query_function (wavparse->srcpad,
209       GST_DEBUG_FUNCPTR (gst_wavparse_pad_query));
210   gst_pad_set_event_function (wavparse->srcpad,
211       GST_DEBUG_FUNCPTR (gst_wavparse_srcpad_event));
212   gst_element_add_pad (GST_ELEMENT_CAST (wavparse), wavparse->srcpad);
213 }
214
215 static void
216 gst_wavparse_destroy_sourcepad (GstWavParse * wavparse)
217 {
218   if (wavparse->srcpad) {
219     gst_element_remove_pad (GST_ELEMENT_CAST (wavparse), wavparse->srcpad);
220     wavparse->srcpad = NULL;
221   }
222 }
223
224 /* Compute (value * nom) % denom, avoiding overflow.  This can be used
225  * to perform ceiling or rounding division together with
226  * gst_util_uint64_scale[_int]. */
227 #define uint64_scale_modulo(val, nom, denom) \
228   ((val % denom) * (nom % denom) % denom)
229
230 /* Like gst_util_uint64_scale, but performs ceiling division. */
231 static guint64
232 uint64_ceiling_scale_int (guint64 val, gint num, gint denom)
233 {
234   guint64 result = gst_util_uint64_scale_int (val, num, denom);
235
236   if (uint64_scale_modulo (val, num, denom) == 0)
237     return result;
238   else
239     return result + 1;
240 }
241
242 /* Like gst_util_uint64_scale, but performs ceiling division. */
243 static guint64
244 uint64_ceiling_scale (guint64 val, guint64 num, guint64 denom)
245 {
246   guint64 result = gst_util_uint64_scale (val, num, denom);
247
248   if (uint64_scale_modulo (val, num, denom) == 0)
249     return result;
250   else
251     return result + 1;
252 }
253
254
255 /* FIXME: why is that not in use? */
256 #if 0
257 static void
258 gst_wavparse_parse_adtl (GstWavParse * wavparse, int len)
259 {
260   guint32 got_bytes;
261   GstByteStream *bs = wavparse->bs;
262   gst_riff_chunk *temp_chunk, chunk;
263   guint8 *tempdata;
264   struct _gst_riff_labl labl, *temp_labl;
265   struct _gst_riff_ltxt ltxt, *temp_ltxt;
266   struct _gst_riff_note note, *temp_note;
267   char *label_name;
268   GstProps *props;
269   GstPropsEntry *entry;
270   GstCaps *new_caps;
271   GList *caps = NULL;
272
273   props = wavparse->metadata->properties;
274
275   while (len > 0) {
276     got_bytes =
277         gst_bytestream_peek_bytes (bs, &tempdata, sizeof (gst_riff_chunk));
278     if (got_bytes != sizeof (gst_riff_chunk)) {
279       return;
280     }
281     temp_chunk = (gst_riff_chunk *) tempdata;
282
283     chunk.id = GUINT32_FROM_LE (temp_chunk->id);
284     chunk.size = GUINT32_FROM_LE (temp_chunk->size);
285
286     if (chunk.size == 0) {
287       gst_bytestream_flush (bs, sizeof (gst_riff_chunk));
288       len -= sizeof (gst_riff_chunk);
289       continue;
290     }
291
292     switch (chunk.id) {
293       case GST_RIFF_adtl_labl:
294         got_bytes =
295             gst_bytestream_peek_bytes (bs, &tempdata,
296             sizeof (struct _gst_riff_labl));
297         if (got_bytes != sizeof (struct _gst_riff_labl)) {
298           return;
299         }
300
301         temp_labl = (struct _gst_riff_labl *) tempdata;
302         labl.id = GUINT32_FROM_LE (temp_labl->id);
303         labl.size = GUINT32_FROM_LE (temp_labl->size);
304         labl.identifier = GUINT32_FROM_LE (temp_labl->identifier);
305
306         gst_bytestream_flush (bs, sizeof (struct _gst_riff_labl));
307         len -= sizeof (struct _gst_riff_labl);
308
309         got_bytes = gst_bytestream_peek_bytes (bs, &tempdata, labl.size - 4);
310         if (got_bytes != labl.size - 4) {
311           return;
312         }
313
314         label_name = (char *) tempdata;
315
316         gst_bytestream_flush (bs, ((labl.size - 4) + 1) & ~1);
317         len -= (((labl.size - 4) + 1) & ~1);
318
319         new_caps = gst_caps_new ("label",
320             "application/x-gst-metadata",
321             gst_props_new ("identifier", G_TYPE_INT (labl.identifier),
322                 "name", G_TYPE_STRING (label_name), NULL));
323
324         if (gst_props_get (props, "labels", &caps, NULL)) {
325           caps = g_list_append (caps, new_caps);
326         } else {
327           caps = g_list_append (NULL, new_caps);
328
329           entry = gst_props_entry_new ("labels", GST_PROPS_GLIST (caps));
330           gst_props_add_entry (props, entry);
331         }
332
333         break;
334
335       case GST_RIFF_adtl_ltxt:
336         got_bytes =
337             gst_bytestream_peek_bytes (bs, &tempdata,
338             sizeof (struct _gst_riff_ltxt));
339         if (got_bytes != sizeof (struct _gst_riff_ltxt)) {
340           return;
341         }
342
343         temp_ltxt = (struct _gst_riff_ltxt *) tempdata;
344         ltxt.id = GUINT32_FROM_LE (temp_ltxt->id);
345         ltxt.size = GUINT32_FROM_LE (temp_ltxt->size);
346         ltxt.identifier = GUINT32_FROM_LE (temp_ltxt->identifier);
347         ltxt.length = GUINT32_FROM_LE (temp_ltxt->length);
348         ltxt.purpose = GUINT32_FROM_LE (temp_ltxt->purpose);
349         ltxt.country = GUINT16_FROM_LE (temp_ltxt->country);
350         ltxt.language = GUINT16_FROM_LE (temp_ltxt->language);
351         ltxt.dialect = GUINT16_FROM_LE (temp_ltxt->dialect);
352         ltxt.codepage = GUINT16_FROM_LE (temp_ltxt->codepage);
353
354         gst_bytestream_flush (bs, sizeof (struct _gst_riff_ltxt));
355         len -= sizeof (struct _gst_riff_ltxt);
356
357         if (ltxt.size - 20 > 0) {
358           got_bytes = gst_bytestream_peek_bytes (bs, &tempdata, ltxt.size - 20);
359           if (got_bytes != ltxt.size - 20) {
360             return;
361           }
362
363           gst_bytestream_flush (bs, ((ltxt.size - 20) + 1) & ~1);
364           len -= (((ltxt.size - 20) + 1) & ~1);
365
366           label_name = (char *) tempdata;
367         } else {
368           label_name = "";
369         }
370
371         new_caps = gst_caps_new ("ltxt",
372             "application/x-gst-metadata",
373             gst_props_new ("identifier", G_TYPE_INT (ltxt.identifier),
374                 "name", G_TYPE_STRING (label_name),
375                 "length", G_TYPE_INT (ltxt.length), NULL));
376
377         if (gst_props_get (props, "ltxts", &caps, NULL)) {
378           caps = g_list_append (caps, new_caps);
379         } else {
380           caps = g_list_append (NULL, new_caps);
381
382           entry = gst_props_entry_new ("ltxts", GST_PROPS_GLIST (caps));
383           gst_props_add_entry (props, entry);
384         }
385
386         break;
387
388       case GST_RIFF_adtl_note:
389         got_bytes =
390             gst_bytestream_peek_bytes (bs, &tempdata,
391             sizeof (struct _gst_riff_note));
392         if (got_bytes != sizeof (struct _gst_riff_note)) {
393           return;
394         }
395
396         temp_note = (struct _gst_riff_note *) tempdata;
397         note.id = GUINT32_FROM_LE (temp_note->id);
398         note.size = GUINT32_FROM_LE (temp_note->size);
399         note.identifier = GUINT32_FROM_LE (temp_note->identifier);
400
401         gst_bytestream_flush (bs, sizeof (struct _gst_riff_note));
402         len -= sizeof (struct _gst_riff_note);
403
404         got_bytes = gst_bytestream_peek_bytes (bs, &tempdata, note.size - 4);
405         if (got_bytes != note.size - 4) {
406           return;
407         }
408
409         gst_bytestream_flush (bs, ((note.size - 4) + 1) & ~1);
410         len -= (((note.size - 4) + 1) & ~1);
411
412         label_name = (char *) tempdata;
413
414         new_caps = gst_caps_new ("note",
415             "application/x-gst-metadata",
416             gst_props_new ("identifier", G_TYPE_INT (note.identifier),
417                 "name", G_TYPE_STRING (label_name), NULL));
418
419         if (gst_props_get (props, "notes", &caps, NULL)) {
420           caps = g_list_append (caps, new_caps);
421         } else {
422           caps = g_list_append (NULL, new_caps);
423
424           entry = gst_props_entry_new ("notes", GST_PROPS_GLIST (caps));
425           gst_props_add_entry (props, entry);
426         }
427
428         break;
429
430       default:
431         g_print ("Unknown chunk: %" GST_FOURCC_FORMAT "\n",
432             GST_FOURCC_ARGS (chunk.id));
433         return;
434     }
435   }
436
437   g_object_notify (G_OBJECT (wavparse), "metadata");
438 }
439
440 static void
441 gst_wavparse_parse_cues (GstWavParse * wavparse, int len)
442 {
443   guint32 got_bytes;
444   GstByteStream *bs = wavparse->bs;
445   struct _gst_riff_cue *temp_cue, cue;
446   struct _gst_riff_cuepoints *points;
447   guint8 *tempdata;
448   int i;
449   GList *cues = NULL;
450   GstPropsEntry *entry;
451
452   while (len > 0) {
453     int required;
454
455     got_bytes =
456         gst_bytestream_peek_bytes (bs, &tempdata,
457         sizeof (struct _gst_riff_cue));
458     temp_cue = (struct _gst_riff_cue *) tempdata;
459
460     /* fixup for our big endian friends */
461     cue.id = GUINT32_FROM_LE (temp_cue->id);
462     cue.size = GUINT32_FROM_LE (temp_cue->size);
463     cue.cuepoints = GUINT32_FROM_LE (temp_cue->cuepoints);
464
465     gst_bytestream_flush (bs, sizeof (struct _gst_riff_cue));
466     if (got_bytes != sizeof (struct _gst_riff_cue)) {
467       return;
468     }
469
470     len -= sizeof (struct _gst_riff_cue);
471
472     /* -4 because cue.size contains the cuepoints size
473        and we've already flushed that out of the system */
474     required = cue.size - 4;
475     got_bytes = gst_bytestream_peek_bytes (bs, &tempdata, required);
476     gst_bytestream_flush (bs, ((required) + 1) & ~1);
477     if (got_bytes != required) {
478       return;
479     }
480
481     len -= (((cue.size - 4) + 1) & ~1);
482
483     /* now we have an array of struct _gst_riff_cuepoints in tempdata */
484     points = (struct _gst_riff_cuepoints *) tempdata;
485
486     for (i = 0; i < cue.cuepoints; i++) {
487       GstCaps *caps;
488
489       caps = gst_caps_new ("cues",
490           "application/x-gst-metadata",
491           gst_props_new ("identifier", G_TYPE_INT (points[i].identifier),
492               "position", G_TYPE_INT (points[i].offset), NULL));
493       cues = g_list_append (cues, caps);
494     }
495
496     entry = gst_props_entry_new ("cues", GST_PROPS_GLIST (cues));
497     gst_props_add_entry (wavparse->metadata->properties, entry);
498   }
499
500   g_object_notify (G_OBJECT (wavparse), "metadata");
501 }
502
503 /* Read 'fmt ' header */
504 static gboolean
505 gst_wavparse_fmt (GstWavParse * wav)
506 {
507   gst_riff_strf_auds *header = NULL;
508   GstCaps *caps;
509
510   if (!gst_riff_read_strf_auds (wav, &header))
511     goto no_fmt;
512
513   wav->format = header->format;
514   wav->rate = header->rate;
515   wav->channels = header->channels;
516   if (wav->channels == 0)
517     goto no_channels;
518
519   wav->blockalign = header->blockalign;
520   wav->width = (header->blockalign * 8) / header->channels;
521   wav->depth = header->size;
522   wav->bps = header->av_bps;
523   if (wav->bps <= 0)
524     goto no_bps;
525
526   /* Note: gst_riff_create_audio_caps might need to fix values in
527    * the header header depending on the format, so call it first */
528   caps = gst_riff_create_audio_caps (header->format, NULL, header, NULL);
529   g_free (header);
530
531   if (caps == NULL)
532     goto no_caps;
533
534   gst_wavparse_create_sourcepad (wav);
535   gst_pad_use_fixed_caps (wav->srcpad);
536   gst_pad_set_active (wav->srcpad, TRUE);
537   gst_pad_set_caps (wav->srcpad, caps);
538   gst_caps_free (caps);
539   gst_element_add_pad (GST_ELEMENT_CAST (wav), wav->srcpad);
540   gst_element_no_more_pads (GST_ELEMENT_CAST (wav));
541
542   GST_DEBUG ("frequency %d, channels %d", wav->rate, wav->channels);
543
544   return TRUE;
545
546   /* ERRORS */
547 no_fmt:
548   {
549     GST_ELEMENT_ERROR (wav, STREAM, TYPE_NOT_FOUND, (NULL),
550         ("No FMT tag found"));
551     return FALSE;
552   }
553 no_channels:
554   {
555     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
556         ("Stream claims to contain zero channels - invalid data"));
557     g_free (header);
558     return FALSE;
559   }
560 no_bps:
561   {
562     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
563         ("Stream claims to bitrate of <= zero - invalid data"));
564     g_free (header);
565     return FALSE;
566   }
567 no_caps:
568   {
569     GST_ELEMENT_ERROR (wav, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
570     return FALSE;
571   }
572 }
573
574 static gboolean
575 gst_wavparse_other (GstWavParse * wav)
576 {
577   guint32 tag, length;
578
579   if (!gst_riff_peek_head (wav, &tag, &length, NULL)) {
580     GST_WARNING_OBJECT (wav, "could not peek head");
581     return FALSE;
582   }
583   GST_DEBUG_OBJECT (wav, "got tag (%08x) %4.4s, length %d", tag,
584       (gchar *) & tag, length);
585
586   switch (tag) {
587     case GST_RIFF_TAG_LIST:
588       if (!(tag = gst_riff_peek_list (wav))) {
589         GST_WARNING_OBJECT (wav, "could not peek list");
590         return FALSE;
591       }
592
593       switch (tag) {
594         case GST_RIFF_LIST_INFO:
595           if (!gst_riff_read_list (wav, &tag) || !gst_riff_read_info (wav)) {
596             GST_WARNING_OBJECT (wav, "could not read list");
597             return FALSE;
598           }
599           break;
600
601         case GST_RIFF_LIST_adtl:
602           if (!gst_riff_read_skip (wav)) {
603             GST_WARNING_OBJECT (wav, "could not read skip");
604             return FALSE;
605           }
606           break;
607
608         default:
609           GST_DEBUG_OBJECT (wav, "skipping tag (%08x) %4.4s", tag,
610               (gchar *) & tag);
611           if (!gst_riff_read_skip (wav)) {
612             GST_WARNING_OBJECT (wav, "could not read skip");
613             return FALSE;
614           }
615           break;
616       }
617
618       break;
619
620     case GST_RIFF_TAG_data:
621       if (!gst_bytestream_flush (wav->bs, 8)) {
622         GST_WARNING_OBJECT (wav, "could not flush 8 bytes");
623         return FALSE;
624       }
625
626       GST_DEBUG_OBJECT (wav, "switching to data mode");
627       wav->state = GST_WAVPARSE_DATA;
628       wav->datastart = gst_bytestream_tell (wav->bs);
629       if (length == 0) {
630         guint64 file_length;
631
632         /* length is 0, data probably stretches to the end
633          * of file */
634         GST_DEBUG_OBJECT (wav, "length is 0 trying to find length");
635         /* get length of file */
636         file_length = gst_bytestream_length (wav->bs);
637         if (file_length == -1) {
638           GST_DEBUG_OBJECT (wav,
639               "could not get file length, assuming data to eof");
640           /* could not get length, assuming till eof */
641           length = G_MAXUINT32;
642         }
643         if (file_length > G_MAXUINT32) {
644           GST_DEBUG_OBJECT (wav, "file length %" G_GUINT64_FORMAT
645               ", clipping to 32 bits", file_length);
646           /* could not get length, assuming till eof */
647           length = G_MAXUINT32;
648         } else {
649           GST_DEBUG_OBJECT (wav, "file length %" G_GUINT64_FORMAT
650               ", datalength %u", file_length, length);
651           /* substract offset of datastart from length */
652           length = file_length - wav->datastart;
653           GST_DEBUG_OBJECT (wav, "datalength %u", length);
654         }
655       }
656       wav->datasize = (guint64) length;
657       GST_DEBUG_OBJECT (wav, "datasize = %ld", length)
658           break;
659
660     case GST_RIFF_TAG_cue:
661       if (!gst_riff_read_skip (wav)) {
662         GST_WARNING_OBJECT (wav, "could not read skip");
663         return FALSE;
664       }
665       break;
666
667     default:
668       GST_DEBUG_OBJECT (wav, "skipping tag (%08x) %4.4s", tag, (gchar *) & tag);
669       if (!gst_riff_read_skip (wav))
670         return FALSE;
671       break;
672   }
673
674   return TRUE;
675 }
676 #endif
677
678
679 static gboolean
680 gst_wavparse_parse_file_header (GstElement * element, GstBuffer * buf)
681 {
682   guint32 doctype;
683
684   if (!gst_riff_parse_file_header (element, buf, &doctype))
685     return FALSE;
686
687   if (doctype != GST_RIFF_RIFF_WAVE)
688     goto not_wav;
689
690   return TRUE;
691
692   /* ERRORS */
693 not_wav:
694   {
695     GST_ELEMENT_ERROR (element, STREAM, WRONG_TYPE, (NULL),
696         ("File is not a WAVE file: %" GST_FOURCC_FORMAT,
697             GST_FOURCC_ARGS (doctype)));
698     return FALSE;
699   }
700 }
701
702 static GstFlowReturn
703 gst_wavparse_stream_init (GstWavParse * wav)
704 {
705   GstFlowReturn res;
706   GstBuffer *buf = NULL;
707
708   if ((res = gst_pad_pull_range (wav->sinkpad,
709               wav->offset, 12, &buf)) != GST_FLOW_OK)
710     return res;
711   else if (!gst_wavparse_parse_file_header (GST_ELEMENT_CAST (wav), buf))
712     return GST_FLOW_ERROR;
713
714   wav->offset += 12;
715
716   return GST_FLOW_OK;
717 }
718
719 static gboolean
720 gst_wavparse_time_to_bytepos (GstWavParse * wav, gint64 ts, gint64 * bytepos)
721 {
722   /* -1 always maps to -1 */
723   if (ts == -1) {
724     *bytepos = -1;
725     return TRUE;
726   }
727
728   /* 0 always maps to 0 */
729   if (ts == 0) {
730     *bytepos = 0;
731     return TRUE;
732   }
733
734   if (wav->bps > 0) {
735     *bytepos = uint64_ceiling_scale (ts, (guint64) wav->bps, GST_SECOND);
736     return TRUE;
737   } else if (wav->fact) {
738     guint64 bps =
739         gst_util_uint64_scale_int (wav->datasize, wav->rate, wav->fact);
740     *bytepos = uint64_ceiling_scale (ts, bps, GST_SECOND);
741     return TRUE;
742   }
743
744   return FALSE;
745 }
746
747 /* This function is used to perform seeks on the element.
748  *
749  * It also works when event is NULL, in which case it will just
750  * start from the last configured segment. This technique is
751  * used when activating the element and to perform the seek in
752  * READY.
753  */
754 static gboolean
755 gst_wavparse_perform_seek (GstWavParse * wav, GstEvent * event)
756 {
757   gboolean res;
758   gdouble rate;
759   GstFormat format, bformat;
760   GstSeekFlags flags;
761   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
762   gint64 cur, stop, upstream_size;
763   gboolean flush;
764   gboolean update;
765   GstSegment seeksegment = { 0, };
766   gint64 last_stop;
767
768   if (event) {
769     GST_DEBUG_OBJECT (wav, "doing seek with event");
770
771     gst_event_parse_seek (event, &rate, &format, &flags,
772         &cur_type, &cur, &stop_type, &stop);
773
774     /* no negative rates yet */
775     if (rate < 0.0)
776       goto negative_rate;
777
778     if (format != wav->segment.format) {
779       GST_INFO_OBJECT (wav, "converting seek-event from %s to %s",
780           gst_format_get_name (format),
781           gst_format_get_name (wav->segment.format));
782       res = TRUE;
783       if (cur_type != GST_SEEK_TYPE_NONE)
784         res =
785             gst_pad_query_convert (wav->srcpad, format, cur,
786             wav->segment.format, &cur);
787       if (res && stop_type != GST_SEEK_TYPE_NONE)
788         res =
789             gst_pad_query_convert (wav->srcpad, format, stop,
790             wav->segment.format, &stop);
791       if (!res)
792         goto no_format;
793
794       format = wav->segment.format;
795     }
796   } else {
797     GST_DEBUG_OBJECT (wav, "doing seek without event");
798     flags = 0;
799     rate = 1.0;
800     cur_type = GST_SEEK_TYPE_SET;
801     stop_type = GST_SEEK_TYPE_SET;
802   }
803
804   /* in push mode, we must delegate to upstream */
805   if (wav->streaming) {
806     gboolean res = FALSE;
807
808     /* if streaming not yet started; only prepare initial newsegment */
809     if (!event || wav->state != GST_WAVPARSE_DATA) {
810       if (wav->start_segment)
811         gst_event_unref (wav->start_segment);
812       // TODO
813 /*      wav->start_segment =
814           gst_event_new_new_segment (FALSE, wav->segment.rate,
815           wav->segment.format, wav->segment.last_stop, wav->segment.duration,
816           wav->segment.last_stop);*/
817       res = TRUE;
818     } else {
819       /* convert seek positions to byte positions in data sections */
820       if (format == GST_FORMAT_TIME) {
821         /* should not fail */
822         if (!gst_wavparse_time_to_bytepos (wav, cur, &cur))
823           goto no_position;
824         if (!gst_wavparse_time_to_bytepos (wav, stop, &stop))
825           goto no_position;
826       }
827       /* mind sample boundary and header */
828       if (cur >= 0) {
829         cur -= (cur % wav->bytes_per_sample);
830         cur += wav->datastart;
831       }
832       if (stop >= 0) {
833         stop -= (stop % wav->bytes_per_sample);
834         stop += wav->datastart;
835       }
836       GST_DEBUG_OBJECT (wav, "Pushing BYTE seek rate %g, "
837           "start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT, rate, cur,
838           stop);
839       /* BYTE seek event */
840       event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, cur_type, cur,
841           stop_type, stop);
842       res = gst_pad_push_event (wav->sinkpad, event);
843     }
844     return res;
845   }
846
847   /* get flush flag */
848   flush = flags & GST_SEEK_FLAG_FLUSH;
849
850   /* now we need to make sure the streaming thread is stopped. We do this by
851    * either sending a FLUSH_START event downstream which will cause the
852    * streaming thread to stop with a WRONG_STATE.
853    * For a non-flushing seek we simply pause the task, which will happen as soon
854    * as it completes one iteration (and thus might block when the sink is
855    * blocking in preroll). */
856   if (flush) {
857     if (wav->srcpad) {
858       GST_DEBUG_OBJECT (wav, "sending flush start");
859       gst_pad_push_event (wav->srcpad, gst_event_new_flush_start ());
860     }
861   } else {
862     gst_pad_pause_task (wav->sinkpad);
863   }
864
865   /* we should now be able to grab the streaming thread because we stopped it
866    * with the above flush/pause code */
867   GST_PAD_STREAM_LOCK (wav->sinkpad);
868
869   /* save current position */
870   last_stop = wav->segment.position;
871
872   GST_DEBUG_OBJECT (wav, "stopped streaming at %" G_GINT64_FORMAT, last_stop);
873
874   /* copy segment, we need this because we still need the old
875    * segment when we close the current segment. */
876   memcpy (&seeksegment, &wav->segment, sizeof (GstSegment));
877
878   /* configure the seek parameters in the seeksegment. We will then have the
879    * right values in the segment to perform the seek */
880   if (event) {
881     GST_DEBUG_OBJECT (wav, "configuring seek");
882     gst_segment_do_seek (&seeksegment, rate, format, flags,
883         cur_type, cur, stop_type, stop, &update);
884   }
885
886   /* figure out the last position we need to play. If it's configured (stop !=
887    * -1), use that, else we play until the total duration of the file */
888   if ((stop = seeksegment.stop) == -1)
889     stop = seeksegment.duration;
890
891   GST_DEBUG_OBJECT (wav, "cur_type =%d", cur_type);
892   if ((cur_type != GST_SEEK_TYPE_NONE)) {
893     /* bring offset to bytes, if the bps is 0, we have the segment in BYTES and
894      * we can just copy the last_stop. If not, we use the bps to convert TIME to
895      * bytes. */
896     if (!gst_wavparse_time_to_bytepos (wav, seeksegment.position,
897             (gint64 *) & wav->offset))
898       wav->offset = seeksegment.position;
899     GST_LOG_OBJECT (wav, "offset=%" G_GUINT64_FORMAT, wav->offset);
900     wav->offset -= (wav->offset % wav->bytes_per_sample);
901     GST_LOG_OBJECT (wav, "offset=%" G_GUINT64_FORMAT, wav->offset);
902     wav->offset += wav->datastart;
903     GST_LOG_OBJECT (wav, "offset=%" G_GUINT64_FORMAT, wav->offset);
904   } else {
905     GST_LOG_OBJECT (wav, "continue from offset=%" G_GUINT64_FORMAT,
906         wav->offset);
907   }
908
909   if (stop_type != GST_SEEK_TYPE_NONE) {
910     if (!gst_wavparse_time_to_bytepos (wav, stop, (gint64 *) & wav->end_offset))
911       wav->end_offset = stop;
912     GST_LOG_OBJECT (wav, "end_offset=%" G_GUINT64_FORMAT, wav->end_offset);
913     wav->end_offset -= (wav->end_offset % wav->bytes_per_sample);
914     GST_LOG_OBJECT (wav, "end_offset=%" G_GUINT64_FORMAT, wav->end_offset);
915     wav->end_offset += wav->datastart;
916     GST_LOG_OBJECT (wav, "end_offset=%" G_GUINT64_FORMAT, wav->end_offset);
917   } else {
918     GST_LOG_OBJECT (wav, "continue to end_offset=%" G_GUINT64_FORMAT,
919         wav->end_offset);
920   }
921
922   /* make sure filesize is not exceeded due to rounding errors or so,
923    * same precaution as in _stream_headers */
924   bformat = GST_FORMAT_BYTES;
925   if (gst_pad_peer_query_duration (wav->sinkpad, bformat, &upstream_size))
926     wav->end_offset = MIN (wav->end_offset, upstream_size);
927
928   /* this is the range of bytes we will use for playback */
929   wav->offset = MIN (wav->offset, wav->end_offset);
930   wav->dataleft = wav->end_offset - wav->offset;
931
932   GST_DEBUG_OBJECT (wav,
933       "seek: rate %lf, offset %" G_GUINT64_FORMAT ", end %" G_GUINT64_FORMAT
934       ", segment %" GST_TIME_FORMAT " -- %" GST_TIME_FORMAT, rate, wav->offset,
935       wav->end_offset, GST_TIME_ARGS (seeksegment.start), GST_TIME_ARGS (stop));
936
937   /* prepare for streaming again */
938   if (wav->srcpad) {
939     if (flush) {
940       /* if we sent a FLUSH_START, we now send a FLUSH_STOP */
941       GST_DEBUG_OBJECT (wav, "sending flush stop");
942       gst_pad_push_event (wav->srcpad, gst_event_new_flush_stop (TRUE));
943     }
944   }
945
946   /* now we did the seek and can activate the new segment values */
947   memcpy (&wav->segment, &seeksegment, sizeof (GstSegment));
948
949   /* if we're doing a segment seek, post a SEGMENT_START message */
950   if (wav->segment.flags & GST_SEEK_FLAG_SEGMENT) {
951     gst_element_post_message (GST_ELEMENT_CAST (wav),
952         gst_message_new_segment_start (GST_OBJECT_CAST (wav),
953             wav->segment.format, wav->segment.position));
954   }
955
956   /* now create the newsegment */
957   GST_DEBUG_OBJECT (wav, "Creating newsegment from %" G_GINT64_FORMAT
958       " to %" G_GINT64_FORMAT, wav->segment.position, stop);
959
960   /* store the newsegment event so it can be sent from the streaming thread. */
961   if (wav->start_segment)
962     gst_event_unref (wav->start_segment);
963   wav->start_segment = gst_event_new_segment (&wav->segment);
964
965   /* mark discont if we are going to stream from another position. */
966   if (last_stop != wav->segment.position) {
967     GST_DEBUG_OBJECT (wav, "mark DISCONT, we did a seek to another position");
968     wav->discont = TRUE;
969   }
970
971   /* and start the streaming task again */
972   if (!wav->streaming) {
973     gst_pad_start_task (wav->sinkpad, (GstTaskFunction) gst_wavparse_loop,
974         wav->sinkpad);
975   }
976
977   GST_PAD_STREAM_UNLOCK (wav->sinkpad);
978
979   return TRUE;
980
981   /* ERRORS */
982 negative_rate:
983   {
984     GST_DEBUG_OBJECT (wav, "negative playback rates are not supported yet.");
985     return FALSE;
986   }
987 no_format:
988   {
989     GST_DEBUG_OBJECT (wav, "unsupported format given, seek aborted.");
990     return FALSE;
991   }
992 no_position:
993   {
994     GST_DEBUG_OBJECT (wav,
995         "Could not determine byte position for desired time");
996     return FALSE;
997   }
998 }
999
1000 /*
1001  * gst_wavparse_peek_chunk_info:
1002  * @wav Wavparse object
1003  * @tag holder for tag
1004  * @size holder for tag size
1005  *
1006  * Peek next chunk info (tag and size)
1007  *
1008  * Returns: %TRUE when the chunk info (header) is available
1009  */
1010 static gboolean
1011 gst_wavparse_peek_chunk_info (GstWavParse * wav, guint32 * tag, guint32 * size)
1012 {
1013   const guint8 *data = NULL;
1014
1015   if (gst_adapter_available (wav->adapter) < 8)
1016     return FALSE;
1017
1018   data = gst_adapter_map (wav->adapter, 8);
1019   *tag = GST_READ_UINT32_LE (data);
1020   *size = GST_READ_UINT32_LE (data + 4);
1021   gst_adapter_unmap (wav->adapter);
1022
1023   GST_DEBUG ("Next chunk size is %d bytes, type %" GST_FOURCC_FORMAT, *size,
1024       GST_FOURCC_ARGS (*tag));
1025
1026   return TRUE;
1027 }
1028
1029 /*
1030  * gst_wavparse_peek_chunk:
1031  * @wav Wavparse object
1032  * @tag holder for tag
1033  * @size holder for tag size
1034  *
1035  * Peek enough data for one full chunk
1036  *
1037  * Returns: %TRUE when the full chunk is available
1038  */
1039 static gboolean
1040 gst_wavparse_peek_chunk (GstWavParse * wav, guint32 * tag, guint32 * size)
1041 {
1042   guint32 peek_size = 0;
1043   guint available;
1044
1045   if (!gst_wavparse_peek_chunk_info (wav, tag, size))
1046     return FALSE;
1047
1048   /* size 0 -> empty data buffer would surprise most callers,
1049    * large size -> do not bother trying to squeeze that into adapter,
1050    * so we throw poor man's exception, which can be caught if caller really
1051    * wants to handle 0 size chunk */
1052   if (!(*size) || (*size) >= (1 << 30)) {
1053     GST_INFO ("Invalid/unexpected chunk size %d for tag %" GST_FOURCC_FORMAT,
1054         *size, GST_FOURCC_ARGS (*tag));
1055     /* chain should give up */
1056     wav->abort_buffering = TRUE;
1057     return FALSE;
1058   }
1059   peek_size = (*size + 1) & ~1;
1060   available = gst_adapter_available (wav->adapter);
1061
1062   if (available >= (8 + peek_size)) {
1063     return TRUE;
1064   } else {
1065     GST_LOG ("but only %u bytes available now", available);
1066     return FALSE;
1067   }
1068 }
1069
1070 /*
1071  * gst_wavparse_calculate_duration:
1072  * @wav: wavparse object
1073  *
1074  * Calculate duration on demand and store in @wav. Prefer bps, but use fact as a
1075  * fallback.
1076  *
1077  * Returns: %TRUE if duration is available.
1078  */
1079 static gboolean
1080 gst_wavparse_calculate_duration (GstWavParse * wav)
1081 {
1082   if (wav->duration > 0)
1083     return TRUE;
1084
1085   if (wav->bps > 0) {
1086     GST_INFO_OBJECT (wav, "Got datasize %" G_GUINT64_FORMAT, wav->datasize);
1087     wav->duration =
1088         uint64_ceiling_scale (wav->datasize, GST_SECOND, (guint64) wav->bps);
1089     GST_INFO_OBJECT (wav, "Got duration (bps) %" GST_TIME_FORMAT,
1090         GST_TIME_ARGS (wav->duration));
1091     return TRUE;
1092   } else if (wav->fact) {
1093     wav->duration = uint64_ceiling_scale_int (GST_SECOND, wav->fact, wav->rate);
1094     GST_INFO_OBJECT (wav, "Got duration (fact) %" GST_TIME_FORMAT,
1095         GST_TIME_ARGS (wav->duration));
1096     return TRUE;
1097   }
1098   return FALSE;
1099 }
1100
1101 static gboolean
1102 gst_waveparse_ignore_chunk (GstWavParse * wav, GstBuffer * buf, guint32 tag,
1103     guint32 size)
1104 {
1105   guint flush;
1106
1107   if (wav->streaming) {
1108     if (!gst_wavparse_peek_chunk (wav, &tag, &size))
1109       return FALSE;
1110   }
1111   GST_DEBUG_OBJECT (wav, "Ignoring tag %" GST_FOURCC_FORMAT,
1112       GST_FOURCC_ARGS (tag));
1113   flush = 8 + ((size + 1) & ~1);
1114   wav->offset += flush;
1115   if (wav->streaming) {
1116     gst_adapter_flush (wav->adapter, flush);
1117   } else {
1118     gst_buffer_unref (buf);
1119   }
1120
1121   return TRUE;
1122 }
1123
1124 #define MAX_BUFFER_SIZE 4096
1125
1126 static GstFlowReturn
1127 gst_wavparse_stream_headers (GstWavParse * wav)
1128 {
1129   GstFlowReturn res = GST_FLOW_OK;
1130   GstBuffer *buf = NULL;
1131   gst_riff_strf_auds *header = NULL;
1132   guint32 tag, size;
1133   gboolean gotdata = FALSE;
1134   GstCaps *caps = NULL;
1135   gchar *codec_name = NULL;
1136   GstEvent **event_p;
1137   gint64 upstream_size = 0;
1138
1139   /* search for "_fmt" chunk, which should be first */
1140   while (!wav->got_fmt) {
1141     GstBuffer *extra;
1142
1143     /* The header starts with a 'fmt ' tag */
1144     if (wav->streaming) {
1145       if (!gst_wavparse_peek_chunk (wav, &tag, &size))
1146         return res;
1147
1148       gst_adapter_flush (wav->adapter, 8);
1149       wav->offset += 8;
1150
1151       if (size) {
1152         buf = gst_adapter_take_buffer (wav->adapter, size);
1153         if (size & 1)
1154           gst_adapter_flush (wav->adapter, 1);
1155         wav->offset += GST_ROUND_UP_2 (size);
1156       } else {
1157         buf = gst_buffer_new ();
1158       }
1159     } else {
1160       if ((res = gst_riff_read_chunk (GST_ELEMENT_CAST (wav), wav->sinkpad,
1161                   &wav->offset, &tag, &buf)) != GST_FLOW_OK)
1162         return res;
1163     }
1164
1165     if (tag == GST_RIFF_TAG_JUNK || tag == GST_RIFF_TAG_JUNQ ||
1166         tag == GST_RIFF_TAG_bext || tag == GST_RIFF_TAG_BEXT ||
1167         tag == GST_RIFF_TAG_LIST || tag == GST_RIFF_TAG_ID32 ||
1168         tag == GST_RIFF_TAG_IDVX) {
1169       GST_DEBUG_OBJECT (wav, "skipping %" GST_FOURCC_FORMAT " chunk",
1170           GST_FOURCC_ARGS (tag));
1171       gst_buffer_unref (buf);
1172       buf = NULL;
1173       continue;
1174     }
1175
1176     if (tag != GST_RIFF_TAG_fmt)
1177       goto invalid_wav;
1178
1179     if (!(gst_riff_parse_strf_auds (GST_ELEMENT_CAST (wav), buf, &header,
1180                 &extra)))
1181       goto parse_header_error;
1182
1183     buf = NULL;                 /* parse_strf_auds() took ownership of buffer */
1184
1185     /* do sanity checks of header fields */
1186     if (header->channels == 0)
1187       goto no_channels;
1188     if (header->rate == 0)
1189       goto no_rate;
1190
1191     GST_DEBUG_OBJECT (wav, "creating the caps");
1192
1193     /* Note: gst_riff_create_audio_caps might need to fix values in
1194      * the header header depending on the format, so call it first */
1195     caps = gst_riff_create_audio_caps (header->format, NULL, header, extra,
1196         NULL, &codec_name);
1197
1198     if (extra)
1199       gst_buffer_unref (extra);
1200
1201     if (!caps)
1202       goto unknown_format;
1203
1204     /* do more sanity checks of header fields
1205      * (these can be sanitized by gst_riff_create_audio_caps()
1206      */
1207     wav->format = header->format;
1208     wav->rate = header->rate;
1209     wav->channels = header->channels;
1210     wav->blockalign = header->blockalign;
1211     wav->depth = header->size;
1212     wav->av_bps = header->av_bps;
1213     wav->vbr = FALSE;
1214
1215     g_free (header);
1216     header = NULL;
1217
1218     /* do format specific handling */
1219     switch (wav->format) {
1220       case GST_RIFF_WAVE_FORMAT_MPEGL12:
1221       case GST_RIFF_WAVE_FORMAT_MPEGL3:
1222       {
1223         /* Note: workaround for mp2/mp3 embedded in wav, that relies on the
1224          * bitrate inside the mpeg stream */
1225         GST_INFO ("resetting bps from %d to 0 for mp2/3", wav->av_bps);
1226         wav->bps = 0;
1227         break;
1228       }
1229       case GST_RIFF_WAVE_FORMAT_PCM:
1230         if (wav->blockalign > wav->channels * (guint) ceil (wav->depth / 8.0))
1231           goto invalid_blockalign;
1232         /* fall through */
1233       default:
1234         if (wav->av_bps > wav->blockalign * wav->rate)
1235           goto invalid_bps;
1236         /* use the configured bps */
1237         wav->bps = wav->av_bps;
1238         break;
1239     }
1240
1241     wav->width = (wav->blockalign * 8) / wav->channels;
1242     wav->bytes_per_sample = wav->channels * wav->width / 8;
1243
1244     if (wav->bytes_per_sample <= 0)
1245       goto no_bytes_per_sample;
1246
1247     GST_DEBUG_OBJECT (wav, "blockalign = %u", (guint) wav->blockalign);
1248     GST_DEBUG_OBJECT (wav, "width      = %u", (guint) wav->width);
1249     GST_DEBUG_OBJECT (wav, "depth      = %u", (guint) wav->depth);
1250     GST_DEBUG_OBJECT (wav, "av_bps     = %u", (guint) wav->av_bps);
1251     GST_DEBUG_OBJECT (wav, "frequency  = %u", (guint) wav->rate);
1252     GST_DEBUG_OBJECT (wav, "channels   = %u", (guint) wav->channels);
1253     GST_DEBUG_OBJECT (wav, "bytes_per_sample = %u", wav->bytes_per_sample);
1254
1255     /* bps can be 0 when we don't have a valid bitrate (mostly for compressed
1256      * formats). This will make the element output a BYTE format segment and
1257      * will not timestamp the outgoing buffers.
1258      */
1259     GST_DEBUG_OBJECT (wav, "bps        = %u", (guint) wav->bps);
1260
1261     GST_DEBUG_OBJECT (wav, "caps = %" GST_PTR_FORMAT, caps);
1262
1263     /* create pad later so we can sniff the first few bytes
1264      * of the real data and correct our caps if necessary */
1265     gst_caps_replace (&wav->caps, caps);
1266     gst_caps_replace (&caps, NULL);
1267
1268     wav->got_fmt = TRUE;
1269
1270     if (codec_name) {
1271       wav->tags = gst_tag_list_new_empty ();
1272
1273       gst_tag_list_add (wav->tags, GST_TAG_MERGE_REPLACE,
1274           GST_TAG_AUDIO_CODEC, codec_name, NULL);
1275
1276       g_free (codec_name);
1277       codec_name = NULL;
1278     }
1279
1280   }
1281
1282   gst_pad_peer_query_duration (wav->sinkpad, GST_FORMAT_BYTES, &upstream_size);
1283   GST_DEBUG_OBJECT (wav, "upstream size %" G_GUINT64_FORMAT, upstream_size);
1284
1285   /* loop headers until we get data */
1286   while (!gotdata) {
1287     if (wav->streaming) {
1288       if (!gst_wavparse_peek_chunk_info (wav, &tag, &size))
1289         goto exit;
1290     } else {
1291       guint8 *data;
1292
1293       if ((res =
1294               gst_pad_pull_range (wav->sinkpad, wav->offset, 8,
1295                   &buf)) != GST_FLOW_OK)
1296         goto header_read_error;
1297       data = gst_buffer_map (buf, NULL, NULL, -1);
1298       tag = GST_READ_UINT32_LE (data);
1299       size = GST_READ_UINT32_LE (data + 4);
1300       gst_buffer_unmap (buf, data, -1);
1301     }
1302
1303     GST_INFO_OBJECT (wav,
1304         "Got TAG: %" GST_FOURCC_FORMAT ", offset %" G_GUINT64_FORMAT,
1305         GST_FOURCC_ARGS (tag), wav->offset);
1306
1307     /* wav is a st00pid format, we don't know for sure where data starts.
1308      * So we have to go bit by bit until we find the 'data' header
1309      */
1310     switch (tag) {
1311       case GST_RIFF_TAG_data:{
1312         GST_DEBUG_OBJECT (wav, "Got 'data' TAG, size : %d", size);
1313         if (wav->streaming) {
1314           gst_adapter_flush (wav->adapter, 8);
1315           gotdata = TRUE;
1316         } else {
1317           gst_buffer_unref (buf);
1318         }
1319         wav->offset += 8;
1320         wav->datastart = wav->offset;
1321         /* If size is zero, then the data chunk probably actually extends to
1322            the end of the file */
1323         if (size == 0 && upstream_size) {
1324           size = upstream_size - wav->datastart;
1325         }
1326         /* Or the file might be truncated */
1327         else if (upstream_size) {
1328           size = MIN (size, (upstream_size - wav->datastart));
1329         }
1330         wav->datasize = (guint64) size;
1331         wav->dataleft = (guint64) size;
1332         wav->end_offset = size + wav->datastart;
1333         if (!wav->streaming) {
1334           /* We will continue parsing tags 'till end */
1335           wav->offset += size;
1336         }
1337         GST_DEBUG_OBJECT (wav, "datasize = %d", size);
1338         break;
1339       }
1340       case GST_RIFF_TAG_fact:{
1341         if (wav->format != GST_RIFF_WAVE_FORMAT_MPEGL12 &&
1342             wav->format != GST_RIFF_WAVE_FORMAT_MPEGL3) {
1343           const guint data_size = 4;
1344
1345           GST_INFO_OBJECT (wav, "Have fact chunk");
1346           if (size < data_size) {
1347             if (!gst_waveparse_ignore_chunk (wav, buf, tag, size)) {
1348               /* need more data */
1349               goto exit;
1350             }
1351             GST_DEBUG_OBJECT (wav, "need %d, available %d; ignoring chunk",
1352                 data_size, size);
1353             break;
1354           }
1355           /* number of samples (for compressed formats) */
1356           if (wav->streaming) {
1357             const guint8 *data = NULL;
1358
1359             if (!gst_wavparse_peek_chunk (wav, &tag, &size)) {
1360               goto exit;
1361             }
1362             gst_adapter_flush (wav->adapter, 8);
1363             data = gst_adapter_map (wav->adapter, data_size);
1364             wav->fact = GST_READ_UINT32_LE (data);
1365             gst_adapter_unmap (wav->adapter);
1366             gst_adapter_flush (wav->adapter, GST_ROUND_UP_2 (size));
1367           } else {
1368             gst_buffer_unref (buf);
1369             if ((res =
1370                     gst_pad_pull_range (wav->sinkpad, wav->offset + 8,
1371                         data_size, &buf)) != GST_FLOW_OK)
1372               goto header_read_error;
1373             gst_buffer_extract (buf, 0, &wav->fact, 4);
1374             wav->fact = GUINT32_FROM_LE (wav->fact);
1375             gst_buffer_unref (buf);
1376           }
1377           GST_DEBUG_OBJECT (wav, "have fact %u", wav->fact);
1378           wav->offset += 8 + GST_ROUND_UP_2 (size);
1379           break;
1380         } else {
1381           if (!gst_waveparse_ignore_chunk (wav, buf, tag, size)) {
1382             /* need more data */
1383             goto exit;
1384           }
1385         }
1386         break;
1387       }
1388       case GST_RIFF_TAG_acid:{
1389         const gst_riff_acid *acid = NULL;
1390         const guint data_size = sizeof (gst_riff_acid);
1391         gfloat tempo;
1392
1393         GST_INFO_OBJECT (wav, "Have acid chunk");
1394         if (size < data_size) {
1395           if (!gst_waveparse_ignore_chunk (wav, buf, tag, size)) {
1396             /* need more data */
1397             goto exit;
1398           }
1399           GST_DEBUG_OBJECT (wav, "need %d, available %d; ignoring chunk",
1400               data_size, size);
1401           break;
1402         }
1403         if (wav->streaming) {
1404           if (!gst_wavparse_peek_chunk (wav, &tag, &size)) {
1405             goto exit;
1406           }
1407           gst_adapter_flush (wav->adapter, 8);
1408           acid = (const gst_riff_acid *) gst_adapter_map (wav->adapter,
1409               data_size);
1410           tempo = acid->tempo;
1411           gst_adapter_unmap (wav->adapter);
1412         } else {
1413           gst_buffer_unref (buf);
1414           if ((res =
1415                   gst_pad_pull_range (wav->sinkpad, wav->offset + 8,
1416                       size, &buf)) != GST_FLOW_OK)
1417             goto header_read_error;
1418           acid = (const gst_riff_acid *) gst_buffer_map (buf, NULL, NULL,
1419               GST_MAP_READ);
1420           tempo = acid->tempo;
1421           gst_buffer_unmap (buf, (guint8 *) acid, -1);
1422         }
1423         /* send data as tags */
1424         if (!wav->tags)
1425           wav->tags = gst_tag_list_new_empty ();
1426         gst_tag_list_add (wav->tags, GST_TAG_MERGE_REPLACE,
1427             GST_TAG_BEATS_PER_MINUTE, tempo, NULL);
1428
1429         size = GST_ROUND_UP_2 (size);
1430         if (wav->streaming) {
1431           gst_adapter_flush (wav->adapter, size);
1432         } else {
1433           gst_buffer_unref (buf);
1434         }
1435         wav->offset += 8 + size;
1436         break;
1437       }
1438         /* FIXME: all list tags after data are ignored in streaming mode */
1439       case GST_RIFF_TAG_LIST:{
1440         guint32 ltag;
1441
1442         if (wav->streaming) {
1443           const guint8 *data = NULL;
1444
1445           if (gst_adapter_available (wav->adapter) < 12) {
1446             goto exit;
1447           }
1448           data = gst_adapter_map (wav->adapter, 12);
1449           ltag = GST_READ_UINT32_LE (data + 8);
1450           gst_adapter_unmap (wav->adapter);
1451         } else {
1452           gst_buffer_unref (buf);
1453           if ((res =
1454                   gst_pad_pull_range (wav->sinkpad, wav->offset, 12,
1455                       &buf)) != GST_FLOW_OK)
1456             goto header_read_error;
1457           gst_buffer_extract (buf, 8, &ltag, 4);
1458           ltag = GUINT32_FROM_LE (ltag);
1459         }
1460         switch (ltag) {
1461           case GST_RIFF_LIST_INFO:{
1462             const gint data_size = size - 4;
1463             GstTagList *new;
1464
1465             GST_INFO_OBJECT (wav, "Have LIST chunk INFO size %u", data_size);
1466             if (wav->streaming) {
1467               if (!gst_wavparse_peek_chunk (wav, &tag, &size)) {
1468                 goto exit;
1469               }
1470               gst_adapter_flush (wav->adapter, 12);
1471               wav->offset += 12;
1472               if (data_size > 0) {
1473                 buf = gst_adapter_take_buffer (wav->adapter, data_size);
1474                 if (data_size & 1)
1475                   gst_adapter_flush (wav->adapter, 1);
1476               }
1477             } else {
1478               wav->offset += 12;
1479               gst_buffer_unref (buf);
1480               if (data_size > 0) {
1481                 if ((res =
1482                         gst_pad_pull_range (wav->sinkpad, wav->offset,
1483                             data_size, &buf)) != GST_FLOW_OK)
1484                   goto header_read_error;
1485               }
1486             }
1487             if (data_size > 0) {
1488               /* parse tags */
1489               gst_riff_parse_info (GST_ELEMENT (wav), buf, &new);
1490               if (new) {
1491                 GstTagList *old = wav->tags;
1492                 wav->tags =
1493                     gst_tag_list_merge (old, new, GST_TAG_MERGE_REPLACE);
1494                 if (old)
1495                   gst_tag_list_free (old);
1496                 gst_tag_list_free (new);
1497               }
1498               gst_buffer_unref (buf);
1499               wav->offset += GST_ROUND_UP_2 (data_size);
1500             }
1501             break;
1502           }
1503           default:
1504             GST_INFO_OBJECT (wav, "Ignoring LIST chunk %" GST_FOURCC_FORMAT,
1505                 GST_FOURCC_ARGS (ltag));
1506             if (!gst_waveparse_ignore_chunk (wav, buf, tag, size))
1507               /* need more data */
1508               goto exit;
1509             break;
1510         }
1511         break;
1512       }
1513       default:
1514         if (!gst_waveparse_ignore_chunk (wav, buf, tag, size))
1515           /* need more data */
1516           goto exit;
1517         break;
1518     }
1519
1520     if (upstream_size && (wav->offset >= upstream_size)) {
1521       /* Now we are gone through the whole file */
1522       gotdata = TRUE;
1523     }
1524   }
1525
1526   GST_DEBUG_OBJECT (wav, "Finished parsing headers");
1527
1528   if (wav->bps <= 0 && wav->fact) {
1529 #if 0
1530     /* not a good idea, as for embedded mp2/mp3 we set bps to 0 earlier */
1531     wav->bps =
1532         (guint32) gst_util_uint64_scale ((guint64) wav->rate, wav->datasize,
1533         (guint64) wav->fact);
1534     GST_INFO_OBJECT (wav, "calculated bps : %d, enabling VBR", wav->bps);
1535 #endif
1536     wav->vbr = TRUE;
1537   }
1538
1539   if (gst_wavparse_calculate_duration (wav)) {
1540     gst_segment_init (&wav->segment, GST_FORMAT_TIME);
1541     wav->segment.duration = wav->duration;
1542   } else {
1543     /* no bitrate, let downstream peer do the math, we'll feed it bytes. */
1544     gst_segment_init (&wav->segment, GST_FORMAT_BYTES);
1545     wav->segment.duration = wav->datasize;
1546   }
1547
1548   /* now we have all the info to perform a pending seek if any, if no
1549    * event, this will still do the right thing and it will also send
1550    * the right newsegment event downstream. */
1551   gst_wavparse_perform_seek (wav, wav->seek_event);
1552   /* remove pending event */
1553   event_p = &wav->seek_event;
1554   gst_event_replace (event_p, NULL);
1555
1556   /* we just started, we are discont */
1557   wav->discont = TRUE;
1558
1559   wav->state = GST_WAVPARSE_DATA;
1560
1561   /* determine reasonable max buffer size,
1562    * that is, buffers not too small either size or time wise
1563    * so we do not end up with too many of them */
1564   /* var abuse */
1565   upstream_size = 0;
1566   gst_wavparse_time_to_bytepos (wav, 40 * GST_MSECOND, &upstream_size);
1567   wav->max_buf_size = upstream_size;
1568   wav->max_buf_size = MAX (wav->max_buf_size, MAX_BUFFER_SIZE);
1569   if (wav->blockalign > 0)
1570     wav->max_buf_size -= (wav->max_buf_size % wav->blockalign);
1571
1572   GST_DEBUG_OBJECT (wav, "max buffer size %d", wav->max_buf_size);
1573
1574   return GST_FLOW_OK;
1575
1576   /* ERROR */
1577 exit:
1578   {
1579     if (codec_name)
1580       g_free (codec_name);
1581     if (header)
1582       g_free (header);
1583     if (caps)
1584       gst_caps_unref (caps);
1585     return res;
1586   }
1587 fail:
1588   {
1589     res = GST_FLOW_ERROR;
1590     goto exit;
1591   }
1592 invalid_wav:
1593   {
1594     GST_ELEMENT_ERROR (wav, STREAM, TYPE_NOT_FOUND, (NULL),
1595         ("Invalid WAV header (no fmt at start): %"
1596             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
1597     goto fail;
1598   }
1599 parse_header_error:
1600   {
1601     GST_ELEMENT_ERROR (wav, STREAM, DEMUX, (NULL),
1602         ("Couldn't parse audio header"));
1603     goto fail;
1604   }
1605 no_channels:
1606   {
1607     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1608         ("Stream claims to contain no channels - invalid data"));
1609     goto fail;
1610   }
1611 no_rate:
1612   {
1613     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1614         ("Stream with sample_rate == 0 - invalid data"));
1615     goto fail;
1616   }
1617 invalid_blockalign:
1618   {
1619     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1620         ("Stream claims blockalign = %u, which is more than %u - invalid data",
1621             wav->blockalign, wav->channels * (guint) ceil (wav->depth / 8.0)));
1622     goto fail;
1623   }
1624 invalid_bps:
1625   {
1626     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1627         ("Stream claims av_bsp = %u, which is more than %u - invalid data",
1628             wav->av_bps, wav->blockalign * wav->rate));
1629     goto fail;
1630   }
1631 no_bytes_per_sample:
1632   {
1633     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1634         ("Could not caluclate bytes per sample - invalid data"));
1635     goto fail;
1636   }
1637 unknown_format:
1638   {
1639     GST_ELEMENT_ERROR (wav, STREAM, TYPE_NOT_FOUND, (NULL),
1640         ("No caps found for format 0x%x, %d channels, %d Hz",
1641             wav->format, wav->channels, wav->rate));
1642     goto fail;
1643   }
1644 header_read_error:
1645   {
1646     GST_ELEMENT_ERROR (wav, STREAM, DEMUX, (NULL),
1647         ("Couldn't read in header %d (%s)", res, gst_flow_get_name (res)));
1648     goto fail;
1649   }
1650 }
1651
1652 /*
1653  * Read WAV file tag when streaming
1654  */
1655 static GstFlowReturn
1656 gst_wavparse_parse_stream_init (GstWavParse * wav)
1657 {
1658   if (gst_adapter_available (wav->adapter) >= 12) {
1659     GstBuffer *tmp;
1660
1661     /* _take flushes the data */
1662     tmp = gst_adapter_take_buffer (wav->adapter, 12);
1663
1664     GST_DEBUG ("Parsing wav header");
1665     if (!gst_wavparse_parse_file_header (GST_ELEMENT_CAST (wav), tmp))
1666       return GST_FLOW_ERROR;
1667
1668     wav->offset += 12;
1669     /* Go to next state */
1670     wav->state = GST_WAVPARSE_HEADER;
1671   }
1672   return GST_FLOW_OK;
1673 }
1674
1675 /* handle an event sent directly to the element.
1676  *
1677  * This event can be sent either in the READY state or the
1678  * >READY state. The only event of interest really is the seek
1679  * event.
1680  *
1681  * In the READY state we can only store the event and try to
1682  * respect it when going to PAUSED. We assume we are in the
1683  * READY state when our parsing state != GST_WAVPARSE_DATA.
1684  *
1685  * When we are steaming, we can simply perform the seek right
1686  * away.
1687  */
1688 static gboolean
1689 gst_wavparse_send_event (GstElement * element, GstEvent * event)
1690 {
1691   GstWavParse *wav = GST_WAVPARSE (element);
1692   gboolean res = FALSE;
1693   GstEvent **event_p;
1694
1695   GST_DEBUG_OBJECT (wav, "received event %s", GST_EVENT_TYPE_NAME (event));
1696
1697   switch (GST_EVENT_TYPE (event)) {
1698     case GST_EVENT_SEEK:
1699       if (wav->state == GST_WAVPARSE_DATA) {
1700         /* we can handle the seek directly when streaming data */
1701         res = gst_wavparse_perform_seek (wav, event);
1702       } else {
1703         GST_DEBUG_OBJECT (wav, "queuing seek for later");
1704
1705         event_p = &wav->seek_event;
1706         gst_event_replace (event_p, event);
1707
1708         /* we always return true */
1709         res = TRUE;
1710       }
1711       break;
1712     default:
1713       break;
1714   }
1715   gst_event_unref (event);
1716   return res;
1717 }
1718
1719 static gboolean
1720 gst_wavparse_have_dts_caps (const GstCaps * caps, GstTypeFindProbability prob)
1721 {
1722   GstStructure *s;
1723
1724   s = gst_caps_get_structure (caps, 0);
1725   if (!gst_structure_has_name (s, "audio/x-dts"))
1726     return FALSE;
1727   if (prob >= GST_TYPE_FIND_LIKELY)
1728     return TRUE;
1729   /* DTS at non-0 offsets and without second sync may yield POSSIBLE .. */
1730   if (prob < GST_TYPE_FIND_POSSIBLE)
1731     return FALSE;
1732   /* .. in which case we want at least a valid-looking rate and channels */
1733   if (!gst_structure_has_field (s, "channels"))
1734     return FALSE;
1735   /* and for extra assurance we could also check the rate from the DTS frame
1736    * against the one in the wav header, but for now let's not do that */
1737   return gst_structure_has_field (s, "rate");
1738 }
1739
1740 static void
1741 gst_wavparse_add_src_pad (GstWavParse * wav, GstBuffer * buf)
1742 {
1743   GstStructure *s;
1744
1745   GST_DEBUG_OBJECT (wav, "adding src pad");
1746
1747   if (wav->caps) {
1748     s = gst_caps_get_structure (wav->caps, 0);
1749     if (s && gst_structure_has_name (s, "audio/x-raw") && buf != NULL) {
1750       GstTypeFindProbability prob;
1751       GstCaps *tf_caps;
1752
1753       tf_caps = gst_type_find_helper_for_buffer (GST_OBJECT (wav), buf, &prob);
1754       if (tf_caps != NULL) {
1755         GST_LOG ("typefind caps = %" GST_PTR_FORMAT ", P=%d", tf_caps, prob);
1756         if (gst_wavparse_have_dts_caps (tf_caps, prob)) {
1757           GST_INFO_OBJECT (wav, "Found DTS marker in file marked as raw PCM");
1758           gst_caps_unref (wav->caps);
1759           wav->caps = tf_caps;
1760
1761           gst_tag_list_add (wav->tags, GST_TAG_MERGE_REPLACE,
1762               GST_TAG_AUDIO_CODEC, "dts", NULL);
1763         } else {
1764           GST_DEBUG_OBJECT (wav, "found caps %" GST_PTR_FORMAT " for stream "
1765               "marked as raw PCM audio, but ignoring for now", tf_caps);
1766           gst_caps_unref (tf_caps);
1767         }
1768       }
1769     }
1770   }
1771
1772   gst_pad_set_caps (wav->srcpad, wav->caps);
1773   gst_caps_replace (&wav->caps, NULL);
1774
1775   if (wav->start_segment) {
1776     GST_DEBUG_OBJECT (wav, "Send start segment event on newpad");
1777     gst_pad_push_event (wav->srcpad, wav->start_segment);
1778     wav->start_segment = NULL;
1779   }
1780
1781   if (wav->tags) {
1782     gst_pad_push_event (wav->srcpad, gst_event_new_tag (wav->tags));
1783     wav->tags = NULL;
1784   }
1785 }
1786
1787 static GstFlowReturn
1788 gst_wavparse_stream_data (GstWavParse * wav)
1789 {
1790   GstBuffer *buf = NULL;
1791   GstFlowReturn res = GST_FLOW_OK;
1792   guint64 desired, obtained;
1793   GstClockTime timestamp, next_timestamp, duration;
1794   guint64 pos, nextpos;
1795
1796 iterate_adapter:
1797   GST_LOG_OBJECT (wav,
1798       "offset: %" G_GINT64_FORMAT " , end: %" G_GINT64_FORMAT " , dataleft: %"
1799       G_GINT64_FORMAT, wav->offset, wav->end_offset, wav->dataleft);
1800
1801   /* Get the next n bytes and output them */
1802   if (wav->dataleft == 0 || wav->dataleft < wav->blockalign)
1803     goto found_eos;
1804
1805   /* scale the amount of data by the segment rate so we get equal
1806    * amounts of data regardless of the playback rate */
1807   desired =
1808       MIN (gst_guint64_to_gdouble (wav->dataleft),
1809       wav->max_buf_size * ABS (wav->segment.rate));
1810
1811   if (desired >= wav->blockalign && wav->blockalign > 0)
1812     desired -= (desired % wav->blockalign);
1813
1814   GST_LOG_OBJECT (wav, "Fetching %" G_GINT64_FORMAT " bytes of data "
1815       "from the sinkpad", desired);
1816
1817   if (wav->streaming) {
1818     guint avail = gst_adapter_available (wav->adapter);
1819     guint extra;
1820
1821     /* flush some bytes if evil upstream sends segment that starts
1822      * before data or does is not send sample aligned segment */
1823     if (G_LIKELY (wav->offset >= wav->datastart)) {
1824       extra = (wav->offset - wav->datastart) % wav->bytes_per_sample;
1825     } else {
1826       extra = wav->datastart - wav->offset;
1827     }
1828
1829     if (G_UNLIKELY (extra)) {
1830       extra = wav->bytes_per_sample - extra;
1831       if (extra <= avail) {
1832         GST_DEBUG_OBJECT (wav, "flushing %d bytes to sample boundary", extra);
1833         gst_adapter_flush (wav->adapter, extra);
1834         wav->offset += extra;
1835         wav->dataleft -= extra;
1836         goto iterate_adapter;
1837       } else {
1838         GST_DEBUG_OBJECT (wav, "flushing %d bytes", avail);
1839         gst_adapter_clear (wav->adapter);
1840         wav->offset += avail;
1841         wav->dataleft -= avail;
1842         return GST_FLOW_OK;
1843       }
1844     }
1845
1846     if (avail < desired) {
1847       GST_LOG_OBJECT (wav, "Got only %d bytes of data from the sinkpad", avail);
1848       return GST_FLOW_OK;
1849     }
1850
1851     buf = gst_adapter_take_buffer (wav->adapter, desired);
1852   } else {
1853     if ((res = gst_pad_pull_range (wav->sinkpad, wav->offset,
1854                 desired, &buf)) != GST_FLOW_OK)
1855       goto pull_error;
1856
1857     /* we may get a short buffer at the end of the file */
1858     if (gst_buffer_get_size (buf) < desired) {
1859       gsize size = gst_buffer_get_size (buf);
1860
1861       GST_LOG_OBJECT (wav, "Got only %" G_GSIZE_FORMAT " bytes of data", size);
1862       if (size >= wav->blockalign) {
1863         buf = gst_buffer_make_writable (buf);
1864         gst_buffer_resize (buf, 0, size - (size % wav->blockalign));
1865       } else {
1866         gst_buffer_unref (buf);
1867         goto found_eos;
1868       }
1869     }
1870   }
1871
1872   obtained = gst_buffer_get_size (buf);
1873
1874   /* our positions in bytes */
1875   pos = wav->offset - wav->datastart;
1876   nextpos = pos + obtained;
1877
1878   /* update offsets, does not overflow. */
1879   buf = gst_buffer_make_writable (buf);
1880   GST_BUFFER_OFFSET (buf) = pos / wav->bytes_per_sample;
1881   GST_BUFFER_OFFSET_END (buf) = nextpos / wav->bytes_per_sample;
1882
1883   /* first chunk of data? create the source pad. We do this only here so
1884    * we can detect broken .wav files with dts disguised as raw PCM (sigh) */
1885   if (G_UNLIKELY (wav->first)) {
1886     wav->first = FALSE;
1887     /* this will also push the segment events */
1888     gst_wavparse_add_src_pad (wav, buf);
1889   } else {
1890     /* If we have a pending start segment, send it now. */
1891     if (G_UNLIKELY (wav->start_segment != NULL)) {
1892       gst_pad_push_event (wav->srcpad, wav->start_segment);
1893       wav->start_segment = NULL;
1894     }
1895   }
1896
1897   if (wav->bps > 0) {
1898     /* and timestamps if we have a bitrate, be careful for overflows */
1899     timestamp = uint64_ceiling_scale (pos, GST_SECOND, (guint64) wav->bps);
1900     next_timestamp =
1901         uint64_ceiling_scale (nextpos, GST_SECOND, (guint64) wav->bps);
1902     duration = next_timestamp - timestamp;
1903
1904     /* update current running segment position */
1905     if (G_LIKELY (next_timestamp >= wav->segment.start))
1906       wav->segment.position = next_timestamp;
1907   } else if (wav->fact) {
1908     guint64 bps =
1909         gst_util_uint64_scale_int (wav->datasize, wav->rate, wav->fact);
1910     /* and timestamps if we have a bitrate, be careful for overflows */
1911     timestamp = uint64_ceiling_scale (pos, GST_SECOND, bps);
1912     next_timestamp = uint64_ceiling_scale (nextpos, GST_SECOND, bps);
1913     duration = next_timestamp - timestamp;
1914   } else {
1915     /* no bitrate, all we know is that the first sample has timestamp 0, all
1916      * other positions and durations have unknown timestamp. */
1917     if (pos == 0)
1918       timestamp = 0;
1919     else
1920       timestamp = GST_CLOCK_TIME_NONE;
1921     duration = GST_CLOCK_TIME_NONE;
1922     /* update current running segment position with byte offset */
1923     if (G_LIKELY (nextpos >= wav->segment.start))
1924       wav->segment.position = nextpos;
1925   }
1926   if ((pos > 0) && wav->vbr) {
1927     /* don't set timestamps for VBR files if it's not the first buffer */
1928     timestamp = GST_CLOCK_TIME_NONE;
1929     duration = GST_CLOCK_TIME_NONE;
1930   }
1931   if (wav->discont) {
1932     GST_DEBUG_OBJECT (wav, "marking DISCONT");
1933     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1934     wav->discont = FALSE;
1935   }
1936
1937   GST_BUFFER_TIMESTAMP (buf) = timestamp;
1938   GST_BUFFER_DURATION (buf) = duration;
1939
1940   GST_LOG_OBJECT (wav,
1941       "Got buffer. timestamp:%" GST_TIME_FORMAT " , duration:%" GST_TIME_FORMAT
1942       ", size:%" G_GSIZE_FORMAT, GST_TIME_ARGS (timestamp),
1943       GST_TIME_ARGS (duration), gst_buffer_get_size (buf));
1944
1945   if ((res = gst_pad_push (wav->srcpad, buf)) != GST_FLOW_OK)
1946     goto push_error;
1947
1948   if (obtained < wav->dataleft) {
1949     wav->offset += obtained;
1950     wav->dataleft -= obtained;
1951   } else {
1952     wav->offset += wav->dataleft;
1953     wav->dataleft = 0;
1954   }
1955
1956   /* Iterate until need more data, so adapter size won't grow */
1957   if (wav->streaming) {
1958     GST_LOG_OBJECT (wav,
1959         "offset: %" G_GINT64_FORMAT " , end: %" G_GINT64_FORMAT, wav->offset,
1960         wav->end_offset);
1961     goto iterate_adapter;
1962   }
1963   return res;
1964
1965   /* ERROR */
1966 found_eos:
1967   {
1968     GST_DEBUG_OBJECT (wav, "found EOS");
1969     return GST_FLOW_UNEXPECTED;
1970   }
1971 pull_error:
1972   {
1973     /* check if we got EOS */
1974     if (res == GST_FLOW_UNEXPECTED)
1975       goto found_eos;
1976
1977     GST_WARNING_OBJECT (wav,
1978         "Error getting %" G_GINT64_FORMAT " bytes from the "
1979         "sinkpad (dataleft = %" G_GINT64_FORMAT ")", desired, wav->dataleft);
1980     return res;
1981   }
1982 push_error:
1983   {
1984     GST_INFO_OBJECT (wav,
1985         "Error pushing on srcpad %s:%s, reason %s, is linked? = %d",
1986         GST_DEBUG_PAD_NAME (wav->srcpad), gst_flow_get_name (res),
1987         gst_pad_is_linked (wav->srcpad));
1988     return res;
1989   }
1990 }
1991
1992 static void
1993 gst_wavparse_loop (GstPad * pad)
1994 {
1995   GstFlowReturn ret;
1996   GstWavParse *wav = GST_WAVPARSE (GST_PAD_PARENT (pad));
1997
1998   GST_LOG_OBJECT (wav, "process data");
1999
2000   switch (wav->state) {
2001     case GST_WAVPARSE_START:
2002       GST_INFO_OBJECT (wav, "GST_WAVPARSE_START");
2003       if ((ret = gst_wavparse_stream_init (wav)) != GST_FLOW_OK)
2004         goto pause;
2005
2006       wav->state = GST_WAVPARSE_HEADER;
2007       /* fall-through */
2008
2009     case GST_WAVPARSE_HEADER:
2010       GST_INFO_OBJECT (wav, "GST_WAVPARSE_HEADER");
2011       if ((ret = gst_wavparse_stream_headers (wav)) != GST_FLOW_OK)
2012         goto pause;
2013
2014       wav->state = GST_WAVPARSE_DATA;
2015       GST_INFO_OBJECT (wav, "GST_WAVPARSE_DATA");
2016       /* fall-through */
2017
2018     case GST_WAVPARSE_DATA:
2019       if ((ret = gst_wavparse_stream_data (wav)) != GST_FLOW_OK)
2020         goto pause;
2021       break;
2022     default:
2023       g_assert_not_reached ();
2024   }
2025   return;
2026
2027   /* ERRORS */
2028 pause:
2029   {
2030     const gchar *reason = gst_flow_get_name (ret);
2031
2032     GST_DEBUG_OBJECT (wav, "pausing task, reason %s", reason);
2033     gst_pad_pause_task (pad);
2034
2035     if (ret == GST_FLOW_UNEXPECTED) {
2036       /* handle end-of-stream/segment */
2037       /* so align our position with the end of it, if there is one
2038        * this ensures a subsequent will arrive at correct base/acc time */
2039       if (wav->segment.format == GST_FORMAT_TIME) {
2040         if (wav->segment.rate > 0.0 &&
2041             GST_CLOCK_TIME_IS_VALID (wav->segment.stop))
2042           wav->segment.position = wav->segment.stop;
2043         else if (wav->segment.rate < 0.0)
2044           wav->segment.position = wav->segment.start;
2045       }
2046       /* add pad before we perform EOS */
2047       if (G_UNLIKELY (wav->first)) {
2048         wav->first = FALSE;
2049         gst_wavparse_add_src_pad (wav, NULL);
2050       }
2051
2052       if (wav->state == GST_WAVPARSE_START)
2053         GST_ELEMENT_ERROR (wav, STREAM, WRONG_TYPE,
2054             ("No valid input found before end of stream"), (NULL));
2055
2056       /* perform EOS logic */
2057       if (wav->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2058         GstClockTime stop;
2059
2060         if ((stop = wav->segment.stop) == -1)
2061           stop = wav->segment.duration;
2062
2063         gst_element_post_message (GST_ELEMENT_CAST (wav),
2064             gst_message_new_segment_done (GST_OBJECT_CAST (wav),
2065                 wav->segment.format, stop));
2066       } else {
2067         if (wav->srcpad != NULL)
2068           gst_pad_push_event (wav->srcpad, gst_event_new_eos ());
2069       }
2070     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2071       /* for fatal errors we post an error message, post the error
2072        * first so the app knows about the error first. */
2073       GST_ELEMENT_ERROR (wav, STREAM, FAILED,
2074           (_("Internal data flow error.")),
2075           ("streaming task paused, reason %s (%d)", reason, ret));
2076       if (wav->srcpad != NULL)
2077         gst_pad_push_event (wav->srcpad, gst_event_new_eos ());
2078     }
2079     return;
2080   }
2081 }
2082
2083 static GstFlowReturn
2084 gst_wavparse_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
2085 {
2086   GstFlowReturn ret;
2087   GstWavParse *wav = GST_WAVPARSE (parent);
2088
2089   GST_LOG_OBJECT (wav, "adapter_push %" G_GSIZE_FORMAT " bytes",
2090       gst_buffer_get_size (buf));
2091
2092   gst_adapter_push (wav->adapter, buf);
2093
2094   switch (wav->state) {
2095     case GST_WAVPARSE_START:
2096       GST_INFO_OBJECT (wav, "GST_WAVPARSE_START");
2097       if ((ret = gst_wavparse_parse_stream_init (wav)) != GST_FLOW_OK)
2098         goto done;
2099
2100       if (wav->state != GST_WAVPARSE_HEADER)
2101         break;
2102
2103       /* otherwise fall-through */
2104     case GST_WAVPARSE_HEADER:
2105       GST_INFO_OBJECT (wav, "GST_WAVPARSE_HEADER");
2106       if ((ret = gst_wavparse_stream_headers (wav)) != GST_FLOW_OK)
2107         goto done;
2108
2109       if (!wav->got_fmt || wav->datastart == 0)
2110         break;
2111
2112       wav->state = GST_WAVPARSE_DATA;
2113       GST_INFO_OBJECT (wav, "GST_WAVPARSE_DATA");
2114
2115       /* fall-through */
2116     case GST_WAVPARSE_DATA:
2117       if (buf && GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT))
2118         wav->discont = TRUE;
2119       if ((ret = gst_wavparse_stream_data (wav)) != GST_FLOW_OK)
2120         goto done;
2121       break;
2122     default:
2123       g_return_val_if_reached (GST_FLOW_ERROR);
2124   }
2125 done:
2126   if (G_UNLIKELY (wav->abort_buffering)) {
2127     wav->abort_buffering = FALSE;
2128     ret = GST_FLOW_ERROR;
2129     /* sort of demux/parse error */
2130     GST_ELEMENT_ERROR (wav, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
2131   }
2132
2133   return ret;
2134 }
2135
2136 static GstFlowReturn
2137 gst_wavparse_flush_data (GstWavParse * wav)
2138 {
2139   GstFlowReturn ret = GST_FLOW_OK;
2140   guint av;
2141
2142   if ((av = gst_adapter_available (wav->adapter)) > 0) {
2143     wav->dataleft = av;
2144     wav->end_offset = wav->offset + av;
2145     ret = gst_wavparse_stream_data (wav);
2146   }
2147
2148   return ret;
2149 }
2150
2151 static gboolean
2152 gst_wavparse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
2153 {
2154   GstWavParse *wav = GST_WAVPARSE (parent);
2155   gboolean ret = TRUE;
2156
2157   GST_LOG_OBJECT (wav, "handling %s event", GST_EVENT_TYPE_NAME (event));
2158
2159   switch (GST_EVENT_TYPE (event)) {
2160     case GST_EVENT_CAPS:
2161     {
2162       /* discard, we'll come up with proper src caps */
2163       gst_event_unref (event);
2164       break;
2165     }
2166     case GST_EVENT_SEGMENT:
2167     {
2168       gint64 start, stop, offset = 0, end_offset = -1;
2169       GstSegment segment;
2170
2171       /* some debug output */
2172       gst_event_copy_segment (event, &segment);
2173       GST_DEBUG_OBJECT (wav, "received newsegment %" GST_SEGMENT_FORMAT,
2174           &segment);
2175
2176       if (wav->state != GST_WAVPARSE_DATA) {
2177         GST_DEBUG_OBJECT (wav, "still starting, eating event");
2178         goto exit;
2179       }
2180
2181       /* now we are either committed to TIME or BYTE format,
2182        * and we only expect a BYTE segment, e.g. following a seek */
2183       if (segment.format == GST_FORMAT_BYTES) {
2184         /* handle (un)signed issues */
2185         start = segment.start;
2186         stop = segment.stop;
2187         if (start > 0) {
2188           offset = start;
2189           start -= wav->datastart;
2190           start = MAX (start, 0);
2191         }
2192         if (stop > 0) {
2193           end_offset = stop;
2194           segment.stop -= wav->datastart;
2195           segment.stop = MAX (stop, 0);
2196         }
2197         if (wav->segment.format == GST_FORMAT_TIME) {
2198           guint64 bps = wav->bps;
2199
2200           /* operating in format TIME, so we can convert */
2201           if (!bps && wav->fact)
2202             bps =
2203                 gst_util_uint64_scale_int (wav->datasize, wav->rate, wav->fact);
2204           if (bps) {
2205             if (start >= 0)
2206               start =
2207                   uint64_ceiling_scale (start, GST_SECOND, (guint64) wav->bps);
2208             if (stop >= 0)
2209               stop =
2210                   uint64_ceiling_scale (stop, GST_SECOND, (guint64) wav->bps);
2211           }
2212         }
2213       } else {
2214         GST_DEBUG_OBJECT (wav, "unsupported segment format, ignoring");
2215         goto exit;
2216       }
2217
2218       segment.start = start;
2219       segment.stop = stop;
2220
2221       /* accept upstream's notion of segment and distribute along */
2222       segment.time = segment.start = segment.position;
2223       segment.duration = wav->segment.duration;
2224       segment.base = gst_segment_to_running_time (&wav->segment,
2225           GST_FORMAT_TIME, wav->segment.position);
2226
2227       gst_segment_copy_into (&segment, &wav->segment);
2228
2229       /* also store the newsegment event for the streaming thread */
2230       if (wav->start_segment)
2231         gst_event_unref (wav->start_segment);
2232       GST_DEBUG_OBJECT (wav, "Storing newseg %" GST_SEGMENT_FORMAT, &segment);
2233       wav->start_segment = gst_event_new_segment (&segment);
2234
2235       /* stream leftover data in current segment */
2236       gst_wavparse_flush_data (wav);
2237       /* and set up streaming thread for next one */
2238       wav->offset = offset;
2239       wav->end_offset = end_offset;
2240       if (wav->end_offset > 0) {
2241         wav->dataleft = wav->end_offset - wav->offset;
2242       } else {
2243         /* infinity; upstream will EOS when done */
2244         wav->dataleft = G_MAXUINT64;
2245       }
2246     exit:
2247       gst_event_unref (event);
2248       break;
2249     }
2250     case GST_EVENT_EOS:
2251       /* add pad if needed so EOS is seen downstream */
2252       if (G_UNLIKELY (wav->first)) {
2253         wav->first = FALSE;
2254         gst_wavparse_add_src_pad (wav, NULL);
2255       } else {
2256         /* stream leftover data in current segment */
2257         gst_wavparse_flush_data (wav);
2258       }
2259
2260       if (wav->state == GST_WAVPARSE_START)
2261         GST_ELEMENT_ERROR (wav, STREAM, WRONG_TYPE,
2262             ("No valid input found before end of stream"), (NULL));
2263
2264       /* fall-through */
2265     case GST_EVENT_FLUSH_STOP:
2266     {
2267       GstClockTime dur;
2268
2269       gst_adapter_clear (wav->adapter);
2270       wav->discont = TRUE;
2271       dur = wav->segment.duration;
2272       gst_segment_init (&wav->segment, wav->segment.format);
2273       wav->segment.duration = dur;
2274       /* fall-through */
2275     }
2276     default:
2277       ret = gst_pad_event_default (wav->sinkpad, parent, event);
2278       break;
2279   }
2280
2281   return ret;
2282 }
2283
2284 #if 0
2285 /* convert and query stuff */
2286 static const GstFormat *
2287 gst_wavparse_get_formats (GstPad * pad)
2288 {
2289   static GstFormat formats[] = {
2290     GST_FORMAT_TIME,
2291     GST_FORMAT_BYTES,
2292     GST_FORMAT_DEFAULT,         /* a "frame", ie a set of samples per Hz */
2293     0
2294   };
2295
2296   return formats;
2297 }
2298 #endif
2299
2300 static gboolean
2301 gst_wavparse_pad_convert (GstPad * pad,
2302     GstFormat src_format, gint64 src_value,
2303     GstFormat * dest_format, gint64 * dest_value)
2304 {
2305   GstWavParse *wavparse;
2306   gboolean res = TRUE;
2307
2308   wavparse = GST_WAVPARSE (GST_PAD_PARENT (pad));
2309
2310   if (*dest_format == src_format) {
2311     *dest_value = src_value;
2312     return TRUE;
2313   }
2314
2315   if ((wavparse->bps == 0) && !wavparse->fact)
2316     goto no_bps_fact;
2317
2318   GST_INFO_OBJECT (wavparse, "converting value from %s to %s",
2319       gst_format_get_name (src_format), gst_format_get_name (*dest_format));
2320
2321   switch (src_format) {
2322     case GST_FORMAT_BYTES:
2323       switch (*dest_format) {
2324         case GST_FORMAT_DEFAULT:
2325           *dest_value = src_value / wavparse->bytes_per_sample;
2326           /* make sure we end up on a sample boundary */
2327           *dest_value -= *dest_value % wavparse->bytes_per_sample;
2328           break;
2329         case GST_FORMAT_TIME:
2330           /* src_value + datastart = offset */
2331           GST_INFO_OBJECT (wavparse,
2332               "src=%" G_GINT64_FORMAT ", offset=%" G_GINT64_FORMAT, src_value,
2333               wavparse->offset);
2334           if (wavparse->bps > 0)
2335             *dest_value = uint64_ceiling_scale (src_value, GST_SECOND,
2336                 (guint64) wavparse->bps);
2337           else if (wavparse->fact) {
2338             guint64 bps = uint64_ceiling_scale_int (wavparse->datasize,
2339                 wavparse->rate, wavparse->fact);
2340
2341             *dest_value = uint64_ceiling_scale_int (src_value, GST_SECOND, bps);
2342           } else {
2343             res = FALSE;
2344           }
2345           break;
2346         default:
2347           res = FALSE;
2348           goto done;
2349       }
2350       break;
2351
2352     case GST_FORMAT_DEFAULT:
2353       switch (*dest_format) {
2354         case GST_FORMAT_BYTES:
2355           *dest_value = src_value * wavparse->bytes_per_sample;
2356           break;
2357         case GST_FORMAT_TIME:
2358           *dest_value = gst_util_uint64_scale (src_value, GST_SECOND,
2359               (guint64) wavparse->rate);
2360           break;
2361         default:
2362           res = FALSE;
2363           goto done;
2364       }
2365       break;
2366
2367     case GST_FORMAT_TIME:
2368       switch (*dest_format) {
2369         case GST_FORMAT_BYTES:
2370           if (wavparse->bps > 0)
2371             *dest_value = gst_util_uint64_scale (src_value,
2372                 (guint64) wavparse->bps, GST_SECOND);
2373           else {
2374             guint64 bps = gst_util_uint64_scale_int (wavparse->datasize,
2375                 wavparse->rate, wavparse->fact);
2376
2377             *dest_value = gst_util_uint64_scale (src_value, bps, GST_SECOND);
2378           }
2379           /* make sure we end up on a sample boundary */
2380           *dest_value -= *dest_value % wavparse->blockalign;
2381           break;
2382         case GST_FORMAT_DEFAULT:
2383           *dest_value = gst_util_uint64_scale (src_value,
2384               (guint64) wavparse->rate, GST_SECOND);
2385           break;
2386         default:
2387           res = FALSE;
2388           goto done;
2389       }
2390       break;
2391
2392     default:
2393       res = FALSE;
2394       goto done;
2395   }
2396
2397 done:
2398   return res;
2399
2400   /* ERRORS */
2401 no_bps_fact:
2402   {
2403     GST_DEBUG_OBJECT (wavparse, "bps 0 or no fact chunk, cannot convert");
2404     res = FALSE;
2405     goto done;
2406   }
2407 }
2408
2409 /* handle queries for location and length in requested format */
2410 static gboolean
2411 gst_wavparse_pad_query (GstPad * pad, GstObject * parent, GstQuery * query)
2412 {
2413   gboolean res = TRUE;
2414   GstWavParse *wav = GST_WAVPARSE (parent);
2415
2416   /* only if we know */
2417   if (wav->state != GST_WAVPARSE_DATA) {
2418     return FALSE;
2419   }
2420
2421   GST_LOG_OBJECT (pad, "%s query", GST_QUERY_TYPE_NAME (query));
2422
2423   switch (GST_QUERY_TYPE (query)) {
2424     case GST_QUERY_POSITION:
2425     {
2426       gint64 curb;
2427       gint64 cur;
2428       GstFormat format;
2429
2430       /* this is not very precise, as we have pushed severla buffer upstream for prerolling */
2431       curb = wav->offset - wav->datastart;
2432       gst_query_parse_position (query, &format, NULL);
2433       GST_INFO_OBJECT (wav, "pos query at %" G_GINT64_FORMAT, curb);
2434
2435       switch (format) {
2436         case GST_FORMAT_TIME:
2437           res = gst_wavparse_pad_convert (pad, GST_FORMAT_BYTES, curb,
2438               &format, &cur);
2439           break;
2440         default:
2441           format = GST_FORMAT_BYTES;
2442           cur = curb;
2443           break;
2444       }
2445       if (res)
2446         gst_query_set_position (query, format, cur);
2447       break;
2448     }
2449     case GST_QUERY_DURATION:
2450     {
2451       gint64 duration = 0;
2452       GstFormat format;
2453
2454       gst_query_parse_duration (query, &format, NULL);
2455
2456       switch (format) {
2457         case GST_FORMAT_TIME:{
2458           if ((res = gst_wavparse_calculate_duration (wav))) {
2459             duration = wav->duration;
2460           }
2461           break;
2462         }
2463         default:
2464           format = GST_FORMAT_BYTES;
2465           duration = wav->datasize;
2466           break;
2467       }
2468       gst_query_set_duration (query, format, duration);
2469       break;
2470     }
2471     case GST_QUERY_CONVERT:
2472     {
2473       gint64 srcvalue, dstvalue;
2474       GstFormat srcformat, dstformat;
2475
2476       gst_query_parse_convert (query, &srcformat, &srcvalue,
2477           &dstformat, &dstvalue);
2478       res = gst_wavparse_pad_convert (pad, srcformat, srcvalue,
2479           &dstformat, &dstvalue);
2480       if (res)
2481         gst_query_set_convert (query, srcformat, srcvalue, dstformat, dstvalue);
2482       break;
2483     }
2484     case GST_QUERY_SEEKING:{
2485       GstFormat fmt;
2486       gboolean seekable = FALSE;
2487
2488       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
2489       if (fmt == wav->segment.format) {
2490         if (wav->streaming) {
2491           GstQuery *q;
2492
2493           q = gst_query_new_seeking (GST_FORMAT_BYTES);
2494           if ((res = gst_pad_peer_query (wav->sinkpad, q))) {
2495             gst_query_parse_seeking (q, &fmt, &seekable, NULL, NULL);
2496             GST_LOG_OBJECT (wav, "upstream BYTE seekable %d", seekable);
2497           }
2498           gst_query_unref (q);
2499         } else {
2500           GST_LOG_OBJECT (wav, "looping => seekable");
2501           seekable = TRUE;
2502           res = TRUE;
2503         }
2504       } else if (fmt == GST_FORMAT_TIME) {
2505         res = TRUE;
2506       }
2507       if (res) {
2508         gst_query_set_seeking (query, fmt, seekable, 0, wav->segment.duration);
2509       }
2510       break;
2511     }
2512     default:
2513       res = gst_pad_query_default (pad, parent, query);
2514       break;
2515   }
2516   return res;
2517 }
2518
2519 static gboolean
2520 gst_wavparse_srcpad_event (GstPad * pad, GstObject * parent, GstEvent * event)
2521 {
2522   GstWavParse *wavparse = GST_WAVPARSE (parent);
2523   gboolean res = FALSE;
2524
2525   GST_DEBUG_OBJECT (wavparse, "%s event", GST_EVENT_TYPE_NAME (event));
2526
2527   switch (GST_EVENT_TYPE (event)) {
2528     case GST_EVENT_SEEK:
2529       /* can only handle events when we are in the data state */
2530       if (wavparse->state == GST_WAVPARSE_DATA) {
2531         res = gst_wavparse_perform_seek (wavparse, event);
2532       }
2533       gst_event_unref (event);
2534       break;
2535     default:
2536       res = gst_pad_push_event (wavparse->sinkpad, event);
2537       break;
2538   }
2539   return res;
2540 }
2541
2542 static gboolean
2543 gst_wavparse_sink_activate (GstPad * sinkpad, GstObject * parent)
2544 {
2545   GstWavParse *wav = GST_WAVPARSE (parent);
2546   GstQuery *query;
2547   gboolean pull_mode;
2548
2549   if (wav->adapter) {
2550     gst_adapter_clear (wav->adapter);
2551     g_object_unref (wav->adapter);
2552     wav->adapter = NULL;
2553   }
2554
2555   query = gst_query_new_scheduling ();
2556
2557   if (!gst_pad_peer_query (sinkpad, query)) {
2558     gst_query_unref (query);
2559     goto activate_push;
2560   }
2561
2562   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
2563   gst_query_unref (query);
2564
2565   if (!pull_mode)
2566     goto activate_push;
2567
2568   GST_DEBUG_OBJECT (sinkpad, "activating pull");
2569   wav->streaming = FALSE;
2570   return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
2571
2572 activate_push:
2573   {
2574     GST_DEBUG_OBJECT (sinkpad, "activating push");
2575     wav->streaming = TRUE;
2576     wav->adapter = gst_adapter_new ();
2577     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
2578   }
2579 }
2580
2581
2582 static gboolean
2583 gst_wavparse_sink_activate_mode (GstPad * sinkpad, GstObject * parent,
2584     GstPadMode mode, gboolean active)
2585 {
2586   gboolean res;
2587
2588   switch (mode) {
2589     case GST_PAD_MODE_PUSH:
2590       res = TRUE;
2591       break;
2592     case GST_PAD_MODE_PULL:
2593       if (active) {
2594         /* if we have a scheduler we can start the task */
2595         res = gst_pad_start_task (sinkpad, (GstTaskFunction) gst_wavparse_loop,
2596             sinkpad);
2597       } else {
2598         res = gst_pad_stop_task (sinkpad);
2599       }
2600       break;
2601     default:
2602       res = FALSE;
2603       break;
2604   }
2605   return res;
2606 }
2607
2608 static GstStateChangeReturn
2609 gst_wavparse_change_state (GstElement * element, GstStateChange transition)
2610 {
2611   GstStateChangeReturn ret;
2612   GstWavParse *wav = GST_WAVPARSE (element);
2613
2614   switch (transition) {
2615     case GST_STATE_CHANGE_NULL_TO_READY:
2616       break;
2617     case GST_STATE_CHANGE_READY_TO_PAUSED:
2618       gst_wavparse_reset (wav);
2619       break;
2620     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2621       break;
2622     default:
2623       break;
2624   }
2625
2626   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2627
2628   switch (transition) {
2629     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2630       break;
2631     case GST_STATE_CHANGE_PAUSED_TO_READY:
2632       gst_wavparse_destroy_sourcepad (wav);
2633       gst_wavparse_reset (wav);
2634       break;
2635     case GST_STATE_CHANGE_READY_TO_NULL:
2636       break;
2637     default:
2638       break;
2639   }
2640   return ret;
2641 }
2642
2643 static gboolean
2644 plugin_init (GstPlugin * plugin)
2645 {
2646   gst_riff_init ();
2647
2648   return gst_element_register (plugin, "wavparse", GST_RANK_PRIMARY,
2649       GST_TYPE_WAVPARSE);
2650 }
2651
2652 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2653     GST_VERSION_MINOR,
2654     "wavparse",
2655     "Parse a .wav file into raw audio",
2656     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)