gstwavpackdec.c 15.6 KB
Newer Older
1
/* GStreamer Wavpack plugin
2
3
4
 * Copyright (c) 2005 Arwed v. Merkatz <v.merkatz@gmx.net>
 * Copyright (c) 2006 Edward Hervey <bilboed@gmail.com>
 * Copyright (c) 2006 Sebastian Dröge <slomo@circular-chaos.org>
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *
 * gstwavpackdec.c: raw Wavpack bitstream decoder
 *
 * 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.
 */

24
25
26
/**
 * SECTION:element-wavpackdec
 *
27
 * WavpackDec decodes framed (for example by the WavpackParse element)
28
29
30
 * Wavpack streams and decodes them to raw audio.
 * <ulink url="http://www.wavpack.com/">Wavpack</ulink> is an open-source
 * audio codec that features both lossless and lossy encoding.
31
32
 *
 * <refsect2>
33
 * <title>Example launch line</title>
34
 * |[
35
 * gst-launch filesrc location=test.wv ! wavpackparse ! wavpackdec ! audioconvert ! audioresample ! autoaudiosink
36
 * ]| This pipeline decodes the Wavpack file test.wv into raw audio buffers and
37
38
39
40
 * tries to play it back using an automatically found audio sink.
 * </refsect2>
 */

41
42
43
44
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

45
#include <gst/gst.h>
46
#include <gst/audio/audio.h>
47
#include <gst/audio/multichannel.h>
48
49
50
51
52
53
54

#include <math.h>
#include <string.h>

#include <wavpack/wavpack.h>
#include "gstwavpackdec.h"
#include "gstwavpackcommon.h"
55
56
57
58
#include "gstwavpackstreamreader.h"


#define WAVPACK_DEC_MAX_ERRORS 16
59

60
61
GST_DEBUG_CATEGORY_STATIC (gst_wavpack_dec_debug);
#define GST_CAT_DEFAULT gst_wavpack_dec_debug
62
63
64
65
66

static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("audio/x-wavpack, "
67
        "width = (int) [ 1, 32 ], "
68
        "channels = (int) [ 1, 8 ], "
69
        "rate = (int) [ 6000, 192000 ], " "framed = (boolean) true")
70
71
72
73
74
75
    );

static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("audio/x-raw-int, "
76
77
        "width = (int) 32, "
        "depth = (int) [ 1, 32 ], "
78
        "channels = (int) [ 1, 8 ], "
79
        "rate = (int) [ 6000, 192000 ], "
80
        "endianness = (int) BYTE_ORDER, " "signed = (boolean) true")
81
82
    );

83
static GstFlowReturn gst_wavpack_dec_chain (GstPad * pad, GstBuffer * buffer);
84
static gboolean gst_wavpack_dec_sink_set_caps (GstPad * pad, GstCaps * caps);
85
static gboolean gst_wavpack_dec_sink_event (GstPad * pad, GstEvent * event);
86
87
88
static void gst_wavpack_dec_finalize (GObject * object);
static GstStateChangeReturn gst_wavpack_dec_change_state (GstElement * element,
    GstStateChange transition);
89
static void gst_wavpack_dec_post_tags (GstWavpackDec * dec);
90

91
GST_BOILERPLATE (GstWavpackDec, gst_wavpack_dec, GstElement, GST_TYPE_ELEMENT);
92
93

static void
94
gst_wavpack_dec_base_init (gpointer klass)
95
96
97
98
99
100
101
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&src_factory));
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&sink_factory));
102
103
104
105
106
  gst_element_class_set_details_simple (element_class, "Wavpack audio decoder",
      "Codec/Decoder/Audio",
      "Decodes Wavpack audio data",
      "Arwed v. Merkatz <v.merkatz@gmx.net>, "
      "Sebastian Dröge <slomo@circular-chaos.org>");
107
108
109
110
111
}

static void
gst_wavpack_dec_class_init (GstWavpackDecClass * klass)
{
112
113
  GObjectClass *gobject_class = (GObjectClass *) klass;
  GstElementClass *gstelement_class = (GstElementClass *) klass;
114

115
116
  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_wavpack_dec_change_state);
117
  gobject_class->finalize = gst_wavpack_dec_finalize;
118
119
}

120
121
122
123
124
125
126
127
128
static void
gst_wavpack_dec_reset (GstWavpackDec * dec)
{
  dec->wv_id.buffer = NULL;
  dec->wv_id.position = dec->wv_id.length = 0;

  dec->error_count = 0;

  dec->channels = 0;
129
  dec->channel_mask = 0;
130
131
132
  dec->sample_rate = 0;
  dec->depth = 0;

133
  gst_segment_init (&dec->segment, GST_FORMAT_TIME);
134
  dec->next_block_index = 0;
135
136
}

