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