ab6a0776d33810d116911fda0de47d631724806e
[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   GstBuffer *buf;
639
640   GST_DEBUG_OBJECT (vd, "parsing comment packet");
641
642   buf = gst_buffer_new ();
643   GST_BUFFER_DATA (buf) = gst_ogg_packet_data (packet);
644   GST_BUFFER_SIZE (buf) = gst_ogg_packet_size (packet);
645
646   list =
647       gst_tag_list_from_vorbiscomment_buffer (buf, (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   gst_buffer_unref (buf);
657
658   if (!vd->taglist) {
659     GST_ERROR_OBJECT (vd, "couldn't decode comments");
660     vd->taglist = gst_tag_list_new ();
661   }
662   if (encoder) {
663     if (encoder[0])
664       gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
665           GST_TAG_ENCODER, encoder, NULL);
666     g_free (encoder);
667   }
668   gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
669       GST_TAG_ENCODER_VERSION, vd->vi.version,
670       GST_TAG_AUDIO_CODEC, "Vorbis", NULL);
671   if (vd->vi.bitrate_nominal > 0 && vd->vi.bitrate_nominal <= 0x7FFFFFFF) {
672     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
673         GST_TAG_NOMINAL_BITRATE, (guint) vd->vi.bitrate_nominal, NULL);
674     bitrate = vd->vi.bitrate_nominal;
675   }
676   if (vd->vi.bitrate_upper > 0 && vd->vi.bitrate_upper <= 0x7FFFFFFF) {
677     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
678         GST_TAG_MAXIMUM_BITRATE, (guint) vd->vi.bitrate_upper, NULL);
679     if (!bitrate)
680       bitrate = vd->vi.bitrate_upper;
681   }
682   if (vd->vi.bitrate_lower > 0 && vd->vi.bitrate_lower <= 0x7FFFFFFF) {
683     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
684         GST_TAG_MINIMUM_BITRATE, (guint) vd->vi.bitrate_lower, NULL);
685     if (!bitrate)
686       bitrate = vd->vi.bitrate_lower;
687   }
688   if (bitrate) {
689     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
690         GST_TAG_BITRATE, (guint) bitrate, NULL);
691   }
692
693   if (vd->initialized) {
694     gst_element_found_tags_for_pad (GST_ELEMENT_CAST (vd), vd->srcpad,
695         vd->taglist);
696     vd->taglist = NULL;
697   } else {
698     /* Only post them as messages for the time being. *
699      * They will be pushed on the pad once the decoder is initialized */
700     gst_element_post_message (GST_ELEMENT_CAST (vd),
701         gst_message_new_tag (GST_OBJECT (vd), gst_tag_list_copy (vd->taglist)));
702   }
703
704   return GST_FLOW_OK;
705 }
706
707 static GstFlowReturn
708 vorbis_handle_type_packet (GstVorbisDec * vd)
709 {
710   GList *walk;
711   gint res;
712
713   g_assert (vd->initialized == FALSE);
714
715   if (G_UNLIKELY ((res = vorbis_synthesis_init (&vd->vd, &vd->vi))))
716     goto synthesis_init_error;
717
718   if (G_UNLIKELY ((res = vorbis_block_init (&vd->vd, &vd->vb))))
719     goto block_init_error;
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   if ((ret = vorbis_synthesis_headerin (&vd->vi, &vd->vc, packet)))
764     goto header_read_error;
765
766   switch ((gst_ogg_packet_data (packet))[0]) {
767     case 0x01:
768       res = vorbis_handle_identification_packet (vd);
769       break;
770     case 0x03:
771       res = vorbis_handle_comment_packet (vd, packet);
772       break;
773     case 0x05:
774       res = vorbis_handle_type_packet (vd);
775       break;
776     default:
777       /* ignore */
778       g_warning ("unknown vorbis header packet found");
779       res = GST_FLOW_OK;
780       break;
781   }
782   return res;
783
784   /* ERRORS */
785 header_read_error:
786   {
787     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
788         (NULL), ("couldn't read header packet (%d)", ret));
789     return GST_FLOW_ERROR;
790   }
791 }
792
793 static GstFlowReturn
794 vorbis_dec_push_forward (GstVorbisDec * dec, GstBuffer * buf)
795 {
796   GstFlowReturn result;
797
798   /* clip */
799   if (!(buf = gst_audio_buffer_clip (buf, &dec->segment, dec->vi.rate,
800               dec->vi.channels * dec->width))) {
801     GST_LOG_OBJECT (dec, "clipped buffer");
802     return GST_FLOW_OK;
803   }
804
805   if (dec->discont) {
806     GST_LOG_OBJECT (dec, "setting DISCONT");
807     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
808     dec->discont = FALSE;
809   }
810
811   GST_DEBUG_OBJECT (dec,
812       "pushing time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
813       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
814       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
815
816   result = gst_pad_push (dec->srcpad, buf);
817
818   return result;
819 }
820
821 static GstFlowReturn
822 vorbis_dec_push_reverse (GstVorbisDec * dec, GstBuffer * buf)
823 {
824   GstFlowReturn result = GST_FLOW_OK;
825
826   dec->queued = g_list_prepend (dec->queued, buf);
827
828   return result;
829 }
830
831 static void
832 vorbis_do_timestamps (GstVorbisDec * vd, GstBuffer * buf, gboolean reverse,
833     GstClockTime timestamp, GstClockTime duration)
834 {
835   /* interpolate reverse */
836   if (vd->last_timestamp != -1 && duration != -1 && reverse)
837     vd->last_timestamp -= duration;
838
839   /* take buffer timestamp, use interpolated timestamp otherwise */
840   if (timestamp != -1)
841     vd->last_timestamp = timestamp;
842   else
843     timestamp = vd->last_timestamp;
844
845   /* interpolate forwards */
846   if (vd->last_timestamp != -1 && duration != -1 && !reverse)
847     vd->last_timestamp += duration;
848
849   GST_LOG_OBJECT (vd,
850       "keeping timestamp %" GST_TIME_FORMAT " ts %" GST_TIME_FORMAT " dur %"
851       GST_TIME_FORMAT, GST_TIME_ARGS (vd->last_timestamp),
852       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
853
854   if (buf) {
855     GST_BUFFER_TIMESTAMP (buf) = timestamp;
856     GST_BUFFER_DURATION (buf) = duration;
857   }
858 }
859
860 static GstFlowReturn
861 vorbis_handle_data_packet (GstVorbisDec * vd, ogg_packet * packet,
862     GstClockTime timestamp, GstClockTime duration)
863 {
864   vorbis_sample_t **pcm;
865   guint sample_count;
866   GstBuffer *out = NULL;
867   GstFlowReturn result;
868   gint 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   vd->copy_samples ((vorbis_sample_t *) GST_BUFFER_DATA (out), pcm,
909       sample_count, vd->vi.channels, vd->width);
910
911   GST_LOG_OBJECT (vd, "setting output size to %d", size);
912   GST_BUFFER_SIZE (out) = size;
913
914   /* this should not overflow */
915   if (duration == -1)
916     duration = sample_count * GST_SECOND / vd->vi.rate;
917
918   vorbis_do_timestamps (vd, out, FALSE, timestamp, duration);
919
920   if (vd->segment.rate >= 0.0)
921     result = vorbis_dec_push_forward (vd, out);
922   else
923     result = vorbis_dec_push_reverse (vd, out);
924
925 done:
926   if (out == NULL) {
927     /* no output, still keep track of timestamps */
928     vorbis_do_timestamps (vd, NULL, FALSE, timestamp, duration);
929   }
930   vorbis_synthesis_read (&vd->vd, sample_count);
931
932   return result;
933
934   /* ERRORS */
935 not_initialized:
936   {
937     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
938         (NULL), ("no header sent yet"));
939     return GST_FLOW_ERROR;
940   }
941 could_not_read:
942   {
943     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
944         (NULL), ("couldn't read data packet"));
945     return GST_FLOW_ERROR;
946   }
947 not_accepted:
948   {
949     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
950         (NULL), ("vorbis decoder did not accept data packet"));
951     return GST_FLOW_ERROR;
952   }
953 wrong_samples:
954   {
955     gst_buffer_unref (out);
956     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
957         (NULL), ("vorbis decoder reported wrong number of samples"));
958     return GST_FLOW_ERROR;
959   }
960 }
961
962 static GstFlowReturn
963 vorbis_dec_decode_buffer (GstVorbisDec * vd, GstBuffer * buffer)
964 {
965   ogg_packet *packet;
966   ogg_packet_wrapper packet_wrapper;
967   GstFlowReturn result = GST_FLOW_OK;
968
969   /* make ogg_packet out of the buffer */
970   gst_ogg_packet_wrapper_from_buffer (&packet_wrapper, buffer);
971   packet = gst_ogg_packet_from_wrapper (&packet_wrapper);
972   /* set some more stuff */
973   packet->granulepos = -1;
974   packet->packetno = 0;         /* we don't care */
975   /* EOS does not matter, it is used in vorbis to implement clipping the last
976    * block of samples based on the granulepos. We clip based on segments. */
977   packet->e_o_s = 0;
978
979   GST_LOG_OBJECT (vd, "decode buffer of size %ld", packet->bytes);
980
981   /* error out on empty header packets, but just skip empty data packets */
982   if (G_UNLIKELY (packet->bytes == 0)) {
983     if (vd->initialized)
984       goto empty_buffer;
985     else
986       goto empty_header;
987   }
988
989   /* switch depending on packet type */
990   if ((gst_ogg_packet_data (packet))[0] & 1) {
991     if (vd->initialized) {
992       GST_WARNING_OBJECT (vd, "Already initialized, so ignoring header packet");
993       goto done;
994     }
995     result = vorbis_handle_header_packet (vd, packet);
996   } else {
997     GstClockTime timestamp, duration;
998
999     timestamp = GST_BUFFER_TIMESTAMP (buffer);
1000     duration = GST_BUFFER_DURATION (buffer);
1001
1002     result = vorbis_handle_data_packet (vd, packet, timestamp, duration);
1003   }
1004
1005 done:
1006   return result;
1007
1008 empty_buffer:
1009   {
1010     /* don't error out here, just ignore the buffer, it's invalid for vorbis
1011      * but not fatal. */
1012     GST_WARNING_OBJECT (vd, "empty buffer received, ignoring");
1013     result = GST_FLOW_OK;
1014     goto done;
1015   }
1016
1017 /* ERRORS */
1018 empty_header:
1019   {
1020     GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL), ("empty header received"));
1021     result = GST_FLOW_ERROR;
1022     vd->discont = TRUE;
1023     goto done;
1024   }
1025 }
1026
1027 /*
1028  * Input:
1029  *  Buffer decoding order:  7  8  9  4  5  6  3  1  2  EOS
1030  *  Discont flag:           D        D        D  D
1031  *
1032  * - Each Discont marks a discont in the decoding order.
1033  *
1034  * for vorbis, each buffer is a keyframe when we have the previous
1035  * buffer. This means that to decode buffer 7, we need buffer 6, which
1036  * arrives out of order.
1037  *
1038  * we first gather buffers in the gather queue until we get a DISCONT. We
1039  * prepend each incomming buffer so that they are in reversed order.
1040  *
1041  *    gather queue:    9  8  7
1042  *    decode queue:
1043  *    output queue:
1044  *
1045  * When a DISCONT is received (buffer 4), we move the gather queue to the
1046  * decode queue. This is simply done be taking the head of the gather queue
1047  * and prepending it to the decode queue. This yields:
1048  *
1049  *    gather queue:
1050  *    decode queue:    7  8  9
1051  *    output queue:
1052  *
1053  * Then we decode each buffer in the decode queue in order and put the output
1054  * buffer in the output queue. The first buffer (7) will not produce any output
1055  * because it needs the previous buffer (6) which did not arrive yet. This
1056  * yields:
1057  *
1058  *    gather queue:
1059  *    decode queue:    7  8  9
1060  *    output queue:    9  8
1061  *
1062  * Then we remove the consumed buffers from the decode queue. Buffer 7 is not
1063  * completely consumed, we need to keep it around for when we receive buffer
1064  * 6. This yields:
1065  *
1066  *    gather queue:
1067  *    decode queue:    7
1068  *    output queue:    9  8
1069  *
1070  * Then we accumulate more buffers:
1071  *
1072  *    gather queue:    6  5  4
1073  *    decode queue:    7
1074  *    output queue:
1075  *
1076  * prepending to the decode queue on DISCONT yields:
1077  *
1078  *    gather queue:
1079  *    decode queue:    4  5  6  7
1080  *    output queue:
1081  *
1082  * after decoding and keeping buffer 4:
1083  *
1084  *    gather queue:
1085  *    decode queue:    4
1086  *    output queue:    7  6  5
1087  *
1088  * Etc..
1089  */
1090 static GstFlowReturn
1091 vorbis_dec_flush_decode (GstVorbisDec * dec)
1092 {
1093   GstFlowReturn res = GST_FLOW_OK;
1094   GList *walk;
1095
1096   walk = dec->decode;
1097
1098   GST_DEBUG_OBJECT (dec, "flushing buffers to decoder");
1099
1100   while (walk) {
1101     GList *next;
1102     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1103
1104     GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1105         buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1106
1107     next = g_list_next (walk);
1108
1109     /* decode buffer, prepend to output queue */
1110     res = vorbis_dec_decode_buffer (dec, buf);
1111
1112     /* if we generated output, we can discard the buffer, else we
1113      * keep it in the queue */
1114     if (dec->queued) {
1115       GST_DEBUG_OBJECT (dec, "decoded buffer to %p", dec->queued->data);
1116       dec->decode = g_list_delete_link (dec->decode, walk);
1117       gst_buffer_unref (buf);
1118     } else {
1119       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1120     }
1121     walk = next;
1122   }
1123   while (dec->queued) {
1124     GstBuffer *buf = GST_BUFFER_CAST (dec->queued->data);
1125     GstClockTime timestamp, duration;
1126
1127     timestamp = GST_BUFFER_TIMESTAMP (buf);
1128     duration = GST_BUFFER_DURATION (buf);
1129
1130     vorbis_do_timestamps (dec, buf, TRUE, timestamp, duration);
1131     res = vorbis_dec_push_forward (dec, buf);
1132
1133     dec->queued = g_list_delete_link (dec->queued, dec->queued);
1134   }
1135   return res;
1136 }
1137
1138 static GstFlowReturn
1139 vorbis_dec_chain_reverse (GstVorbisDec * vd, gboolean discont, GstBuffer * buf)
1140 {
1141   GstFlowReturn result = GST_FLOW_OK;
1142
1143   /* if we have a discont, move buffers to the decode list */
1144   if (G_UNLIKELY (discont)) {
1145     GST_DEBUG_OBJECT (vd, "received discont");
1146     while (vd->gather) {
1147       GstBuffer *gbuf;
1148
1149       gbuf = GST_BUFFER_CAST (vd->gather->data);
1150       /* remove from the gather list */
1151       vd->gather = g_list_delete_link (vd->gather, vd->gather);
1152       /* copy to decode queue */
1153       vd->decode = g_list_prepend (vd->decode, gbuf);
1154     }
1155     /* flush and decode the decode queue */
1156     result = vorbis_dec_flush_decode (vd);
1157   }
1158
1159   if (G_LIKELY (buf)) {
1160     GST_DEBUG_OBJECT (vd,
1161         "gathering buffer %p of size %u, time %" GST_TIME_FORMAT
1162         ", dur %" GST_TIME_FORMAT, buf, GST_BUFFER_SIZE (buf),
1163         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1164         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1165
1166     /* add buffer to gather queue */
1167     vd->gather = g_list_prepend (vd->gather, buf);
1168   }
1169
1170   return result;
1171 }
1172
1173 static GstFlowReturn
1174 vorbis_dec_chain_forward (GstVorbisDec * vd, gboolean discont,
1175     GstBuffer * buffer)
1176 {
1177   GstFlowReturn result;
1178
1179   result = vorbis_dec_decode_buffer (vd, buffer);
1180
1181   gst_buffer_unref (buffer);
1182
1183   return result;
1184 }
1185
1186 static GstFlowReturn
1187 vorbis_dec_chain (GstPad * pad, GstBuffer * buffer)
1188 {
1189   GstVorbisDec *vd;
1190   GstFlowReturn result = GST_FLOW_OK;
1191   gboolean discont;
1192
1193   vd = GST_VORBIS_DEC (gst_pad_get_parent (pad));
1194
1195   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1196
1197   /* resync on DISCONT */
1198   if (G_UNLIKELY (discont)) {
1199     GST_DEBUG_OBJECT (vd, "received DISCONT buffer");
1200     vd->last_timestamp = GST_CLOCK_TIME_NONE;
1201 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
1202     vorbis_synthesis_restart (&vd->vd);
1203 #endif
1204     vd->discont = TRUE;
1205   }
1206
1207   if (vd->segment.rate >= 0.0)
1208     result = vorbis_dec_chain_forward (vd, discont, buffer);
1209   else
1210     result = vorbis_dec_chain_reverse (vd, discont, buffer);
1211
1212   gst_object_unref (vd);
1213
1214   return result;
1215 }
1216
1217 static GstStateChangeReturn
1218 vorbis_dec_change_state (GstElement * element, GstStateChange transition)
1219 {
1220   GstVorbisDec *vd = GST_VORBIS_DEC (element);
1221   GstStateChangeReturn res;
1222
1223   switch (transition) {
1224     case GST_STATE_CHANGE_NULL_TO_READY:
1225       break;
1226     case GST_STATE_CHANGE_READY_TO_PAUSED:
1227       vorbis_info_init (&vd->vi);
1228       vorbis_comment_init (&vd->vc);
1229       vd->initialized = FALSE;
1230       gst_vorbis_dec_reset (vd);
1231       break;
1232     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1233       break;
1234     default:
1235       break;
1236   }
1237
1238   res = parent_class->change_state (element, transition);
1239
1240   switch (transition) {
1241     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1242       break;
1243     case GST_STATE_CHANGE_PAUSED_TO_READY:
1244       GST_DEBUG_OBJECT (vd, "PAUSED -> READY, clearing vorbis structures");
1245       vd->initialized = FALSE;
1246       vorbis_block_clear (&vd->vb);
1247       vorbis_dsp_clear (&vd->vd);
1248       vorbis_comment_clear (&vd->vc);
1249       vorbis_info_clear (&vd->vi);
1250       gst_vorbis_dec_reset (vd);
1251       break;
1252     case GST_STATE_CHANGE_READY_TO_NULL:
1253       break;
1254     default:
1255       break;
1256   }
1257
1258   return res;
1259 }