137
static void
138
gst_wavpack_dec_init (GstWavpackDec * dec, GstWavpackDecClass * gklass)
139
{
140
141
  dec->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
  gst_pad_set_chain_function (dec->sinkpad,
142
      GST_DEBUG_FUNCPTR (gst_wavpack_dec_chain));
143
144
  gst_pad_set_setcaps_function (dec->sinkpad,
      GST_DEBUG_FUNCPTR (gst_wavpack_dec_sink_set_caps));
145
  gst_pad_set_event_function (dec->sinkpad,
146
      GST_DEBUG_FUNCPTR (gst_wavpack_dec_sink_event));
147
  gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
148

149
150
151
  dec->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
  gst_pad_use_fixed_caps (dec->srcpad);
  gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
152

153
154
  dec->context = NULL;
  dec->stream_reader = gst_wavpack_stream_reader_new ();
155

156
  gst_wavpack_dec_reset (dec);
157
}
158

159
160
161
static void
gst_wavpack_dec_finalize (GObject * object)
{
162
  GstWavpackDec *dec = GST_WAVPACK_DEC (object);
163

164
165
  g_free (dec->stream_reader);
  dec->stream_reader = NULL;
166

167
  G_OBJECT_CLASS (parent_class)->finalize (object);
168
169
}

170
171
static gboolean
gst_wavpack_dec_sink_set_caps (GstPad * pad, GstCaps * caps)
172
{
173
174
  GstWavpackDec *dec = GST_WAVPACK_DEC (gst_pad_get_parent (pad));
  GstStructure *structure = gst_caps_get_structure (caps, 0);
175

176
177
178
179
180
  /* Check if we can set the caps here already */
  if (gst_structure_get_int (structure, "channels", &dec->channels) &&
      gst_structure_get_int (structure, "rate", &dec->sample_rate) &&
      gst_structure_get_int (structure, "width", &dec->depth)) {
    GstCaps *caps;
181
    GstAudioChannelPosition *pos;
182

183
184
185
186
187
188
189
    caps = gst_caps_new_simple ("audio/x-raw-int",
        "rate", G_TYPE_INT, dec->sample_rate,
        "channels", G_TYPE_INT, dec->channels,
        "depth", G_TYPE_INT, dec->depth,
        "width", G_TYPE_INT, 32,
        "endianness", G_TYPE_INT, G_BYTE_ORDER,
        "signed", G_TYPE_BOOLEAN, TRUE, NULL);
190

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    /* If we already have the channel layout set from upstream
     * take this */
    if (gst_structure_has_field (structure, "channel-positions")) {
      pos = gst_audio_get_channel_positions (structure);
      if (pos != NULL && dec->channels > 2) {
        GstStructure *new_str = gst_caps_get_structure (caps, 0);

        gst_audio_set_channel_positions (new_str, pos);
        dec->channel_mask =
            gst_wavpack_get_channel_mask_from_positions (pos, dec->channels);
      }

      if (pos != NULL)
        g_free (pos);
    }

207
208
209
210
211
212
213
214
215
    GST_DEBUG_OBJECT (dec, "setting caps %" GST_PTR_FORMAT, caps);

    /* should always succeed */
    gst_pad_set_caps (dec->srcpad, caps);
    gst_caps_unref (caps);

    /* send GST_TAG_AUDIO_CODEC and GST_TAG_BITRATE tags before something
     * is decoded or after the format has changed */
    gst_wavpack_dec_post_tags (dec);
216
  }
217
218
219
220

  gst_object_unref (dec);

  return TRUE;
221
222
}

223
static void
224
gst_wavpack_dec_post_tags (GstWavpackDec * dec)
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
{
  GstTagList *list;
  GstFormat format_time = GST_FORMAT_TIME, format_bytes = GST_FORMAT_BYTES;
  gint64 duration, size;

  list = gst_tag_list_new ();

  gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
      GST_TAG_AUDIO_CODEC, "Wavpack", NULL);

  /* try to estimate the average bitrate */
  if (gst_pad_query_peer_duration (dec->sinkpad, &format_bytes, &size) &&
      gst_pad_query_peer_duration (dec->sinkpad, &format_time, &duration) &&
      size > 0 && duration > 0) {
    guint64 bitrate;

    bitrate = gst_util_uint64_scale (size, 8 * GST_SECOND, duration);
    gst_tag_list_add (list, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
        (guint) bitrate, NULL);
  }

  gst_element_post_message (GST_ELEMENT (dec),
      gst_message_new_tag (GST_OBJECT (dec), list));
}

