vorbisdec.c 30.8 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
}

169
static void
170
vorbis_dec_finalize (GObject * object)
171
{
172
  /* Release any possibly allocated libvorbis data.
173
174
175
176
177
178
179
180
   * _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);
181
182

  G_OBJECT_CLASS (parent_class)->finalize (object);
183
184
}

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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;
}


204
static gboolean
205
206
207
vorbis_dec_convert (GstPad * pad,
    GstFormat src_format, gint64 src_value,
    GstFormat * dest_format, gint64 * dest_value)
208
{
209
210
211
  gboolean res = TRUE;
  GstVorbisDec *dec;
  guint64 scale = 1;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
212

Wim Taymans's avatar
Wim Taymans committed
213
214
215
216
217
  if (src_format == *dest_format) {
    *dest_value = src_value;
    return TRUE;
  }

218
219
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));

220
  if (!dec->initialized)
221
222
    goto no_header;

223
224
  if (dec->sinkpad == pad &&
      (src_format == GST_FORMAT_BYTES || *dest_format == GST_FORMAT_BYTES))
225
    goto no_format;
226

227
  switch (src_format) {
228
    case GST_FORMAT_TIME:
229
230
231
232
      switch (*dest_format) {
        case GST_FORMAT_BYTES:
          scale = sizeof (float) * dec->vi.channels;
        case GST_FORMAT_DEFAULT:
233
234
235
          *dest_value =
              scale * gst_util_uint64_scale_int (src_value, dec->vi.rate,
              GST_SECOND);
236
237
238
239
240
          break;
        default:
          res = FALSE;
      }
      break;
241
    case GST_FORMAT_DEFAULT:
242
243
244
245
246
      switch (*dest_format) {
        case GST_FORMAT_BYTES:
          *dest_value = src_value * sizeof (float) * dec->vi.channels;
          break;
        case GST_FORMAT_TIME:
247
          *dest_value =
248
              gst_util_uint64_scale_int (src_value, GST_SECOND, dec->vi.rate);
249
250
251
252
253
          break;
        default:
          res = FALSE;
      }
      break;
254
    case GST_FORMAT_BYTES:
255
256
257
258
259
      switch (*dest_format) {
        case GST_FORMAT_DEFAULT:
          *dest_value = src_value / (sizeof (float) * dec->vi.channels);
          break;
        case GST_FORMAT_TIME:
260
          *dest_value = gst_util_uint64_scale_int (src_value, GST_SECOND,
261
              dec->vi.rate * sizeof (float) * dec->vi.channels);
262
263
264
265
266
          break;
        default:
          res = FALSE;
      }
      break;
267
    default:
268
      res = FALSE;
269
  }
270
271
done:
  gst_object_unref (dec);
272

273
  return res;
274
275
276
277
278
279
280
281
282
283
284
285
286
287

  /* 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;
  }
288
}
289
290

static gboolean
Wim Taymans's avatar
Wim Taymans committed
291
vorbis_dec_src_query (GstPad * pad, GstQuery * query)
292
{
Wim Taymans's avatar
Wim Taymans committed
293
  GstVorbisDec *dec;
294
  gboolean res = FALSE;
Wim Taymans's avatar
Wim Taymans committed
295

296
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
Wim Taymans's avatar
Wim Taymans committed
297
298
299
300

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_POSITION:
    {
301
302
303
      gint64 granulepos, value;
      GstFormat my_format, format;
      gint64 time;
Wim Taymans's avatar
Wim Taymans committed
304

305
      /* we start from the last seen granulepos */
Wim Taymans's avatar
Wim Taymans committed
306
307
      granulepos = dec->granulepos;

Wim Taymans's avatar
Wim Taymans committed
308
      gst_query_parse_position (query, &format, NULL);
Wim Taymans's avatar
Wim Taymans committed
309

310
311
312
      /* 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
313
      if (!(res =
314
315
              vorbis_dec_convert (pad, GST_FORMAT_DEFAULT, granulepos,
                  &my_format, &time)))
Wim Taymans's avatar
Wim Taymans committed
316
317
        goto error;

318
      /* correct for the segment values */
319
320
321
322
323
324
325
326
      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;
327

Wim Taymans's avatar
Wim Taymans committed
328
      gst_query_set_position (query, format, value);
Wim Taymans's avatar
Wim Taymans committed
329
330

      GST_LOG_OBJECT (dec,
331
          "query %p: we return %lld (format %u)", query, value, format);
Wim Taymans's avatar
Wim Taymans committed
332
333
334

      break;
    }
