vorbisdec.c 32.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* GStreamer
 * Copyright (C) 2004 Benjamin Otte <in7y118@public.uni-hamburg.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

Wim Taymans's avatar
Wim Taymans committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * SECTION:element-vorbisdec
 * @short_description: a decoder that decodes Vorbis to raw audio
 * @see_also: vorbisenc, oggdemux
 *
 * <refsect2>
 * <para>
 * This element decodes a Vorbis stream to raw float audio.
 * <ulink url="http://www.vorbis.com/">Vorbis</ulink> is a royalty-free
 * audio codec maintained by the <ulink url="http://www.xiph.org/">Xiph.org
 * Foundation</ulink>.
 * </para>
 * <title>Example pipelines</title>
 * <para>
 * <programlisting>
 * gst-launch -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! alsasink
 * </programlisting>
 * Decode an Ogg/Vorbis. To create an Ogg/Vorbis file refer to the documentation of vorbisenc.
 * </para>
 * </refsect2>
 *
 * Last reviewed on 2006-03-01 (0.10.4)
 */

44
45
46
47
48
49
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include "vorbisdec.h"
#include <string.h>
50
#include <gst/audio/audio.h>
51
#include <gst/tag/tag.h>
Ronald S. Bultje's avatar
Ronald S. Bultje committed
52
#include <gst/audio/multichannel.h>
53

54
55
56
GST_DEBUG_CATEGORY_EXTERN (vorbisdec_debug);
#define GST_CAT_DEFAULT vorbisdec_debug

Stefan Kost's avatar
Stefan Kost committed
57
static const GstElementDetails vorbis_dec_details =
j^'s avatar
j^ committed
58
GST_ELEMENT_DETAILS ("Vorbis audio decoder",
59
60
61
    "Codec/Decoder/Audio",
    "decode raw vorbis streams to float audio",
    "Benjamin Otte <in7y118@public.uni-hamburg.de>");
62
63

static GstStaticPadTemplate vorbis_dec_src_factory =
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
64
65
66
67
GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("audio/x-raw-float, "
68
69
        "rate = (int) [ 1, MAX ], "
        "channels = (int) [ 1, 256 ], " "endianness = (int) BYTE_ORDER, "
70
/* no ifdef in macros, please
71
72
73
#ifdef GST_VORBIS_DEC_SEQUENTIAL
      "layout = \"sequential\", "
#endif
74
*/
Wim Taymans's avatar
Wim Taymans committed
75
        "width = (int) 32")
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
76
    );
77
78

static GstStaticPadTemplate vorbis_dec_sink_factory =
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
79
80
81
82
83
GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("audio/x-vorbis")
    );
84
85

GST_BOILERPLATE (GstVorbisDec, gst_vorbis_dec, GstElement, GST_TYPE_ELEMENT);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
86

87
static void vorbis_dec_finalize (GObject * object);
88
89
static gboolean vorbis_dec_sink_event (GstPad * pad, GstEvent * event);
static GstFlowReturn vorbis_dec_chain (GstPad * pad, GstBuffer * buffer);
90
91
static GstStateChangeReturn vorbis_dec_change_state (GstElement * element,
    GstStateChange transition);
Wim Taymans's avatar
Wim Taymans committed
92

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
93
static gboolean vorbis_dec_src_event (GstPad * pad, GstEvent * event);
Wim Taymans's avatar
Wim Taymans committed
94
static gboolean vorbis_dec_src_query (GstPad * pad, GstQuery * query);
95
96
97
static gboolean vorbis_dec_convert (GstPad * pad,
    GstFormat src_format, gint64 src_value,
    GstFormat * dest_format, gint64 * dest_value);
98

Wim Taymans's avatar
Wim Taymans committed
99
static gboolean vorbis_dec_sink_query (GstPad * pad, GstQuery * query);
100
101
102
103
104

static void
gst_vorbis_dec_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
Johan Dahlin's avatar
Johan Dahlin committed
105
106
107
108
109
110
111
  GstPadTemplate *src_template, *sink_template;

  src_template = gst_static_pad_template_get (&vorbis_dec_src_factory);
  gst_element_class_add_pad_template (element_class, src_template);

  sink_template = gst_static_pad_template_get (&vorbis_dec_sink_factory);
  gst_element_class_add_pad_template (element_class, sink_template);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
112

113
114
115
116
  gst_element_class_set_details (element_class, &vorbis_dec_details);
}

static void
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
117
gst_vorbis_dec_class_init (GstVorbisDecClass * klass)
118
{
119
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
120
121
  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);

122
  gobject_class->finalize = vorbis_dec_finalize;
123

124
  gstelement_class->change_state = GST_DEBUG_FUNCPTR (vorbis_dec_change_state);
125
126
}

127
128
129
130
131
static const GstQueryType *
vorbis_get_query_types (GstPad * pad)
{
  static const GstQueryType vorbis_dec_src_query_types[] = {
    GST_QUERY_POSITION,
132
133
    GST_QUERY_DURATION,
    GST_QUERY_CONVERT,
134
135
136
137
138
139
    0
  };

  return vorbis_dec_src_query_types;
}