250
251
static GstFlowReturn
gst_wavpack_dec_chain (GstPad * pad, GstBuffer * buf)
252
{
253
  GstWavpackDec *dec;
254
  GstBuffer *outbuf = NULL;
255
  GstFlowReturn ret = GST_FLOW_OK;
256
  WavpackHeader wph;
257
258
259
260
261
262
263
264
265
266
267
268
  int32_t decoded, unpacked_size;
  gboolean format_changed;

  dec = GST_WAVPACK_DEC (GST_PAD_PARENT (pad));

  /* check input, we only accept framed input with complete chunks */
  if (GST_BUFFER_SIZE (buf) < sizeof (WavpackHeader))
    goto input_not_framed;

  if (!gst_wavpack_read_header (&wph, GST_BUFFER_DATA (buf)))
    goto invalid_header;

269
270
271
272
  if (GST_BUFFER_SIZE (buf) < wph.ckSize + 4 * 1 + 4)
    goto input_not_framed;

  if (!(wph.flags & INITIAL_BLOCK))
273
274
275
276
277
    goto input_not_framed;

  dec->wv_id.buffer = GST_BUFFER_DATA (buf);
  dec->wv_id.length = GST_BUFFER_SIZE (buf);
  dec->wv_id.position = 0;
278

279
280
281
  /* create a new wavpack context if there is none yet but if there
   * was already one (i.e. caps were set on the srcpad) check whether
   * the new one has the same caps */
282
  if (!dec->context) {
283
    gchar error_msg[80];
284

285
286
    dec->context = WavpackOpenFileInputEx (dec->stream_reader,
        &dec->wv_id, NULL, error_msg, OPEN_STREAMING, 0);
287

288
289
290
291
292
293
294
    if (!dec->context) {
      GST_WARNING ("Couldn't decode buffer: %s", error_msg);
      dec->error_count++;
      if (dec->error_count <= WAVPACK_DEC_MAX_ERRORS) {
        goto out;               /* just return OK for now */
      } else {
        goto decode_error;
295
296
297
298
      }
    }
  }

299
300
301
302
303
304
305
  g_assert (dec->context != NULL);

  dec->error_count = 0;

  format_changed =
      (dec->sample_rate != WavpackGetSampleRate (dec->context)) ||
      (dec->channels != WavpackGetNumChannels (dec->context)) ||
306
      (dec->depth != WavpackGetBitsPerSample (dec->context)) ||
307
308
309
#ifdef WAVPACK_OLD_API
      (dec->channel_mask != dec->context->config.channel_mask);
#else
310
      (dec->channel_mask != WavpackGetChannelMask (dec->context));
311
#endif
312
313

  if (!GST_PAD_CAPS (dec->srcpad) || format_changed) {
314
    GstCaps *caps;
315
    gint channel_mask;
316

317
318
    dec->sample_rate = WavpackGetSampleRate (dec->context);
    dec->channels = WavpackGetNumChannels (dec->context);
319
    dec->depth = WavpackGetBitsPerSample (dec->context);
320

321
    caps = gst_caps_new_simple ("audio/x-raw-int",
322
323
        "rate", G_TYPE_INT, dec->sample_rate,
        "channels", G_TYPE_INT, dec->channels,
324
        "depth", G_TYPE_INT, dec->depth,
325
        "width", G_TYPE_INT, 32,
326
        "endianness", G_TYPE_INT, G_BYTE_ORDER,
327
328
        "signed", G_TYPE_BOOLEAN, TRUE, NULL);

329
330
331
#ifdef WAVPACK_OLD_API
    channel_mask = dec->context->config.channel_mask;
#else
332
    channel_mask = WavpackGetChannelMask (dec->context);
333
#endif
334
335
336
337
338
339
340
341
342
343
344
    if (channel_mask == 0)
      channel_mask = gst_wavpack_get_default_channel_mask (dec->channels);

    dec->channel_mask = channel_mask;

    /* Only set the channel layout for more than two channels
     * otherwise things break unfortunately */
    if (channel_mask != 0 && dec->channels > 2)
      if (!gst_wavpack_set_channel_layout (caps, channel_mask))
        GST_WARNING_OBJECT (dec, "Failed to set channel layout");

345
346
347
348
    GST_DEBUG_OBJECT (dec, "setting caps %" GST_PTR_FORMAT, caps);

    /* should always succeed */
    gst_pad_set_caps (dec->srcpad, caps);
349
    gst_caps_unref (caps);
350
351
352

    /* send GST_TAG_AUDIO_CODEC and GST_TAG_BITRATE tags before something
     * is decoded or after the format has changed */
353
    gst_wavpack_dec_post_tags (dec);
354
355
  }

356
  /* alloc output buffer */
357
  unpacked_size = 4 * wph.block_samples * dec->channels;
358
359
  ret = gst_pad_alloc_buffer (dec->srcpad, GST_BUFFER_OFFSET (buf),
      unpacked_size, GST_PAD_CAPS (dec->srcpad), &outbuf);
360

361
362
  if (ret != GST_FLOW_OK)
    goto out;
363

364
365
  gst_buffer_copy_metadata (outbuf, buf, GST_BUFFER_COPY_TIMESTAMPS);

366
367
368
  /* If we got a DISCONT buffer forward the flag. Nothing else
   * has to be done as libwavpack doesn't store state between
   * Wavpack blocks */
369
  if (GST_BUFFER_IS_DISCONT (buf) || dec->next_block_index != wph.block_index)
370
    GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
371

372
373
  dec->next_block_index = wph.block_index + wph.block_samples;

374
375
376
377
378
379
  /* decode */
  decoded = WavpackUnpackSamples (dec->context,
      (int32_t *) GST_BUFFER_DATA (outbuf), wph.block_samples);
  if (decoded != wph.block_samples)
    goto decode_error;

380
381
  if ((outbuf = gst_audio_buffer_clip (outbuf, &dec->segment,
              dec->sample_rate, 4 * dec->channels))) {
382
    GST_LOG_OBJECT (dec, "pushing buffer with time %" GST_TIME_FORMAT,
383
        GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)));
