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