140
static void
141
gst_vorbis_dec_init (GstVorbisDec * dec, GstVorbisDecClass * g_class)
142
{
143
144
  dec->sinkpad = gst_pad_new_from_static_template (&vorbis_dec_sink_factory,
      "sink");
Johan Dahlin's avatar
Johan Dahlin committed
145

146
147
148
149
150
151
  gst_pad_set_event_function (dec->sinkpad,
      GST_DEBUG_FUNCPTR (vorbis_dec_sink_event));
  gst_pad_set_chain_function (dec->sinkpad,
      GST_DEBUG_FUNCPTR (vorbis_dec_chain));
  gst_pad_set_query_function (dec->sinkpad,
      GST_DEBUG_FUNCPTR (vorbis_dec_sink_query));
152
153
  gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);

154
155
  dec->srcpad = gst_pad_new_from_static_template (&vorbis_dec_src_factory,
      "src");
Johan Dahlin's avatar
Johan Dahlin committed
156

157
158
159
160
161
162
  gst_pad_set_event_function (dec->srcpad,
      GST_DEBUG_FUNCPTR (vorbis_dec_src_event));
  gst_pad_set_query_type_function (dec->srcpad,
      GST_DEBUG_FUNCPTR (vorbis_get_query_types));
  gst_pad_set_query_function (dec->srcpad,
      GST_DEBUG_FUNCPTR (vorbis_dec_src_query));
163
  gst_pad_use_fixed_caps (dec->srcpad);
164
  gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
Wim Taymans's avatar
Wim Taymans committed
165
166

  dec->queued = NULL;
167
168
  dec->pendingevents = NULL;
  dec->taglist = NULL;
169
170
}

171
static void
172
vorbis_dec_finalize (GObject * object)
173
{
174
  /* Release any possibly allocated libvorbis data.
175
176
177
178
179
180
181
182
   * _clear functions can safely be called multiple times
   */
  GstVorbisDec *vd = GST_VORBIS_DEC (object);

  vorbis_block_clear (&vd->vb);
  vorbis_dsp_clear (&vd->vd);
  vorbis_comment_clear (&vd->vc);
  vorbis_info_clear (&vd->vi);
183
184

  G_OBJECT_CLASS (parent_class)->finalize (object);
185
186
}

187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
static void
gst_vorbis_dec_reset (GstVorbisDec * dec)
{
  GList *walk;

  dec->cur_timestamp = GST_CLOCK_TIME_NONE;
  dec->prev_timestamp = GST_CLOCK_TIME_NONE;
  dec->granulepos = -1;
  dec->discont = TRUE;
  gst_segment_init (&dec->segment, GST_FORMAT_TIME);

  for (walk = dec->queued; walk; walk = g_list_next (walk)) {
    gst_buffer_unref (GST_BUFFER_CAST (walk->data));
  }
  g_list_free (dec->queued);
  dec->queued = NULL;
203
204
205
206
207
208
209
210
211
212

  for (walk = dec->pendingevents; walk; walk = g_list_next (walk)) {
    gst_event_unref (GST_EVENT_CAST (walk->data));
  }
  g_list_free (dec->pendingevents);
  dec->pendingevents = NULL;

  if (dec->taglist)
    gst_tag_list_free (dec->taglist);
  dec->taglist = NULL;
213
214
215
}


216
static gboolean
217
218
219
vorbis_dec_convert (GstPad * pad,
    GstFormat src_format, gint64 src_value,
    GstFormat * dest_format, gint64 * dest_value)
220
{
221
222
223
  gboolean res = TRUE;
  GstVorbisDec *dec;
  guint64 scale = 1;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
224

Wim Taymans's avatar
Wim Taymans committed
225
226
227
228
229
  if (src_format == *dest_format) {
    *dest_value = src_value;
    return TRUE;
  }

230
231
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));

232
  if (!dec->initialized)
233
234
    goto no_header;

235
236
  if (dec->sinkpad == pad &&
      (src_format == GST_FORMAT_BYTES || *dest_format == GST_FORMAT_BYTES))
237
    goto no_format;
238

239
  switch (src_format) {
240
    case GST_FORMAT_TIME:
241
242
243
244
      switch (*dest_format) {
        case GST_FORMAT_BYTES:
          scale = sizeof (float) * dec->vi.channels;
        case GST_FORMAT_DEFAULT:
245
246
247
          *dest_value =
              scale * gst_util_uint64_scale_int (src_value, dec->vi.rate,
              GST_SECOND);
248
249
250
251
252
          break;
        default:
          res = FALSE;
      }
      break;
253
    case GST_FORMAT_DEFAULT:
254
255
256
257
258
      switch (*dest_format) {
        case GST_FORMAT_BYTES:
          *dest_value = src_value * sizeof (float) * dec->vi.channels;
          break;
        case GST_FORMAT_TIME:
259
          *dest_value =
260
              gst_util_uint64_scale_int (src_value, GST_SECOND, dec->vi.rate);
261
262
263
264
265
          break;
        default:
          res = FALSE;
      }
      break;
266
    case GST_FORMAT_BYTES:
267
268
269
270
271
      switch (*dest_format) {
        case GST_FORMAT_DEFAULT:
          *dest_value = src_value / (sizeof (float) * dec->vi.channels);
          break;
        case GST_FORMAT_TIME:
272
          *dest_value = gst_util_uint64_scale_int (src_value, GST_SECOND,
273
              dec->vi.rate * sizeof (float) * dec->vi.channels);
274
275
276
277
278
          break;
        default:
          res = FALSE;
      }
      break;
279
    default:
280
      res = FALSE;
281
  }
282
283
done:
  gst_object_unref (dec);
284

285
  return res;
286
287
288
289
290
291
292
293
294
295
296
297
298
299

  /* ERRORS */
