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