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,
312           GST_TIME_ARGS (time));
313
314       /* and convert to the final format */
315       if (!(res =
316               vorbis_dec_convert (pad, GST_FORMAT_TIME, time, &format, &value)))
317         goto error;
318
319       gst_query_set_position (*query, format, value);
320
321       GST_LOG_OBJECT (dec,
322           "query %p: we return %" G_GINT64_FORMAT " (format %u)", *query, value,
323           format);
324
325       break;
326     }
327     case GST_QUERY_DURATION:
328     {
329       res = gst_pad_peer_query (dec->sinkpad, query);
330       if (!res)
331         goto error;
332
333       break;
334     }
335     case GST_QUERY_CONVERT:
336     {
337       GstFormat src_fmt, dest_fmt;
338       gint64 src_val, dest_val;
339
340       gst_query_parse_convert (*query, &src_fmt, &src_val, &dest_fmt,
341           &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,
380           &dest_val);
381       if (!(res =
382               vorbis_dec_convert (pad, src_fmt, src_val, &dest_fmt, &dest_val)))
383         goto error;
384       gst_query_set_convert (*query, src_fmt, src_val, dest_fmt, dest_val);
385       break;
386     }
387     default:
388       res = gst_pad_query_default (pad, query);
389       break;
390   }
391
392 done:
393   gst_object_unref (dec);
394
395   return res;
396
397   /* ERRORS */
398 error:
399   {
400     GST_DEBUG_OBJECT (dec, "error converting value");
401     goto done;
402   }
403 }
404
405 static gboolean
406 vorbis_dec_src_event (GstPad * pad, GstEvent * event)
407 {
408   gboolean res = TRUE;
409   GstVorbisDec *dec;
410
411   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
412   if (G_UNLIKELY (dec == NULL)) {
413     gst_event_unref (event);
414     return FALSE;
415   }
416
417   switch (GST_EVENT_TYPE (event)) {
418     case GST_EVENT_SEEK:
419     {
420       GstFormat format, tformat;
421       gdouble rate;
422       GstEvent *real_seek;
423       GstSeekFlags flags;
424       GstSeekType cur_type, stop_type;
425       gint64 cur, stop;
426       gint64 tcur, tstop;
427       guint32 seqnum;
428
429       gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
430           &stop_type, &stop);
431       seqnum = gst_event_get_seqnum (event);
432       gst_event_unref (event);
433
434       /* First bring the requested format to time */
435       tformat = GST_FORMAT_TIME;
436       if (!(res = vorbis_dec_convert (pad, format, cur, &tformat, &tcur)))
437         goto convert_error;
438       if (!(res = vorbis_dec_convert (pad, format, stop, &tformat, &tstop)))
439         goto convert_error;
440
441       /* then seek with time on the peer */
442       real_seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
443           flags, cur_type, tcur, stop_type, tstop);
444       gst_event_set_seqnum (real_seek, seqnum);
445
446       res = gst_pad_push_event (dec->sinkpad, real_seek);
447       break;
448     }
449     default:
450       res = gst_pad_push_event (dec->sinkpad, event);
451       break;
452   }
453 done:
454   gst_object_unref (dec);
455
456   return res;
457
458   /* ERRORS */
459 convert_error:
460   {
461     GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
462     goto done;
463   }
464 }
465
466 static gboolean
467 vorbis_dec_sink_event (GstPad * pad, GstEvent * event)
468 {
469   gboolean ret = FALSE;
470   GstVorbisDec *dec;
471
472   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
473
474   GST_LOG_OBJECT (dec, "handling event");
475   switch (GST_EVENT_TYPE (event)) {
476     case GST_EVENT_EOS:
477       if (dec->segment.rate < 0.0)
478         vorbis_dec_chain_reverse (dec, TRUE, NULL);
479       ret = gst_pad_push_event (dec->srcpad, event);
480       break;
481     case GST_EVENT_FLUSH_START:
482       ret = gst_pad_push_event (dec->srcpad, event);
483       break;
484     case GST_EVENT_FLUSH_STOP:
485       /* here we must clean any state in the decoder */
486 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
487       vorbis_synthesis_restart (&dec->vd);
488 #endif
489       gst_vorbis_dec_reset (dec);
490       ret = gst_pad_push_event (dec->srcpad, event);
491       break;
492     case GST_EVENT_SEGMENT:
493     {
494       GstSegment segment;
495
496       gst_event_parse_segment (event, &segment);
497
498       /* we need time for now */
499       if (segment.format != GST_FORMAT_TIME)
500         goto newseg_wrong_format;
501
502       GST_DEBUG_OBJECT (dec, "segment: %" GST_SEGMENT_FORMAT, &segment);
503
504       /* now configure the values */
505       gst_segment_copy_into (&segment, &dec->segment);
506       dec->seqnum = gst_event_get_seqnum (event);
507
508       if (dec->initialized)
509         /* and forward */
510         ret = gst_pad_push_event (dec->srcpad, event);
511       else {
512         /* store it to send once we're initialized */
513         dec->pendingevents = g_list_append (dec->pendingevents, event);
514         ret = TRUE;
515       }
516       break;
517     }
518     case GST_EVENT_TAG:
519     {
520       if (dec->initialized)
521         /* and forward */
522         ret = gst_pad_push_event (dec->srcpad, event);
523       else {
524         /* store it to send once we're initialized */
525         dec->pendingevents = g_list_append (dec->pendingevents, event);
526         ret = TRUE;
527       }
528       break;
529     }
530     default:
531       ret = gst_pad_event_default (pad, event);
532       break;
533   }
534 done:
535   gst_object_unref (dec);
536
537   return ret;
538
539   /* ERRORS */
540 newseg_wrong_format:
541   {
542     GST_DEBUG_OBJECT (dec, "received non TIME newsegment");
543     goto done;
544   }
545 }
546
547 static GstFlowReturn
548 vorbis_handle_identification_packet (GstVorbisDec * vd)
549 {
550   GstCaps *caps;
551   const GstAudioChannelPosition *pos = NULL;
552   gint width = GST_VORBIS_DEC_DEFAULT_SAMPLE_WIDTH;
553
554   switch (vd->vi.channels) {
555     case 1:
556     case 2:
557       /* nothing */
558       break;
559     case 3:
560     case 4:
561     case 5:
562     case 6:
563     case 7:
564     case 8:
565       pos = gst_vorbis_channel_positions[vd->vi.channels - 1];
566       break;
567     default:{
568       gint i;
569       GstAudioChannelPosition *posn =
570           g_new (GstAudioChannelPosition, vd->vi.channels);
571
572       GST_ELEMENT_WARNING (GST_ELEMENT (vd), STREAM, DECODE,
573           (NULL), ("Using NONE channel layout for more than 8 channels"));
574
575       for (i = 0; i < vd->vi.channels; i++)
576         posn[i] = GST_AUDIO_CHANNEL_POSITION_NONE;
577
578       pos = posn;
579     }
580   }
581
582   /* negotiate width with downstream */
583   caps = gst_pad_get_allowed_caps (vd->srcpad);
584   if (caps) {
585     if (!gst_caps_is_empty (caps)) {
586       GstStructure *s;
587
588       s = gst_caps_get_structure (caps, 0);
589       /* template ensures 16 or 32 */
590       gst_structure_get_int (s, "width", &width);
591
592       GST_INFO_OBJECT (vd, "using %s with %d channels and %d bit audio depth",
593           gst_structure_get_name (s), vd->vi.channels, width);
594     }
595     gst_caps_unref (caps);
596   }
597   vd->width = width >> 3;
598
599   /* select a copy_samples function, this way we can have specialized versions
600    * for mono/stereo and avoid the depth switch in tremor case */
601   vd->copy_samples = get_copy_sample_func (vd->vi.channels, vd->width);
602
603   caps = gst_caps_copy (gst_pad_get_pad_template_caps (vd->srcpad));
604   gst_caps_set_simple (caps, "rate", G_TYPE_INT, vd->vi.rate,
605       "channels", G_TYPE_INT, vd->vi.channels,
606       "width", G_TYPE_INT, width, NULL);
607
608   if (pos) {
609     gst_audio_set_channel_positions (gst_caps_get_structure (caps, 0), pos);
610   }
611
612   if (vd->vi.channels > 8) {
613     g_free ((GstAudioChannelPosition *) pos);
614   }
615
616   gst_pad_set_caps (vd->srcpad, caps);
617   gst_caps_unref (caps);
618
619   return GST_FLOW_OK;
620 }
621
622 static GstFlowReturn
623 vorbis_handle_comment_packet (GstVorbisDec * vd, ogg_packet * packet)
624 {
625   guint bitrate = 0;
626   gchar *encoder = NULL;
627   GstTagList *list, *old_list;
628   guint8 *data;
629   gsize size;
630
631   GST_DEBUG_OBJECT (vd, "parsing comment packet");
632
633   data = gst_ogg_packet_data (packet);
634   size = gst_ogg_packet_size (packet);
635
636   list =
637       gst_tag_list_from_vorbiscomment (data, size, (guint8 *) "\003vorbis", 7,
638       &encoder);
639
640   old_list = vd->taglist;
641   vd->taglist = gst_tag_list_merge (vd->taglist, list, GST_TAG_MERGE_REPLACE);
642
643   if (old_list)
644     gst_tag_list_free (old_list);
645   gst_tag_list_free (list);
646
647   if (!vd->taglist) {
648     GST_ERROR_OBJECT (vd, "couldn't decode comments");
649     vd->taglist = gst_tag_list_new ();
650   }
651   if (encoder) {
652     if (encoder[0])
653       gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
654           GST_TAG_ENCODER, encoder, NULL);
655     g_free (encoder);
656   }
657   gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
658       GST_TAG_ENCODER_VERSION, vd->vi.version,
659       GST_TAG_AUDIO_CODEC, "Vorbis", NULL);
660   if (vd->vi.bitrate_nominal > 0 && vd->vi.bitrate_nominal <= 0x7FFFFFFF) {
661     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
662         GST_TAG_NOMINAL_BITRATE, (guint) vd->vi.bitrate_nominal, NULL);
663     bitrate = vd->vi.bitrate_nominal;
664   }
665   if (vd->vi.bitrate_upper > 0 && vd->vi.bitrate_upper <= 0x7FFFFFFF) {
666     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
667         GST_TAG_MAXIMUM_BITRATE, (guint) vd->vi.bitrate_upper, NULL);
668     if (!bitrate)
669       bitrate = vd->vi.bitrate_upper;
670   }
671   if (vd->vi.bitrate_lower > 0 && vd->vi.bitrate_lower <= 0x7FFFFFFF) {
672     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
673         GST_TAG_MINIMUM_BITRATE, (guint) vd->vi.bitrate_lower, NULL);
674     if (!bitrate)
675       bitrate = vd->vi.bitrate_lower;
676   }
677   if (bitrate) {
678     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
679         GST_TAG_BITRATE, (guint) bitrate, NULL);
680   }
681
682   if (vd->initialized) {
683     gst_element_found_tags_for_pad (GST_ELEMENT_CAST (vd), vd->srcpad,
684         vd->taglist);
685     vd->taglist = NULL;
686   } else {
687     /* Only post them as messages for the time being. *
688      * They will be pushed on the pad once the decoder is initialized */
689     gst_element_post_message (GST_ELEMENT_CAST (vd),
690         gst_message_new_tag (GST_OBJECT (vd), gst_tag_list_copy (vd->taglist)));
691   }
692
693   return GST_FLOW_OK;
694 }
695
696 static GstFlowReturn
697 vorbis_handle_type_packet (GstVorbisDec * vd)
698 {
699   GList *walk;
700   gint res;
701
702   g_assert (vd->initialized == FALSE);
703
704 #ifdef USE_TREMOLO
705   if (G_UNLIKELY ((res = vorbis_dsp_init (&vd->vd, &vd->vi))))
706     goto synthesis_init_error;
707 #else
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 #endif
714
715   vd->initialized = TRUE;
716
717   if (vd->pendingevents) {
718     for (walk = vd->pendingevents; walk; walk = g_list_next (walk))
719       gst_pad_push_event (vd->srcpad, GST_EVENT_CAST (walk->data));
720     g_list_free (vd->pendingevents);
721     vd->pendingevents = NULL;
722   }
723
724   if (vd->taglist) {
725     /* The tags have already been sent on the bus as messages. */
726     gst_pad_push_event (vd->srcpad, gst_event_new_tag (vd->taglist));
727     vd->taglist = NULL;
728   }
729   return GST_FLOW_OK;
730
731   /* ERRORS */
732 synthesis_init_error:
733   {
734     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
735         (NULL), ("couldn't initialize synthesis (%d)", res));
736     return GST_FLOW_ERROR;
737   }
738 block_init_error:
739   {
740     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
741         (NULL), ("couldn't initialize block (%d)", res));
742     return GST_FLOW_ERROR;
743   }
744 }
745
746 static GstFlowReturn
747 vorbis_handle_header_packet (GstVorbisDec * vd, ogg_packet * packet)
748 {
749   GstFlowReturn res;
750   gint ret;
751
752   GST_DEBUG_OBJECT (vd, "parsing header packet");
753
754   /* Packetno = 0 if the first byte is exactly 0x01 */
755   packet->b_o_s = ((gst_ogg_packet_data (packet))[0] == 0x1) ? 1 : 0;
756
757 #ifdef USE_TREMOLO
758   if ((ret = vorbis_dsp_headerin (&vd->vi, &vd->vc, packet)))
759 #else
760   if ((ret = vorbis_synthesis_headerin (&vd->vi, &vd->vc, packet)))
761 #endif
762     goto header_read_error;
763
764   switch ((gst_ogg_packet_data (packet))[0]) {
765     case 0x01:
766       res = vorbis_handle_identification_packet (vd);
767       break;
768     case 0x03:
769       res = vorbis_handle_comment_packet (vd, packet);
770       break;
771     case 0x05:
772       res = vorbis_handle_type_packet (vd);
773       break;
774     default:
775       /* ignore */
776       g_warning ("unknown vorbis header packet found");
777       res = GST_FLOW_OK;
778       break;
779   }
780   return res;
781
782   /* ERRORS */
783 header_read_error:
784   {
785     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
786         (NULL), ("couldn't read header packet (%d)", ret));
787     return GST_FLOW_ERROR;
788   }
789 }
790
791 static GstFlowReturn
792 vorbis_dec_push_forward (GstVorbisDec * dec, GstBuffer * buf)
793 {
794   GstFlowReturn result;
795
796   /* clip */
797   if (!(buf = gst_audio_buffer_clip (buf, &dec->segment, dec->vi.rate,
798               dec->vi.channels * dec->width))) {
799     GST_LOG_OBJECT (dec, "clipped buffer");
800     return GST_FLOW_OK;
801   }
802
803   if (dec->discont) {
804     GST_LOG_OBJECT (dec, "setting DISCONT");
805     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
806     dec->discont = FALSE;
807   }
808
809   GST_DEBUG_OBJECT (dec,
810       "pushing time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
811       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
812       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
813
814   result = gst_pad_push (dec->srcpad, buf);
815
816   return result;
817 }
818
819 static GstFlowReturn
820 vorbis_dec_push_reverse (GstVorbisDec * dec, GstBuffer * buf)
821 {
822   GstFlowReturn result = GST_FLOW_OK;
823
824   dec->queued = g_list_prepend (dec->queued, buf);
825
826   return result;
827 }
828
829 static void
830 vorbis_do_timestamps (GstVorbisDec * vd, GstBuffer * buf, gboolean reverse,
831     GstClockTime timestamp, GstClockTime duration)
832 {
833   /* interpolate reverse */
834   if (vd->last_timestamp != -1 && duration != -1 && reverse)
835     vd->last_timestamp -= duration;
836
837   /* take buffer timestamp, use interpolated timestamp otherwise */
838   if (timestamp != -1)
839     vd->last_timestamp = timestamp;
840   else
841     timestamp = vd->last_timestamp;
842
843   /* interpolate forwards */
844   if (vd->last_timestamp != -1 && duration != -1 && !reverse)
845     vd->last_timestamp += duration;
846
847   GST_LOG_OBJECT (vd,
848       "keeping timestamp %" GST_TIME_FORMAT " ts %" GST_TIME_FORMAT " dur %"
849       GST_TIME_FORMAT, GST_TIME_ARGS (vd->last_timestamp),
850       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
851
852   if (buf) {
853     GST_BUFFER_TIMESTAMP (buf) = timestamp;
854     GST_BUFFER_DURATION (buf) = duration;
855   }
856 }
857
858 static GstFlowReturn
859 vorbis_handle_data_packet (GstVorbisDec * vd, ogg_packet * packet,
860     GstClockTime timestamp, GstClockTime duration)
861 {
862 #ifdef USE_TREMOLO
863   vorbis_sample_t *pcm;
864 #else
865   vorbis_sample_t **pcm;
866 #endif
867   guint sample_count;
868   GstBuffer *out = NULL;
869   GstFlowReturn result;
870   guint8 *data;
871   gsize size;
872
873   if (G_UNLIKELY (!vd->initialized))
874     goto not_initialized;
875
876   /* normal data packet */
877   /* FIXME, we can skip decoding if the packet is outside of the
878    * segment, this is however not very trivial as we need a previous
879    * packet to decode the current one so we must be carefull not to
880    * throw away too much. For now we decode everything and clip right
881    * before pushing data. */
882
883 #ifdef USE_TREMOLO
884   if (G_UNLIKELY (vorbis_dsp_synthesis (&vd->vd, packet, 1)))
885     goto could_not_read;
886 #else
887   if (G_UNLIKELY (vorbis_synthesis (&vd->vb, packet)))
888     goto could_not_read;
889
890   if (G_UNLIKELY (vorbis_synthesis_blockin (&vd->vd, &vd->vb) < 0))
891     goto not_accepted;
892 #endif
893
894   /* assume all goes well here */
895   result = GST_FLOW_OK;
896
897   /* count samples ready for reading */
898 #ifdef USE_TREMOLO
899   if ((sample_count = vorbis_dsp_pcmout (&vd->vd, NULL, 0)) == 0)
900 #else
901   if ((sample_count = vorbis_synthesis_pcmout (&vd->vd, NULL)) == 0)
902 #endif
903     goto done;
904
905   size = sample_count * vd->vi.channels * vd->width;
906   GST_LOG_OBJECT (vd, "%d samples ready for reading, size %d", sample_count,
907       size);
908
909   /* alloc buffer for it */
910   out = gst_buffer_new_and_alloc (size);
911
912   /* get samples ready for reading now, should be sample_count */
913 #ifdef USE_TREMOLO
914   pcm = GST_BUFFER_DATA (out);
915   if (G_UNLIKELY ((vorbis_dsp_pcmout (&vd->vd, pcm,
916                   sample_count)) != sample_count))
917 #else
918   if (G_UNLIKELY ((vorbis_synthesis_pcmout (&vd->vd, &pcm)) != sample_count))
919 #endif
920     goto wrong_samples;
921
922 #ifndef USE_TREMOLO
923   /* copy samples in buffer */
924   data = gst_buffer_map (out, NULL, NULL, GST_MAP_WRITE);
925   vd->copy_samples ((vorbis_sample_t *) data, pcm,
926       sample_count, vd->vi.channels, vd->width);
927 #endif
928
929   GST_LOG_OBJECT (vd, "setting output size to %d", size);
930   gst_buffer_unmap (out, data, size);
931
932   /* this should not overflow */
933   if (duration == -1)
934     duration = sample_count * GST_SECOND / vd->vi.rate;
935
936   vorbis_do_timestamps (vd, out, FALSE, timestamp, duration);
937
938   if (vd->segment.rate >= 0.0)
939     result = vorbis_dec_push_forward (vd, out);
940   else
941     result = vorbis_dec_push_reverse (vd, out);
942
943 done:
944   if (out == NULL) {
945     /* no output, still keep track of timestamps */
946     vorbis_do_timestamps (vd, NULL, FALSE, timestamp, duration);
947   }
948 #ifdef USE_TREMOLO
949   vorbis_dsp_read (&vd->vd, sample_count);
950 #else
951   vorbis_synthesis_read (&vd->vd, sample_count);
952 #endif
953
954   return result;
955
956   /* ERRORS */
957 not_initialized:
958   {
959     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
960         (NULL), ("no header sent yet"));
961     return GST_FLOW_ERROR;
962   }
963 could_not_read:
964   {
965     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
966         (NULL), ("couldn't read data packet"));
967     return GST_FLOW_ERROR;
968   }
969 not_accepted:
970   {
971     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
972         (NULL), ("vorbis decoder did not accept data packet"));
973     return GST_FLOW_ERROR;
974   }
975 wrong_samples:
976   {
977     gst_buffer_unref (out);
978     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
979         (NULL), ("vorbis decoder reported wrong number of samples"));
980     return GST_FLOW_ERROR;
981   }
982 }
983
984 static GstFlowReturn
985 vorbis_dec_decode_buffer (GstVorbisDec * vd, GstBuffer * buffer)
986 {
987   ogg_packet *packet;
988   ogg_packet_wrapper packet_wrapper;
989   GstFlowReturn result = GST_FLOW_OK;
990
991   /* make ogg_packet out of the buffer */
992   gst_ogg_packet_wrapper_map (&packet_wrapper, buffer);
993   packet = gst_ogg_packet_from_wrapper (&packet_wrapper);
994   /* set some more stuff */
995   packet->granulepos = -1;
996   packet->packetno = 0;         /* we don't care */
997   /* EOS does not matter, it is used in vorbis to implement clipping the last
998    * block of samples based on the granulepos. We clip based on segments. */
999   packet->e_o_s = 0;
1000
1001   GST_LOG_OBJECT (vd, "decode buffer of size %ld", packet->bytes);
1002
1003   /* error out on empty header packets, but just skip empty data packets */
1004   if (G_UNLIKELY (packet->bytes == 0)) {
1005     if (vd->initialized)
1006       goto empty_buffer;
1007     else
1008       goto empty_header;
1009   }
1010
1011   /* switch depending on packet type */
1012   if ((gst_ogg_packet_data (packet))[0] & 1) {
1013     if (vd->initialized) {
1014       GST_WARNING_OBJECT (vd, "Already initialized, so ignoring header packet");
1015       goto done;
1016     }
1017     result = vorbis_handle_header_packet (vd, packet);
1018   } else {
1019     GstClockTime timestamp, duration;
1020
1021     timestamp = GST_BUFFER_TIMESTAMP (buffer);
1022     duration = GST_BUFFER_DURATION (buffer);
1023
1024     result = vorbis_handle_data_packet (vd, packet, timestamp, duration);
1025   }
1026
1027 done:
1028   gst_ogg_packet_wrapper_unmap (&packet_wrapper, buffer);
1029
1030   return result;
1031
1032 empty_buffer:
1033   {
1034     /* don't error out here, just ignore the buffer, it's invalid for vorbis
1035      * but not fatal. */
1036     GST_WARNING_OBJECT (vd, "empty buffer received, ignoring");
1037     result = GST_FLOW_OK;
1038     goto done;
1039   }
1040
1041 /* ERRORS */
1042 empty_header:
1043   {
1044     GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL), ("empty header received"));
1045     result = GST_FLOW_ERROR;
1046     vd->discont = TRUE;
1047     goto done;
1048   }
1049 }
1050
1051 /*
1052  * Input:
1053  *  Buffer decoding order:  7  8  9  4  5  6  3  1  2  EOS
1054  *  Discont flag:           D        D        D  D
1055  *
1056  * - Each Discont marks a discont in the decoding order.
1057  *
1058  * for vorbis, each buffer is a keyframe when we have the previous
1059  * buffer. This means that to decode buffer 7, we need buffer 6, which
1060  * arrives out of order.
1061  *
1062  * we first gather buffers in the gather queue until we get a DISCONT. We
1063  * prepend each incomming buffer so that they are in reversed order.
1064  *
1065  *    gather queue:    9  8  7
1066  *    decode queue:
1067  *    output queue:
1068  *
1069  * When a DISCONT is received (buffer 4), we move the gather queue to the
1070  * decode queue. This is simply done be taking the head of the gather queue
1071  * and prepending it to the decode queue. This yields:
1072  *
1073  *    gather queue:
1074  *    decode queue:    7  8  9
1075  *    output queue:
1076  *
1077  * Then we decode each buffer in the decode queue in order and put the output
1078  * buffer in the output queue. The first buffer (7) will not produce any output
1079  * because it needs the previous buffer (6) which did not arrive yet. This
1080  * yields:
1081  *
1082  *    gather queue:
1083  *    decode queue:    7  8  9
1084  *    output queue:    9  8
1085  *
1086  * Then we remove the consumed buffers from the decode queue. Buffer 7 is not
1087  * completely consumed, we need to keep it around for when we receive buffer
1088  * 6. This yields:
1089  *
1090  *    gather queue:
1091  *    decode queue:    7
1092  *    output queue:    9  8
1093  *
1094  * Then we accumulate more buffers:
1095  *
1096  *    gather queue:    6  5  4
1097  *    decode queue:    7
1098  *    output queue:
1099  *
1100  * prepending to the decode queue on DISCONT yields:
1101  *
1102  *    gather queue:
1103  *    decode queue:    4  5  6  7
1104  *    output queue:
1105  *
1106  * after decoding and keeping buffer 4:
1107  *
1108  *    gather queue:
1109  *    decode queue:    4
1110  *    output queue:    7  6  5
1111  *
1112  * Etc..
1113  */
1114 static GstFlowReturn
1115 vorbis_dec_flush_decode (GstVorbisDec * dec)
1116 {
1117   GstFlowReturn res = GST_FLOW_OK;
1118   GList *walk;
1119
1120   walk = dec->decode;
1121
1122   GST_DEBUG_OBJECT (dec, "flushing buffers to decoder");
1123
1124   while (walk) {
1125     GList *next;
1126     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1127
1128     GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1129         buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1130
1131     next = g_list_next (walk);
1132
1133     /* decode buffer, prepend to output queue */
1134     res = vorbis_dec_decode_buffer (dec, buf);
1135
1136     /* if we generated output, we can discard the buffer, else we
1137      * keep it in the queue */
1138     if (dec->queued) {
1139       GST_DEBUG_OBJECT (dec, "decoded buffer to %p", dec->queued->data);
1140       dec->decode = g_list_delete_link (dec->decode, walk);
1141       gst_buffer_unref (buf);
1142     } else {
1143       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1144     }
1145     walk = next;
1146   }
1147   while (dec->queued) {
1148     GstBuffer *buf = GST_BUFFER_CAST (dec->queued->data);
1149     GstClockTime timestamp, duration;
1150
1151     timestamp = GST_BUFFER_TIMESTAMP (buf);
1152     duration = GST_BUFFER_DURATION (buf);
1153
1154     vorbis_do_timestamps (dec, buf, TRUE, timestamp, duration);
1155     res = vorbis_dec_push_forward (dec, buf);
1156
1157     dec->queued = g_list_delete_link (dec->queued, dec->queued);
1158   }
1159   return res;
1160 }
1161
1162 static GstFlowReturn
1163 vorbis_dec_chain_reverse (GstVorbisDec * vd, gboolean discont, GstBuffer * buf)
1164 {
1165   GstFlowReturn result = GST_FLOW_OK;
1166
1167   /* if we have a discont, move buffers to the decode list */
1168   if (G_UNLIKELY (discont)) {
1169     GST_DEBUG_OBJECT (vd, "received discont");
1170     while (vd->gather) {
1171       GstBuffer *gbuf;
1172
1173       gbuf = GST_BUFFER_CAST (vd->gather->data);
1174       /* remove from the gather list */
1175       vd->gather = g_list_delete_link (vd->gather, vd->gather);
1176       /* copy to decode queue */
1177       vd->decode = g_list_prepend (vd->decode, gbuf);
1178     }
1179     /* flush and decode the decode queue */
1180     result = vorbis_dec_flush_decode (vd);
1181   }
1182
1183   if (G_LIKELY (buf)) {
1184     GST_DEBUG_OBJECT (vd,
1185         "gathering buffer %p of size %u, time %" GST_TIME_FORMAT
1186         ", dur %" GST_TIME_FORMAT, buf, gst_buffer_get_size (buf),
1187         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1188         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1189
1190     /* add buffer to gather queue */
1191     vd->gather = g_list_prepend (vd->gather, buf);
1192   }
1193
1194   return result;
1195 }
1196
1197 static GstFlowReturn
1198 vorbis_dec_chain_forward (GstVorbisDec * vd, gboolean discont,
1199     GstBuffer * buffer)
1200 {
1201   GstFlowReturn result;
1202
1203   result = vorbis_dec_decode_buffer (vd, buffer);
1204
1205   gst_buffer_unref (buffer);
1206
1207   return result;
1208 }
1209
1210 static GstFlowReturn
1211 vorbis_dec_chain (GstPad * pad, GstBuffer * buffer)
1212 {
1213   GstVorbisDec *vd;
1214   GstFlowReturn result = GST_FLOW_OK;
1215   gboolean discont;
1216
1217   vd = GST_VORBIS_DEC (gst_pad_get_parent (pad));
1218
1219   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1220
1221   /* resync on DISCONT */
1222   if (G_UNLIKELY (discont)) {
1223     GST_DEBUG_OBJECT (vd, "received DISCONT buffer");
1224     vd->last_timestamp = GST_CLOCK_TIME_NONE;
1225 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
1226     vorbis_synthesis_restart (&vd->vd);
1227 #endif
1228     vd->discont = TRUE;
1229   }
1230
1231   if (vd->segment.rate >= 0.0)
1232     result = vorbis_dec_chain_forward (vd, discont, buffer);
1233   else
1234     result = vorbis_dec_chain_reverse (vd, discont, buffer);
1235
1236   gst_object_unref (vd);
1237
1238   return result;
1239 }
1240
1241 static GstStateChangeReturn
1242 vorbis_dec_change_state (GstElement * element, GstStateChange transition)
1243 {
1244   GstVorbisDec *vd = GST_VORBIS_DEC (element);
1245   GstStateChangeReturn res;
1246
1247   switch (transition) {
1248     case GST_STATE_CHANGE_NULL_TO_READY:
1249       break;
1250     case GST_STATE_CHANGE_READY_TO_PAUSED:
1251       vorbis_info_init (&vd->vi);
1252       vorbis_comment_init (&vd->vc);
1253       vd->initialized = FALSE;
1254       gst_vorbis_dec_reset (vd);
1255       break;
1256     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1257       break;
1258     default:
1259       break;
1260   }
1261
1262   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1263
1264   switch (transition) {
1265     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1266       break;
1267     case GST_STATE_CHANGE_PAUSED_TO_READY:
1268       GST_DEBUG_OBJECT (vd, "PAUSED -> READY, clearing vorbis structures");
1269       vd->initialized = FALSE;
1270
1271 #ifndef USE_TREMOLO
1272       vorbis_block_clear (&vd->vb);
1273 #endif
1274
1275       vorbis_dsp_clear (&vd->vd);
1276       vorbis_comment_clear (&vd->vc);
1277       vorbis_info_clear (&vd->vi);
1278       gst_vorbis_dec_reset (vd);
1279       break;
1280     case GST_STATE_CHANGE_READY_TO_NULL:
1281       break;
1282     default:
1283       break;
1284   }
1285
1286   return res;
1287 }