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