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