Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / ext / vorbis / gstvorbisdec.c
1 /* GStreamer
2  * Copyright (C) 2004 Benjamin Otte <in7y118@public.uni-hamburg.de>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-vorbisdec
22  * @see_also: vorbisenc, oggdemux
23  *
24  * This element decodes a Vorbis stream to raw float audio.
25  * <ulink url="http://www.vorbis.com/">Vorbis</ulink> is a royalty-free
26  * audio codec maintained by the <ulink url="http://www.xiph.org/">Xiph.org
27  * Foundation</ulink>.
28  *
29  * <refsect2>
30  * <title>Example pipelines</title>
31  * |[
32  * gst-launch -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! alsasink
33  * ]| Decode an Ogg/Vorbis. To create an Ogg/Vorbis file refer to the documentation of vorbisenc.
34  * </refsect2>
35  *
36  * Last reviewed on 2006-03-01 (0.10.4)
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #include "gstvorbisdec.h"
44 #include <string.h>
45 #include <gst/audio/audio.h>
46 #include <gst/tag/tag.h>
47 #include <gst/audio/multichannel.h>
48
49 #include "gstvorbiscommon.h"
50
51 GST_DEBUG_CATEGORY_EXTERN (vorbisdec_debug);
52 #define GST_CAT_DEFAULT vorbisdec_debug
53
54 static GstStaticPadTemplate vorbis_dec_src_factory =
55 GST_STATIC_PAD_TEMPLATE ("src",
56     GST_PAD_SRC,
57     GST_PAD_ALWAYS,
58     GST_VORBIS_DEC_SRC_CAPS);
59
60 static GstStaticPadTemplate vorbis_dec_sink_factory =
61 GST_STATIC_PAD_TEMPLATE ("sink",
62     GST_PAD_SINK,
63     GST_PAD_ALWAYS,
64     GST_STATIC_CAPS ("audio/x-vorbis")
65     );
66
67 #define gst_vorbis_dec_parent_class parent_class
68 G_DEFINE_TYPE (GST_VORBIS_DEC_GLIB_TYPE_NAME, gst_vorbis_dec, GST_TYPE_ELEMENT);
69
70 static void vorbis_dec_finalize (GObject * object);
71 static gboolean vorbis_dec_sink_event (GstPad * pad, GstEvent * event);
72 static GstFlowReturn vorbis_dec_chain (GstPad * pad, GstBuffer * buffer);
73 static GstFlowReturn vorbis_dec_chain_forward (GstVorbisDec * vd,
74     gboolean discont, GstBuffer * buffer);
75 static GstFlowReturn vorbis_dec_chain_reverse (GstVorbisDec * vd,
76     gboolean discont, GstBuffer * buf);
77 static GstStateChangeReturn vorbis_dec_change_state (GstElement * element,
78     GstStateChange transition);
79
80 static gboolean vorbis_dec_src_event (GstPad * pad, GstEvent * event);
81 static gboolean vorbis_dec_src_query (GstPad * pad, GstQuery * query);
82 static gboolean vorbis_dec_convert (GstPad * pad,
83     GstFormat src_format, gint64 src_value,
84     GstFormat dest_format, gint64 * dest_value);
85
86 static gboolean vorbis_dec_sink_query (GstPad * pad, GstQuery * query);
87
88 static void
89 gst_vorbis_dec_class_init (GstVorbisDecClass * klass)
90 {
91   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
92   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
93
94   gobject_class->finalize = vorbis_dec_finalize;
95
96   gst_element_class_add_pad_template (gstelement_class,
97       gst_static_pad_template_get (&vorbis_dec_src_factory));
98
99   gst_element_class_add_pad_template (gstelement_class,
100       gst_static_pad_template_get (&vorbis_dec_sink_factory));
101
102   gst_element_class_set_details_simple (gstelement_class,
103       "Vorbis audio decoder", "Codec/Decoder/Audio",
104       GST_VORBIS_DEC_DESCRIPTION,
105       "Benjamin Otte <otte@gnome.org>, Chris Lord <chris@openedhand.com>");
106
107   gstelement_class->change_state = GST_DEBUG_FUNCPTR (vorbis_dec_change_state);
108 }
109
110 static const GstQueryType *
111 vorbis_get_query_types (GstPad * pad)
112 {
113   static const GstQueryType vorbis_dec_src_query_types[] = {
114     GST_QUERY_POSITION,
115     GST_QUERY_DURATION,
116     GST_QUERY_CONVERT,
117     0
118   };
119
120   return vorbis_dec_src_query_types;
121 }
122
123 static void
124 gst_vorbis_dec_init (GstVorbisDec * dec)
125 {
126   dec->sinkpad = gst_pad_new_from_static_template (&vorbis_dec_sink_factory,
127       "sink");
128
129   gst_pad_set_event_function (dec->sinkpad,
130       GST_DEBUG_FUNCPTR (vorbis_dec_sink_event));
131   gst_pad_set_chain_function (dec->sinkpad,
132       GST_DEBUG_FUNCPTR (vorbis_dec_chain));
133   gst_pad_set_query_function (dec->sinkpad,
134       GST_DEBUG_FUNCPTR (vorbis_dec_sink_query));
135   gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
136
137   dec->srcpad = gst_pad_new_from_static_template (&vorbis_dec_src_factory,
138       "src");
139
140   gst_pad_set_event_function (dec->srcpad,
141       GST_DEBUG_FUNCPTR (vorbis_dec_src_event));
142   gst_pad_set_query_type_function (dec->srcpad,
143       GST_DEBUG_FUNCPTR (vorbis_get_query_types));
144   gst_pad_set_query_function (dec->srcpad,
145       GST_DEBUG_FUNCPTR (vorbis_dec_src_query));
146   gst_pad_use_fixed_caps (dec->srcpad);
147   gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
148
149   dec->queued = NULL;
150   dec->pendingevents = NULL;
151   dec->taglist = NULL;
152 }
153
154 static void
155 vorbis_dec_finalize (GObject * object)
156 {
157   /* Release any possibly allocated libvorbis data.
158    * _clear functions can safely be called multiple times
159    */
160   GstVorbisDec *vd = GST_VORBIS_DEC (object);
161
162 #ifndef USE_TREMOLO
163   vorbis_block_clear (&vd->vb);
164 #endif
165
166   vorbis_dsp_clear (&vd->vd);
167   vorbis_comment_clear (&vd->vc);
168   vorbis_info_clear (&vd->vi);
169
170   G_OBJECT_CLASS (parent_class)->finalize (object);
171 }
172
173 static void
174 gst_vorbis_dec_reset (GstVorbisDec * dec)
175 {
176   dec->last_timestamp = GST_CLOCK_TIME_NONE;
177   dec->discont = TRUE;
178   dec->seqnum = gst_util_seqnum_next ();
179   gst_segment_init (&dec->segment, GST_FORMAT_TIME);
180
181   g_list_foreach (dec->queued, (GFunc) gst_mini_object_unref, NULL);
182   g_list_free (dec->queued);
183   dec->queued = NULL;
184   g_list_foreach (dec->gather, (GFunc) gst_mini_object_unref, NULL);
185   g_list_free (dec->gather);
186   dec->gather = NULL;
187   g_list_foreach (dec->decode, (GFunc) gst_mini_object_unref, NULL);
188   g_list_free (dec->decode);
189   dec->decode = NULL;
190   g_list_foreach (dec->pendingevents, (GFunc) gst_mini_object_unref, NULL);
191   g_list_free (dec->pendingevents);
192   dec->pendingevents = NULL;
193
194   if (dec->taglist)
195     gst_tag_list_free (dec->taglist);
196   dec->taglist = NULL;
197 }
198
199
200 static gboolean
201 vorbis_dec_convert (GstPad * pad,
202     GstFormat src_format, gint64 src_value,
203     GstFormat dest_format, gint64 * dest_value)
204 {
205   gboolean res = TRUE;
206   GstVorbisDec *dec;
207
208   if (src_format == dest_format) {
209     *dest_value = src_value;
210     return TRUE;
211   }
212
213   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
214
215   if (!dec->initialized)
216     goto no_header;
217
218   if (dec->sinkpad == pad &&
219       (src_format == GST_FORMAT_BYTES || dest_format == GST_FORMAT_BYTES))
220     goto no_format;
221
222   res = gst_audio_info_convert (&dec->info, src_format, src_value, dest_format,
223       dest_value);
224
225 done:
226   gst_object_unref (dec);
227
228   return res;
229
230   /* ERRORS */
231 no_header:
232   {
233     GST_DEBUG_OBJECT (dec, "no header packets received");
234     res = FALSE;
235     goto done;
236   }
237 no_format:
238   {
239     GST_DEBUG_OBJECT (dec, "formats unsupported");
240     res = FALSE;
241     goto done;
242   }
243 }
244
245 static gboolean
246 vorbis_dec_src_query (GstPad * pad, GstQuery * query)
247 {
248   GstVorbisDec *dec;
249   gboolean res = FALSE;
250
251   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
252   if (G_UNLIKELY (dec == NULL))
253     return FALSE;
254
255   switch (GST_QUERY_TYPE (query)) {
256     case GST_QUERY_POSITION:
257     {
258       gint64 value;
259       GstFormat format;
260       gint64 time;
261
262       gst_query_parse_position (query, &format, NULL);
263
264       /* we start from the last seen time */
265       time = dec->last_timestamp;
266       /* correct for the segment values */
267       time = gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, time);
268
269       GST_LOG_OBJECT (dec,
270           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
271
272       /* and convert to the final format */
273       if (!(res =
274               vorbis_dec_convert (pad, GST_FORMAT_TIME, time, format, &value)))
275         goto error;
276
277       gst_query_set_position (query, format, value);
278
279       GST_LOG_OBJECT (dec,
280           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
281           format);
282
283       break;
284     }
285     case GST_QUERY_DURATION:
286     {
287       res = gst_pad_peer_query (dec->sinkpad, query);
288       if (!res)
289         goto error;
290
291       break;
292     }
293     case GST_QUERY_CONVERT:
294     {
295       GstFormat src_fmt, dest_fmt;
296       gint64 src_val, dest_val;
297
298       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
299       if (!(res =
300               vorbis_dec_convert (pad, src_fmt, src_val, dest_fmt, &dest_val)))
301         goto error;
302       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
303       break;
304     }
305     default:
306       res = gst_pad_query_default (pad, query);
307       break;
308   }
309 done:
310   gst_object_unref (dec);
311
312   return res;
313
314   /* ERRORS */
315 error:
316   {
317     GST_WARNING_OBJECT (dec, "error handling query");
318     goto done;
319   }
320 }
321
322 static gboolean
323 vorbis_dec_sink_query (GstPad * pad, GstQuery * query)
324 {
325   GstVorbisDec *dec;
326   gboolean res;
327
328   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
329
330   switch (GST_QUERY_TYPE (query)) {
331     case GST_QUERY_CONVERT:
332     {
333       GstFormat src_fmt, dest_fmt;
334       gint64 src_val, dest_val;
335
336       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
337       if (!(res =
338               vorbis_dec_convert (pad, src_fmt, src_val, dest_fmt, &dest_val)))
339         goto error;
340       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
341       break;
342     }
343     default:
344       res = gst_pad_query_default (pad, query);
345       break;
346   }
347
348 done:
349   gst_object_unref (dec);
350
351   return res;
352
353   /* ERRORS */
354 error:
355   {
356     GST_DEBUG_OBJECT (dec, "error converting value");
357     goto done;
358   }
359 }
360
361 static gboolean
362 vorbis_dec_src_event (GstPad * pad, GstEvent * event)
363 {
364   gboolean res = TRUE;
365   GstVorbisDec *dec;
366
367   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
368   if (G_UNLIKELY (dec == NULL)) {
369     gst_event_unref (event);
370     return FALSE;
371   }
372
373   switch (GST_EVENT_TYPE (event)) {
374     case GST_EVENT_SEEK:
375     {
376       GstFormat format, tformat;
377       gdouble rate;
378       GstEvent *real_seek;
379       GstSeekFlags flags;
380       GstSeekType cur_type, stop_type;
381       gint64 cur, stop;
382       gint64 tcur, tstop;
383       guint32 seqnum;
384
385       gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
386           &stop_type, &stop);
387       seqnum = gst_event_get_seqnum (event);
388       gst_event_unref (event);
389
390       /* First bring the requested format to time */
391       tformat = GST_FORMAT_TIME;
392       if (!(res = vorbis_dec_convert (pad, format, cur, tformat, &tcur)))
393         goto convert_error;
394       if (!(res = vorbis_dec_convert (pad, format, stop, tformat, &tstop)))
395         goto convert_error;
396
397       /* then seek with time on the peer */
398       real_seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
399           flags, cur_type, tcur, stop_type, tstop);
400       gst_event_set_seqnum (real_seek, seqnum);
401
402       res = gst_pad_push_event (dec->sinkpad, real_seek);
403       break;
404     }
405     default:
406       res = gst_pad_push_event (dec->sinkpad, event);
407       break;
408   }
409 done:
410   gst_object_unref (dec);
411
412   return res;
413
414   /* ERRORS */
415 convert_error:
416   {
417     GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
418     goto done;
419   }
420 }
421
422 static gboolean
423 vorbis_dec_sink_event (GstPad * pad, GstEvent * event)
424 {
425   gboolean ret = FALSE;
426   GstVorbisDec *dec;
427
428   dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
429
430   GST_LOG_OBJECT (dec, "handling event");
431   switch (GST_EVENT_TYPE (event)) {
432     case GST_EVENT_EOS:
433       if (dec->segment.rate < 0.0)
434         vorbis_dec_chain_reverse (dec, TRUE, NULL);
435       ret = gst_pad_push_event (dec->srcpad, event);
436       break;
437     case GST_EVENT_FLUSH_START:
438       ret = gst_pad_push_event (dec->srcpad, event);
439       break;
440     case GST_EVENT_FLUSH_STOP:
441       /* here we must clean any state in the decoder */
442 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
443       vorbis_synthesis_restart (&dec->vd);
444 #endif
445       gst_vorbis_dec_reset (dec);
446       ret = gst_pad_push_event (dec->srcpad, event);
447       break;
448     case GST_EVENT_SEGMENT:
449     {
450       const GstSegment *segment;
451
452       gst_event_parse_segment (event, &segment);
453
454       /* we need time for now */
455       if (segment->format != GST_FORMAT_TIME)
456         goto newseg_wrong_format;
457
458       GST_DEBUG_OBJECT (dec, "segment: %" GST_SEGMENT_FORMAT, segment);
459
460       /* now configure the values */
461       gst_segment_copy_into (segment, &dec->segment);
462       dec->seqnum = gst_event_get_seqnum (event);
463
464       if (dec->initialized)
465         /* and forward */
466         ret = gst_pad_push_event (dec->srcpad, event);
467       else {
468         /* store it to send once we're initialized */
469         dec->pendingevents = g_list_append (dec->pendingevents, event);
470         ret = TRUE;
471       }
472       break;
473     }
474     case GST_EVENT_TAG:
475     {
476       if (dec->initialized)
477         /* and forward */
478         ret = gst_pad_push_event (dec->srcpad, event);
479       else {
480         /* store it to send once we're initialized */
481         dec->pendingevents = g_list_append (dec->pendingevents, event);
482         ret = TRUE;
483       }
484       break;
485     }
486     default:
487       ret = gst_pad_event_default (pad, event);
488       break;
489   }
490 done:
491   gst_object_unref (dec);
492
493   return ret;
494
495   /* ERRORS */
496 newseg_wrong_format:
497   {
498     GST_DEBUG_OBJECT (dec, "received non TIME newsegment");
499     goto done;
500   }
501 }
502
503 static GstFlowReturn
504 vorbis_handle_identification_packet (GstVorbisDec * vd)
505 {
506   GstCaps *caps;
507   GstAudioInfo info;
508   const GstAudioChannelPosition *pos = NULL;
509
510   gst_audio_info_set_format (&info, GST_VORBIS_AUDIO_FORMAT, vd->vi.rate,
511       vd->vi.channels);
512
513   switch (info.channels) {
514     case 1:
515     case 2:
516       /* nothing */
517       break;
518     case 3:
519     case 4:
520     case 5:
521     case 6:
522     case 7:
523     case 8:
524       pos = gst_vorbis_channel_positions[info.channels - 1];
525       break;
526     default:
527     {
528       gint i, max_pos = MAX (info.channels, 64);
529
530       GST_ELEMENT_WARNING (vd, STREAM, DECODE,
531           (NULL), ("Using NONE channel layout for more than 8 channels"));
532       for (i = 0; i < max_pos; i++)
533         info.position[i] = GST_AUDIO_CHANNEL_POSITION_NONE;
534     }
535   }
536
537   caps = gst_audio_info_to_caps (&info);
538   gst_pad_set_caps (vd->srcpad, caps);
539   gst_caps_unref (caps);
540
541   vd->info = info;
542   /* select a copy_samples function, this way we can have specialized versions
543    * for mono/stereo and avoid the depth switch in tremor case */
544   vd->copy_samples = get_copy_sample_func (info.channels);
545
546   return GST_FLOW_OK;
547 }
548
549 static GstFlowReturn
550 vorbis_handle_comment_packet (GstVorbisDec * vd, ogg_packet * packet)
551 {
552   guint bitrate = 0;
553   gchar *encoder = NULL;
554   GstTagList *list, *old_list;
555   guint8 *data;
556   gsize size;
557
558   GST_DEBUG_OBJECT (vd, "parsing comment packet");
559
560   data = gst_ogg_packet_data (packet);
561   size = gst_ogg_packet_size (packet);
562
563   list =
564       gst_tag_list_from_vorbiscomment (data, size, (guint8 *) "\003vorbis", 7,
565       &encoder);
566
567   old_list = vd->taglist;
568   vd->taglist = gst_tag_list_merge (vd->taglist, list, GST_TAG_MERGE_REPLACE);
569
570   if (old_list)
571     gst_tag_list_free (old_list);
572   gst_tag_list_free (list);
573
574   if (!vd->taglist) {
575     GST_ERROR_OBJECT (vd, "couldn't decode comments");
576     vd->taglist = gst_tag_list_new ();
577   }
578   if (encoder) {
579     if (encoder[0])
580       gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
581           GST_TAG_ENCODER, encoder, NULL);
582     g_free (encoder);
583   }
584   gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
585       GST_TAG_ENCODER_VERSION, vd->vi.version,
586       GST_TAG_AUDIO_CODEC, "Vorbis", NULL);
587   if (vd->vi.bitrate_nominal > 0 && vd->vi.bitrate_nominal <= 0x7FFFFFFF) {
588     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
589         GST_TAG_NOMINAL_BITRATE, (guint) vd->vi.bitrate_nominal, NULL);
590     bitrate = vd->vi.bitrate_nominal;
591   }
592   if (vd->vi.bitrate_upper > 0 && vd->vi.bitrate_upper <= 0x7FFFFFFF) {
593     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
594         GST_TAG_MAXIMUM_BITRATE, (guint) vd->vi.bitrate_upper, NULL);
595     if (!bitrate)
596       bitrate = vd->vi.bitrate_upper;
597   }
598   if (vd->vi.bitrate_lower > 0 && vd->vi.bitrate_lower <= 0x7FFFFFFF) {
599     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
600         GST_TAG_MINIMUM_BITRATE, (guint) vd->vi.bitrate_lower, NULL);
601     if (!bitrate)
602       bitrate = vd->vi.bitrate_lower;
603   }
604   if (bitrate) {
605     gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
606         GST_TAG_BITRATE, (guint) bitrate, NULL);
607   }
608
609   if (vd->initialized) {
610     gst_element_found_tags_for_pad (GST_ELEMENT_CAST (vd), vd->srcpad,
611         vd->taglist);
612     vd->taglist = NULL;
613   } else {
614     /* Only post them as messages for the time being. *
615      * They will be pushed on the pad once the decoder is initialized */
616     gst_element_post_message (GST_ELEMENT_CAST (vd),
617         gst_message_new_tag (GST_OBJECT (vd), gst_tag_list_copy (vd->taglist)));
618   }
619
620   return GST_FLOW_OK;
621 }
622
623 static GstFlowReturn
624 vorbis_handle_type_packet (GstVorbisDec * vd)
625 {
626   GList *walk;
627   gint res;
628
629   g_assert (vd->initialized == FALSE);
630
631 #ifdef USE_TREMOLO
632   if (G_UNLIKELY ((res = vorbis_dsp_init (&vd->vd, &vd->vi))))
633     goto synthesis_init_error;
634 #else
635   if (G_UNLIKELY ((res = vorbis_synthesis_init (&vd->vd, &vd->vi))))
636     goto synthesis_init_error;
637
638   if (G_UNLIKELY ((res = vorbis_block_init (&vd->vd, &vd->vb))))
639     goto block_init_error;
640 #endif
641
642   vd->initialized = TRUE;
643
644   if (vd->pendingevents) {
645     for (walk = vd->pendingevents; walk; walk = g_list_next (walk))
646       gst_pad_push_event (vd->srcpad, GST_EVENT_CAST (walk->data));
647     g_list_free (vd->pendingevents);
648     vd->pendingevents = NULL;
649   }
650
651   if (vd->taglist) {
652     /* The tags have already been sent on the bus as messages. */
653     gst_pad_push_event (vd->srcpad, gst_event_new_tag (vd->taglist));
654     vd->taglist = NULL;
655   }
656   return GST_FLOW_OK;
657
658   /* ERRORS */
659 synthesis_init_error:
660   {
661     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
662         (NULL), ("couldn't initialize synthesis (%d)", res));
663     return GST_FLOW_ERROR;
664   }
665 block_init_error:
666   {
667     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
668         (NULL), ("couldn't initialize block (%d)", res));
669     return GST_FLOW_ERROR;
670   }
671 }
672
673 static GstFlowReturn
674 vorbis_handle_header_packet (GstVorbisDec * vd, ogg_packet * packet)
675 {
676   GstFlowReturn res;
677   gint ret;
678
679   GST_DEBUG_OBJECT (vd, "parsing header packet");
680
681   /* Packetno = 0 if the first byte is exactly 0x01 */
682   packet->b_o_s = ((gst_ogg_packet_data (packet))[0] == 0x1) ? 1 : 0;
683
684 #ifdef USE_TREMOLO
685   if ((ret = vorbis_dsp_headerin (&vd->vi, &vd->vc, packet)))
686 #else
687   if ((ret = vorbis_synthesis_headerin (&vd->vi, &vd->vc, packet)))
688 #endif
689     goto header_read_error;
690
691   switch ((gst_ogg_packet_data (packet))[0]) {
692     case 0x01:
693       res = vorbis_handle_identification_packet (vd);
694       break;
695     case 0x03:
696       res = vorbis_handle_comment_packet (vd, packet);
697       break;
698     case 0x05:
699       res = vorbis_handle_type_packet (vd);
700       break;
701     default:
702       /* ignore */
703       g_warning ("unknown vorbis header packet found");
704       res = GST_FLOW_OK;
705       break;
706   }
707   return res;
708
709   /* ERRORS */
710 header_read_error:
711   {
712     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
713         (NULL), ("couldn't read header packet (%d)", ret));
714     return GST_FLOW_ERROR;
715   }
716 }
717
718 static GstFlowReturn
719 vorbis_dec_push_forward (GstVorbisDec * dec, GstBuffer * buf)
720 {
721   GstFlowReturn result;
722
723   /* clip */
724   if (!(buf = gst_audio_buffer_clip (buf, &dec->segment, dec->vi.rate,
725               dec->info.bpf))) {
726     GST_LOG_OBJECT (dec, "clipped buffer");
727     return GST_FLOW_OK;
728   }
729
730   if (dec->discont) {
731     GST_LOG_OBJECT (dec, "setting DISCONT");
732     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
733     dec->discont = FALSE;
734   }
735
736   GST_DEBUG_OBJECT (dec,
737       "pushing time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
738       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
739       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
740
741   result = gst_pad_push (dec->srcpad, buf);
742
743   return result;
744 }
745
746 static GstFlowReturn
747 vorbis_dec_push_reverse (GstVorbisDec * dec, GstBuffer * buf)
748 {
749   GstFlowReturn result = GST_FLOW_OK;
750
751   dec->queued = g_list_prepend (dec->queued, buf);
752
753   return result;
754 }
755
756 static void
757 vorbis_do_timestamps (GstVorbisDec * vd, GstBuffer * buf, gboolean reverse,
758     GstClockTime timestamp, GstClockTime duration)
759 {
760   /* interpolate reverse */
761   if (vd->last_timestamp != -1 && duration != -1 && reverse)
762     vd->last_timestamp -= duration;
763
764   /* take buffer timestamp, use interpolated timestamp otherwise */
765   if (timestamp != -1)
766     vd->last_timestamp = timestamp;
767   else
768     timestamp = vd->last_timestamp;
769
770   /* interpolate forwards */
771   if (vd->last_timestamp != -1 && duration != -1 && !reverse)
772     vd->last_timestamp += duration;
773
774   GST_LOG_OBJECT (vd,
775       "keeping timestamp %" GST_TIME_FORMAT " ts %" GST_TIME_FORMAT " dur %"
776       GST_TIME_FORMAT, GST_TIME_ARGS (vd->last_timestamp),
777       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
778
779   if (buf) {
780     GST_BUFFER_TIMESTAMP (buf) = timestamp;
781     GST_BUFFER_DURATION (buf) = duration;
782   }
783 }
784
785 static GstFlowReturn
786 vorbis_handle_data_packet (GstVorbisDec * vd, ogg_packet * packet,
787     GstClockTime timestamp, GstClockTime duration)
788 {
789 #ifndef USE_TREMOLO
790   vorbis_sample_t **pcm;
791 #endif
792   guint sample_count;
793   GstBuffer *out = NULL;
794   GstFlowReturn result;
795   guint8 *data;
796   gsize size;
797
798   if (G_UNLIKELY (!vd->initialized))
799     goto not_initialized;
800
801   /* normal data packet */
802   /* FIXME, we can skip decoding if the packet is outside of the
803    * segment, this is however not very trivial as we need a previous
804    * packet to decode the current one so we must be carefull not to
805    * throw away too much. For now we decode everything and clip right
806    * before pushing data. */
807
808 #ifdef USE_TREMOLO
809   if (G_UNLIKELY (vorbis_dsp_synthesis (&vd->vd, packet, 1)))
810     goto could_not_read;
811 #else
812   if (G_UNLIKELY (vorbis_synthesis (&vd->vb, packet)))
813     goto could_not_read;
814
815   if (G_UNLIKELY (vorbis_synthesis_blockin (&vd->vd, &vd->vb) < 0))
816     goto not_accepted;
817 #endif
818
819   /* assume all goes well here */
820   result = GST_FLOW_OK;
821
822   /* count samples ready for reading */
823 #ifdef USE_TREMOLO
824   if ((sample_count = vorbis_dsp_pcmout (&vd->vd, NULL, 0)) == 0)
825 #else
826   if ((sample_count = vorbis_synthesis_pcmout (&vd->vd, NULL)) == 0)
827 #endif
828     goto done;
829
830   size = sample_count * vd->info.bpf;
831   GST_LOG_OBJECT (vd, "%d samples ready for reading, size %" G_GSIZE_FORMAT,
832       sample_count, size);
833
834   /* alloc buffer for it */
835   out = gst_buffer_new_and_alloc (size);
836
837   data = gst_buffer_map (out, NULL, NULL, GST_MAP_WRITE);
838   /* get samples ready for reading now, should be sample_count */
839 #ifdef USE_TREMOLO
840   if (G_UNLIKELY ((vorbis_dsp_pcmout (&vd->vd, data,
841                   sample_count)) != sample_count))
842 #else
843   if (G_UNLIKELY ((vorbis_synthesis_pcmout (&vd->vd, &pcm)) != sample_count))
844 #endif
845     goto wrong_samples;
846
847 #ifndef USE_TREMOLO
848   /* copy samples in buffer */
849   vd->copy_samples ((vorbis_sample_t *) data, pcm,
850       sample_count, vd->info.channels);
851 #endif
852
853   GST_LOG_OBJECT (vd, "setting output size to %" G_GSIZE_FORMAT, size);
854   gst_buffer_unmap (out, data, size);
855
856   /* this should not overflow */
857   if (duration == -1)
858     duration = sample_count * GST_SECOND / vd->vi.rate;
859
860   vorbis_do_timestamps (vd, out, FALSE, timestamp, duration);
861
862   if (vd->segment.rate >= 0.0)
863     result = vorbis_dec_push_forward (vd, out);
864   else
865     result = vorbis_dec_push_reverse (vd, out);
866
867 done:
868   if (out == NULL) {
869     /* no output, still keep track of timestamps */
870     vorbis_do_timestamps (vd, NULL, FALSE, timestamp, duration);
871   }
872 #ifdef USE_TREMOLO
873   vorbis_dsp_read (&vd->vd, sample_count);
874 #else
875   vorbis_synthesis_read (&vd->vd, sample_count);
876 #endif
877
878   return result;
879
880   /* ERRORS */
881 not_initialized:
882   {
883     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
884         (NULL), ("no header sent yet"));
885     return GST_FLOW_ERROR;
886   }
887 could_not_read:
888   {
889     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
890         (NULL), ("couldn't read data packet"));
891     return GST_FLOW_ERROR;
892   }
893 not_accepted:
894   {
895     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
896         (NULL), ("vorbis decoder did not accept data packet"));
897     return GST_FLOW_ERROR;
898   }
899 wrong_samples:
900   {
901     gst_buffer_unref (out);
902     GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
903         (NULL), ("vorbis decoder reported wrong number of samples"));
904     return GST_FLOW_ERROR;
905   }
906 }
907
908 static GstFlowReturn
909 vorbis_dec_handle_header_buffer (GstVorbisDec * vd, GstBuffer * buffer)
910 {
911   ogg_packet *packet;
912   ogg_packet_wrapper packet_wrapper;
913   GstFlowReturn ret;
914
915   gst_ogg_packet_wrapper_map (&packet_wrapper, buffer);
916   packet = gst_ogg_packet_from_wrapper (&packet_wrapper);
917
918   ret = vorbis_handle_header_packet (vd, packet);
919
920   gst_ogg_packet_wrapper_unmap (&packet_wrapper, buffer);
921
922   return ret;
923 }
924
925
926 #define MIN_NUM_HEADERS 3
927 static GstFlowReturn
928 vorbis_dec_handle_header_caps (GstVorbisDec * vd, GstBuffer * buffer)
929 {
930   GstFlowReturn result = GST_FLOW_OK;
931   GstCaps *caps;
932   GstStructure *s;
933   const GValue *array;
934   const GValue *value = NULL;
935   GstBuffer *buf = NULL;
936
937   if ((caps = gst_pad_get_current_caps (vd->sinkpad)) == NULL)
938     goto no_caps;
939
940   if ((s = gst_caps_get_structure (caps, 0)) == NULL)
941     goto no_caps;
942
943   array = gst_structure_get_value (s, "streamheader");
944
945   if (array == NULL || (gst_value_array_get_size (array) < MIN_NUM_HEADERS))
946     goto array_error;
947
948   /* initial header */
949   value = gst_value_array_get_value (array, 0);
950   buf = gst_value_get_buffer (value);
951   if (!buf)
952     goto null_buffer;
953   result = vorbis_dec_handle_header_buffer (vd, buf);
954   if (result != GST_FLOW_OK)
955     goto buffer_error;
956
957   /* comment header */
958   value = gst_value_array_get_value (array, 1);
959   buf = gst_value_get_buffer (value);
960   if (!buf)
961     goto null_buffer;
962   result = vorbis_dec_handle_header_buffer (vd, buf);
963   if (result != GST_FLOW_OK)
964     goto buffer_error;
965
966   /* bitstream codebook header */
967   value = gst_value_array_get_value (array, 2);
968   buf = gst_value_get_buffer (value);
969   if (!buf)
970     goto null_buffer;
971   result = vorbis_dec_handle_header_buffer (vd, buf);
972   if (result != GST_FLOW_OK)
973     goto buffer_error;
974
975   return result;
976
977 no_caps:
978   {
979     GST_WARNING_OBJECT (vd, "no caps negotiated");
980     return GST_FLOW_NOT_NEGOTIATED;
981   }
982 array_error:
983   {
984     GST_WARNING_OBJECT (vd, "streamheader array not found");
985     return GST_FLOW_NOT_NEGOTIATED;
986   }
987 null_buffer:
988   {
989     GST_WARNING_OBJECT (vd, "streamheader with null buffer received");
990     return GST_FLOW_NOT_NEGOTIATED;
991   }
992 buffer_error:
993   {
994     GST_WARNING_OBJECT (vd, "error handling buffer");
995     return GST_FLOW_NOT_NEGOTIATED;
996   }
997 }
998
999 static GstFlowReturn
1000 vorbis_dec_decode_buffer (GstVorbisDec * vd, GstBuffer * buffer)
1001 {
1002   ogg_packet *packet;
1003   ogg_packet_wrapper packet_wrapper;
1004   GstFlowReturn result = GST_FLOW_OK;
1005
1006   /* make ogg_packet out of the buffer */
1007   gst_ogg_packet_wrapper_map (&packet_wrapper, buffer);
1008   packet = gst_ogg_packet_from_wrapper (&packet_wrapper);
1009   /* set some more stuff */
1010   packet->granulepos = -1;
1011   packet->packetno = 0;         /* we don't care */
1012   /* EOS does not matter, it is used in vorbis to implement clipping the last
1013    * block of samples based on the granulepos. We clip based on segments. */
1014   packet->e_o_s = 0;
1015
1016   GST_LOG_OBJECT (vd, "decode buffer of size %ld", packet->bytes);
1017
1018   /* error out on empty header packets, but just skip empty data packets */
1019   if (G_UNLIKELY (packet->bytes == 0)) {
1020     if (vd->initialized)
1021       goto empty_buffer;
1022     else
1023       goto empty_header;
1024   }
1025
1026   /* switch depending on packet type */
1027   if ((gst_ogg_packet_data (packet))[0] & 1) {
1028     if (vd->initialized) {
1029       GST_WARNING_OBJECT (vd, "Already initialized, so ignoring header packet");
1030       goto done;
1031     }
1032     result = vorbis_handle_header_packet (vd, packet);
1033   } else {
1034     GstClockTime timestamp, duration;
1035
1036     /* try to find header in caps so we can initialize the decoder */
1037     if (!vd->initialized) {
1038       result = vorbis_dec_handle_header_caps (vd, buffer);
1039       if (result != GST_FLOW_OK)
1040         goto invalid_caps_header;
1041     }
1042
1043     timestamp = GST_BUFFER_TIMESTAMP (buffer);
1044     duration = GST_BUFFER_DURATION (buffer);
1045
1046     result = vorbis_handle_data_packet (vd, packet, timestamp, duration);
1047   }
1048
1049 done:
1050   gst_ogg_packet_wrapper_unmap (&packet_wrapper, buffer);
1051
1052   return result;
1053
1054 empty_buffer:
1055   {
1056     /* don't error out here, just ignore the buffer, it's invalid for vorbis
1057      * but not fatal. */
1058     GST_WARNING_OBJECT (vd, "empty buffer received, ignoring");
1059     result = GST_FLOW_OK;
1060     goto done;
1061   }
1062
1063 /* ERRORS */
1064 empty_header:
1065   {
1066     GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL), ("empty header received"));
1067     result = GST_FLOW_ERROR;
1068     vd->discont = TRUE;
1069     goto done;
1070   }
1071
1072 invalid_caps_header:
1073   {
1074     GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL),
1075         ("invalid streamheader in caps"));
1076     goto done;
1077   }
1078 }
1079
1080 /*
1081  * Input:
1082  *  Buffer decoding order:  7  8  9  4  5  6  3  1  2  EOS
1083  *  Discont flag:           D        D        D  D
1084  *
1085  * - Each Discont marks a discont in the decoding order.
1086  *
1087  * for vorbis, each buffer is a keyframe when we have the previous
1088  * buffer. This means that to decode buffer 7, we need buffer 6, which
1089  * arrives out of order.
1090  *
1091  * we first gather buffers in the gather queue until we get a DISCONT. We
1092  * prepend each incomming buffer so that they are in reversed order.
1093  *
1094  *    gather queue:    9  8  7
1095  *    decode queue:
1096  *    output queue:
1097  *
1098  * When a DISCONT is received (buffer 4), we move the gather queue to the
1099  * decode queue. This is simply done be taking the head of the gather queue
1100  * and prepending it to the decode queue. This yields:
1101  *
1102  *    gather queue:
1103  *    decode queue:    7  8  9
1104  *    output queue:
1105  *
1106  * Then we decode each buffer in the decode queue in order and put the output
1107  * buffer in the output queue. The first buffer (7) will not produce any output
1108  * because it needs the previous buffer (6) which did not arrive yet. This
1109  * yields:
1110  *
1111  *    gather queue:
1112  *    decode queue:    7  8  9
1113  *    output queue:    9  8
1114  *
1115  * Then we remove the consumed buffers from the decode queue. Buffer 7 is not
1116  * completely consumed, we need to keep it around for when we receive buffer
1117  * 6. This yields:
1118  *
1119  *    gather queue:
1120  *    decode queue:    7
1121  *    output queue:    9  8
1122  *
1123  * Then we accumulate more buffers:
1124  *
1125  *    gather queue:    6  5  4
1126  *    decode queue:    7
1127  *    output queue:
1128  *
1129  * prepending to the decode queue on DISCONT yields:
1130  *
1131  *    gather queue:
1132  *    decode queue:    4  5  6  7
1133  *    output queue:
1134  *
1135  * after decoding and keeping buffer 4:
1136  *
1137  *    gather queue:
1138  *    decode queue:    4
1139  *    output queue:    7  6  5
1140  *
1141  * Etc..
1142  */
1143 static GstFlowReturn
1144 vorbis_dec_flush_decode (GstVorbisDec * dec)
1145 {
1146   GstFlowReturn res = GST_FLOW_OK;
1147   GList *walk;
1148
1149   walk = dec->decode;
1150
1151   GST_DEBUG_OBJECT (dec, "flushing buffers to decoder");
1152
1153   while (walk) {
1154     GList *next;
1155     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1156
1157     GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1158         buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1159
1160     next = g_list_next (walk);
1161
1162     /* decode buffer, prepend to output queue */
1163     res = vorbis_dec_decode_buffer (dec, buf);
1164
1165     /* if we generated output, we can discard the buffer, else we
1166      * keep it in the queue */
1167     if (dec->queued) {
1168       GST_DEBUG_OBJECT (dec, "decoded buffer to %p", dec->queued->data);
1169       dec->decode = g_list_delete_link (dec->decode, walk);
1170       gst_buffer_unref (buf);
1171     } else {
1172       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1173     }
1174     walk = next;
1175   }
1176   while (dec->queued) {
1177     GstBuffer *buf = GST_BUFFER_CAST (dec->queued->data);
1178     GstClockTime timestamp, duration;
1179
1180     timestamp = GST_BUFFER_TIMESTAMP (buf);
1181     duration = GST_BUFFER_DURATION (buf);
1182
1183     vorbis_do_timestamps (dec, buf, TRUE, timestamp, duration);
1184     res = vorbis_dec_push_forward (dec, buf);
1185
1186     dec->queued = g_list_delete_link (dec->queued, dec->queued);
1187   }
1188   return res;
1189 }
1190
1191 static GstFlowReturn
1192 vorbis_dec_chain_reverse (GstVorbisDec * vd, gboolean discont, GstBuffer * buf)
1193 {
1194   GstFlowReturn result = GST_FLOW_OK;
1195
1196   /* if we have a discont, move buffers to the decode list */
1197   if (G_UNLIKELY (discont)) {
1198     GST_DEBUG_OBJECT (vd, "received discont");
1199     while (vd->gather) {
1200       GstBuffer *gbuf;
1201
1202       gbuf = GST_BUFFER_CAST (vd->gather->data);
1203       /* remove from the gather list */
1204       vd->gather = g_list_delete_link (vd->gather, vd->gather);
1205       /* copy to decode queue */
1206       vd->decode = g_list_prepend (vd->decode, gbuf);
1207     }
1208     /* flush and decode the decode queue */
1209     result = vorbis_dec_flush_decode (vd);
1210   }
1211
1212   if (G_LIKELY (buf)) {
1213     GST_DEBUG_OBJECT (vd,
1214         "gathering buffer %p of size %" G_GSIZE_FORMAT
1215         ", time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
1216         buf, gst_buffer_get_size (buf),
1217         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1218         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1219
1220     /* add buffer to gather queue */
1221     vd->gather = g_list_prepend (vd->gather, buf);
1222   }
1223
1224   return result;
1225 }
1226
1227 static GstFlowReturn
1228 vorbis_dec_chain_forward (GstVorbisDec * vd, gboolean discont,
1229     GstBuffer * buffer)
1230 {
1231   GstFlowReturn result;
1232
1233   result = vorbis_dec_decode_buffer (vd, buffer);
1234
1235   gst_buffer_unref (buffer);
1236
1237   return result;
1238 }
1239
1240 static GstFlowReturn
1241 vorbis_dec_chain (GstPad * pad, GstBuffer * buffer)
1242 {
1243   GstVorbisDec *vd;
1244   GstFlowReturn result = GST_FLOW_OK;
1245   gboolean discont;
1246
1247   vd = GST_VORBIS_DEC (gst_pad_get_parent (pad));
1248
1249   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1250
1251   /* resync on DISCONT */
1252   if (G_UNLIKELY (discont)) {
1253     GST_DEBUG_OBJECT (vd, "received DISCONT buffer");
1254     vd->last_timestamp = GST_CLOCK_TIME_NONE;
1255 #ifdef HAVE_VORBIS_SYNTHESIS_RESTART
1256     vorbis_synthesis_restart (&vd->vd);
1257 #endif
1258     vd->discont = TRUE;
1259   }
1260
1261   if (vd->segment.rate >= 0.0)
1262     result = vorbis_dec_chain_forward (vd, discont, buffer);
1263   else
1264     result = vorbis_dec_chain_reverse (vd, discont, buffer);
1265
1266   gst_object_unref (vd);
1267
1268   return result;
1269 }
1270
1271 static GstStateChangeReturn
1272 vorbis_dec_change_state (GstElement * element, GstStateChange transition)
1273 {
1274   GstVorbisDec *vd = GST_VORBIS_DEC (element);
1275   GstStateChangeReturn res;
1276
1277   switch (transition) {
1278     case GST_STATE_CHANGE_NULL_TO_READY:
1279       break;
1280     case GST_STATE_CHANGE_READY_TO_PAUSED:
1281       vorbis_info_init (&vd->vi);
1282       vorbis_comment_init (&vd->vc);
1283       vd->initialized = FALSE;
1284       gst_vorbis_dec_reset (vd);
1285       break;
1286     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1287       break;
1288     default:
1289       break;
1290   }
1291
1292   res = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1293
1294   switch (transition) {
1295     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1296       break;
1297     case GST_STATE_CHANGE_PAUSED_TO_READY:
1298       GST_DEBUG_OBJECT (vd, "PAUSED -> READY, clearing vorbis structures");
1299       vd->initialized = FALSE;
1300
1301 #ifndef USE_TREMOLO
1302       vorbis_block_clear (&vd->vb);
1303 #endif
1304
1305       vorbis_dsp_clear (&vd->vd);
1306       vorbis_comment_clear (&vd->vc);
1307       vorbis_info_clear (&vd->vi);
1308       gst_vorbis_dec_reset (vd);
1309       break;
1310     case GST_STATE_CHANGE_READY_TO_NULL:
1311       break;
1312     default:
1313       break;
1314   }
1315
1316   return res;
1317 }