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