no_header:
  {
    GST_DEBUG_OBJECT (dec, "no header packets received");
    res = FALSE;
    goto done;
  }
no_format:
  {
    GST_DEBUG_OBJECT (dec, "formats unsupported");
    res = FALSE;
    goto done;
  }
300
}
301
302

static gboolean
Wim Taymans's avatar
Wim Taymans committed
303
vorbis_dec_src_query (GstPad * pad, GstQuery * query)
304
{
Wim Taymans's avatar
Wim Taymans committed
305
  GstVorbisDec *dec;
306
  gboolean res = FALSE;
Wim Taymans's avatar
Wim Taymans committed
307

308
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
Wim Taymans's avatar
Wim Taymans committed
309
310
311
312

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_POSITION:
    {
313
314
315
      gint64 granulepos, value;
      GstFormat my_format, format;
      gint64 time;
Wim Taymans's avatar
Wim Taymans committed
316

317
      /* we start from the last seen granulepos */
Wim Taymans's avatar
Wim Taymans committed
318
319
      granulepos = dec->granulepos;

Wim Taymans's avatar
Wim Taymans committed
320
      gst_query_parse_position (query, &format, NULL);
Wim Taymans's avatar
Wim Taymans committed
321

322
323
324
      /* and convert to the final format in two steps with time as the
       * intermediate step */
      my_format = GST_FORMAT_TIME;
Wim Taymans's avatar
Wim Taymans committed
325
      if (!(res =
326
327
              vorbis_dec_convert (pad, GST_FORMAT_DEFAULT, granulepos,
                  &my_format, &time)))
Wim Taymans's avatar
Wim Taymans committed
328
329
        goto error;

330
      /* correct for the segment values */
331
332
333
334
335
336
337
338
      time = gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, time);

      GST_LOG_OBJECT (dec,
          "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));

      /* and convert to the final format */
      if (!(res = vorbis_dec_convert (pad, my_format, time, &format, &value)))
        goto error;
339

Wim Taymans's avatar
Wim Taymans committed
340
      gst_query_set_position (query, format, value);
Wim Taymans's avatar
Wim Taymans committed
341
342

      GST_LOG_OBJECT (dec,
343
          "query %p: we return %lld (format %u)", query, value, format);
Wim Taymans's avatar
Wim Taymans committed
344
345
346

      break;
    }
Wim Taymans's avatar
Wim Taymans committed
347
348
    case GST_QUERY_DURATION:
    {
349
350
351
      GstPad *peer;

      if (!(peer = gst_pad_get_peer (dec->sinkpad))) {
352
353
354
355
        GST_WARNING_OBJECT (dec, "sink pad %" GST_PTR_FORMAT " is not linked",
            dec->sinkpad);
        goto error;
      }
356
357
358
359

      res = gst_pad_query (peer, query);
      gst_object_unref (peer);
      if (!res)
Wim Taymans's avatar
Wim Taymans committed
360
        goto error;
361

Wim Taymans's avatar
Wim Taymans committed
362
363
      break;
    }
Wim Taymans's avatar
Wim Taymans committed
364
365
366
367
368
369
370
371
372
373
374
375
376
    case GST_QUERY_CONVERT:
    {
      GstFormat src_fmt, dest_fmt;
      gint64 src_val, dest_val;

      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
      if (!(res =
              vorbis_dec_convert (pad, src_fmt, src_val, &dest_fmt, &dest_val)))
        goto error;
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
      break;
    }
    default:
377
      res = gst_pad_query_default (pad, query);
Wim Taymans's avatar
Wim Taymans committed
378
379
      break;
  }
380
381
382
done:
  gst_object_unref (dec);

Wim Taymans's avatar
Wim Taymans committed
383
  return res;
384

385
  /* ERRORS */
Wim Taymans's avatar
Wim Taymans committed
386
387
error:
  {
388
    GST_WARNING_OBJECT (dec, "error handling query");
389
    goto done;
390
  }
Wim Taymans's avatar
Wim Taymans committed
391
}
392

Wim Taymans's avatar
Wim Taymans committed
393
394
395
396
397
398
static gboolean
vorbis_dec_sink_query (GstPad * pad, GstQuery * query)
{
  GstVorbisDec *dec;
  gboolean res;

399
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
400

Wim Taymans's avatar
Wim Taymans committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_CONVERT:
    {
      GstFormat src_fmt, dest_fmt;
      gint64 src_val, dest_val;

      gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
      if (!(res =
              vorbis_dec_convert (pad, src_fmt, src_val, &dest_fmt, &dest_val)))
        goto error;
      gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
      break;
    }
    default:
415
      res = gst_pad_query_default (pad, query);
Wim Taymans's avatar
Wim Taymans committed
416
417
      break;
  }
418
419
420
421

done:
  gst_object_unref (dec);

Wim Taymans's avatar
Wim Taymans committed
422
  return res;
423
424
425
426
427
428
429

  /* ERRORS */
error:
  {
    GST_DEBUG_OBJECT (dec, "error converting value");
    goto done;
  }
430
431
}

