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