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