432
static gboolean
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
433
vorbis_dec_src_event (GstPad * pad, GstEvent * event)
434
435
{
  gboolean res = TRUE;
436
437
438
  GstVorbisDec *dec;

  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
439
440

  switch (GST_EVENT_TYPE (event)) {
441
442
    case GST_EVENT_SEEK:
    {
443
444
445
446
447
448
449
450
451
452
      GstFormat format, tformat;
      gdouble rate;
      GstEvent *real_seek;
      GstSeekFlags flags;
      GstSeekType cur_type, stop_type;
      gint64 cur, stop;
      gint64 tcur, tstop;

      gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
          &stop_type, &stop);
453
      gst_event_unref (event);
454
455
456
457
458
459
460
461
462

      /* we have to ask our peer to seek to time here as we know
       * nothing about how to generate a granulepos from the src
       * formats or anything.
       *
       * First bring the requested format to time
       */
      tformat = GST_FORMAT_TIME;
      if (!(res = vorbis_dec_convert (pad, format, cur, &tformat, &tcur)))
463
        goto convert_error;
464
      if (!(res = vorbis_dec_convert (pad, format, stop, &tformat, &tstop)))
465
        goto convert_error;
466
467
468
469
470

      /* then seek with time on the peer */
      real_seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
          flags, cur_type, tcur, stop_type, tstop);

471
      res = gst_pad_push_event (dec->sinkpad, real_seek);
472

473
474
475
      break;
    }
    default:
476
      res = gst_pad_push_event (dec->sinkpad, event);
477
478
      break;
  }
479
480
done:
  gst_object_unref (dec);
481
482

  return res;
483

484
  /* ERRORS */
485
convert_error:
486
487
488
489
  {
    GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
    goto done;
  }
490
}
491

492
493
static gboolean
vorbis_dec_sink_event (GstPad * pad, GstEvent * event)
494
{
495
  gboolean ret = FALSE;
496
497
  GstVorbisDec *dec;

Wim Taymans's avatar
Wim Taymans committed
498
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
499

500
501
  GST_LOG_OBJECT (dec, "handling event");
  switch (GST_EVENT_TYPE (event)) {
Wim Taymans's avatar
Wim Taymans committed
502
503
504
    case GST_EVENT_EOS:
      ret = gst_pad_push_event (dec->srcpad, event);
      break;
505
506
507
508
    case GST_EVENT_FLUSH_START:
      ret = gst_pad_push_event (dec->srcpad, event);
      break;
    case GST_EVENT_FLUSH_STOP:
509
510
511
512
513
      /* here we must clean any state in the decoder */
#ifdef HAVE_VORBIS_SYNTHESIS_RESTART
      vorbis_synthesis_restart (&dec->vd);
#endif
      gst_vorbis_dec_reset (dec);
514
515
      ret = gst_pad_push_event (dec->srcpad, event);
      break;
516
    case GST_EVENT_NEWSEGMENT:
517
518
    {
      GstFormat format;
519
      gdouble rate, arate;
Wim Taymans's avatar
Wim Taymans committed
520
      gint64 start, stop, time;
521
      gboolean update;
522

523
524
      gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
          &start, &stop, &time);
525

526
      /* we need time and a positive rate for now */
527
528
529
530
531
532
      if (format != GST_FORMAT_TIME)
        goto newseg_wrong_format;

      if (rate <= 0.0)
        goto newseg_wrong_rate;

533
534
535
536
537
538
      GST_DEBUG_OBJECT (dec,
          "newsegment: update %d, rate %g, arate %g, start %" GST_TIME_FORMAT
          ", stop %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT,
          update, rate, arate, GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
          GST_TIME_ARGS (time));

539
      /* now configure the values */
540
541
      gst_segment_set_newsegment_full (&dec->segment, update,
          rate, arate, format, start, stop, time);
542

543
544
545
546
547
548
549
550
      if (dec->initialized)
        /* and forward */
        ret = gst_pad_push_event (dec->srcpad, event);
      else {
        /* store it to send once we're initialized */
        dec->pendingevents = g_list_append (dec->pendingevents, event);
        ret = TRUE;
      }
551
      break;
552
    }
553
    default:
Wim Taymans's avatar
Wim Taymans committed
554
      ret = gst_pad_push_event (dec->srcpad, event);
555
556
      break;
  }
557
done:
Wim Taymans's avatar
Wim Taymans committed
558
559
  gst_object_unref (dec);

560
  return ret;
561

562
563
564
  /* ERRORS */
newseg_wrong_format:
  {
565
    GST_DEBUG_OBJECT (dec, "received non TIME newsegment");
566
567
568
569
    goto done;
  }
newseg_wrong_rate:
  {
570
    GST_DEBUG_OBJECT (dec, "negative rates not supported yet");
571
572
    goto done;
  }
573
574
}

