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