Wim Taymans's avatar
Wim Taymans committed
335
336
    case GST_QUERY_DURATION:
    {
337
338
339
      GstPad *peer;

      if (!(peer = gst_pad_get_peer (dec->sinkpad))) {
340
341
342
343
        GST_WARNING_OBJECT (dec, "sink pad %" GST_PTR_FORMAT " is not linked",
            dec->sinkpad);
        goto error;
      }
344
345
346
347

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

Wim Taymans's avatar
Wim Taymans committed
350
351
      break;
    }
Wim Taymans's avatar
Wim Taymans committed
352
353
354
355
356
357
358
359
360
361
362
363
364
    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:
365
      res = gst_pad_query_default (pad, query);
Wim Taymans's avatar
Wim Taymans committed
366
367
      break;
  }
368
369
370
done:
  gst_object_unref (dec);

Wim Taymans's avatar
Wim Taymans committed
371
  return res;
372

373
  /* ERRORS */
Wim Taymans's avatar
Wim Taymans committed
374
375
error:
  {
376
    GST_WARNING_OBJECT (dec, "error handling query");
377
    goto done;
378
  }
Wim Taymans's avatar
Wim Taymans committed
379
}
380

Wim Taymans's avatar
Wim Taymans committed
381
382
383
384
385
386
static gboolean
vorbis_dec_sink_query (GstPad * pad, GstQuery * query)
{
  GstVorbisDec *dec;
  gboolean res;

387
  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
388

Wim Taymans's avatar
Wim Taymans committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
  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:
403
      res = gst_pad_query_default (pad, query);
Wim Taymans's avatar
Wim Taymans committed
404
405
      break;
  }
406
407
408
409

done:
  gst_object_unref (dec);

Wim Taymans's avatar
Wim Taymans committed
410
  return res;
411
412
413
414
415
416
417

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

420
static gboolean
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
421
vorbis_dec_src_event (GstPad * pad, GstEvent * event)
422
423
{
  gboolean res = TRUE;
424
425
426
  GstVorbisDec *dec;

  dec = GST_VORBIS_DEC (gst_pad_get_parent (pad));
427
428

  switch (GST_EVENT_TYPE (event)) {
429
430
    case GST_EVENT_SEEK:
    {
431
432
433
434
435
436
437
438
439
440
      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);
441
      gst_event_unref (event);
442
443
444
445
446
447
448
449
450

      /* 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)))
451
        goto convert_error;
452
      if (!(res = vorbis_dec_convert (pad, format, stop, &tformat, &tstop)))
453
        goto convert_error;
454
455
456
457
458

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

459
      res = gst_pad_push_event (dec->sinkpad, real_seek);
460

461
462
463
      break;
    }
    default:
464
      res = gst_pad_push_event (dec->sinkpad, event);
465
466
      break;
  }
467
468
done:
  gst_object_unref (dec);
469
470

  return res;
471

472
  /* ERRORS */
473
convert_error:
474
475
476
477
  {
    GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
    goto done;
  }
478
}
479

480
481
static gboolean
vorbis_dec_sink_event (GstPad * pad, GstEvent * event)
482
{
483
  gboolean ret = FALSE;
484
485
  GstVorbisDec *dec;

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

488
489
  GST_LOG_OBJECT (dec, "handling event");
  switch (GST_EVENT_TYPE (event)) {
Wim Taymans's avatar
Wim Taymans committed
490
491
492
    case GST_EVENT_EOS:
      ret = gst_pad_push_event (dec->srcpad, event);
      break;
493
494
495
496
    case GST_EVENT_FLUSH_START:
      ret = gst_pad_push_event (dec->srcpad, event);
      break;
    case GST_EVENT_FLUSH_STOP:
497
498
499
500
501
      /* 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);
502
503
      ret = gst_pad_push_event (dec->srcpad, event);
      break;
504
    case GST_EVENT_NEWSEGMENT:
505
506
    {
      GstFormat format;
507
      gdouble rate, arate;
Wim Taymans's avatar
Wim Taymans committed
508
      gint64 start, stop, time;
509
      gboolean update;
510

511
512
      gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
          &start, &stop, &time);
513

514
      /* we need time and a positive rate for now */
515
516
517
518
519
520
      if (format != GST_FORMAT_TIME)
        goto newseg_wrong_format;

      if (rate <= 0.0)
        goto newseg_wrong_rate;

521
522
523
524
525
526
      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));

527
      /* now configure the values */
528
529
      gst_segment_set_newsegment_full (&dec->segment, update,
          rate, arate, format, start, stop, time);
530

531
      /* and forward */
Wim Taymans's avatar
Wim Taymans committed
532
      ret = gst_pad_push_event (dec->srcpad, event);
533
      break;
534
    }