575
static GstFlowReturn
576
vorbis_handle_identification_packet (GstVorbisDec * vd)
577
578
579
580
581
582
583
584
585
586
{
  GstCaps *caps;
  const GstAudioChannelPosition *pos = NULL;

  switch (vd->vi.channels) {
    case 1:
    case 2:
      /* nothing */
      break;
    case 3:{
587
      static const GstAudioChannelPosition pos3[] = {
588
589
590
591
592
593
594
595
        GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
        GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
        GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT
      };
      pos = pos3;
      break;
    }
    case 4:{
596
      static const GstAudioChannelPosition pos4[] = {
597
598
599
600
601
602
603
604
605
        GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
        GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
        GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
        GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT
      };
      pos = pos4;
      break;
    }
    case 5:{
606
      static const GstAudioChannelPosition pos5[] = {
607
608
609
610
611
612
613
614
615
616
        GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
        GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
        GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
        GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
        GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT
      };
      pos = pos5;
      break;
    }
    case 6:{
617
      static const GstAudioChannelPosition pos6[] = {
618
619
620
621
622
623
624
625
626
627
        GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
        GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
        GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
        GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
        GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT,
        GST_AUDIO_CHANNEL_POSITION_LFE
      };
      pos = pos6;
      break;
    }
628
629
    default:
      goto channel_count_error;
630
  }
631
632
633
634
635
636

  caps = gst_caps_new_simple ("audio/x-raw-float",
      "rate", G_TYPE_INT, vd->vi.rate,
      "channels", G_TYPE_INT, vd->vi.channels,
      "endianness", G_TYPE_INT, G_BYTE_ORDER, "width", G_TYPE_INT, 32, NULL);

637
638
639
640
641
642
643
  if (pos) {
    gst_audio_set_channel_positions (gst_caps_get_structure (caps, 0), pos);
  }
  gst_pad_set_caps (vd->srcpad, caps);
  gst_caps_unref (caps);

  return GST_FLOW_OK;
644
645
646
647
648
649
650
651

  /* ERROR */
channel_count_error:
  {
    GST_ELEMENT_ERROR (vd, STREAM, NOT_IMPLEMENTED, (NULL),
        ("Unsupported channel count %d", vd->vi.channels));
    return GST_FLOW_ERROR;
  }
652
653
}

654
655
656
657
658
static GstFlowReturn
vorbis_handle_comment_packet (GstVorbisDec * vd, ogg_packet * packet)
{
  guint bitrate = 0;
  gchar *encoder = NULL;
659
  GstTagList *list;
660
661
662
663
664
665
666
  GstBuffer *buf;

  GST_DEBUG_OBJECT (vd, "parsing comment packet");

  buf = gst_buffer_new_and_alloc (packet->bytes);
  GST_BUFFER_DATA (buf) = packet->packet;

667
  list =
668
      gst_tag_list_from_vorbiscomment_buffer (buf, (guint8 *) "\003vorbis", 7,
669
670
671
      &encoder);

  vd->taglist = gst_tag_list_merge (vd->taglist, list, GST_TAG_MERGE_REPLACE);
672

673
  gst_tag_list_free (list);
674
675
  gst_buffer_unref (buf);

676
  if (!vd->taglist) {
677
    GST_ERROR_OBJECT (vd, "couldn't decode comments");
678
    vd->taglist = gst_tag_list_new ();
679
680
  }
  if (encoder) {
681
    gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
682
683
684
        GST_TAG_ENCODER, encoder, NULL);
    g_free (encoder);
  }
685
  gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
686
687
688
      GST_TAG_ENCODER_VERSION, vd->vi.version,
      GST_TAG_AUDIO_CODEC, "Vorbis", NULL);
  if (vd->vi.bitrate_nominal > 0) {
689
    gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
690
691
692
693
        GST_TAG_NOMINAL_BITRATE, (guint) vd->vi.bitrate_nominal, NULL);
    bitrate = vd->vi.bitrate_nominal;
  }
  if (vd->vi.bitrate_upper > 0) {
694
    gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
695
696
697
698
699
        GST_TAG_MAXIMUM_BITRATE, (guint) vd->vi.bitrate_upper, NULL);
    if (!bitrate)
      bitrate = vd->vi.bitrate_upper;
  }
  if (vd->vi.bitrate_lower > 0) {
700
    gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
701
702
703
704
705
        GST_TAG_MINIMUM_BITRATE, (guint) vd->vi.bitrate_lower, NULL);
    if (!bitrate)
      bitrate = vd->vi.bitrate_lower;
  }
  if (bitrate) {
706
    gst_tag_list_add (vd->taglist, GST_TAG_MERGE_REPLACE,
707
708
709
        GST_TAG_BITRATE, (guint) bitrate, NULL);
  }

710
711
712
713
  if (vd->initialized) {
    gst_element_found_tags_for_pad (GST_ELEMENT_CAST (vd), vd->srcpad,
        vd->taglist);
    vd->taglist = NULL;
714
715
716
717
718
  } else {
    /* Only post them as messages for the time being. *
     * They will be pushed on the pad once the decoder is initialized */
    gst_element_post_message (GST_ELEMENT_CAST (vd),
        gst_message_new_tag (GST_OBJECT (vd), gst_tag_list_copy (vd->taglist)));
719
  }
720
721
722
723
724
725
726

  return GST_FLOW_OK;
}

static GstFlowReturn
vorbis_handle_type_packet (GstVorbisDec * vd)
{
727
728
  GList *walk;

729
730
  g_assert (vd->initialized == FALSE);

731
732
733
734
  vorbis_synthesis_init (&vd->vd, &vd->vi);
  vorbis_block_init (&vd->vd, &vd->vb);
  vd->initialized = TRUE;

735
736
737
738
739
740
741
742
  if (vd->pendingevents) {
    for (walk = vd->pendingevents; walk; walk = g_list_next (walk))
      gst_pad_push_event (vd->srcpad, GST_EVENT_CAST (walk->data));
    g_list_free (vd->pendingevents);
    vd->pendingevents = NULL;
  }

  if (vd->taglist) {
743
744
    /* The tags have already been sent on the bus as messages. */
    gst_pad_push_event (vd->srcpad, gst_event_new_tag (vd->taglist));
745
746
747
    vd->taglist = NULL;
  }

748
749
750
  return GST_FLOW_OK;
}

