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