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