751
752
753
754
755
static GstFlowReturn
vorbis_handle_header_packet (GstVorbisDec * vd, ogg_packet * packet)
{
  GstFlowReturn res;

756
  GST_DEBUG_OBJECT (vd, "parsing header packet");
757
758
759
760
761
762
763

  /* Packetno = 0 if the first byte is exactly 0x01 */
  packet->b_o_s = (packet->packet[0] == 0x1) ? 1 : 0;

  if (vorbis_synthesis_headerin (&vd->vi, &vd->vc, packet))
    goto header_read_error;

764
765
  switch (packet->packet[0]) {
    case 0x01:
766
767
      res = vorbis_handle_identification_packet (vd);
      break;
768
    case 0x03:
769
770
      res = vorbis_handle_comment_packet (vd, packet);
      break;
771
    case 0x05:
772
      res = vorbis_handle_type_packet (vd);
773
774
775
      break;
    default:
      /* ignore */
776
      g_warning ("unknown vorbis header packet found");
777
778
779
780
781
782
783
784
785
786
787
788
789
790
      res = GST_FLOW_OK;
      break;
  }
  return res;

  /* ERRORS */
header_read_error:
  {
    GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
        (NULL), ("couldn't read header packet"));
    return GST_FLOW_ERROR;
  }
}

791
792
/* These samples can be outside of the float -1.0 -- 1.0 range, this
 * is allowed, downstream elements are supposed to clip */
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
static void
copy_samples (float *out, float **in, guint samples, gint channels)
{
  gint i, j;

#ifdef GST_VORBIS_DEC_SEQUENTIAL
  for (i = 0; i < channels; i++) {
    memcpy (out, in[i], samples * sizeof (float));
    out += samples;
  }
#else
  for (j = 0; j < samples; j++) {
    for (i = 0; i < channels; i++) {
      *out++ = in[i][j];
    }
  }
#endif
}

812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/* clip output samples to the segment boundaries
 */
static gboolean
vorbis_do_clip (GstVorbisDec * dec, GstBuffer * buf)
{
  gint64 start, stop, cstart, cstop, diff;

  start = GST_BUFFER_TIMESTAMP (buf);
  stop = start + GST_BUFFER_DURATION (buf);

  if (!gst_segment_clip (&dec->segment, GST_FORMAT_TIME,
          start, stop, &cstart, &cstop))
    goto clipped;

  /* see if some clipping happened */
  diff = cstart - start;
  if (diff > 0) {
    GST_BUFFER_TIMESTAMP (buf) = cstart;
    GST_BUFFER_DURATION (buf) -= diff;

    /* bring clipped time to samples */
    diff = gst_util_uint64_scale_int (diff, dec->vi.rate, GST_SECOND);
    /* samples to bytes */
    diff *= (sizeof (float) * dec->vi.channels);
    GST_DEBUG_OBJECT (dec, "clipping start to %" GST_TIME_FORMAT " %"
        G_GUINT64_FORMAT " bytes", GST_TIME_ARGS (cstart), diff);
    GST_BUFFER_DATA (buf) += diff;
    GST_BUFFER_SIZE (buf) -= diff;
  }
  diff = stop - cstop;
  if (diff > 0) {
    GST_BUFFER_DURATION (buf) -= diff;

    /* bring clipped time to samples and then to bytes */
    diff = gst_util_uint64_scale_int (diff, dec->vi.rate, GST_SECOND);
    diff *= (sizeof (float) * dec->vi.channels);
    GST_DEBUG_OBJECT (dec, "clipping stop to %" GST_TIME_FORMAT " %"
        G_GUINT64_FORMAT " bytes", GST_TIME_ARGS (cstop), diff);
    GST_BUFFER_SIZE (buf) -= diff;
  }

  return FALSE;

  /* dropped buffer */
clipped:
  {
    GST_DEBUG_OBJECT (dec, "clipped buffer");
    gst_buffer_unref (buf);
    return TRUE;
  }
}

Wim Taymans's avatar
Wim Taymans committed
864
865
866
867
868
869
870
871
872
873
874
static GstFlowReturn
vorbis_dec_push (GstVorbisDec * dec, GstBuffer * buf)
{
  GstFlowReturn result;
  gint64 outoffset = GST_BUFFER_OFFSET (buf);

  if (outoffset == -1) {
    dec->queued = g_list_append (dec->queued, buf);
    GST_DEBUG_OBJECT (dec, "queued buffer");
    result = GST_FLOW_OK;
  } else {
875
    if (G_UNLIKELY (dec->queued)) {
Wim Taymans's avatar
Wim Taymans committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
      gint64 size;
      GList *walk;

      GST_DEBUG_OBJECT (dec, "first buffer with offset %lld", outoffset);

      size = g_list_length (dec->queued);
      for (walk = g_list_last (dec->queued); walk;
          walk = g_list_previous (walk)) {
        GstBuffer *buffer = GST_BUFFER (walk->data);

        outoffset -=
            GST_BUFFER_SIZE (buffer) / (sizeof (float) * dec->vi.channels);

        GST_BUFFER_OFFSET (buffer) = outoffset;
890
        GST_BUFFER_TIMESTAMP (buffer) =
891
            gst_util_uint64_scale_int (outoffset, GST_SECOND, dec->vi.rate);
892
893
        GST_DEBUG_OBJECT (dec, "patch buffer %" G_GUINT64_FORMAT
            " offset %" G_GUINT64_FORMAT, size, outoffset);
Wim Taymans's avatar
Wim Taymans committed
894
895
896
897
898
        size--;
      }
      for (walk = dec->queued; walk; walk = g_list_next (walk)) {
        GstBuffer *buffer = GST_BUFFER (walk->data);

899
900
901
902
903
        /* clips or returns FALSE with buffer unreffed when completely
         * clipped */
        if (vorbis_do_clip (dec, buffer))
          continue;

904
905
906
907
        if (dec->discont) {
          GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
          dec->discont = FALSE;
        }
908
        /* ignore the result */
Wim Taymans's avatar
Wim Taymans committed
909
910
911
912
913
        gst_pad_push (dec->srcpad, buffer);
      }
      g_list_free (dec->queued);
      dec->queued = NULL;
    }
914
915
916
917
918

    /* clip */
    if (vorbis_do_clip (dec, buf))
      return GST_FLOW_OK;

919
920
921
922
    if (dec->discont) {
      GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
      dec->discont = FALSE;
    }
Wim Taymans's avatar
Wim Taymans committed
923
924
925
926
927
928
    result = gst_pad_push (dec->srcpad, buf);
  }

  return result;
}