535
    default:
Wim Taymans's avatar
Wim Taymans committed
536
      ret = gst_pad_push_event (dec->srcpad, event);
537
538
      break;
  }
539
done:
Wim Taymans's avatar
Wim Taymans committed
540
541
  gst_object_unref (dec);

542
  return ret;
543

544
545
546
  /* ERRORS */
newseg_wrong_format:
  {
547
    GST_DEBUG_OBJECT (dec, "received non TIME newsegment");
548
549
550
551
    goto done;
  }
newseg_wrong_rate:
  {
552
    GST_DEBUG_OBJECT (dec, "negative rates not supported yet");
553
554
    goto done;
  }
555
556
}

557
static GstFlowReturn
558
vorbis_handle_identification_packet (GstVorbisDec * vd)
559
560
561
562
563
564
565
566
567
568
{
  GstCaps *caps;
  const GstAudioChannelPosition *pos = NULL;

  switch (vd->vi.channels) {
    case 1:
    case 2:
      /* nothing */
      break;
    case 3:{
569
      static const GstAudioChannelPosition pos3[] = {
570
571
572
573
574
575
576
577
        GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
        GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
        GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT
      };
      pos = pos3;
      break;
    }
    case 4:{
578
      static const GstAudioChannelPosition pos4[] = {
579
580
581
582
583
584
585
586
587
        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:{
588
      static const GstAudioChannelPosition pos5[] = {
589
590
591
592
593
594
595
596
597
598
        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:{
599
      static const GstAudioChannelPosition pos6[] = {
600
601
602
603
604
605
606
607
608
609
        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;
    }
610
611
    default:
      goto channel_count_error;
612
  }
613
614
615
616
617
618

  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);

619
620
621
622
623
624
625
  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;
626
627
628
629
630
631
632
633

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

636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
static GstFlowReturn
vorbis_handle_comment_packet (GstVorbisDec * vd, ogg_packet * packet)
{
  guint bitrate = 0;
  gchar *encoder = NULL;
  GstTagList *list;
  GstBuffer *buf;

  GST_DEBUG_OBJECT (vd, "parsing comment packet");

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

  list =
      gst_tag_list_from_vorbiscomment_buffer (buf, (guint8 *) "\003vorbis", 7,
      &encoder);

  gst_buffer_unref (buf);

  if (!list) {
    GST_ERROR_OBJECT (vd, "couldn't decode comments");
    list = gst_tag_list_new ();
  }
  if (encoder) {
    gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
        GST_TAG_ENCODER, encoder, NULL);
    g_free (encoder);
  }
  gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
      GST_TAG_ENCODER_VERSION, vd->vi.version,
      GST_TAG_AUDIO_CODEC, "Vorbis", NULL);
  if (vd->vi.bitrate_nominal > 0) {
    gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
        GST_TAG_NOMINAL_BITRATE, (guint) vd->vi.bitrate_nominal, NULL);
    bitrate = vd->vi.bitrate_nominal;
  }
  if (vd->vi.bitrate_upper > 0) {
    gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
        GST_TAG_MAXIMUM_BITRATE, (guint) vd->vi.bitrate_upper, NULL);
    if (!bitrate)
      bitrate = vd->vi.bitrate_upper;
  }
  if (vd->vi.bitrate_lower > 0) {
    gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
        GST_TAG_MINIMUM_BITRATE, (guint) vd->vi.bitrate_lower, NULL);
    if (!bitrate)
      bitrate = vd->vi.bitrate_lower;
  }
  if (bitrate) {
    gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
        GST_TAG_BITRATE, (guint) bitrate, NULL);
  }

