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