929
930
931
932
933
static GstFlowReturn
vorbis_handle_data_packet (GstVorbisDec * vd, ogg_packet * packet)
{
  float **pcm;
  guint sample_count;
934
  GstBuffer *out;
935
  GstFlowReturn result;
936
  gint size;
937
938
939
940

  if (!vd->initialized)
    goto not_initialized;

941
942
943
944
945
946
947
948
  /* FIXME, we should queue undecoded packets here until we get
   * a timestamp, then we reverse timestamp the queued packets and
   * clip them, then we decode only the ones we want and don't
   * keep decoded data in memory.
   * Ideally, of course, the demuxer gives us a valid timestamp on
   * the first packet.
   */

949
  /* normal data packet */
950
951
952
953
954
  /* FIXME, we can skip decoding if the packet is outside of the
   * segment, this is however not very trivial as we need a previous
   * packet to decode the current one so we must be carefull not to
   * throw away too much. For now we decode everything and clip right
   * before pushing data. */
955
  if (G_UNLIKELY (vorbis_synthesis (&vd->vb, packet)))
956
957
    goto could_not_read;

958
  if (G_UNLIKELY (vorbis_synthesis_blockin (&vd->vd, &vd->vb) < 0))
959
960
    goto not_accepted;

961
962
  /* assume all goes well here */
  result = GST_FLOW_OK;
963

964
965
966
  /* count samples ready for reading */
  if ((sample_count = vorbis_synthesis_pcmout (&vd->vd, NULL)) == 0)
    goto done;
967

968
969
  size = sample_count * vd->vi.channels * sizeof (float);

970
  /* alloc buffer for it */
Andy Wingo's avatar
Andy Wingo committed
971
972
  result =
      gst_pad_alloc_buffer_and_set_caps (vd->srcpad, GST_BUFFER_OFFSET_NONE,
973
      size, GST_PAD_CAPS (vd->srcpad), &out);
974
  if (G_UNLIKELY (result != GST_FLOW_OK))
975
    goto done;
976

977
  /* get samples ready for reading now, should be sample_count */
978
  if (G_UNLIKELY ((vorbis_synthesis_pcmout (&vd->vd, &pcm)) != sample_count))
979
    goto wrong_samples;
980

981
982
983
  /* copy samples in buffer */
  copy_samples ((float *) GST_BUFFER_DATA (out), pcm, sample_count,
      vd->vi.channels);
984

985
  GST_BUFFER_SIZE (out) = size;
986
987
988
989
  GST_BUFFER_OFFSET (out) = vd->granulepos;
  if (vd->granulepos != -1) {
    GST_BUFFER_OFFSET_END (out) = vd->granulepos + sample_count;
    GST_BUFFER_TIMESTAMP (out) =
990
        gst_util_uint64_scale_int (vd->granulepos, GST_SECOND, vd->vi.rate);
991
  } else {
992
    GST_BUFFER_TIMESTAMP (out) = -1;
993
  }
Wim Taymans's avatar
Wim Taymans committed
994
  /* this should not overflow */
995
996
  GST_BUFFER_DURATION (out) = sample_count * GST_SECOND / vd->vi.rate;

997
998
  if (vd->cur_timestamp != GST_CLOCK_TIME_NONE) {
    GST_BUFFER_TIMESTAMP (out) = vd->cur_timestamp;
999
1000
    GST_DEBUG_OBJECT (vd,
        "cur_timestamp: %" GST_TIME_FORMAT " + %" GST_TIME_FORMAT " = % "
1001
1002
1003
1004
1005
1006
1007
1008
1009
        GST_TIME_FORMAT, GST_TIME_ARGS (vd->cur_timestamp),
        GST_TIME_ARGS (GST_BUFFER_DURATION (out)),
        GST_TIME_ARGS (vd->cur_timestamp + GST_BUFFER_DURATION (out)));
    vd->cur_timestamp += GST_BUFFER_DURATION (out);
    GST_BUFFER_OFFSET (out) = GST_CLOCK_TIME_TO_FRAMES (vd->cur_timestamp,
        vd->vi.rate);
    GST_BUFFER_OFFSET_END (out) = GST_BUFFER_OFFSET (out) + sample_count;
  }

1010
1011
  if (vd->granulepos != -1)
    vd->granulepos += sample_count;
1012

1013
1014
1015
  result = vorbis_dec_push (vd, out);

done:
1016
1017
  vorbis_synthesis_read (&vd->vd, sample_count);

Wim Taymans's avatar
Wim Taymans committed
1018
1019
1020
1021
  /* granulepos is the last sample in the packet */
  if (packet->granulepos != -1)
    vd->granulepos = packet->granulepos;

1022
1023
1024
1025
1026
1027
  return result;

  /* ERRORS */
not_initialized:
  {
    GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
1028
        (NULL), ("no header sent yet"));
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
    return GST_FLOW_ERROR;
  }
