ext/wavpack/: Use GSlice for allocating index entries and use gst_element_class_set_d...
[platform/upstream/gst-plugins-good.git] / ext / wavpack / gstwavpackdec.c
1 /* GStreamer Wavpack plugin
2  * Copyright (c) 2005 Arwed v. Merkatz <v.merkatz@gmx.net>
3  * Copyright (c) 2006 Edward Hervey <bilboed@gmail.com>
4  * Copyright (c) 2006 Sebastian Dröge <slomo@circular-chaos.org>
5  *
6  * gstwavpackdec.c: raw Wavpack bitstream decoder
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /**
25  * SECTION:element-wavpackdec
26  *
27  * <refsect2>
28  * WavpackDec decodes framed (for example by the WavpackParse element)
29  * Wavpack streams and decodes them to raw audio.
30  * <ulink url="http://www.wavpack.com/">Wavpack</ulink> is an open-source
31  * audio codec that features both lossless and lossy encoding.
32  * <title>Example launch line</title>
33  * <para>
34  * <programlisting>
35  * gst-launch filesrc location=test.wv ! wavpackparse ! wavpackdec ! audioconvert ! audioresample ! autoaudiosink
36  * </programlisting>
37  * This pipeline decodes the Wavpack file test.wv into raw audio buffers and
38  * tries to play it back using an automatically found audio sink.
39  * </para>
40  * </refsect2>
41  */
42
43 #ifdef HAVE_CONFIG_H
44 #include "config.h"
45 #endif
46
47 #include <gst/gst.h>
48 #include <gst/audio/audio.h>
49 #include <gst/audio/multichannel.h>
50
51 #include <math.h>
52 #include <string.h>
53
54 #include <wavpack/wavpack.h>
55 #include "gstwavpackdec.h"
56 #include "gstwavpackcommon.h"
57 #include "gstwavpackstreamreader.h"
58
59
60 #define WAVPACK_DEC_MAX_ERRORS 16
61
62 GST_DEBUG_CATEGORY_STATIC (gst_wavpack_dec_debug);
63 #define GST_CAT_DEFAULT gst_wavpack_dec_debug
64
65 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
66     GST_PAD_SINK,
67     GST_PAD_ALWAYS,
68     GST_STATIC_CAPS ("audio/x-wavpack, "
69         "width = (int) [ 1, 32 ], "
70         "channels = (int) [ 1, 8 ], "
71         "rate = (int) [ 6000, 192000 ], " "framed = (boolean) true")
72     );
73
74 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
75     GST_PAD_SRC,
76     GST_PAD_ALWAYS,
77     GST_STATIC_CAPS ("audio/x-raw-int, "
78         "width = (int) 32, "
79         "depth = (int) [ 1, 32 ], "
80         "channels = (int) [ 1, 8 ], "
81         "rate = (int) [ 6000, 192000 ], "
82         "endianness = (int) BYTE_ORDER, " "signed = (boolean) true")
83     );
84
85 static GstFlowReturn gst_wavpack_dec_chain (GstPad * pad, GstBuffer * buffer);
86 static gboolean gst_wavpack_dec_sink_set_caps (GstPad * pad, GstCaps * caps);
87 static gboolean gst_wavpack_dec_sink_event (GstPad * pad, GstEvent * event);
88 static void gst_wavpack_dec_finalize (GObject * object);
89 static GstStateChangeReturn gst_wavpack_dec_change_state (GstElement * element,
90     GstStateChange transition);
91 static gboolean gst_wavpack_dec_sink_event (GstPad * pad, GstEvent * event);
92 static void gst_wavpack_dec_post_tags (GstWavpackDec * dec);
93
94 GST_BOILERPLATE (GstWavpackDec, gst_wavpack_dec, GstElement, GST_TYPE_ELEMENT);
95
96 static void
97 gst_wavpack_dec_base_init (gpointer klass)
98 {
99   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
100
101   gst_element_class_add_pad_template (element_class,
102       gst_static_pad_template_get (&src_factory));
103   gst_element_class_add_pad_template (element_class,
104       gst_static_pad_template_get (&sink_factory));
105   gst_element_class_set_details_simple (element_class, "Wavpack audio decoder",
106       "Codec/Decoder/Audio",
107       "Decodes Wavpack audio data",
108       "Arwed v. Merkatz <v.merkatz@gmx.net>, "
109       "Sebastian Dröge <slomo@circular-chaos.org>");
110 }
111
112 static void
113 gst_wavpack_dec_class_init (GstWavpackDecClass * klass)
114 {
115   GObjectClass *gobject_class = (GObjectClass *) klass;
116   GstElementClass *gstelement_class = (GstElementClass *) klass;
117
118   gstelement_class->change_state =
119       GST_DEBUG_FUNCPTR (gst_wavpack_dec_change_state);
120   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_wavpack_dec_finalize);
121 }
122
123 static void
124 gst_wavpack_dec_reset (GstWavpackDec * dec)
125 {
126   dec->wv_id.buffer = NULL;
127   dec->wv_id.position = dec->wv_id.length = 0;
128
129   dec->error_count = 0;
130
131   dec->channels = 0;
132   dec->channel_mask = 0;
133   dec->sample_rate = 0;
134   dec->depth = 0;
135
136   gst_segment_init (&dec->segment, GST_FORMAT_TIME);
137   dec->next_block_index = 0;
138 }
139
140 static void
141 gst_wavpack_dec_init (GstWavpackDec * dec, GstWavpackDecClass * gklass)
142 {
143   dec->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
144   gst_pad_set_chain_function (dec->sinkpad,
145       GST_DEBUG_FUNCPTR (gst_wavpack_dec_chain));
146   gst_pad_set_setcaps_function (dec->sinkpad,
147       GST_DEBUG_FUNCPTR (gst_wavpack_dec_sink_set_caps));
148   gst_pad_set_event_function (dec->sinkpad,
149       GST_DEBUG_FUNCPTR (gst_wavpack_dec_sink_event));
150   gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
151
152   dec->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
153   gst_pad_use_fixed_caps (dec->srcpad);
154   gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
155
156   dec->context = NULL;
157   dec->stream_reader = gst_wavpack_stream_reader_new ();
158
159   gst_wavpack_dec_reset (dec);
160 }
161
162 static void
163 gst_wavpack_dec_finalize (GObject * object)
164 {
165   GstWavpackDec *dec = GST_WAVPACK_DEC (object);
166
167   g_free (dec->stream_reader);
168   dec->stream_reader = NULL;
169
170   G_OBJECT_CLASS (parent_class)->finalize (object);
171 }
172
173 static gboolean
174 gst_wavpack_dec_sink_set_caps (GstPad * pad, GstCaps * caps)
175 {
176   GstWavpackDec *dec = GST_WAVPACK_DEC (gst_pad_get_parent (pad));
177   GstStructure *structure = gst_caps_get_structure (caps, 0);
178
179   /* Check if we can set the caps here already */
180   if (gst_structure_get_int (structure, "channels", &dec->channels) &&
181       gst_structure_get_int (structure, "rate", &dec->sample_rate) &&
182       gst_structure_get_int (structure, "width", &dec->depth)) {
183     GstCaps *caps;
184     GstAudioChannelPosition *pos;
185
186     caps = gst_caps_new_simple ("audio/x-raw-int",
187         "rate", G_TYPE_INT, dec->sample_rate,
188         "channels", G_TYPE_INT, dec->channels,
189         "depth", G_TYPE_INT, dec->depth,
190         "width", G_TYPE_INT, 32,
191         "endianness", G_TYPE_INT, G_BYTE_ORDER,
192         "signed", G_TYPE_BOOLEAN, TRUE, NULL);
193
194     /* If we already have the channel layout set from upstream
195      * take this */
196     if (gst_structure_has_field (structure, "channel-positions")) {
197       pos = gst_audio_get_channel_positions (structure);
198       if (pos != NULL && dec->channels > 2) {
199         GstStructure *new_str = gst_caps_get_structure (caps, 0);
200
201         gst_audio_set_channel_positions (new_str, pos);
202         dec->channel_mask =
203             gst_wavpack_get_channel_mask_from_positions (pos, dec->channels);
204       }
205
206       if (pos != NULL)
207         g_free (pos);
208     }
209
210     GST_DEBUG_OBJECT (dec, "setting caps %" GST_PTR_FORMAT, caps);
211
212     /* should always succeed */
213     gst_pad_set_caps (dec->srcpad, caps);
214     gst_caps_unref (caps);
215
216     /* send GST_TAG_AUDIO_CODEC and GST_TAG_BITRATE tags before something
217      * is decoded or after the format has changed */
218     gst_wavpack_dec_post_tags (dec);
219   }
220
221   gst_object_unref (dec);
222
223   return TRUE;
224 }
225
226 static void
227 gst_wavpack_dec_post_tags (GstWavpackDec * dec)
228 {
229   GstTagList *list;
230   GstFormat format_time = GST_FORMAT_TIME, format_bytes = GST_FORMAT_BYTES;
231   gint64 duration, size;
232
233   list = gst_tag_list_new ();
234
235   gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
236       GST_TAG_AUDIO_CODEC, "Wavpack", NULL);
237
238   /* try to estimate the average bitrate */
239   if (gst_pad_query_peer_duration (dec->sinkpad, &format_bytes, &size) &&
240       gst_pad_query_peer_duration (dec->sinkpad, &format_time, &duration) &&
241       size > 0 && duration > 0) {
242     guint64 bitrate;
243
244     bitrate = gst_util_uint64_scale (size, 8 * GST_SECOND, duration);
245     gst_tag_list_add (list, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
246         (guint) bitrate, NULL);
247   }
248
249   gst_element_post_message (GST_ELEMENT (dec),
250       gst_message_new_tag (GST_OBJECT (dec), list));
251 }
252
253 static GstFlowReturn
254 gst_wavpack_dec_chain (GstPad * pad, GstBuffer * buf)
255 {
256   GstWavpackDec *dec;
257   GstBuffer *outbuf;
258   GstFlowReturn ret = GST_FLOW_OK;
259   WavpackHeader wph;
260   int32_t decoded, unpacked_size;
261   gboolean format_changed;
262
263   dec = GST_WAVPACK_DEC (GST_PAD_PARENT (pad));
264
265   /* check input, we only accept framed input with complete chunks */
266   if (GST_BUFFER_SIZE (buf) < sizeof (WavpackHeader))
267     goto input_not_framed;
268
269   if (!gst_wavpack_read_header (&wph, GST_BUFFER_DATA (buf)))
270     goto invalid_header;
271
272   if (GST_BUFFER_SIZE (buf) < wph.ckSize + 4 * 1 + 4)
273     goto input_not_framed;
274
275   if (!(wph.flags & INITIAL_BLOCK))
276     goto input_not_framed;
277
278   dec->wv_id.buffer = GST_BUFFER_DATA (buf);
279   dec->wv_id.length = GST_BUFFER_SIZE (buf);
280   dec->wv_id.position = 0;
281
282   /* create a new wavpack context if there is none yet but if there
283    * was already one (i.e. caps were set on the srcpad) check whether
284    * the new one has the same caps */
285   if (!dec->context) {
286     gchar error_msg[80];
287
288     dec->context = WavpackOpenFileInputEx (dec->stream_reader,
289         &dec->wv_id, NULL, error_msg, OPEN_STREAMING, 0);
290
291     if (!dec->context) {
292       GST_WARNING ("Couldn't decode buffer: %s", error_msg);
293       dec->error_count++;
294       if (dec->error_count <= WAVPACK_DEC_MAX_ERRORS) {
295         goto out;               /* just return OK for now */
296       } else {
297         goto decode_error;
298       }
299     }
300   }
301
302   g_assert (dec->context != NULL);
303
304   dec->error_count = 0;
305
306   format_changed =
307       (dec->sample_rate != WavpackGetSampleRate (dec->context)) ||
308       (dec->channels != WavpackGetNumChannels (dec->context)) ||
309       (dec->depth != WavpackGetBitsPerSample (dec->context)) ||
310 #ifdef WAVPACK_OLD_API
311       (dec->channel_mask != dec->context->config.channel_mask);
312 #else
313       (dec->channel_mask != WavpackGetChannelMask (dec->context));
314 #endif
315
316   if (!GST_PAD_CAPS (dec->srcpad) || format_changed) {
317     GstCaps *caps;
318     gint channel_mask;
319
320     dec->sample_rate = WavpackGetSampleRate (dec->context);
321     dec->channels = WavpackGetNumChannels (dec->context);
322     dec->depth = WavpackGetBitsPerSample (dec->context);
323
324     caps = gst_caps_new_simple ("audio/x-raw-int",
325         "rate", G_TYPE_INT, dec->sample_rate,
326         "channels", G_TYPE_INT, dec->channels,
327         "depth", G_TYPE_INT, dec->depth,
328         "width", G_TYPE_INT, 32,
329         "endianness", G_TYPE_INT, G_BYTE_ORDER,
330         "signed", G_TYPE_BOOLEAN, TRUE, NULL);
331
332 #ifdef WAVPACK_OLD_API
333     channel_mask = dec->context->config.channel_mask;
334 #else
335     channel_mask = WavpackGetChannelMask (dec->context);
336 #endif
337     if (channel_mask == 0)
338       channel_mask = gst_wavpack_get_default_channel_mask (dec->channels);
339
340     dec->channel_mask = channel_mask;
341
342     /* Only set the channel layout for more than two channels
343      * otherwise things break unfortunately */
344     if (channel_mask != 0 && dec->channels > 2)
345       if (!gst_wavpack_set_channel_layout (caps, channel_mask))
346         GST_WARNING_OBJECT (dec, "Failed to set channel layout");
347
348     GST_DEBUG_OBJECT (dec, "setting caps %" GST_PTR_FORMAT, caps);
349
350     /* should always succeed */
351     gst_pad_set_caps (dec->srcpad, caps);
352     gst_caps_unref (caps);
353
354     /* send GST_TAG_AUDIO_CODEC and GST_TAG_BITRATE tags before something
355      * is decoded or after the format has changed */
356     gst_wavpack_dec_post_tags (dec);
357   }
358
359   /* alloc output buffer */
360   unpacked_size = 4 * wph.block_samples * dec->channels;
361   ret = gst_pad_alloc_buffer (dec->srcpad, GST_BUFFER_OFFSET (buf),
362       unpacked_size, GST_PAD_CAPS (dec->srcpad), &outbuf);
363
364   if (ret != GST_FLOW_OK)
365     goto out;
366
367   gst_buffer_copy_metadata (outbuf, buf, GST_BUFFER_COPY_TIMESTAMPS);
368
369   /* If we got a DISCONT buffer forward the flag. Nothing else
370    * has to be done as libwavpack doesn't store state between
371    * Wavpack blocks */
372   if (GST_BUFFER_IS_DISCONT (buf) || dec->next_block_index != wph.block_index)
373     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
374
375   dec->next_block_index = wph.block_index + wph.block_samples;
376
377   /* decode */
378   decoded = WavpackUnpackSamples (dec->context,
379       (int32_t *) GST_BUFFER_DATA (outbuf), wph.block_samples);
380   if (decoded != wph.block_samples)
381     goto decode_error;
382
383   if ((outbuf = gst_audio_buffer_clip (outbuf, &dec->segment,
384               dec->sample_rate, 4 * dec->channels))) {
385     GST_LOG_OBJECT (dec, "pushing buffer with time %" GST_TIME_FORMAT,
386         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)));
387     ret = gst_pad_push (dec->srcpad, outbuf);
388   }
389
390 out:
391
392   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
393     GST_DEBUG_OBJECT (dec, "flow: %s", gst_flow_get_name (ret));
394   }
395
396   gst_buffer_unref (buf);
397
398   return ret;
399
400 /* ERRORS */
401 input_not_framed:
402   {
403     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Expected framed input"));
404     gst_buffer_unref (buf);
405     return GST_FLOW_ERROR;
406   }
407 invalid_header:
408   {
409     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Invalid wavpack header"));
410     gst_buffer_unref (buf);
411     return GST_FLOW_ERROR;
412   }
413 decode_error:
414   {
415     const gchar *reason = "unknown";
416
417     if (dec->context) {
418 #ifdef WAVPACK_OLD_API
419       reason = dec->context->error_message;
420 #else
421       reason = WavpackGetErrorMessage (dec->context);
422 #endif
423     } else {
424       reason = "couldn't create decoder context";
425     }
426     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
427         ("Failed to decode wavpack stream: %s", reason));
428     gst_buffer_unref (outbuf);
429     gst_buffer_unref (buf);
430     return GST_FLOW_ERROR;
431   }
432 }
433
434 static gboolean
435 gst_wavpack_dec_sink_event (GstPad * pad, GstEvent * event)
436 {
437   GstWavpackDec *dec = GST_WAVPACK_DEC (gst_pad_get_parent (pad));
438
439   GST_LOG_OBJECT (dec, "Received %s event", GST_EVENT_TYPE_NAME (event));
440   switch (GST_EVENT_TYPE (event)) {
441     case GST_EVENT_NEWSEGMENT:{
442       GstFormat fmt;
443       gboolean is_update;
444       gint64 start, end, base;
445       gdouble rate;
446
447       gst_event_parse_new_segment (event, &is_update, &rate, &fmt, &start,
448           &end, &base);
449       if (fmt == GST_FORMAT_TIME) {
450         GST_DEBUG ("Got NEWSEGMENT event in GST_FORMAT_TIME, passing on (%"
451             GST_TIME_FORMAT " - %" GST_TIME_FORMAT ")", GST_TIME_ARGS (start),
452             GST_TIME_ARGS (end));
453         gst_segment_set_newsegment (&dec->segment, is_update, rate, fmt,
454             start, end, base);
455       } else {
456         gst_segment_init (&dec->segment, GST_FORMAT_TIME);
457       }
458       break;
459     }
460     default:
461       break;
462   }
463
464   gst_object_unref (dec);
465   return gst_pad_event_default (pad, event);
466 }
467
468 static GstStateChangeReturn
469 gst_wavpack_dec_change_state (GstElement * element, GstStateChange transition)
470 {
471   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
472   GstWavpackDec *dec = GST_WAVPACK_DEC (element);
473
474   switch (transition) {
475     case GST_STATE_CHANGE_NULL_TO_READY:
476       break;
477     case GST_STATE_CHANGE_READY_TO_PAUSED:
478       break;
479     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
480       break;
481     default:
482       break;
483   }
484
485   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
486
487   switch (transition) {
488     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
489       break;
490     case GST_STATE_CHANGE_PAUSED_TO_READY:
491       if (dec->context) {
492         WavpackCloseFile (dec->context);
493         dec->context = NULL;
494       }
495
496       gst_wavpack_dec_reset (dec);
497       break;
498     case GST_STATE_CHANGE_READY_TO_NULL:
499       break;
500     default:
501       break;
502   }
503
504   return ret;
505 }
506
507 gboolean
508 gst_wavpack_dec_plugin_init (GstPlugin * plugin)
509 {
510   if (!gst_element_register (plugin, "wavpackdec",
511           GST_RANK_PRIMARY, GST_TYPE_WAVPACK_DEC))
512     return FALSE;
513   GST_DEBUG_CATEGORY_INIT (gst_wavpack_dec_debug, "wavpack_dec", 0,
514       "Wavpack decoder");
515   return TRUE;
516 }