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