could_not_read:
  {
    GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
        (NULL), ("couldn't read data packet"));
    return GST_FLOW_ERROR;
  }
not_accepted:
  {
    GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
        (NULL), ("vorbis decoder did not accept data packet"));
    return GST_FLOW_ERROR;
  }
1043
1044
1045
1046
1047
1048
1049
wrong_samples:
  {
    gst_buffer_unref (out);
    GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
        (NULL), ("vorbis decoder reported wrong number of samples"));
    return GST_FLOW_ERROR;
  }
1050
1051
}

1052
1053
static GstFlowReturn
vorbis_dec_chain (GstPad * pad, GstBuffer * buffer)
1054
1055
{
  GstVorbisDec *vd;
1056
1057
  ogg_packet packet;
  GstFlowReturn result = GST_FLOW_OK;
1058
1059
  GstClockTime timestamp;
  guint64 offset_end;
1060

1061
  vd = GST_VORBIS_DEC (gst_pad_get_parent (pad));
1062

1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
  /* resync on DISCONT */
  if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
    GST_DEBUG_OBJECT (vd, "received DISCONT buffer");
    vd->granulepos = -1;
    vd->cur_timestamp = GST_CLOCK_TIME_NONE;
    vd->prev_timestamp = GST_CLOCK_TIME_NONE;
#ifdef HAVE_VORBIS_SYNTHESIS_RESTART
    vorbis_synthesis_restart (&vd->vd);
#endif
    vd->discont = TRUE;
1073
  }
1074

1075
1076
1077
  timestamp = GST_BUFFER_TIMESTAMP (buffer);
  offset_end = GST_BUFFER_OFFSET_END (buffer);

1078
1079
  /* only ogg has granulepos, demuxers of other container formats 
   * might provide us with timestamps instead (e.g. matroskademux) */
1080
  if (offset_end == GST_BUFFER_OFFSET_NONE && timestamp != GST_CLOCK_TIME_NONE) {
1081
    /* we might get multiple consecutive buffers with the same timestamp */
1082
1083
1084
    if (timestamp != vd->prev_timestamp) {
      vd->cur_timestamp = timestamp;
      vd->prev_timestamp = timestamp;
1085
1086
1087
1088
1089
1090
    }
  } else {
    vd->cur_timestamp = GST_CLOCK_TIME_NONE;
    vd->prev_timestamp = GST_CLOCK_TIME_NONE;
  }

1091
  /* make ogg_packet out of the buffer */
1092
1093
  packet.packet = GST_BUFFER_DATA (buffer);
  packet.bytes = GST_BUFFER_SIZE (buffer);
1094
  packet.granulepos = offset_end;
1095
  packet.packetno = 0;          /* we don't care */
1096
  /*
1097
1098
   * FIXME. Is there anyway to know that this is the last packet and
   * set e_o_s??
1099
1100
   * Yes there is, keep one packet at all times and only push out when
   * you receive a new one.  Implement this.
1101
1102
1103
   */
  packet.e_o_s = 0;

1104
  if (G_UNLIKELY (packet.bytes < 1))
1105
1106
    goto wrong_size;

1107
1108
  GST_DEBUG_OBJECT (vd, "vorbis granule: %" G_GINT64_FORMAT,
      (gint64) packet.granulepos);
1109

1110
1111
  /* switch depending on packet type */
  if (packet.packet[0] & 1) {
1112
    if (vd->initialized) {
1113
1114
      GST_WARNING_OBJECT (vd, "Ignoring header");
      goto done;
1115
    }
1116
    result = vorbis_handle_header_packet (vd, &packet);
1117
  } else {
1118
1119
    result = vorbis_handle_data_packet (vd, &packet);
  }
1120

1121
  GST_DEBUG_OBJECT (vd, "offset end: %" G_GUINT64_FORMAT, offset_end);
1122

1123
done:
1124
  gst_buffer_unref (buffer);
1125
  gst_object_unref (vd);
1126
1127

  return result;
1128
1129
1130
1131

  /* ERRORS */
wrong_size:
  {
1132
1133
    GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL), ("empty buffer received"));
    result = GST_FLOW_ERROR;
1134
1135
1136
    vd->discont = TRUE;
    goto done;
  }
1137
1138
}

1139
1140
static GstStateChangeReturn
vorbis_dec_change_state (GstElement * element, GstStateChange transition)
1141
1142
{
  GstVorbisDec *vd = GST_VORBIS_DEC (element);
1143
  GstStateChangeReturn res;
1144
1145

  switch (transition) {
1146
    case GST_STATE_CHANGE_NULL_TO_READY:
1147
      break;
1148
    case GST_STATE_CHANGE_READY_TO_PAUSED:
1149
1150
      vorbis_info_init (&vd->vi);
      vorbis_comment_init (&vd->vc);
1151
      vd->initialized = FALSE;