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