689
  gst_element_found_tags_for_pad (GST_ELEMENT_CAST (vd), vd->srcpad, list);
690
691
692
693
694
695
696

  return GST_FLOW_OK;
}

static GstFlowReturn
vorbis_handle_type_packet (GstVorbisDec * vd)
{
697
698
  g_assert (vd->initialized == FALSE);

699
700
701
702
703
704
705
  vorbis_synthesis_init (&vd->vd, &vd->vi);
  vorbis_block_init (&vd->vd, &vd->vb);
  vd->initialized = TRUE;

  return GST_FLOW_OK;
}

706
707
708
709
710
static GstFlowReturn
vorbis_handle_header_packet (GstVorbisDec * vd, ogg_packet * packet)
{
  GstFlowReturn res;

711
  GST_DEBUG_OBJECT (vd, "parsing header packet");
712
713
714
715
716
717
718

  /* 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;

719
720
  switch (packet->packet[0]) {
    case 0x01:
721
722
      res = vorbis_handle_identification_packet (vd);
      break;
723
    case 0x03:
724
725
      res = vorbis_handle_comment_packet (vd, packet);
      break;
726
    case 0x05:
727
      res = vorbis_handle_type_packet (vd);
728
729
730
      break;
    default:
      /* ignore */
731
      g_warning ("unknown vorbis header packet found");
732
733
734
735
736
737
738
739
740
741
742
743
744
745
      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;
  }
}

746
747
/* These samples can be outside of the float -1.0 -- 1.0 range, this
 * is allowed, downstream elements are supposed to clip */
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
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
}

767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
/* 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
819
820
821
822
823
824
825
826
827
828
829
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 {
830
    if (G_UNLIKELY (dec->queued)) {
Wim Taymans's avatar
Wim Taymans committed
831
832
833
834
835
836
837
838
839
840
841
842
843
844
      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;
845
        GST_BUFFER_TIMESTAMP (buffer) =
846
            gst_util_uint64_scale_int (outoffset, GST_SECOND, dec->vi.rate);
847
848
        GST_DEBUG_OBJECT (dec, "patch buffer %" G_GUINT64_FORMAT
            " offset %" G_GUINT64_FORMAT, size, outoffset);
Wim Taymans's avatar
Wim Taymans committed
849
850
851
852
853
        size--;
      }
      for (walk = dec->queued; walk; walk = g_list_next (walk)) {
        GstBuffer *buffer = GST_BUFFER (walk->data);

854
855
856
857
858
        /* clips or returns FALSE with buffer unreffed when completely
         * clipped */
        if (vorbis_do_clip (dec, buffer))
          continue;

859
860
861
862
        if (dec->discont) {
          GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
          dec->discont = FALSE;
        }
863
        /* ignore the result */
Wim Taymans's avatar
Wim Taymans committed
864
865
866
867
868
        gst_pad_push (dec->srcpad, buffer);
      }
      g_list_free (dec->queued);
      dec->queued = NULL;
    }
869
870
871
872
873

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

874
875
876
877
    if (dec->discont) {
      GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
      dec->discont = FALSE;
    }
Wim Taymans's avatar
Wim Taymans committed
878
879
880
881
882
883
    result = gst_pad_push (dec->srcpad, buf);
  }

  return result;
}

