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