384
    ret = gst_pad_push (dec->srcpad, outbuf);
385
  }
386

387
388
389
390
391
392
393
394
out:

  if (G_UNLIKELY (ret != GST_FLOW_OK)) {
    GST_DEBUG_OBJECT (dec, "flow: %s", gst_flow_get_name (ret));
  }

  gst_buffer_unref (buf);

395
  return ret;
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411

/* ERRORS */
input_not_framed:
  {
    GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Expected framed input"));
    gst_buffer_unref (buf);
    return GST_FLOW_ERROR;
  }
invalid_header:
  {
    GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Invalid wavpack header"));
    gst_buffer_unref (buf);
    return GST_FLOW_ERROR;
  }
decode_error:
  {
412
413
414
    const gchar *reason = "unknown";

    if (dec->context) {
415
416
417
#ifdef WAVPACK_OLD_API
      reason = dec->context->error_message;
#else
418
419
420
421
422
      reason = WavpackGetErrorMessage (dec->context);
#endif
    } else {
      reason = "couldn't create decoder context";
    }
423
    GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
424
        ("Failed to decode wavpack stream: %s", reason));
425
426
    if (outbuf)
      gst_buffer_unref (outbuf);
427
428
429
    gst_buffer_unref (buf);
    return GST_FLOW_ERROR;
  }
430
431
432
433
434
}

static gboolean
gst_wavpack_dec_sink_event (GstPad * pad, GstEvent * event)
{
435
  GstWavpackDec *dec = GST_WAVPACK_DEC (gst_pad_get_parent (pad));
436

437
  GST_LOG_OBJECT (dec, "Received %s event", GST_EVENT_TYPE_NAME (event));
438
439
440
441
442
443
444
445
446
447
448
449
450
  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_NEWSEGMENT:{
      GstFormat fmt;
      gboolean is_update;
      gint64 start, end, base;
      gdouble rate;

      gst_event_parse_new_segment (event, &is_update, &rate, &fmt, &start,
          &end, &base);
      if (fmt == GST_FORMAT_TIME) {
        GST_DEBUG ("Got NEWSEGMENT event in GST_FORMAT_TIME, passing on (%"
            GST_TIME_FORMAT " - %" GST_TIME_FORMAT ")", GST_TIME_ARGS (start),
            GST_TIME_ARGS (end));
451
        gst_segment_set_newsegment (&dec->segment, is_update, rate, fmt,
452
453
            start, end, base);
      } else {
454
        gst_segment_init (&dec->segment, GST_FORMAT_TIME);
455
456
457
458
459
460
461
      }
      break;
    }
    default:
      break;
  }

462
  gst_object_unref (dec);
463
464
465
466
467
468
469
  return gst_pad_event_default (pad, event);
}

static GstStateChangeReturn
gst_wavpack_dec_change_state (GstElement * element, GstStateChange transition)
{
  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
470
  GstWavpackDec *dec = GST_WAVPACK_DEC (element);
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      break;
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);

  switch (transition) {
    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
489
490
491
      if (dec->context) {
        WavpackCloseFile (dec->context);
        dec->context = NULL;
492
      }
493
494

      gst_wavpack_dec_reset (dec);
495
496
497
498
499
      break;
    case GST_STATE_CHANGE_READY_TO_NULL:
      break;
    default:
      break;
500
501
502
  }

  return ret;
503
504
505
506
507
}

gboolean
gst_wavpack_dec_plugin_init (GstPlugin * plugin)
{
508
509
510
  if (!gst_element_register (plugin, "wavpackdec",
          GST_RANK_PRIMARY, GST_TYPE_WAVPACK_DEC))
    return FALSE;
511
512
  GST_DEBUG_CATEGORY_INIT (gst_wavpack_dec_debug, "wavpack_dec", 0,
      "Wavpack decoder");
513
  return TRUE;
514
}