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