upload tizen1.0 source
[framework/multimedia/gst-plugins-good0.10.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_pad_template (element_class,
106       gst_static_pad_template_get (&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) {
1204       GST_DEBUG_OBJECT (wav, "skipping %" GST_FOURCC_FORMAT " chunk",
1205           GST_FOURCC_ARGS (tag));
1206       gst_buffer_unref (buf);
1207       buf = NULL;
1208       continue;
1209     }
1210
1211     if (tag != GST_RIFF_TAG_fmt)
1212       goto invalid_wav;
1213
1214     if (!(gst_riff_parse_strf_auds (GST_ELEMENT_CAST (wav), buf, &header,
1215                 &extra)))
1216       goto parse_header_error;
1217
1218     buf = NULL;                 /* parse_strf_auds() took ownership of buffer */
1219
1220     /* do sanity checks of header fields */
1221     if (header->channels == 0)
1222       goto no_channels;
1223     if (header->rate == 0)
1224       goto no_rate;
1225
1226     GST_DEBUG_OBJECT (wav, "creating the caps");
1227
1228     /* Note: gst_riff_create_audio_caps might need to fix values in
1229      * the header header depending on the format, so call it first */
1230     caps = gst_riff_create_audio_caps (header->format, NULL, header, extra,
1231         NULL, &codec_name);
1232
1233     if (extra)
1234       gst_buffer_unref (extra);
1235
1236     if (!caps)
1237       goto unknown_format;
1238
1239     /* do more sanity checks of header fields
1240      * (these can be sanitized by gst_riff_create_audio_caps()
1241      */
1242     wav->format = header->format;
1243     wav->rate = header->rate;
1244     wav->channels = header->channels;
1245     wav->blockalign = header->blockalign;
1246     wav->depth = header->size;
1247     wav->av_bps = header->av_bps;
1248     wav->vbr = FALSE;
1249
1250     g_free (header);
1251     header = NULL;
1252
1253     /* do format specific handling */
1254     switch (wav->format) {
1255       case GST_RIFF_WAVE_FORMAT_MPEGL12:
1256       case GST_RIFF_WAVE_FORMAT_MPEGL3:
1257       {
1258         /* Note: workaround for mp2/mp3 embedded in wav, that relies on the
1259          * bitrate inside the mpeg stream */
1260         GST_INFO ("resetting bps from %d to 0 for mp2/3", wav->av_bps);
1261         wav->bps = 0;
1262         break;
1263       }
1264       case GST_RIFF_WAVE_FORMAT_PCM:
1265         if (wav->blockalign > wav->channels * (guint) ceil (wav->depth / 8.0))
1266           goto invalid_blockalign;
1267         /* fall through */
1268       default:
1269         if (wav->av_bps > wav->blockalign * wav->rate)
1270           goto invalid_bps;
1271         /* use the configured bps */
1272         wav->bps = wav->av_bps;
1273         break;
1274     }
1275
1276     wav->width = (wav->blockalign * 8) / wav->channels;
1277     wav->bytes_per_sample = wav->channels * wav->width / 8;
1278
1279     if (wav->bytes_per_sample <= 0)
1280       goto no_bytes_per_sample;
1281
1282     GST_DEBUG_OBJECT (wav, "blockalign = %u", (guint) wav->blockalign);
1283     GST_DEBUG_OBJECT (wav, "width      = %u", (guint) wav->width);
1284     GST_DEBUG_OBJECT (wav, "depth      = %u", (guint) wav->depth);
1285     GST_DEBUG_OBJECT (wav, "av_bps     = %u", (guint) wav->av_bps);
1286     GST_DEBUG_OBJECT (wav, "frequency  = %u", (guint) wav->rate);
1287     GST_DEBUG_OBJECT (wav, "channels   = %u", (guint) wav->channels);
1288     GST_DEBUG_OBJECT (wav, "bytes_per_sample = %u", wav->bytes_per_sample);
1289
1290     /* bps can be 0 when we don't have a valid bitrate (mostly for compressed
1291      * formats). This will make the element output a BYTE format segment and
1292      * will not timestamp the outgoing buffers.
1293      */
1294     GST_DEBUG_OBJECT (wav, "bps        = %u", (guint) wav->bps);
1295
1296     GST_DEBUG_OBJECT (wav, "caps = %" GST_PTR_FORMAT, caps);
1297
1298     /* create pad later so we can sniff the first few bytes
1299      * of the real data and correct our caps if necessary */
1300     gst_caps_replace (&wav->caps, caps);
1301     gst_caps_replace (&caps, NULL);
1302
1303     wav->got_fmt = TRUE;
1304
1305     if (codec_name) {
1306       wav->tags = gst_tag_list_new ();
1307
1308       gst_tag_list_add (wav->tags, GST_TAG_MERGE_REPLACE,
1309           GST_TAG_AUDIO_CODEC, codec_name, NULL);
1310
1311       g_free (codec_name);
1312       codec_name = NULL;
1313     }
1314
1315   }
1316
1317   bformat = GST_FORMAT_BYTES;
1318   gst_pad_query_peer_duration (wav->sinkpad, &bformat, &upstream_size);
1319   GST_DEBUG_OBJECT (wav, "upstream size %" G_GUINT64_FORMAT, upstream_size);
1320
1321   /* loop headers until we get data */
1322   while (!gotdata) {
1323     if (wav->streaming) {
1324       if (!gst_wavparse_peek_chunk_info (wav, &tag, &size))
1325         goto exit;
1326     } else {
1327       if ((res =
1328               gst_pad_pull_range (wav->sinkpad, wav->offset, 8,
1329                   &buf)) != GST_FLOW_OK)
1330         goto header_read_error;
1331       tag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
1332       size = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 4);
1333     }
1334
1335     GST_INFO_OBJECT (wav,
1336         "Got TAG: %" GST_FOURCC_FORMAT ", offset %" G_GUINT64_FORMAT,
1337         GST_FOURCC_ARGS (tag), wav->offset);
1338
1339     /* wav is a st00pid format, we don't know for sure where data starts.
1340      * So we have to go bit by bit until we find the 'data' header
1341      */
1342     switch (tag) {
1343       case GST_RIFF_TAG_data:{
1344         GST_DEBUG_OBJECT (wav, "Got 'data' TAG, size : %d", size);
1345         if (wav->streaming) {
1346           gst_adapter_flush (wav->adapter, 8);
1347           gotdata = TRUE;
1348         } else {
1349           gst_buffer_unref (buf);
1350         }
1351         wav->offset += 8;
1352         wav->datastart = wav->offset;
1353         /* If size is zero, then the data chunk probably actually extends to
1354            the end of the file */
1355         if (size == 0 && upstream_size) {
1356           size = upstream_size - wav->datastart;
1357         }
1358         /* Or the file might be truncated */
1359         else if (upstream_size) {
1360           size = MIN (size, (upstream_size - wav->datastart));
1361         }
1362         wav->datasize = (guint64) size;
1363         wav->dataleft = (guint64) size;
1364         wav->end_offset = size + wav->datastart;
1365         if (!wav->streaming) {
1366           /* We will continue parsing tags 'till end */
1367           wav->offset += size;
1368         }
1369         GST_DEBUG_OBJECT (wav, "datasize = %d", size);
1370         break;
1371       }
1372       case GST_RIFF_TAG_fact:{
1373         if (wav->format != GST_RIFF_WAVE_FORMAT_MPEGL12 &&
1374             wav->format != GST_RIFF_WAVE_FORMAT_MPEGL3) {
1375           const guint data_size = 4;
1376
1377           GST_INFO_OBJECT (wav, "Have fact chunk");
1378           if (size < data_size) {
1379             if (!gst_waveparse_ignore_chunk (wav, buf, tag, size)) {
1380               /* need more data */
1381               goto exit;
1382             }
1383             GST_DEBUG_OBJECT (wav, "need %d, available %d; ignoring chunk",
1384                 data_size, size);
1385             break;
1386           }
1387           /* number of samples (for compressed formats) */
1388           if (wav->streaming) {
1389             const guint8 *data = NULL;
1390
1391             if (!gst_wavparse_peek_chunk (wav, &tag, &size)) {
1392               goto exit;
1393             }
1394             gst_adapter_flush (wav->adapter, 8);
1395             data = gst_adapter_peek (wav->adapter, data_size);
1396             wav->fact = GST_READ_UINT32_LE (data);
1397             gst_adapter_flush (wav->adapter, GST_ROUND_UP_2 (size));
1398           } else {
1399             gst_buffer_unref (buf);
1400             if ((res =
1401                     gst_pad_pull_range (wav->sinkpad, wav->offset + 8,
1402                         data_size, &buf)) != GST_FLOW_OK)
1403               goto header_read_error;
1404             wav->fact = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf));
1405             gst_buffer_unref (buf);
1406           }
1407           GST_DEBUG_OBJECT (wav, "have fact %u", wav->fact);
1408           wav->offset += 8 + GST_ROUND_UP_2 (size);
1409           break;
1410         } else {
1411           if (!gst_waveparse_ignore_chunk (wav, buf, tag, size)) {
1412             /* need more data */
1413             goto exit;
1414           }
1415         }
1416         break;
1417       }
1418       case GST_RIFF_TAG_acid:{
1419         const gst_riff_acid *acid = NULL;
1420         const guint data_size = sizeof (gst_riff_acid);
1421
1422         GST_INFO_OBJECT (wav, "Have acid chunk");
1423         if (size < data_size) {
1424           if (!gst_waveparse_ignore_chunk (wav, buf, tag, size)) {
1425             /* need more data */
1426             goto exit;
1427           }
1428           GST_DEBUG_OBJECT (wav, "need %d, available %d; ignoring chunk",
1429               data_size, size);
1430           break;
1431         }
1432         if (wav->streaming) {
1433           if (!gst_wavparse_peek_chunk (wav, &tag, &size)) {
1434             goto exit;
1435           }
1436           gst_adapter_flush (wav->adapter, 8);
1437           acid = (const gst_riff_acid *) gst_adapter_peek (wav->adapter,
1438               data_size);
1439         } else {
1440           gst_buffer_unref (buf);
1441           if ((res =
1442                   gst_pad_pull_range (wav->sinkpad, wav->offset + 8,
1443                       size, &buf)) != GST_FLOW_OK)
1444             goto header_read_error;
1445           acid = (const gst_riff_acid *) GST_BUFFER_DATA (buf);
1446         }
1447         /* send data as tags */
1448         if (!wav->tags)
1449           wav->tags = gst_tag_list_new ();
1450         gst_tag_list_add (wav->tags, GST_TAG_MERGE_REPLACE,
1451             GST_TAG_BEATS_PER_MINUTE, acid->tempo, NULL);
1452
1453         size = GST_ROUND_UP_2 (size);
1454         if (wav->streaming) {
1455           gst_adapter_flush (wav->adapter, size);
1456         } else {
1457           gst_buffer_unref (buf);
1458         }
1459         wav->offset += 8 + size;
1460         break;
1461       }
1462         /* FIXME: all list tags after data are ignored in streaming mode */
1463       case GST_RIFF_TAG_LIST:{
1464         guint32 ltag;
1465
1466         if (wav->streaming) {
1467           const guint8 *data = NULL;
1468
1469           if (gst_adapter_available (wav->adapter) < 12) {
1470             goto exit;
1471           }
1472           data = gst_adapter_peek (wav->adapter, 12);
1473           ltag = GST_READ_UINT32_LE (data + 8);
1474         } else {
1475           gst_buffer_unref (buf);
1476           if ((res =
1477                   gst_pad_pull_range (wav->sinkpad, wav->offset, 12,
1478                       &buf)) != GST_FLOW_OK)
1479             goto header_read_error;
1480           ltag = GST_READ_UINT32_LE (GST_BUFFER_DATA (buf) + 8);
1481         }
1482         switch (ltag) {
1483           case GST_RIFF_LIST_INFO:{
1484             const gint data_size = size - 4;
1485             GstTagList *new;
1486
1487             GST_INFO_OBJECT (wav, "Have LIST chunk INFO size %u", data_size);
1488             if (wav->streaming) {
1489               if (!gst_wavparse_peek_chunk (wav, &tag, &size)) {
1490                 goto exit;
1491               }
1492               gst_adapter_flush (wav->adapter, 12);
1493               wav->offset += 12;
1494               if (data_size > 0) {
1495                 buf = gst_adapter_take_buffer (wav->adapter, data_size);
1496                 if (data_size & 1)
1497                   gst_adapter_flush (wav->adapter, 1);
1498               }
1499             } else {
1500               wav->offset += 12;
1501               gst_buffer_unref (buf);
1502               if (data_size > 0) {
1503                 if ((res =
1504                         gst_pad_pull_range (wav->sinkpad, wav->offset,
1505                             data_size, &buf)) != GST_FLOW_OK)
1506                   goto header_read_error;
1507               }
1508             }
1509             if (data_size > 0) {
1510               /* parse tags */
1511               gst_riff_parse_info (GST_ELEMENT (wav), buf, &new);
1512               if (new) {
1513                 GstTagList *old = wav->tags;
1514                 wav->tags =
1515                     gst_tag_list_merge (old, new, GST_TAG_MERGE_REPLACE);
1516                 if (old)
1517                   gst_tag_list_free (old);
1518                 gst_tag_list_free (new);
1519               }
1520               gst_buffer_unref (buf);
1521               wav->offset += GST_ROUND_UP_2 (data_size);
1522             }
1523             break;
1524           }
1525           default:
1526             GST_INFO_OBJECT (wav, "Ignoring LIST chunk %" GST_FOURCC_FORMAT,
1527                 GST_FOURCC_ARGS (ltag));
1528             if (!gst_waveparse_ignore_chunk (wav, buf, tag, size))
1529               /* need more data */
1530               goto exit;
1531             break;
1532         }
1533         break;
1534       }
1535       default:
1536         if (!gst_waveparse_ignore_chunk (wav, buf, tag, size))
1537           /* need more data */
1538           goto exit;
1539         break;
1540     }
1541
1542     if (upstream_size && (wav->offset >= upstream_size)) {
1543       /* Now we are gone through the whole file */
1544       gotdata = TRUE;
1545     }
1546   }
1547
1548   GST_DEBUG_OBJECT (wav, "Finished parsing headers");
1549
1550   if (wav->bps <= 0 && wav->fact) {
1551 #if 0
1552     /* not a good idea, as for embedded mp2/mp3 we set bps to 0 earlier */
1553     wav->bps =
1554         (guint32) gst_util_uint64_scale ((guint64) wav->rate, wav->datasize,
1555         (guint64) wav->fact);
1556     GST_INFO_OBJECT (wav, "calculated bps : %d, enabling VBR", wav->bps);
1557 #endif
1558     wav->vbr = TRUE;
1559   }
1560
1561   if (gst_wavparse_calculate_duration (wav)) {
1562     gst_segment_init (&wav->segment, GST_FORMAT_TIME);
1563     gst_segment_set_duration (&wav->segment, GST_FORMAT_TIME, wav->duration);
1564   } else {
1565     /* no bitrate, let downstream peer do the math, we'll feed it bytes. */
1566     gst_segment_init (&wav->segment, GST_FORMAT_BYTES);
1567     gst_segment_set_duration (&wav->segment, GST_FORMAT_BYTES, wav->datasize);
1568   }
1569
1570   /* now we have all the info to perform a pending seek if any, if no
1571    * event, this will still do the right thing and it will also send
1572    * the right newsegment event downstream. */
1573   gst_wavparse_perform_seek (wav, wav->seek_event);
1574   /* remove pending event */
1575   event_p = &wav->seek_event;
1576   gst_event_replace (event_p, NULL);
1577
1578   /* we just started, we are discont */
1579   wav->discont = TRUE;
1580
1581   wav->state = GST_WAVPARSE_DATA;
1582
1583   /* determine reasonable max buffer size,
1584    * that is, buffers not too small either size or time wise
1585    * so we do not end up with too many of them */
1586   /* var abuse */
1587   upstream_size = 0;
1588   gst_wavparse_time_to_bytepos (wav, 40 * GST_MSECOND, &upstream_size);
1589   wav->max_buf_size = upstream_size;
1590   wav->max_buf_size = MAX (wav->max_buf_size, MAX_BUFFER_SIZE);
1591   if (wav->blockalign > 0)
1592     wav->max_buf_size -= (wav->max_buf_size % wav->blockalign);
1593
1594   GST_DEBUG_OBJECT (wav, "max buffer size %d", wav->max_buf_size);
1595
1596   return GST_FLOW_OK;
1597
1598   /* ERROR */
1599 exit:
1600   {
1601     if (codec_name)
1602       g_free (codec_name);
1603     if (header)
1604       g_free (header);
1605     if (caps)
1606       gst_caps_unref (caps);
1607     return res;
1608   }
1609 fail:
1610   {
1611     res = GST_FLOW_ERROR;
1612     goto exit;
1613   }
1614 invalid_wav:
1615   {
1616     GST_ELEMENT_ERROR (wav, STREAM, TYPE_NOT_FOUND, (NULL),
1617         ("Invalid WAV header (no fmt at start): %"
1618             GST_FOURCC_FORMAT, GST_FOURCC_ARGS (tag)));
1619     goto fail;
1620   }
1621 parse_header_error:
1622   {
1623     GST_ELEMENT_ERROR (wav, STREAM, DEMUX, (NULL),
1624         ("Couldn't parse audio header"));
1625     goto fail;
1626   }
1627 no_channels:
1628   {
1629     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1630         ("Stream claims to contain no channels - invalid data"));
1631     goto fail;
1632   }
1633 no_rate:
1634   {
1635     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1636         ("Stream with sample_rate == 0 - invalid data"));
1637     goto fail;
1638   }
1639 invalid_blockalign:
1640   {
1641     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1642         ("Stream claims blockalign = %u, which is more than %u - invalid data",
1643             wav->blockalign, wav->channels * (guint) ceil (wav->depth / 8.0)));
1644     goto fail;
1645   }
1646 invalid_bps:
1647   {
1648     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1649         ("Stream claims av_bsp = %u, which is more than %u - invalid data",
1650             wav->av_bps, wav->blockalign * wav->rate));
1651     goto fail;
1652   }
1653 no_bytes_per_sample:
1654   {
1655     GST_ELEMENT_ERROR (wav, STREAM, FAILED, (NULL),
1656         ("Could not caluclate bytes per sample - invalid data"));
1657     goto fail;
1658   }
1659 unknown_format:
1660   {
1661     GST_ELEMENT_ERROR (wav, STREAM, TYPE_NOT_FOUND, (NULL),
1662         ("No caps found for format 0x%x, %d channels, %d Hz",
1663             wav->format, wav->channels, wav->rate));
1664     goto fail;
1665   }
1666 header_read_error:
1667   {
1668     GST_ELEMENT_ERROR (wav, STREAM, DEMUX, (NULL),
1669         ("Couldn't read in header %d (%s)", res, gst_flow_get_name (res)));
1670     goto fail;
1671   }
1672 }
1673
1674 /*
1675  * Read WAV file tag when streaming
1676  */
1677 static GstFlowReturn
1678 gst_wavparse_parse_stream_init (GstWavParse * wav)
1679 {
1680   if (gst_adapter_available (wav->adapter) >= 12) {
1681     GstBuffer *tmp;
1682
1683     /* _take flushes the data */
1684     tmp = gst_adapter_take_buffer (wav->adapter, 12);
1685
1686     GST_DEBUG ("Parsing wav header");
1687     if (!gst_wavparse_parse_file_header (GST_ELEMENT_CAST (wav), tmp))
1688       return GST_FLOW_ERROR;
1689
1690     wav->offset += 12;
1691     /* Go to next state */
1692     wav->state = GST_WAVPARSE_HEADER;
1693   }
1694   return GST_FLOW_OK;
1695 }
1696
1697 /* handle an event sent directly to the element.
1698  *
1699  * This event can be sent either in the READY state or the
1700  * >READY state. The only event of interest really is the seek
1701  * event.
1702  *
1703  * In the READY state we can only store the event and try to
1704  * respect it when going to PAUSED. We assume we are in the
1705  * READY state when our parsing state != GST_WAVPARSE_DATA.
1706  *
1707  * When we are steaming, we can simply perform the seek right
1708  * away.
1709  */
1710 static gboolean
1711 gst_wavparse_send_event (GstElement * element, GstEvent * event)
1712 {
1713   GstWavParse *wav = GST_WAVPARSE (element);
1714   gboolean res = FALSE;
1715   GstEvent **event_p;
1716
1717   GST_DEBUG_OBJECT (wav, "received event %s", GST_EVENT_TYPE_NAME (event));
1718
1719   switch (GST_EVENT_TYPE (event)) {
1720     case GST_EVENT_SEEK:
1721       if (wav->state == GST_WAVPARSE_DATA) {
1722         /* we can handle the seek directly when streaming data */
1723         res = gst_wavparse_perform_seek (wav, event);
1724       } else {
1725         GST_DEBUG_OBJECT (wav, "queuing seek for later");
1726
1727         event_p = &wav->seek_event;
1728         gst_event_replace (event_p, event);
1729
1730         /* we always return true */
1731         res = TRUE;
1732       }
1733       break;
1734     default:
1735       break;
1736   }
1737   gst_event_unref (event);
1738   return res;
1739 }
1740
1741 static gboolean
1742 gst_wavparse_have_dts_caps (const GstCaps * caps, GstTypeFindProbability prob)
1743 {
1744   GstStructure *s;
1745
1746   s = gst_caps_get_structure (caps, 0);
1747   if (!gst_structure_has_name (s, "audio/x-dts"))
1748     return FALSE;
1749   if (prob >= GST_TYPE_FIND_LIKELY)
1750     return TRUE;
1751   /* DTS at non-0 offsets and without second sync may yield POSSIBLE .. */
1752   if (prob < GST_TYPE_FIND_POSSIBLE)
1753     return FALSE;
1754   /* .. in which case we want at least a valid-looking rate and channels */
1755   if (!gst_structure_has_field (s, "channels"))
1756     return FALSE;
1757   /* and for extra assurance we could also check the rate from the DTS frame
1758    * against the one in the wav header, but for now let's not do that */
1759   return gst_structure_has_field (s, "rate");
1760 }
1761
1762 static void
1763 gst_wavparse_add_src_pad (GstWavParse * wav, GstBuffer * buf)
1764 {
1765   GstStructure *s;
1766
1767   GST_DEBUG_OBJECT (wav, "adding src pad");
1768
1769   if (wav->caps) {
1770     s = gst_caps_get_structure (wav->caps, 0);
1771     if (s && gst_structure_has_name (s, "audio/x-raw-int") && buf != NULL) {
1772       GstTypeFindProbability prob;
1773       GstCaps *tf_caps;
1774
1775       tf_caps = gst_type_find_helper_for_buffer (GST_OBJECT (wav), buf, &prob);
1776       if (tf_caps != NULL) {
1777         GST_LOG ("typefind caps = %" GST_PTR_FORMAT ", P=%d", tf_caps, prob);
1778         if (gst_wavparse_have_dts_caps (tf_caps, prob)) {
1779           GST_INFO_OBJECT (wav, "Found DTS marker in file marked as raw PCM");
1780           gst_caps_unref (wav->caps);
1781           wav->caps = tf_caps;
1782
1783           gst_tag_list_add (wav->tags, GST_TAG_MERGE_REPLACE,
1784               GST_TAG_AUDIO_CODEC, "dts", NULL);
1785         } else {
1786           GST_DEBUG_OBJECT (wav, "found caps %" GST_PTR_FORMAT " for stream "
1787               "marked as raw PCM audio, but ignoring for now", tf_caps);
1788           gst_caps_unref (tf_caps);
1789         }
1790       }
1791     }
1792   }
1793
1794   gst_wavparse_create_sourcepad (wav);
1795   gst_pad_set_active (wav->srcpad, TRUE);
1796   gst_pad_set_caps (wav->srcpad, wav->caps);
1797   gst_caps_replace (&wav->caps, NULL);
1798
1799   gst_element_add_pad (GST_ELEMENT_CAST (wav), wav->srcpad);
1800   gst_element_no_more_pads (GST_ELEMENT_CAST (wav));
1801
1802   if (wav->close_segment) {
1803     GST_DEBUG_OBJECT (wav, "Send close segment event on newpad");
1804     gst_pad_push_event (wav->srcpad, wav->close_segment);
1805     wav->close_segment = NULL;
1806   }
1807   if (wav->start_segment) {
1808     GST_DEBUG_OBJECT (wav, "Send start segment event on newpad");
1809     gst_pad_push_event (wav->srcpad, wav->start_segment);
1810     wav->start_segment = NULL;
1811   }
1812
1813   if (wav->tags) {
1814     gst_element_found_tags_for_pad (GST_ELEMENT_CAST (wav), wav->srcpad,
1815         wav->tags);
1816     wav->tags = NULL;
1817   }
1818 }
1819
1820 static GstFlowReturn
1821 gst_wavparse_stream_data (GstWavParse * wav)
1822 {
1823   GstBuffer *buf = NULL;
1824   GstFlowReturn res = GST_FLOW_OK;
1825   guint64 desired, obtained;
1826   GstClockTime timestamp, next_timestamp, duration;
1827   guint64 pos, nextpos;
1828
1829 iterate_adapter:
1830   GST_LOG_OBJECT (wav,
1831       "offset: %" G_GINT64_FORMAT " , end: %" G_GINT64_FORMAT " , dataleft: %"
1832       G_GINT64_FORMAT, wav->offset, wav->end_offset, wav->dataleft);
1833
1834   /* Get the next n bytes and output them */
1835   if (wav->dataleft == 0 || wav->dataleft < wav->blockalign)
1836     goto found_eos;
1837
1838   /* scale the amount of data by the segment rate so we get equal
1839    * amounts of data regardless of the playback rate */
1840   desired =
1841       MIN (gst_guint64_to_gdouble (wav->dataleft),
1842       wav->max_buf_size * wav->segment.abs_rate);
1843
1844   if (desired >= wav->blockalign && wav->blockalign > 0)
1845     desired -= (desired % wav->blockalign);
1846
1847   GST_LOG_OBJECT (wav, "Fetching %" G_GINT64_FORMAT " bytes of data "
1848       "from the sinkpad", desired);
1849
1850   if (wav->streaming) {
1851     guint avail = gst_adapter_available (wav->adapter);
1852     guint extra;
1853
1854     /* flush some bytes if evil upstream sends segment that starts
1855      * before data or does is not send sample aligned segment */
1856     if (G_LIKELY (wav->offset >= wav->datastart)) {
1857       extra = (wav->offset - wav->datastart) % wav->bytes_per_sample;
1858     } else {
1859       extra = wav->datastart - wav->offset;
1860     }
1861
1862     if (G_UNLIKELY (extra)) {
1863       extra = wav->bytes_per_sample - extra;
1864       if (extra <= avail) {
1865         GST_DEBUG_OBJECT (wav, "flushing %d bytes to sample boundary", extra);
1866         gst_adapter_flush (wav->adapter, extra);
1867         wav->offset += extra;
1868         wav->dataleft -= extra;
1869         goto iterate_adapter;
1870       } else {
1871         GST_DEBUG_OBJECT (wav, "flushing %d bytes", avail);
1872         gst_adapter_clear (wav->adapter);
1873         wav->offset += avail;
1874         wav->dataleft -= avail;
1875         return GST_FLOW_OK;
1876       }
1877     }
1878
1879     if (avail < desired) {
1880       GST_LOG_OBJECT (wav, "Got only %d bytes of data from the sinkpad", avail);
1881       return GST_FLOW_OK;
1882     }
1883
1884     buf = gst_adapter_take_buffer (wav->adapter, desired);
1885   } else {
1886     if ((res = gst_pad_pull_range (wav->sinkpad, wav->offset,
1887                 desired, &buf)) != GST_FLOW_OK)
1888       goto pull_error;
1889
1890     /* we may get a short buffer at the end of the file */
1891     if (GST_BUFFER_SIZE (buf) < desired) {
1892       GST_LOG_OBJECT (wav, "Got only %u bytes of data", GST_BUFFER_SIZE (buf));
1893       if (GST_BUFFER_SIZE (buf) >= wav->blockalign) {
1894         buf = gst_buffer_make_metadata_writable (buf);
1895         GST_BUFFER_SIZE (buf) -= (GST_BUFFER_SIZE (buf) % wav->blockalign);
1896       } else {
1897         gst_buffer_unref (buf);
1898         goto found_eos;
1899       }
1900     }
1901   }
1902
1903   obtained = GST_BUFFER_SIZE (buf);
1904
1905   /* our positions in bytes */
1906   pos = wav->offset - wav->datastart;
1907   nextpos = pos + obtained;
1908
1909   /* update offsets, does not overflow. */
1910   GST_BUFFER_OFFSET (buf) = pos / wav->bytes_per_sample;
1911   GST_BUFFER_OFFSET_END (buf) = nextpos / wav->bytes_per_sample;
1912
1913   /* first chunk of data? create the source pad. We do this only here so
1914    * we can detect broken .wav files with dts disguised as raw PCM (sigh) */
1915   if (G_UNLIKELY (wav->first)) {
1916     wav->first = FALSE;
1917     /* this will also push the segment events */
1918     gst_wavparse_add_src_pad (wav, buf);
1919   } else {
1920     /* If we have a pending close/start segment, send it now. */
1921     if (G_UNLIKELY (wav->close_segment != NULL)) {
1922       gst_pad_push_event (wav->srcpad, wav->close_segment);
1923       wav->close_segment = NULL;
1924     }
1925     if (G_UNLIKELY (wav->start_segment != NULL)) {
1926       gst_pad_push_event (wav->srcpad, wav->start_segment);
1927       wav->start_segment = NULL;
1928     }
1929   }
1930
1931   if (wav->bps > 0) {
1932     /* and timestamps if we have a bitrate, be careful for overflows */
1933     timestamp = uint64_ceiling_scale (pos, GST_SECOND, (guint64) wav->bps);
1934     next_timestamp =
1935         uint64_ceiling_scale (nextpos, GST_SECOND, (guint64) wav->bps);
1936     duration = next_timestamp - timestamp;
1937
1938     /* update current running segment position */
1939     if (G_LIKELY (next_timestamp >= wav->segment.start))
1940       gst_segment_set_last_stop (&wav->segment, GST_FORMAT_TIME,
1941           next_timestamp);
1942   } else if (wav->fact) {
1943     guint64 bps =
1944         gst_util_uint64_scale_int (wav->datasize, wav->rate, wav->fact);
1945     /* and timestamps if we have a bitrate, be careful for overflows */
1946     timestamp = uint64_ceiling_scale (pos, GST_SECOND, bps);
1947     next_timestamp = uint64_ceiling_scale (nextpos, GST_SECOND, bps);
1948     duration = next_timestamp - timestamp;
1949   } else {
1950     /* no bitrate, all we know is that the first sample has timestamp 0, all
1951      * other positions and durations have unknown timestamp. */
1952     if (pos == 0)
1953       timestamp = 0;
1954     else
1955       timestamp = GST_CLOCK_TIME_NONE;
1956     duration = GST_CLOCK_TIME_NONE;
1957     /* update current running segment position with byte offset */
1958     if (G_LIKELY (nextpos >= wav->segment.start))
1959       gst_segment_set_last_stop (&wav->segment, GST_FORMAT_BYTES, nextpos);
1960   }
1961   if ((pos > 0) && wav->vbr) {
1962     /* don't set timestamps for VBR files if it's not the first buffer */
1963     timestamp = GST_CLOCK_TIME_NONE;
1964     duration = GST_CLOCK_TIME_NONE;
1965   }
1966   if (wav->discont) {
1967     GST_DEBUG_OBJECT (wav, "marking DISCONT");
1968     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1969     wav->discont = FALSE;
1970   }
1971
1972   GST_BUFFER_TIMESTAMP (buf) = timestamp;
1973   GST_BUFFER_DURATION (buf) = duration;
1974
1975   /* don't forget to set the caps on the buffer */
1976   gst_buffer_set_caps (buf, GST_PAD_CAPS (wav->srcpad));
1977
1978   GST_LOG_OBJECT (wav,
1979       "Got buffer. timestamp:%" GST_TIME_FORMAT " , duration:%" GST_TIME_FORMAT
1980       ", size:%u", GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration),
1981       GST_BUFFER_SIZE (buf));
1982
1983   if ((res = gst_pad_push (wav->srcpad, buf)) != GST_FLOW_OK)
1984     goto push_error;
1985
1986   if (obtained < wav->dataleft) {
1987     wav->offset += obtained;
1988     wav->dataleft -= obtained;
1989   } else {
1990     wav->offset += wav->dataleft;
1991     wav->dataleft = 0;
1992   }
1993
1994   /* Iterate until need more data, so adapter size won't grow */
1995   if (wav->streaming) {
1996     GST_LOG_OBJECT (wav,
1997         "offset: %" G_GINT64_FORMAT " , end: %" G_GINT64_FORMAT, wav->offset,
1998         wav->end_offset);
1999     goto iterate_adapter;
2000   }
2001   return res;
2002
2003   /* ERROR */
2004 found_eos:
2005   {
2006     GST_DEBUG_OBJECT (wav, "found EOS");
2007     return GST_FLOW_UNEXPECTED;
2008   }
2009 pull_error:
2010   {
2011     /* check if we got EOS */
2012     if (res == GST_FLOW_UNEXPECTED)
2013       goto found_eos;
2014
2015     GST_WARNING_OBJECT (wav,
2016         "Error getting %" G_GINT64_FORMAT " bytes from the "
2017         "sinkpad (dataleft = %" G_GINT64_FORMAT ")", desired, wav->dataleft);
2018     return res;
2019   }
2020 push_error:
2021   {
2022     GST_INFO_OBJECT (wav,
2023         "Error pushing on srcpad %s:%s, reason %s, is linked? = %d",
2024         GST_DEBUG_PAD_NAME (wav->srcpad), gst_flow_get_name (res),
2025         gst_pad_is_linked (wav->srcpad));
2026     return res;
2027   }
2028 }
2029
2030 static void
2031 gst_wavparse_loop (GstPad * pad)
2032 {
2033   GstFlowReturn ret;
2034   GstWavParse *wav = GST_WAVPARSE (GST_PAD_PARENT (pad));
2035
2036   GST_LOG_OBJECT (wav, "process data");
2037
2038   switch (wav->state) {
2039     case GST_WAVPARSE_START:
2040       GST_INFO_OBJECT (wav, "GST_WAVPARSE_START");
2041       if ((ret = gst_wavparse_stream_init (wav)) != GST_FLOW_OK)
2042         goto pause;
2043
2044       wav->state = GST_WAVPARSE_HEADER;
2045       /* fall-through */
2046
2047     case GST_WAVPARSE_HEADER:
2048       GST_INFO_OBJECT (wav, "GST_WAVPARSE_HEADER");
2049       if ((ret = gst_wavparse_stream_headers (wav)) != GST_FLOW_OK)
2050         goto pause;
2051
2052       wav->state = GST_WAVPARSE_DATA;
2053       GST_INFO_OBJECT (wav, "GST_WAVPARSE_DATA");
2054       /* fall-through */
2055
2056     case GST_WAVPARSE_DATA:
2057       if ((ret = gst_wavparse_stream_data (wav)) != GST_FLOW_OK)
2058         goto pause;
2059       break;
2060     default:
2061       g_assert_not_reached ();
2062   }
2063   return;
2064
2065   /* ERRORS */
2066 pause:
2067   {
2068     const gchar *reason = gst_flow_get_name (ret);
2069
2070     GST_DEBUG_OBJECT (wav, "pausing task, reason %s", reason);
2071     wav->segment_running = FALSE;
2072     gst_pad_pause_task (pad);
2073
2074     if (ret == GST_FLOW_UNEXPECTED) {
2075       /* add pad before we perform EOS */
2076       if (G_UNLIKELY (wav->first)) {
2077         wav->first = FALSE;
2078         gst_wavparse_add_src_pad (wav, NULL);
2079       }
2080
2081       if (wav->state == GST_WAVPARSE_START)
2082         GST_ELEMENT_ERROR (wav, STREAM, WRONG_TYPE,
2083             ("No valid input found before end of stream"), (NULL));
2084
2085       /* perform EOS logic */
2086       if (wav->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2087         GstClockTime stop;
2088
2089         if ((stop = wav->segment.stop) == -1)
2090           stop = wav->segment.duration;
2091
2092         gst_element_post_message (GST_ELEMENT_CAST (wav),
2093             gst_message_new_segment_done (GST_OBJECT_CAST (wav),
2094                 wav->segment.format, stop));
2095       } else {
2096         if (wav->srcpad != NULL)
2097           gst_pad_push_event (wav->srcpad, gst_event_new_eos ());
2098       }
2099     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2100       /* for fatal errors we post an error message, post the error
2101        * first so the app knows about the error first. */
2102       GST_ELEMENT_ERROR (wav, STREAM, FAILED,
2103           (_("Internal data flow error.")),
2104           ("streaming task paused, reason %s (%d)", reason, ret));
2105       if (wav->srcpad != NULL)
2106         gst_pad_push_event (wav->srcpad, gst_event_new_eos ());
2107     }
2108     return;
2109   }
2110 }
2111
2112 static GstFlowReturn
2113 gst_wavparse_chain (GstPad * pad, GstBuffer * buf)
2114 {
2115   GstFlowReturn ret;
2116   GstWavParse *wav = GST_WAVPARSE (GST_PAD_PARENT (pad));
2117
2118   GST_LOG_OBJECT (wav, "adapter_push %u bytes", GST_BUFFER_SIZE (buf));
2119
2120   gst_adapter_push (wav->adapter, buf);
2121
2122   switch (wav->state) {
2123     case GST_WAVPARSE_START:
2124       GST_INFO_OBJECT (wav, "GST_WAVPARSE_START");
2125       if ((ret = gst_wavparse_parse_stream_init (wav)) != GST_FLOW_OK)
2126         goto done;
2127
2128       if (wav->state != GST_WAVPARSE_HEADER)
2129         break;
2130
2131       /* otherwise fall-through */
2132     case GST_WAVPARSE_HEADER:
2133       GST_INFO_OBJECT (wav, "GST_WAVPARSE_HEADER");
2134       if ((ret = gst_wavparse_stream_headers (wav)) != GST_FLOW_OK)
2135         goto done;
2136
2137       if (!wav->got_fmt || wav->datastart == 0)
2138         break;
2139
2140       wav->state = GST_WAVPARSE_DATA;
2141       GST_INFO_OBJECT (wav, "GST_WAVPARSE_DATA");
2142
2143       /* fall-through */
2144     case GST_WAVPARSE_DATA:
2145       if (buf && GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT))
2146         wav->discont = TRUE;
2147       if ((ret = gst_wavparse_stream_data (wav)) != GST_FLOW_OK)
2148         goto done;
2149       break;
2150     default:
2151       g_return_val_if_reached (GST_FLOW_ERROR);
2152   }
2153 done:
2154   if (G_UNLIKELY (wav->abort_buffering)) {
2155     wav->abort_buffering = FALSE;
2156     ret = GST_FLOW_ERROR;
2157     /* sort of demux/parse error */
2158     GST_ELEMENT_ERROR (wav, STREAM, DEMUX, (NULL), ("unhandled buffer size"));
2159   }
2160
2161   return ret;
2162 }
2163
2164 static GstFlowReturn
2165 gst_wavparse_flush_data (GstWavParse * wav)
2166 {
2167   GstFlowReturn ret = GST_FLOW_OK;
2168   guint av;
2169
2170   if ((av = gst_adapter_available (wav->adapter)) > 0) {
2171     wav->dataleft = av;
2172     wav->end_offset = wav->offset + av;
2173     ret = gst_wavparse_stream_data (wav);
2174   }
2175
2176   return ret;
2177 }
2178
2179 static gboolean
2180 gst_wavparse_sink_event (GstPad * pad, GstEvent * event)
2181 {
2182   GstWavParse *wav = GST_WAVPARSE (GST_PAD_PARENT (pad));
2183   gboolean ret = TRUE;
2184
2185   GST_LOG_OBJECT (wav, "handling %s event", GST_EVENT_TYPE_NAME (event));
2186
2187   switch (GST_EVENT_TYPE (event)) {
2188     case GST_EVENT_NEWSEGMENT:
2189     {
2190       GstFormat format;
2191       gdouble rate, arate;
2192       gint64 start, stop, time, offset = 0, end_offset = -1;
2193       gboolean update;
2194       GstSegment segment;
2195
2196       /* some debug output */
2197       gst_segment_init (&segment, GST_FORMAT_UNDEFINED);
2198       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
2199           &start, &stop, &time);
2200       gst_segment_set_newsegment_full (&segment, update, rate, arate, format,
2201           start, stop, time);
2202       GST_DEBUG_OBJECT (wav,
2203           "received format %d newsegment %" GST_SEGMENT_FORMAT, format,
2204           &segment);
2205
2206       if (wav->state != GST_WAVPARSE_DATA) {
2207         GST_DEBUG_OBJECT (wav, "still starting, eating event");
2208         goto exit;
2209       }
2210
2211       /* now we are either committed to TIME or BYTE format,
2212        * and we only expect a BYTE segment, e.g. following a seek */
2213       if (format == GST_FORMAT_BYTES) {
2214         if (start > 0) {
2215           offset = start;
2216           start -= wav->datastart;
2217           start = MAX (start, 0);
2218         }
2219         if (stop > 0) {
2220           end_offset = stop;
2221           stop -= wav->datastart;
2222           stop = MAX (stop, 0);
2223         }
2224         if (wav->segment.format == GST_FORMAT_TIME) {
2225           guint64 bps = wav->bps;
2226
2227           /* operating in format TIME, so we can convert */
2228           if (!bps && wav->fact)
2229             bps =
2230                 gst_util_uint64_scale_int (wav->datasize, wav->rate, wav->fact);
2231           if (bps) {
2232             if (start >= 0)
2233               start =
2234                   uint64_ceiling_scale (start, GST_SECOND, (guint64) wav->bps);
2235             if (stop >= 0)
2236               stop =
2237                   uint64_ceiling_scale (stop, GST_SECOND, (guint64) wav->bps);
2238           }
2239         }
2240       } else {
2241         GST_DEBUG_OBJECT (wav, "unsupported segment format, ignoring");
2242         goto exit;
2243       }
2244
2245       /* accept upstream's notion of segment and distribute along */
2246       gst_segment_set_newsegment_full (&wav->segment, update, rate, arate,
2247           wav->segment.format, start, stop, start);
2248       /* also store the newsegment event for the streaming thread */
2249       if (wav->start_segment)
2250         gst_event_unref (wav->start_segment);
2251       wav->start_segment =
2252           gst_event_new_new_segment_full (update, rate, arate,
2253           wav->segment.format, start, stop, start);
2254       GST_DEBUG_OBJECT (wav, "Pushing newseg update %d, rate %g, "
2255           "applied rate %g, format %d, start %" G_GINT64_FORMAT ", "
2256           "stop %" G_GINT64_FORMAT, update, rate, arate, wav->segment.format,
2257           start, stop);
2258
2259       /* stream leftover data in current segment */
2260       gst_wavparse_flush_data (wav);
2261       /* and set up streaming thread for next one */
2262       wav->offset = offset;
2263       wav->end_offset = end_offset;
2264       if (wav->end_offset > 0) {
2265         wav->dataleft = wav->end_offset - wav->offset;
2266       } else {
2267         /* infinity; upstream will EOS when done */
2268         wav->dataleft = G_MAXUINT64;
2269       }
2270     exit:
2271       gst_event_unref (event);
2272       break;
2273     }
2274     case GST_EVENT_EOS:
2275       /* add pad if needed so EOS is seen downstream */
2276       if (G_UNLIKELY (wav->first)) {
2277         wav->first = FALSE;
2278         gst_wavparse_add_src_pad (wav, NULL);
2279       } else {
2280         /* stream leftover data in current segment */
2281         gst_wavparse_flush_data (wav);
2282       }
2283
2284       if (wav->state == GST_WAVPARSE_START)
2285         GST_ELEMENT_ERROR (wav, STREAM, WRONG_TYPE,
2286             ("No valid input found before end of stream"), (NULL));
2287
2288       /* fall-through */
2289     case GST_EVENT_FLUSH_STOP:
2290       gst_adapter_clear (wav->adapter);
2291       wav->discont = TRUE;
2292       /* fall-through */
2293     default:
2294       ret = gst_pad_event_default (wav->sinkpad, event);
2295       break;
2296   }
2297
2298   return ret;
2299 }
2300
2301 #if 0
2302 /* convert and query stuff */
2303 static const GstFormat *
2304 gst_wavparse_get_formats (GstPad * pad)
2305 {
2306   static GstFormat formats[] = {
2307     GST_FORMAT_TIME,
2308     GST_FORMAT_BYTES,
2309     GST_FORMAT_DEFAULT,         /* a "frame", ie a set of samples per Hz */
2310     0
2311   };
2312
2313   return formats;
2314 }
2315 #endif
2316
2317 static gboolean
2318 gst_wavparse_pad_convert (GstPad * pad,
2319     GstFormat src_format, gint64 src_value,
2320     GstFormat * dest_format, gint64 * dest_value)
2321 {
2322   GstWavParse *wavparse;
2323   gboolean res = TRUE;
2324
2325   wavparse = GST_WAVPARSE (GST_PAD_PARENT (pad));
2326
2327   if (*dest_format == src_format) {
2328     *dest_value = src_value;
2329     return TRUE;
2330   }
2331
2332   if ((wavparse->bps == 0) && !wavparse->fact)
2333     goto no_bps_fact;
2334
2335   GST_INFO_OBJECT (wavparse, "converting value from %s to %s",
2336       gst_format_get_name (src_format), gst_format_get_name (*dest_format));
2337
2338   switch (src_format) {
2339     case GST_FORMAT_BYTES:
2340       switch (*dest_format) {
2341         case GST_FORMAT_DEFAULT:
2342           *dest_value = src_value / wavparse->bytes_per_sample;
2343           /* make sure we end up on a sample boundary */
2344           *dest_value -= *dest_value % wavparse->bytes_per_sample;
2345           break;
2346         case GST_FORMAT_TIME:
2347           /* src_value + datastart = offset */
2348           GST_INFO_OBJECT (wavparse,
2349               "src=%" G_GINT64_FORMAT ", offset=%" G_GINT64_FORMAT, src_value,
2350               wavparse->offset);
2351           if (wavparse->bps > 0)
2352             *dest_value = uint64_ceiling_scale (src_value, GST_SECOND,
2353                 (guint64) wavparse->bps);
2354           else if (wavparse->fact) {
2355             guint64 bps = uint64_ceiling_scale_int (wavparse->datasize,
2356                 wavparse->rate, wavparse->fact);
2357
2358             *dest_value = uint64_ceiling_scale_int (src_value, GST_SECOND, bps);
2359           } else {
2360             res = FALSE;
2361           }
2362           break;
2363         default:
2364           res = FALSE;
2365           goto done;
2366       }
2367       break;
2368
2369     case GST_FORMAT_DEFAULT:
2370       switch (*dest_format) {
2371         case GST_FORMAT_BYTES:
2372           *dest_value = src_value * wavparse->bytes_per_sample;
2373           break;
2374         case GST_FORMAT_TIME:
2375           *dest_value = gst_util_uint64_scale (src_value, GST_SECOND,
2376               (guint64) wavparse->rate);
2377           break;
2378         default:
2379           res = FALSE;
2380           goto done;
2381       }
2382       break;
2383
2384     case GST_FORMAT_TIME:
2385       switch (*dest_format) {
2386         case GST_FORMAT_BYTES:
2387           if (wavparse->bps > 0)
2388             *dest_value = gst_util_uint64_scale (src_value,
2389                 (guint64) wavparse->bps, GST_SECOND);
2390           else {
2391             guint64 bps = gst_util_uint64_scale_int (wavparse->datasize,
2392                 wavparse->rate, wavparse->fact);
2393
2394             *dest_value = gst_util_uint64_scale (src_value, bps, GST_SECOND);
2395           }
2396           /* make sure we end up on a sample boundary */
2397           *dest_value -= *dest_value % wavparse->blockalign;
2398           break;
2399         case GST_FORMAT_DEFAULT:
2400           *dest_value = gst_util_uint64_scale (src_value,
2401               (guint64) wavparse->rate, GST_SECOND);
2402           break;
2403         default:
2404           res = FALSE;
2405           goto done;
2406       }
2407       break;
2408
2409     default:
2410       res = FALSE;
2411       goto done;
2412   }
2413
2414 done:
2415   return res;
2416
2417   /* ERRORS */
2418 no_bps_fact:
2419   {
2420     GST_DEBUG_OBJECT (wavparse, "bps 0 or no fact chunk, cannot convert");
2421     res = FALSE;
2422     goto done;
2423   }
2424 }
2425
2426 static const GstQueryType *
2427 gst_wavparse_get_query_types (GstPad * pad)
2428 {
2429   static const GstQueryType types[] = {
2430     GST_QUERY_POSITION,
2431     GST_QUERY_DURATION,
2432     GST_QUERY_CONVERT,
2433     GST_QUERY_SEEKING,
2434     0
2435   };
2436
2437   return types;
2438 }
2439
2440 /* handle queries for location and length in requested format */
2441 static gboolean
2442 gst_wavparse_pad_query (GstPad * pad, GstQuery * query)
2443 {
2444   gboolean res = TRUE;
2445   GstWavParse *wav = GST_WAVPARSE (gst_pad_get_parent (pad));
2446
2447   /* only if we know */
2448   if (wav->state != GST_WAVPARSE_DATA) {
2449     gst_object_unref (wav);
2450     return FALSE;
2451   }
2452
2453   GST_LOG_OBJECT (pad, "%s query", GST_QUERY_TYPE_NAME (query));
2454
2455   switch (GST_QUERY_TYPE (query)) {
2456     case GST_QUERY_POSITION:
2457     {
2458       gint64 curb;
2459       gint64 cur;
2460       GstFormat format;
2461
2462       /* this is not very precise, as we have pushed severla buffer upstream for prerolling */
2463       curb = wav->offset - wav->datastart;
2464       gst_query_parse_position (query, &format, NULL);
2465       GST_INFO_OBJECT (wav, "pos query at %" G_GINT64_FORMAT, curb);
2466
2467       switch (format) {
2468         case GST_FORMAT_TIME:
2469           res = gst_wavparse_pad_convert (pad, GST_FORMAT_BYTES, curb,
2470               &format, &cur);
2471           break;
2472         default:
2473           format = GST_FORMAT_BYTES;
2474           cur = curb;
2475           break;
2476       }
2477       if (res)
2478         gst_query_set_position (query, format, cur);
2479       break;
2480     }
2481     case GST_QUERY_DURATION:
2482     {
2483       gint64 duration = 0;
2484       GstFormat format;
2485
2486       gst_query_parse_duration (query, &format, NULL);
2487
2488       switch (format) {
2489         case GST_FORMAT_TIME:{
2490           if ((res = gst_wavparse_calculate_duration (wav))) {
2491             duration = wav->duration;
2492           }
2493           break;
2494         }
2495         default:
2496           format = GST_FORMAT_BYTES;
2497           duration = wav->datasize;
2498           break;
2499       }
2500       gst_query_set_duration (query, format, duration);
2501       break;
2502     }
2503     case GST_QUERY_CONVERT:
2504     {
2505       gint64 srcvalue, dstvalue;
2506       GstFormat srcformat, dstformat;
2507
2508       gst_query_parse_convert (query, &srcformat, &srcvalue,
2509           &dstformat, &dstvalue);
2510       res = gst_wavparse_pad_convert (pad, srcformat, srcvalue,
2511           &dstformat, &dstvalue);
2512       if (res)
2513         gst_query_set_convert (query, srcformat, srcvalue, dstformat, dstvalue);
2514       break;
2515     }
2516     case GST_QUERY_SEEKING:{
2517       GstFormat fmt;
2518       gboolean seekable = FALSE;
2519
2520       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
2521       if (fmt == wav->segment.format) {
2522         if (wav->streaming) {
2523           GstQuery *q;
2524
2525           q = gst_query_new_seeking (GST_FORMAT_BYTES);
2526           if ((res = gst_pad_peer_query (wav->sinkpad, q))) {
2527             gst_query_parse_seeking (q, &fmt, &seekable, NULL, NULL);
2528             GST_LOG_OBJECT (wav, "upstream BYTE seekable %d", seekable);
2529           }
2530           gst_query_unref (q);
2531         } else {
2532           GST_LOG_OBJECT (wav, "looping => seekable");
2533           seekable = TRUE;
2534           res = TRUE;
2535         }
2536       } else if (fmt == GST_FORMAT_TIME) {
2537         res = TRUE;
2538       }
2539       if (res) {
2540         gst_query_set_seeking (query, fmt, seekable, 0, wav->segment.duration);
2541       }
2542       break;
2543     }
2544     default:
2545       res = gst_pad_query_default (pad, query);
2546       break;
2547   }
2548   gst_object_unref (wav);
2549   return res;
2550 }
2551
2552 static gboolean
2553 gst_wavparse_srcpad_event (GstPad * pad, GstEvent * event)
2554 {
2555   GstWavParse *wavparse = GST_WAVPARSE (gst_pad_get_parent (pad));
2556   gboolean res = FALSE;
2557
2558   GST_DEBUG_OBJECT (wavparse, "%s event", GST_EVENT_TYPE_NAME (event));
2559
2560   switch (GST_EVENT_TYPE (event)) {
2561     case GST_EVENT_SEEK:
2562       /* can only handle events when we are in the data state */
2563       if (wavparse->state == GST_WAVPARSE_DATA) {
2564         res = gst_wavparse_perform_seek (wavparse, event);
2565       }
2566       gst_event_unref (event);
2567       break;
2568     default:
2569       res = gst_pad_push_event (wavparse->sinkpad, event);
2570       break;
2571   }
2572   gst_object_unref (wavparse);
2573   return res;
2574 }
2575
2576 static gboolean
2577 gst_wavparse_sink_activate (GstPad * sinkpad)
2578 {
2579   GstWavParse *wav = GST_WAVPARSE (gst_pad_get_parent (sinkpad));
2580   gboolean res;
2581
2582   if (wav->adapter) {
2583     gst_adapter_clear (wav->adapter);
2584     g_object_unref (wav->adapter);
2585     wav->adapter = NULL;
2586   }
2587
2588   if (gst_pad_check_pull_range (sinkpad)) {
2589     GST_DEBUG ("going to pull mode");
2590     wav->streaming = FALSE;
2591     res = gst_pad_activate_pull (sinkpad, TRUE);
2592   } else {
2593     GST_DEBUG ("going to push (streaming) mode");
2594     wav->streaming = TRUE;
2595     wav->adapter = gst_adapter_new ();
2596     res = gst_pad_activate_push (sinkpad, TRUE);
2597   }
2598   gst_object_unref (wav);
2599   return res;
2600 }
2601
2602
2603 static gboolean
2604 gst_wavparse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2605 {
2606   GstWavParse *wav = GST_WAVPARSE (GST_OBJECT_PARENT (sinkpad));
2607
2608   if (active) {
2609     /* if we have a scheduler we can start the task */
2610     wav->segment_running = TRUE;
2611     return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_wavparse_loop,
2612         sinkpad);
2613   } else {
2614     wav->segment_running = FALSE;
2615     return gst_pad_stop_task (sinkpad);
2616   }
2617 };
2618
2619 static GstStateChangeReturn
2620 gst_wavparse_change_state (GstElement * element, GstStateChange transition)
2621 {
2622   GstStateChangeReturn ret;
2623   GstWavParse *wav = GST_WAVPARSE (element);
2624
2625   switch (transition) {
2626     case GST_STATE_CHANGE_NULL_TO_READY:
2627       break;
2628     case GST_STATE_CHANGE_READY_TO_PAUSED:
2629       gst_wavparse_reset (wav);
2630       break;
2631     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2632       break;
2633     default:
2634       break;
2635   }
2636
2637   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2638
2639   switch (transition) {
2640     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2641       break;
2642     case GST_STATE_CHANGE_PAUSED_TO_READY:
2643       gst_wavparse_destroy_sourcepad (wav);
2644       gst_wavparse_reset (wav);
2645       break;
2646     case GST_STATE_CHANGE_READY_TO_NULL:
2647       break;
2648     default:
2649       break;
2650   }
2651   return ret;
2652 }
2653
2654 static gboolean
2655 plugin_init (GstPlugin * plugin)
2656 {
2657   gst_riff_init ();
2658
2659   return gst_element_register (plugin, "wavparse", GST_RANK_PRIMARY,
2660       GST_TYPE_WAVPARSE);
2661 }
2662
2663 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
2664     GST_VERSION_MINOR,
2665     "wavparse",
2666     "Parse a .wav file into raw audio",
2667     plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)