884
885
886
887
888
static GstFlowReturn
vorbis_handle_data_packet (GstVorbisDec * vd, ogg_packet * packet)
{
  float **pcm;
  guint sample_count;
889
  GstBuffer *out;
890
  GstFlowReturn result;
891
  gint size;
892
893
894
895

  if (!vd->initialized)
    goto not_initialized;

896
897
898
899
900
901
902
903
  /* 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.
   */

904
  /* normal data packet */
905
906
907
908
909
  /* 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. */
910
  if (G_UNLIKELY (vorbis_synthesis (&vd->vb, packet)))
911
912
    goto could_not_read;

913
  if (G_UNLIKELY (vorbis_synthesis_blockin (&vd->vd, &vd->vb) < 0))
914
915
    goto not_accepted;

916
917
  /* assume all goes well here */
  result = GST_FLOW_OK;
918

919
920
921
  /* count samples ready for reading */
  if ((sample_count = vorbis_synthesis_pcmout (&vd->vd, NULL)) == 0)
    goto done;
922

923
924
  size = sample_count * vd->vi.channels * sizeof (float);

925
  /* alloc buffer for it */
Andy Wingo's avatar
Andy Wingo committed
926
927
  result =
      gst_pad_alloc_buffer_and_set_caps (vd->srcpad, GST_BUFFER_OFFSET_NONE,
928
      size, GST_PAD_CAPS (vd->srcpad), &out);
929
  if (G_UNLIKELY (result != GST_FLOW_OK))
930
    goto done;
931

932
  /* get samples ready for reading now, should be sample_count */
933
  if (G_UNLIKELY ((vorbis_synthesis_pcmout (&vd->vd, &pcm)) != sample_count))
934
    goto wrong_samples;
935

936
937
938
  /* copy samples in buffer */
  copy_samples ((float *) GST_BUFFER_DATA (out), pcm, sample_count,
      vd->vi.channels);
939

940
  GST_BUFFER_SIZE (out) = size;
941
942
943
944
  GST_BUFFER_OFFSET (out) = vd->granulepos;
  if (vd->granulepos != -1) {
    GST_BUFFER_OFFSET_END (out) = vd->granulepos + sample_count;
    GST_BUFFER_TIMESTAMP (out) =
945
        gst_util_uint64_scale_int (vd->granulepos, GST_SECOND, vd->vi.rate);
946
  } else {
947
    GST_BUFFER_TIMESTAMP (out) = -1;
948
  }
Wim Taymans's avatar
Wim Taymans committed
949
  /* this should not overflow */
950
951
  GST_BUFFER_DURATION (out) = sample_count * GST_SECOND / vd->vi.rate;

952
953
  if (vd->cur_timestamp != GST_CLOCK_TIME_NONE) {
    GST_BUFFER_TIMESTAMP (out) = vd->cur_timestamp;
954
955
    GST_DEBUG_OBJECT (vd,
        "cur_timestamp: %" GST_TIME_FORMAT " + %" GST_TIME_FORMAT " = % "
956
957
958
959
960
961
962
963
964
        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;
  }

965
966
  if (vd->granulepos != -1)
    vd->granulepos += sample_count;
967

968
969
970
  result = vorbis_dec_push (vd, out);

done:
971
972
  vorbis_synthesis_read (&vd->vd, sample_count);

Wim Taymans's avatar
Wim Taymans committed
973
974
975
976
  /* granulepos is the last sample in the packet */
  if (packet->granulepos != -1)
    vd->granulepos = packet->granulepos;

977
978
979
980
981
982
  return result;

  /* ERRORS */
not_initialized:
  {
    GST_ELEMENT_ERROR (GST_ELEMENT (vd), STREAM, DECODE,
983
        (NULL), ("no header sent yet"));
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    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;
  }
998
999
1000
1001
1002
1003
1004
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;
  }
1005
1006
}

