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