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