Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / ext / vorbis / gstvorbisdec.c
1 /* GStreamer
2  * Copyright (C) 2004 Benjamin Otte <in7y118@public.uni-hamburg.de>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-vorbisdec
22  * @see_also: vorbisenc, oggdemux
23  *
24  * This element decodes a Vorbis stream to raw float audio.
25  * <ulink url="http://www.vorbis.com/">Vorbis</ulink> is a royalty-free
26  * audio codec maintained by the <ulink url="http://www.xiph.org/">Xiph.org
27  * Foundation</ulink>.
28  *
29  * <refsect2>
30  * <title>Example pipelines</title>
31  * |[
32  * gst-launch -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! alsasink
33  * ]| Decode an Ogg/Vorbis. To create an Ogg/Vorbis file refer to the documentation of vorbisenc.
34  * </refsect2>
35  *
36  * Last reviewed on 2006-03-01 (0.10.4)
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #include "gstvorbisdec.h"
44 #include <string.h>
45 #include <gst/audio/audio.h>
46 #include <gst/tag/tag.h>
47 #include <gst/audio/multichannel.h>
48
49 #include "gstvorbiscommon.h"
50
51 GST_DEBUG_CATEGORY_EXTERN (vorbisdec_debug);
52 #define GST_CAT_DEFAULT vorbisdec_debug
53
54 static GstStaticPadTemplate vorbis_dec_src_factory =
55 GST_STATIC_PAD_TEMPLATE ("src",
56     GST_PAD_SRC,
57     GST_PAD_ALWAYS,
58     GST_VORBIS_DEC_SRC_CAPS);
59
60 static GstStaticPadTemplate vorbis_dec_sink_factory =
61 GST_STATIC_PAD_TEMPLATE ("sink",
62     GST_PAD_SINK,
63     GST_PAD_ALWAYS,
64     GST_STATIC_CAPS ("audio/x-vorbis")
65     );
66
67 GST_BOILERPLATE (GST_VORBIS_DEC_GLIB_TYPE_NAME, gst_vorbis_dec, GstElement,
68     GST_TYPE_ELEMENT);
69
70 static void vorbis_dec_finalize (GObject * object);
71 static gboolean vorbis_dec_sink_event (GstPad * pad, GstEvent * event);
72 static GstFlowReturn vorbis_dec_chain (GstPad * pad, GstBuffer * buffer);
73 static GstFlowReturn vorbis_dec_chain_forward (GstVorbisDec * vd,
74     gboolean discont, GstBuffer * buffer);
75 static GstFlowReturn vorbis_dec_chain_reverse (GstVorbisDec * vd,
76     gboolean discont, GstBuffer * buf);
77 static GstStateChangeReturn vorbis_dec_change_state (GstElement * element,
78     GstStateChange transition);
79
80 static gboolean vorbis_dec_src_event (GstPad * pad, GstEvent * event);
81 static gboolean vorbis_dec_src_query (GstPad * pad, GstQuery * query);
82 static gboolean vorbis_dec_convert (GstPad * pad,
83     GstFormat src_format, gint64 src_value,
84     GstFormat * dest_format, gint64 * dest_value);
85
86 static gboolean vorbis_dec_sink_query (GstPad * pad, GstQuery * query);
87
88 static void
89 gst_vorbis_dec_base_init (gpointer g_class)
90 {
91   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
92   GstPadTemplate *src_template, *sink_template;
93
94   src_template = gst_static_pad_template_get (&vorbis_dec_src_factory);
95   gst_element_class_add_pad_template (element_class, src_template);
96
97   sink_template = gst_static_pad_template_get (&vorbis_dec_sink_factory);
98   gst_element_class_add_pad_template (element_class, sink_template);
99
100   gst_element_class_set_details_simple (element_class,
101       "Vorbis audio decoder", "Codec/Decoder/Audio",
102       GST_VORBIS_DEC_DESCRIPTION,
103       "Benjamin Otte <otte@gnome.org>, Chris Lord <chris@openedhand.com>");
104 }
105
106 static void
107 gst_vorbis_dec_class_init (GstVorbisDecClass * klass)
108 {
109   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
110   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
111
112   gobject_class->finalize = vorbis_dec_finalize;
113
114   gstelement_class->change_state = GST_DEBUG_FUNCPTR (vorbis_dec_change_state);
115 }
116
117 static const GstQueryType *
118 vorbis_get_query_types (GstPad * pad)
119 {
120   static const GstQueryType vorbis_dec_src_query_types[] = {
121     GST_QUERY_POSITION,
122     GST_QUERY_DURATION,
123     GST_QUERY_CONVERT,
124     0
125   };
126
127   return vorbis_dec_src_query_types;
128 }
129
130 static void
131 gst_vorbis_dec_init (GstVorbisDec * dec, GstVorbisDecClass * g_class)
132 {
133   dec->sinkpad = gst_pad_new_from_static_template (&vorbis_dec_sink_factory,
134       "sink");
135
136   gst_pad_set_event_function (dec->sinkpad,
137       GST_DEBUG_FUNCPTR (vorbis_dec_sink_event));
138   gst_pad_set_chain_function (dec->sinkpad,
139       GST_DEBUG_FUNCPTR (vorbis_dec_chain));
140   gst_pad_set_query_function (dec->sinkpad,
141       GST_DEBUG_FUNCPTR (vorbis_dec_sink_query));
142   gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
143
144   dec->srcpad = gst_pad_new_from_static_template (&vorbis_dec_src_factory,
145       "src");
146
147   gst_pad_set_event_function (dec->srcpad,
148       GST_DEBUG_FUNCPTR (vorbis_dec_src_event));
149   gst_pad_set_query_type_function (dec->srcpad,
150       GST_DEBUG_FUNCPTR (vorbis_get_query_types));
151   gst_pad_set_query_function (dec->srcpad,
152       GST_DEBUG_FUNCPTR (vorbis_dec_src_query));
153   gst_pad_use_fixed_caps (dec->srcpad);
154   gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
155
156   dec->queued = NULL;
157   dec->pendingevents = NULL;
158   dec->taglist = NULL;
159 }
160
161 static void
162 vorbis_dec_finalize (GObject * object)
163 {
164   /* Release any possibly allocated libvorbis data.
165    * _clear functions can safely be called multiple times
166    */
167   GstVorbisDec *vd = GST_VORBIS_DEC (object);
168
169   vorbis_block_clear (&vd->vb);
170   vorbis_dsp_clear (&vd->vd);
171   vorbis_comment_clear (&vd->vc);
172   vorbis_info_clear (&vd->vi);
173
174   G_OBJECT_CLASS (parent_class)->finalize (object);
175 }
176
177 static void
178 gst_vorbis_dec_reset (GstVorbisDec * dec)
179 {
180   dec->last_timestamp = GST_CLOCK_TIME_NONE;
181   dec->discont = TRUE;
182   dec->seqnum = gst_util_seqnum_next ();
183   gst_segment_init (&dec->segment, GST_FORMAT_TIME);
184
185   g_list_foreach (dec->queued, (GFunc) gst_mini_object_unref, NULL);
186   g_list_free (dec->queued);
187   dec->queued = NULL;
188   g_list_foreach (dec->gather, (GFunc) gst_mini_object_unref, NULL);
189   g_list_free (dec->gather);
190   dec->gather = NULL;
191   g_list_foreach (dec->decode, (GFunc) gst_mini_object_unref, NULL);
192   g_list_free (dec->decode);
193   dec->decode = NULL;
194   g_list_foreach (dec->pendingevents, (GFunc) gst_mini_object_unref, NULL);
195   g_list_free (dec->pendingevents);
196   dec->pendingevents = NULL;
197
198   if (dec->taglist)
199     gst_tag_list_free (dec->taglist);
200   dec->taglist = NULL;
201 }
202
203
204 static gboolean
205 vorbis_dec_convert (GstPad * pad,
206     GstFormat src_format, gint64 src_value,
207     GstFormat * dest_format, gint64 * dest_value)
208 {
209   gboolean res = TRUE;
210   GstVorbisDec *dec;
211   guint64 scale = 1;
212
213   if (src_format == *dest_format) {
214     *dest_value = src_value;
215     return TRUE;
216   }
217
218   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
219
220   if (!dec->initialized)
221     goto no_header;
222
223   if (dec->sinkpad == pad &&
224       (src_format == GST_FORMAT_BYTES || *dest_format == GST_FORMAT_BYTES))
225     goto no_format;
226
227   switch (src_format) {
228     case GST_FORMAT_TIME:
229       switch (*dest_format) {
230         case GST_FORMAT_BYTES:
231           scale = dec->width * dec->vi.channels;
232         case GST_FORMAT_DEFAULT:
233           *dest_value =
234               scale * gst_util_uint64_scale_int (src_value, dec->vi.rate,
235               GST_SECOND);
236           break;
237         default:
238           res = FALSE;
239       }
240       break;
241     case GST_FORMAT_DEFAULT:
242       switch (*dest_format) {
243         case GST_FORMAT_BYTES:
244           *dest_value = src_value * dec->width * dec->vi.channels;
245           break;
246         case GST_FORMAT_TIME:
247           *dest_value =
248               gst_util_uint64_scale_int (src_value, GST_SECOND, dec->vi.rate);
249           break;
250         default:
251           res = FALSE;
252       }
253       break;
254     case GST_FORMAT_BYTES:
255       switch (*dest_format) {
256         case GST_FORMAT_DEFAULT:
257           *dest_value = src_value / (dec->width * dec->vi.channels);
258           break;
259         case GST_FORMAT_TIME:
260           *dest_value = gst_util_uint64_scale_int (src_value, GST_SECOND,
261               dec->vi.rate * dec->width * dec->vi.channels);
262           break;
263         default:
264           res = FALSE;
265       }
266       break;
267     default:
268       res = FALSE;
269   }
270 done:
271   gst_object_unref (dec);
272
273   return res;
274
275   /* ERRORS */
276 no_header:
277   {
278     GST_DEBUG_OBJECT (dec, "no header packets received");
279     res = FALSE;
280     goto done;
281   }
282 no_format:
283   {
284     GST_DEBUG_OBJECT (dec, "formats unsupported");
285     res = FALSE;
286     goto done;
287   }
288 }
289
290 static gboolean
291 vorbis_dec_src_query (GstPad * pad, GstQuery * query)
292 {
293   GstVorbisDec *dec;
294   gboolean res = FALSE;
295
296   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
297
298   switch (GST_QUERY_TYPE (query)) {
299     case GST_QUERY_POSITION:
300     {
301       gint64 value;
302       GstFormat format;
303       gint64 time;
304
305       gst_query_parse_position (query, &format, NULL);
306
307       /* we start from the last seen time */
308       time = dec->last_timestamp;
309       /* correct for the segment values */
310       time = gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, time);
311
312       GST_LOG_OBJECT (dec,
313           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
314
315       /* and convert to the final format */
316       if (!(res =
317               vorbis_dec_convert (pad, GST_FORMAT_TIME, time, &format, &value)))
318         goto error;
319
320       gst_query_set_position (query, format, value);
321
322       GST_LOG_OBJECT (dec,
323           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
324           format);
325
326       break;
327     }
328     case GST_QUERY_DURATION:
329     {
330       res = gst_pad_peer_query (dec->sinkpad, query);
331       if (!res)
332         goto error;
333
334       break;
335     }
336     case GST_QUERY_CONVERT:
337     {
338       GstFormat src_fmt, dest_fmt;
339       gint64 src_val, dest_val;
340
341       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
342       if (!(res =
343               vorbis_dec_convert (pad, src_fmt, src_val, &dest_fmt, &dest_val)))
344         goto error;
345       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
346       break;
347     }
348     default:
349       res = gst_pad_query_default (pad, query);
350       break;
351   }
352 done:
353   gst_object_unref (dec);
354
355   return res;
356
357   /* ERRORS */
358 error:
359   {
360     GST_WARNING_OBJECT (dec, "error handling query");
361     goto done;
362   }
363 }
364
365 static gboolean
366 vorbis_dec_sink_query (GstPad * pad, GstQuery * query)
367 {
368   GstVorbisDec *dec;
369   gboolean res;
370
371   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
372
373   switch (GST_QUERY_TYPE (query)) {
374     case GST_QUERY_CONVERT:
375     {
376       GstFormat src_fmt, dest_fmt;
377       gint64 src_val, dest_val;
378
379       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
380       if (!(res =
381               vorbis_dec_convert (pad, src_fmt, src_val, &dest_fmt, &dest_val)))
382         goto error;
383       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
384       break;
385     }
386     default:
387       res = gst_pad_query_default (pad, query);
388       break;
389   }
390
391 done:
392   gst_object_unref (dec);
393
394   return res;
395
396   /* ERRORS */
397 error:
398   {
399     GST_DEBUG_OBJECT (dec, "error converting value");
400     goto done;
401   }
402 }
403
404 static gboolean
405 vorbis_dec_src_event (GstPad * pad, GstEvent * event)
406 {
407   gboolean res = TRUE;
408   GstVorbisDec *dec;
409
410   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
411
412   switch (GST_EVENT_TYPE (event)) {
413     case GST_EVENT_SEEK:
414     {
415       GstFormat format, tformat;
416       gdouble rate;
417       GstEvent *real_seek;
418       GstSeekFlags flags;
419       GstSeekType cur_type, stop_type;
420       gint64 cur, stop;
421       gint64 tcur, tstop;
422       guint32 seqnum;
423
424       gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
425           &stop_type, &stop);
426       seqnum = gst_event_get_seqnum (event);
427       gst_event_unref (event);
428
429       /* First bring the requested format to time */
430       tformat = GST_FORMAT_TIME;
431       if (!(res = vorbis_dec_convert (pad, format, cur, &tformat, &tcur)))
432         goto convert_error;
433       if (!(res = vorbis_dec_convert (pad, format, stop, &tformat, &tstop)))
434         goto convert_error;
435
436       /* then seek with time on the peer */
437       real_seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
438           flags, cur_type, tcur, stop_type, tstop);
439       gst_event_set_seqnum (real_seek, seqnum);
440
441       res = gst_pad_push_event (dec->sinkpad, real_seek);
442       break;
443     }
444     default:
445       res = gst_pad_push_event (dec->sinkpad, event);
446       break;
447   }
448 done:
449   gst_object_unref (dec);
450
451   return res;
452
453   /* ERRORS */
454 convert_error:
455   {
456     GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
457     goto done;
458   }
459 }
460
461 static gboolean
462 vorbis_dec_sink_event (GstPad * pad, GstEvent * event)
463 {
464   gboolean ret = FALSE;
465   GstVorbisDec *dec;
466
467   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
468
469   GST_LOG_OBJECT (dec, "handling event");
470   switch (GST_EVENT_TYPE (event)) {
471     case GST_EVENT_EOS:
472       if (dec->segment.rate < 0.0)
473         vorbis_dec_chain_reverse (dec, TRUE, NULL);
474       ret = gst_pad_push_event (dec->srcpad, event);
475       break;
476     case GST_EVENT_FLUSH_START:
477       ret = gst_pad_push_event (dec->srcpad, event);
478       break;
479     case GST_EVENT_FLUSH_STOP:
480       /* here we must clean any state in the decoder */
481 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
482       vorbis_synthesis_restart (&dec->vd);
483 #endif
484       gst_vorbis_dec_reset (dec);
485       ret = gst_pad_push_event (dec->srcpad, event);
486       break;
487     case GST_EVENT_NEWSEGMENT:
488     {
489       GstFormat format;
490       gdouble rate, arate;
491       gint64 start, stop, time;
492       gboolean update;
493
494       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
495           &start, &stop, &time);
496
497       /* we need time for now */
498       if (format != GST_FORMAT_TIME)
499         goto newseg_wrong_format;
500
501       GST_DEBUG_OBJECT (dec,
502           "newsegment: update %d, rate %g, arate %g, start %" GST_TIME_FORMAT
503           ", stop %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT,
504           update, rate, arate, GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
505           GST_TIME_ARGS (time));
506
507       /* now configure the values */
508       gst_segment_set_newsegment_full (&dec->segment, update,
509           rate, arate, format, start, stop, time);
510       dec->seqnum = gst_event_get_seqnum (event);
511
512       if (dec->initialized)
513         /* and forward */
514         ret = gst_pad_push_event (dec->srcpad, event);
515       else {
516         /* store it to send once we're initialized */
517         dec->pendingevents = g_list_append (dec->pendingevents, event);
518         ret = TRUE;
519       }
520       break;
521     }
522     case GST_EVENT_TAG:
523     {
524       if (dec->initialized)
525         /* and forward */
526         ret = gst_pad_push_event (dec->srcpad, event);
527       else {
528         /* store it to send once we're initialized */
529         dec->pendingevents = g_list_append (dec->pendingevents, event);
530         ret = TRUE;
531       }
532       break;
533     }
534     default:
535       ret = gst_pad_push_event (dec->srcpad, event);
536       break;
537   }
538 done:
539   gst_object_unref (dec);
540
541   return ret;
542
543   /* ERRORS */
544 newseg_wrong_format:
545   {
546     GST_DEBUG_OBJECT (dec, "received non TIME newsegment");
547     goto done;
548   }
549 }
550
551 static GstFlowReturn
552 vorbis_handle_identification_packet (GstVorbisDec * vd)
553 {
554   GstCaps *caps;
555   const GstAudioChannelPosition *pos = NULL;
556   gint width = GST_VORBIS_DEC_DEFAULT_SAMPLE_WIDTH;
557
558   switch (vd->vi.channels) {
559     case 1:
560     case 2:
561       /* nothing */
562       break;
563     case 3:
564     case 4:
565     case 5:
566     case 6:
567     case 7:
568     case 8:
569       pos = gst_vorbis_channel_positions[vd->vi.channels - 1];
570       break;
571     default:{
572       gint i;
573       GstAudioChannelPosition *posn =
574           g_new (GstAudioChannelPosition, vd->vi.channels);
575
576       GST_ELEMENT_WARNING (GST_ELEMENT (vd), STREAM, DECODE,
577           (NULL), ("Using NONE channel layout for more than 8 channels"));
578
579       for (i = 0; i < vd->vi.channels; i++)
580         posn[i] = GST_AUDIO_CHANNEL_POSITION_NONE;
581
582       pos = posn;
583     }
584   }
585
586   /* negotiate width with downstream */
587   caps = gst_pad_get_allowed_caps (vd->srcpad);
588   if (caps) {
589     if (!gst_caps_is_empty (caps)) {
590       GstStructure *s;
591
592       s = gst_caps_get_structure (caps, 0);
593       /* template ensures 16 or 32 */
594       gst_structure_get_int (s, "width", &width);
595
596       GST_INFO_OBJECT (vd, "using %s with %d channels and %d bit audio depth",
597           gst_structure_get_name (s), vd->vi.channels, width);
598     }
599     gst_caps_unref (caps);
600   }
601   vd->width = width >> 3;
602
603   /* select a copy_samples function, this way we can have specialized versions
604    * for mono/stereo and avoid the depth switch in tremor case */
605   vd->copy_samples = get_copy_sample_func (vd->vi.channels, vd->width);
606
607   caps = gst_caps_copy (gst_pad_get_pad_template_caps (vd->srcpad));
608   gst_caps_set_simple (caps, "rate", G_TYPE_INT, vd->vi.rate,
609       "channels", G_TYPE_INT, vd->vi.channels,
610       "width", G_TYPE_INT, width, NULL);
611
612   if (pos) {
613     gst_audio_set_channel_positions (gst_caps_get_structure (caps, 0), pos);
614   }
615
616   if (vd->vi.channels > 8) {
617     g_free ((GstAudioChannelPosition *) pos);
618   }
619
620   gst_pad_set_caps (vd->srcpad, caps);
621   gst_caps_unref (caps);
622
623   return GST_FLOW_OK;
624 }
625
626 static GstFlowReturn
627 vorbis_handle_comment_packet (GstVorbisDec * vd, ogg_packet * packet)
628 {
629   guint bitrate = 0;
630   gchar *encoder = NULL;
631   GstTagList *list, *old_list;
632   guint8 *data;
633   gsize size;
634
635   GST_DEBUG_OBJECT (vd, "parsing comment packet");
636
637   data = gst_ogg_packet_data (packet);
638   size = gst_ogg_packet_size (packet);
639
640   list =
641       gst_tag_list_from_vorbiscomment (data, size, (guint8 *) "\003vorbis", 7,
642       &encoder);
643
644   old_list = vd->taglist;
645   vd->taglist = gst_tag_list_merge (vd->taglist, list, GST_TAG_MERGE_REPLACE);
646
647   if (old_list)
648     gst_tag_list_free (old_list);
649   gst_tag_list_free (list);
650
651   if (!vd->taglist) {
652     GST_ERROR_OBJECT (vd, "couldn't decode comments");
653     vd->taglist = gst_tag_list_new ();
654   }
655   if (encoder) {
656     if (encoder[0])
657       gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
658           GST_TAG_ENCODER, encoder, NULL);
659     g_free (encoder);
660   }
661   gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
662       GST_TAG_ENCODER_VERSION, vd->vi.version,
663       GST_TAG_AUDIO_CODEC, "Vorbis", NULL);
664   if (vd->vi.bitrate_nominal > 0 && vd->vi.bitrate_nominal <= 0x7FFFFFFF) {
665     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
666         GST_TAG_NOMINAL_BITRATE, (guint) vd->vi.bitrate_nominal, NULL);
667     bitrate = vd->vi.bitrate_nominal;
668   }
669   if (vd->vi.bitrate_upper > 0 && vd->vi.bitrate_upper <= 0x7FFFFFFF) {
670     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
671         GST_TAG_MAXIMUM_BITRATE, (guint) vd->vi.bitrate_upper, NULL);
672     if (!bitrate)
673       bitrate = vd->vi.bitrate_upper;
674   }
675   if (vd->vi.bitrate_lower > 0 && vd->vi.bitrate_lower <= 0x7FFFFFFF) {
676     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
677         GST_TAG_MINIMUM_BITRATE, (guint) vd->vi.bitrate_lower, NULL);
678     if (!bitrate)
679       bitrate = vd->vi.bitrate_lower;
680   }
681   if (bitrate) {
682     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
683         GST_TAG_BITRATE, (guint) bitrate, NULL);
684   }
685
686   if (vd->initialized) {
687     gst_element_found_tags_for_pad (GST_ELEMENT_CAST (vd), vd->srcpad,
688         vd->taglist);
689     vd->taglist = NULL;
690   } else {
691     /* Only post them as messages for the time being. *
692      * They will be pushed on the pad once the decoder is initialized */
693     gst_element_post_message (GST_ELEMENT_CAST (vd),
694         gst_message_new_tag (GST_OBJECT (vd), gst_tag_list_copy (vd->taglist)));
695   }
696
697   return GST_FLOW_OK;
698 }
699
700 static GstFlowReturn
701 vorbis_handle_type_packet (GstVorbisDec * vd)
702 {
703   GList *walk;
704   gint res;
705
706   g_assert (vd->initialized == FALSE);
707
708   if (G_UNLIKELY ((res = vorbis_synthesis_init (&vd->vd, &vd->vi))))
709     goto synthesis_init_error;
710
711   if (G_UNLIKELY ((res = vorbis_block_init (&vd->vd, &vd->vb))))
712     goto block_init_error;
713
714   vd->initialized = TRUE;
715
716   if (vd->pendingevents) {
717     for (walk = vd->pendingevents; walk; walk = g_list_next (walk))
718       gst_pad_push_event (vd->srcpad, GST_EVENT_CAST (walk->data));
719     g_list_free (vd->pendingevents);
720     vd->pendingevents = NULL;
721   }
722
723   if (vd->taglist) {
724     /* The tags have already been sent on the bus as messages. */
725     gst_pad_push_event (vd->srcpad, gst_event_new_tag (vd->taglist));
726     vd->taglist = NULL;
727   }
728   return GST_FLOW_OK;
729
730   /* ERRORS */
731 synthesis_init_error:
732   {
733     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
734         (NULL), ("couldn't initialize synthesis (%d)", res));
735     return GST_FLOW_ERROR;
736   }
737 block_init_error:
738   {
739     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
740         (NULL), ("couldn't initialize block (%d)", res));
741     return GST_FLOW_ERROR;
742   }
743 }
744
745 static GstFlowReturn
746 vorbis_handle_header_packet (GstVorbisDec * vd, ogg_packet * packet)
747 {
748   GstFlowReturn res;
749   gint ret;
750
751   GST_DEBUG_OBJECT (vd, "parsing header packet");
752
753   /* Packetno = 0 if the first byte is exactly 0x01 */
754   packet->b_o_s = ((gst_ogg_packet_data (packet))[0] == 0x1) ? 1 : 0;
755
756   if ((ret = vorbis_synthesis_headerin (&vd->vi, &vd->vc, packet)))
757     goto header_read_error;
758
759   switch ((gst_ogg_packet_data (packet))[0]) {
760     case 0x01:
761       res = vorbis_handle_identification_packet (vd);
762       break;
763     case 0x03:
764       res = vorbis_handle_comment_packet (vd, packet);
765       break;
766     case 0x05:
767       res = vorbis_handle_type_packet (vd);
768       break;
769     default:
770       /* ignore */
771       g_warning ("unknown vorbis header packet found");
772       res = GST_FLOW_OK;
773       break;
774   }
775   return res;
776
777   /* ERRORS */
778 header_read_error:
779   {
780     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
781         (NULL), ("couldn't read header packet (%d)", ret));
782     return GST_FLOW_ERROR;
783   }
784 }
785
786 static GstFlowReturn
787 vorbis_dec_push_forward (GstVorbisDec * dec, GstBuffer * buf)
788 {
789   GstFlowReturn result;
790
791   /* clip */
792   if (!(buf = gst_audio_buffer_clip (buf, &dec->segment, dec->vi.rate,
793               dec->vi.channels * dec->width))) {
794     GST_LOG_OBJECT (dec, "clipped buffer");
795     return GST_FLOW_OK;
796   }
797
798   if (dec->discont) {
799     GST_LOG_OBJECT (dec, "setting DISCONT");
800     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
801     dec->discont = FALSE;
802   }
803
804   GST_DEBUG_OBJECT (dec,
805       "pushing time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
806       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
807       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
808
809   result = gst_pad_push (dec->srcpad, buf);
810
811   return result;
812 }
813
814 static GstFlowReturn
815 vorbis_dec_push_reverse (GstVorbisDec * dec, GstBuffer * buf)
816 {
817   GstFlowReturn result = GST_FLOW_OK;
818
819   dec->queued = g_list_prepend (dec->queued, buf);
820
821   return result;
822 }
823
824 static void
825 vorbis_do_timestamps (GstVorbisDec * vd, GstBuffer * buf, gboolean reverse,
826     GstClockTime timestamp, GstClockTime duration)
827 {
828   /* interpolate reverse */
829   if (vd->last_timestamp != -1 && duration != -1 && reverse)
830     vd->last_timestamp -= duration;
831
832   /* take buffer timestamp, use interpolated timestamp otherwise */
833   if (timestamp != -1)
834     vd->last_timestamp = timestamp;
835   else
836     timestamp = vd->last_timestamp;
837
838   /* interpolate forwards */
839   if (vd->last_timestamp != -1 && duration != -1 && !reverse)
840     vd->last_timestamp += duration;
841
842   GST_LOG_OBJECT (vd,
843       "keeping timestamp %" GST_TIME_FORMAT " ts %" GST_TIME_FORMAT " dur %"
844       GST_TIME_FORMAT, GST_TIME_ARGS (vd->last_timestamp),
845       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
846
847   if (buf) {
848     GST_BUFFER_TIMESTAMP (buf) = timestamp;
849     GST_BUFFER_DURATION (buf) = duration;
850   }
851 }
852
853 static GstFlowReturn
854 vorbis_handle_data_packet (GstVorbisDec * vd, ogg_packet * packet,
855     GstClockTime timestamp, GstClockTime duration)
856 {
857   vorbis_sample_t **pcm;
858   guint sample_count;
859   GstBuffer *out = NULL;
860   GstFlowReturn result;
861   guint8 *data;
862   gsize size;
863
864   if (G_UNLIKELY (!vd->initialized))
865     goto not_initialized;
866
867   /* normal data packet */
868   /* FIXME, we can skip decoding if the packet is outside of the
869    * segment, this is however not very trivial as we need a previous
870    * packet to decode the current one so we must be carefull not to
871    * throw away too much. For now we decode everything and clip right
872    * before pushing data. */
873   if (G_UNLIKELY (vorbis_synthesis (&vd->vb, packet)))
874     goto could_not_read;
875
876   if (G_UNLIKELY (vorbis_synthesis_blockin (&vd->vd, &vd->vb) < 0))
877     goto not_accepted;
878
879   /* assume all goes well here */
880   result = GST_FLOW_OK;
881
882   /* count samples ready for reading */
883   if ((sample_count = vorbis_synthesis_pcmout (&vd->vd, NULL)) == 0)
884     goto done;
885
886   size = sample_count * vd->vi.channels * vd->width;
887   GST_LOG_OBJECT (vd, "%d samples ready for reading, size %d", sample_count,
888       size);
889
890   /* alloc buffer for it */
891   result =
892       gst_pad_alloc_buffer_and_set_caps (vd->srcpad, GST_BUFFER_OFFSET_NONE,
893       size, GST_PAD_CAPS (vd->srcpad), &out);
894   if (G_UNLIKELY (result != GST_FLOW_OK))
895     goto done;
896
897   /* get samples ready for reading now, should be sample_count */
898   if (G_UNLIKELY ((vorbis_synthesis_pcmout (&vd->vd, &pcm)) != sample_count))
899     goto wrong_samples;
900
901   /* copy samples in buffer */
902   data = gst_buffer_map (out, NULL, NULL, GST_MAP_WRITE);
903   vd->copy_samples ((vorbis_sample_t *) data, pcm,
904       sample_count, vd->vi.channels, vd->width);
905
906   GST_LOG_OBJECT (vd, "setting output size to %d", size);
907   gst_buffer_unmap (out, data, size);
908
909   /* this should not overflow */
910   if (duration == -1)
911     duration = sample_count * GST_SECOND / vd->vi.rate;
912
913   vorbis_do_timestamps (vd, out, FALSE, timestamp, duration);
914
915   if (vd->segment.rate >= 0.0)
916     result = vorbis_dec_push_forward (vd, out);
917   else
918     result = vorbis_dec_push_reverse (vd, out);
919
920 done:
921   if (out == NULL) {
922     /* no output, still keep track of timestamps */
923     vorbis_do_timestamps (vd, NULL, FALSE, timestamp, duration);
924   }
925   vorbis_synthesis_read (&vd->vd, sample_count);
926
927   return result;
928
929   /* ERRORS */
930 not_initialized:
931   {
932     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
933         (NULL), ("no header sent yet"));
934     return GST_FLOW_ERROR;
935   }
936 could_not_read:
937   {
938     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
939         (NULL), ("couldn't read data packet"));
940     return GST_FLOW_ERROR;
941   }
942 not_accepted:
943   {
944     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
945         (NULL), ("vorbis decoder did not accept data packet"));
946     return GST_FLOW_ERROR;
947   }
948 wrong_samples:
949   {
950     gst_buffer_unref (out);
951     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
952         (NULL), ("vorbis decoder reported wrong number of samples"));
953     return GST_FLOW_ERROR;
954   }
955 }
956
957 static GstFlowReturn
958 vorbis_dec_decode_buffer (GstVorbisDec * vd, GstBuffer * buffer)
959 {
960   ogg_packet *packet;
961   ogg_packet_wrapper packet_wrapper;
962   GstFlowReturn result = GST_FLOW_OK;
963
964   /* make ogg_packet out of the buffer */
965   gst_ogg_packet_wrapper_map (&packet_wrapper, buffer);
966   packet = gst_ogg_packet_from_wrapper (&packet_wrapper);
967   /* set some more stuff */
968   packet->granulepos = -1;
969   packet->packetno = 0;         /* we don't care */
970   /* EOS does not matter, it is used in vorbis to implement clipping the last
971    * block of samples based on the granulepos. We clip based on segments. */
972   packet->e_o_s = 0;
973
974   GST_LOG_OBJECT (vd, "decode buffer of size %ld", packet->bytes);
975
976   /* error out on empty header packets, but just skip empty data packets */
977   if (G_UNLIKELY (packet->bytes == 0)) {
978     if (vd->initialized)
979       goto empty_buffer;
980     else
981       goto empty_header;
982   }
983
984   /* switch depending on packet type */
985   if ((gst_ogg_packet_data (packet))[0] & 1) {
986     if (vd->initialized) {
987       GST_WARNING_OBJECT (vd, "Already initialized, so ignoring header packet");
988       goto done;
989     }
990     result = vorbis_handle_header_packet (vd, packet);
991   } else {
992     GstClockTime timestamp, duration;
993
994     timestamp = GST_BUFFER_TIMESTAMP (buffer);
995     duration = GST_BUFFER_DURATION (buffer);
996
997     result = vorbis_handle_data_packet (vd, packet, timestamp, duration);
998   }
999
1000 done:
1001   gst_ogg_packet_wrapper_unmap (&packet_wrapper, buffer);
1002
1003   return result;
1004
1005 empty_buffer:
1006   {
1007     /* don't error out here, just ignore the buffer, it's invalid for vorbis
1008      * but not fatal. */
1009     GST_WARNING_OBJECT (vd, "empty buffer received, ignoring");
1010     result = GST_FLOW_OK;
1011     goto done;
1012   }
1013
1014 /* ERRORS */
1015 empty_header:
1016   {
1017     GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL), ("empty header received"));
1018     result = GST_FLOW_ERROR;
1019     vd->discont = TRUE;
1020     goto done;
1021   }
1022 }
1023
1024 /*
1025  * Input:
1026  *  Buffer decoding order:  7  8  9  4  5  6  3  1  2  EOS
1027  *  Discont flag:           D        D        D  D
1028  *
1029  * - Each Discont marks a discont in the decoding order.
1030  *
1031  * for vorbis, each buffer is a keyframe when we have the previous
1032  * buffer. This means that to decode buffer 7, we need buffer 6, which
1033  * arrives out of order.
1034  *
1035  * we first gather buffers in the gather queue until we get a DISCONT. We
1036  * prepend each incomming buffer so that they are in reversed order.
1037  *
1038  *    gather queue:    9  8  7
1039  *    decode queue:
1040  *    output queue:
1041  *
1042  * When a DISCONT is received (buffer 4), we move the gather queue to the
1043  * decode queue. This is simply done be taking the head of the gather queue
1044  * and prepending it to the decode queue. This yields:
1045  *
1046  *    gather queue:
1047  *    decode queue:    7  8  9
1048  *    output queue:
1049  *
1050  * Then we decode each buffer in the decode queue in order and put the output
1051  * buffer in the output queue. The first buffer (7) will not produce any output
1052  * because it needs the previous buffer (6) which did not arrive yet. This
1053  * yields:
1054  *
1055  *    gather queue:
1056  *    decode queue:    7  8  9
1057  *    output queue:    9  8
1058  *
1059  * Then we remove the consumed buffers from the decode queue. Buffer 7 is not
1060  * completely consumed, we need to keep it around for when we receive buffer
1061  * 6. This yields:
1062  *
1063  *    gather queue:
1064  *    decode queue:    7
1065  *    output queue:    9  8
1066  *
1067  * Then we accumulate more buffers:
1068  *
1069  *    gather queue:    6  5  4
1070  *    decode queue:    7
1071  *    output queue:
1072  *
1073  * prepending to the decode queue on DISCONT yields:
1074  *
1075  *    gather queue:
1076  *    decode queue:    4  5  6  7
1077  *    output queue:
1078  *
1079  * after decoding and keeping buffer 4:
1080  *
1081  *    gather queue:
1082  *    decode queue:    4
1083  *    output queue:    7  6  5
1084  *
1085  * Etc..
1086  */
1087 static GstFlowReturn
1088 vorbis_dec_flush_decode (GstVorbisDec * dec)
1089 {
1090   GstFlowReturn res = GST_FLOW_OK;
1091   GList *walk;
1092
1093   walk = dec->decode;
1094
1095   GST_DEBUG_OBJECT (dec, "flushing buffers to decoder");
1096
1097   while (walk) {
1098     GList *next;
1099     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1100
1101     GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1102         buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1103
1104     next = g_list_next (walk);
1105
1106     /* decode buffer, prepend to output queue */
1107     res = vorbis_dec_decode_buffer (dec, buf);
1108
1109     /* if we generated output, we can discard the buffer, else we
1110      * keep it in the queue */
1111     if (dec->queued) {
1112       GST_DEBUG_OBJECT (dec, "decoded buffer to %p", dec->queued->data);
1113       dec->decode = g_list_delete_link (dec->decode, walk);
1114       gst_buffer_unref (buf);
1115     } else {
1116       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1117     }
1118     walk = next;
1119   }
1120   while (dec->queued) {
1121     GstBuffer *buf = GST_BUFFER_CAST (dec->queued->data);
1122     GstClockTime timestamp, duration;
1123
1124     timestamp = GST_BUFFER_TIMESTAMP (buf);
1125     duration = GST_BUFFER_DURATION (buf);
1126
1127     vorbis_do_timestamps (dec, buf, TRUE, timestamp, duration);
1128     res = vorbis_dec_push_forward (dec, buf);
1129
1130     dec->queued = g_list_delete_link (dec->queued, dec->queued);
1131   }
1132   return res;
1133 }
1134
1135 static GstFlowReturn
1136 vorbis_dec_chain_reverse (GstVorbisDec * vd, gboolean discont, GstBuffer * buf)
1137 {
1138   GstFlowReturn result = GST_FLOW_OK;
1139
1140   /* if we have a discont, move buffers to the decode list */
1141   if (G_UNLIKELY (discont)) {
1142     GST_DEBUG_OBJECT (vd, "received discont");
1143     while (vd->gather) {
1144       GstBuffer *gbuf;
1145
1146       gbuf = GST_BUFFER_CAST (vd->gather->data);
1147       /* remove from the gather list */
1148       vd->gather = g_list_delete_link (vd->gather, vd->gather);
1149       /* copy to decode queue */
1150       vd->decode = g_list_prepend (vd->decode, gbuf);
1151     }
1152     /* flush and decode the decode queue */
1153     result = vorbis_dec_flush_decode (vd);
1154   }
1155
1156   if (G_LIKELY (buf)) {
1157     GST_DEBUG_OBJECT (vd,
1158         "gathering buffer %p of size %u, time %" GST_TIME_FORMAT
1159         ", dur %" GST_TIME_FORMAT, buf, gst_buffer_get_size (buf),
1160         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1161         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1162
1163     /* add buffer to gather queue */
1164     vd->gather = g_list_prepend (vd->gather, buf);
1165   }
1166
1167   return result;
1168 }
1169
1170 static GstFlowReturn
1171 vorbis_dec_chain_forward (GstVorbisDec * vd, gboolean discont,
1172     GstBuffer * buffer)
1173 {
1174   GstFlowReturn result;
1175
1176   result = vorbis_dec_decode_buffer (vd, buffer);
1177
1178   gst_buffer_unref (buffer);
1179
1180   return result;
1181 }
1182
1183 static GstFlowReturn
1184 vorbis_dec_chain (GstPad * pad, GstBuffer * buffer)
1185 {
1186   GstVorbisDec *vd;
1187   GstFlowReturn result = GST_FLOW_OK;
1188   gboolean discont;
1189
1190   vd = GST_VORBIS_DEC (gst_pad_get_parent (pad));
1191
1192   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1193
1194   /* resync on DISCONT */
1195   if (G_UNLIKELY (discont)) {
1196     GST_DEBUG_OBJECT (vd, "received DISCONT buffer");
1197     vd->last_timestamp = GST_CLOCK_TIME_NONE;
1198 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
1199     vorbis_synthesis_restart (&vd->vd);
1200 #endif
1201     vd->discont = TRUE;
1202   }
1203
1204   if (vd->segment.rate >= 0.0)
1205     result = vorbis_dec_chain_forward (vd, discont, buffer);
1206   else
1207     result = vorbis_dec_chain_reverse (vd, discont, buffer);
1208
1209   gst_object_unref (vd);
1210
1211   return result;
1212 }
1213
1214 static GstStateChangeReturn
1215 vorbis_dec_change_state (GstElement * element, GstStateChange transition)
1216 {
1217   GstVorbisDec *vd = GST_VORBIS_DEC (element);
1218   GstStateChangeReturn res;
1219
1220   switch (transition) {
1221     case GST_STATE_CHANGE_NULL_TO_READY:
1222       break;
1223     case GST_STATE_CHANGE_READY_TO_PAUSED:
1224       vorbis_info_init (&vd->vi);
1225       vorbis_comment_init (&vd->vc);
1226       vd->initialized = FALSE;
1227       gst_vorbis_dec_reset (vd);
1228       break;
1229     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1230       break;
1231     default:
1232       break;
1233   }
1234
1235   res = parent_class->change_state (element, transition);
1236
1237   switch (transition) {
1238     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1239       break;
1240     case GST_STATE_CHANGE_PAUSED_TO_READY:
1241       GST_DEBUG_OBJECT (vd, "PAUSED -> READY, clearing vorbis structures");
1242       vd->initialized = FALSE;
1243       vorbis_block_clear (&vd->vb);
1244       vorbis_dsp_clear (&vd->vd);
1245       vorbis_comment_clear (&vd->vc);
1246       vorbis_info_clear (&vd->vi);
1247       gst_vorbis_dec_reset (vd);
1248       break;
1249     case GST_STATE_CHANGE_READY_TO_NULL:
1250       break;
1251     default:
1252       break;
1253   }
1254
1255   return res;
1256 }