1007
1008
static GstFlowReturn
vorbis_dec_chain (GstPad * pad, GstBuffer * buffer)
1009
1010
{
  GstVorbisDec *vd;
1011
1012
  ogg_packet packet;
  GstFlowReturn result = GST_FLOW_OK;
1013
1014
  GstClockTime timestamp;
  guint64 offset_end;
1015

1016
  vd = GST_VORBIS_DEC (gst_pad_get_parent (pad));
1017

1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
  /* 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;
1028
  }
1029

1030
1031
1032
  timestamp = GST_BUFFER_TIMESTAMP (buffer);
  offset_end = GST_BUFFER_OFFSET_END (buffer);

1033
1034
  /* only ogg has granulepos, demuxers of other container formats 
   * might provide us with timestamps instead (e.g. matroskademux) */
1035
  if (offset_end == GST_BUFFER_OFFSET_NONE && timestamp != GST_CLOCK_TIME_NONE) {
1036
    /* we might get multiple consecutive buffers with the same timestamp */
1037
1038
1039
    if (timestamp != vd->prev_timestamp) {
      vd->cur_timestamp = timestamp;
      vd->prev_timestamp = timestamp;
1040
1041
1042
1043
1044
1045
    }
  } else {
    vd->cur_timestamp = GST_CLOCK_TIME_NONE;
    vd->prev_timestamp = GST_CLOCK_TIME_NONE;
  }

1046
  /* make ogg_packet out of the buffer */
1047
1048
  packet.packet = GST_BUFFER_DATA (buffer);
  packet.bytes = GST_BUFFER_SIZE (buffer);
1049
  packet.granulepos = offset_end;
1050
  packet.packetno = 0;          /* we don't care */
1051
  /*
1052
1053
   * FIXME. Is there anyway to know that this is the last packet and
   * set e_o_s??
1054
1055
   * Yes there is, keep one packet at all times and only push out when
   * you receive a new one.  Implement this.
1056
1057
1058
   */
  packet.e_o_s = 0;

1059
  if (G_UNLIKELY (packet.bytes < 1))
1060
1061
    goto wrong_size;

1062
1063
  GST_DEBUG_OBJECT (vd, "vorbis granule: %" G_GINT64_FORMAT,
      (gint64) packet.granulepos);
1064

1065
1066
  /* switch depending on packet type */
  if (packet.packet[0] & 1) {
1067
    if (vd->initialized) {
1068
1069
      GST_WARNING_OBJECT (vd, "Ignoring header");
      goto done;
1070
    }
1071
    result = vorbis_handle_header_packet (vd, &packet);
1072
  } else {
1073
1074
    result = vorbis_handle_data_packet (vd, &packet);
  }
1075

1076
  GST_DEBUG_OBJECT (vd, "offset end: %" G_GUINT64_FORMAT, offset_end);
1077

1078
done:
1079
  gst_buffer_unref (buffer);
1080
  gst_object_unref (vd);
1081
1082

  return result;
1083
1084
1085
1086

  /* ERRORS */
wrong_size:
  {
1087
1088
    GST_ELEMENT_ERROR (vd, STREAM, DECODE, (NULL), ("empty buffer received"));
    result = GST_FLOW_ERROR;
1089
1090
1091
    vd->discont = TRUE;
    goto done;
  }
1092
1093
}

1094
1095
static GstStateChangeReturn
vorbis_dec_change_state (GstElement * element, GstStateChange transition)
1096
1097
{
  GstVorbisDec *vd = GST_VORBIS_DEC (element);
1098
  GstStateChangeReturn res;
1099
1100

  switch (transition) {
1101
    case GST_STATE_CHANGE_NULL_TO_READY:
1102
      break;
1103
    case GST_STATE_CHANGE_READY_TO_PAUSED:
1104
1105
      vorbis_info_init (&vd->vi);
      vorbis_comment_init (&vd->vc);
1106
      vd->initialized = FALSE;
1107
      gst_vorbis_dec_reset (vd);
1108
      break;
1109
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1110
      break;
1111
1112
1113
1114
    default:
      break;
  }

1115
  res = parent_class->change_state (element, transition);
1116
1117

  switch (transition) {
1118
    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1119
      break;
1120
    case GST_STATE_CHANGE_PAUSED_TO_READY:
1121
      GST_DEBUG_OBJECT (vd, "PAUSED -> READY, clearing vorbis structures");
1122
1123
1124
1125
      vorbis_block_clear (&vd->vb);
      vorbis_dsp_clear (&vd->vd);
      vorbis_comment_clear (&vd->vc);
      vorbis_info_clear (&vd->vi);
1126
      gst_vorbis_dec_reset (vd);
1127
      break;
1128
    case GST_STATE_CHANGE_READY_TO_NULL:
1129
1130
1131
1132
1133
      break;
    default:
      break;
  }

1134
  return res;
1135
}