Use new gst_element_class_set_static_metadata()
[platform/upstream/gstreamer.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  * WavpackDec decodes framed (for example by the WavpackParse element)
28  * Wavpack streams and decodes them to raw audio.
29  * <ulink url="http://www.wavpack.com/">Wavpack</ulink> is an open-source
30  * 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  * tries to play it back using an automatically found audio sink.
38  * </refsect2>
39  */
40
41 #ifdef HAVE_CONFIG_H
42 #include "config.h"
43 #endif
44
45 #include <gst/gst.h>
46 #include <gst/audio/audio.h>
47
48 #include <math.h>
49 #include <string.h>
50
51 #include <wavpack/wavpack.h>
52 #include "gstwavpackdec.h"
53 #include "gstwavpackcommon.h"
54 #include "gstwavpackstreamreader.h"
55
56
57 GST_DEBUG_CATEGORY_STATIC (gst_wavpack_dec_debug);
58 #define GST_CAT_DEFAULT gst_wavpack_dec_debug
59
60 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
61     GST_PAD_SINK,
62     GST_PAD_ALWAYS,
63     GST_STATIC_CAPS ("audio/x-wavpack, "
64         "depth = (int) [ 1, 32 ], "
65         "channels = (int) [ 1, 8 ], "
66         "rate = (int) [ 6000, 192000 ], " "framed = (boolean) true")
67     );
68
69 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
70     GST_PAD_SRC,
71     GST_PAD_ALWAYS,
72     GST_STATIC_CAPS ("audio/x-raw, "
73         "format = (string) S8, "
74         "layout = (string) interleaved, "
75         "channels = (int) [ 1, 8 ], "
76         "rate = (int) [ 6000, 192000 ]; "
77         "audio/x-raw, "
78         "format = (string) " GST_AUDIO_NE (S16) ", "
79         "layout = (string) interleaved, "
80         "channels = (int) [ 1, 8 ], "
81         "rate = (int) [ 6000, 192000 ]; "
82         "audio/x-raw, "
83         "format = (string) " GST_AUDIO_NE (S32) ", "
84         "layout = (string) interleaved, "
85         "channels = (int) [ 1, 8 ], " "rate = (int) [ 6000, 192000 ]")
86     );
87
88 static gboolean gst_wavpack_dec_start (GstAudioDecoder * dec);
89 static gboolean gst_wavpack_dec_stop (GstAudioDecoder * dec);
90 static gboolean gst_wavpack_dec_set_format (GstAudioDecoder * dec,
91     GstCaps * caps);
92 static GstFlowReturn gst_wavpack_dec_handle_frame (GstAudioDecoder * dec,
93     GstBuffer * buffer);
94
95 static void gst_wavpack_dec_finalize (GObject * object);
96 static void gst_wavpack_dec_post_tags (GstWavpackDec * dec);
97
98 #define gst_wavpack_dec_parent_class parent_class
99 G_DEFINE_TYPE (GstWavpackDec, gst_wavpack_dec, GST_TYPE_AUDIO_DECODER);
100
101 static void
102 gst_wavpack_dec_class_init (GstWavpackDecClass * klass)
103 {
104   GObjectClass *gobject_class = (GObjectClass *) klass;
105   GstElementClass *element_class = (GstElementClass *) (klass);
106   GstAudioDecoderClass *base_class = (GstAudioDecoderClass *) (klass);
107
108   gst_element_class_add_pad_template (element_class,
109       gst_static_pad_template_get (&src_factory));
110   gst_element_class_add_pad_template (element_class,
111       gst_static_pad_template_get (&sink_factory));
112   gst_element_class_set_static_metadata (element_class, "Wavpack audio decoder",
113       "Codec/Decoder/Audio",
114       "Decodes Wavpack audio data",
115       "Arwed v. Merkatz <v.merkatz@gmx.net>, "
116       "Sebastian Dröge <slomo@circular-chaos.org>");
117
118   gobject_class->finalize = gst_wavpack_dec_finalize;
119
120   base_class->start = GST_DEBUG_FUNCPTR (gst_wavpack_dec_start);
121   base_class->stop = GST_DEBUG_FUNCPTR (gst_wavpack_dec_stop);
122   base_class->set_format = GST_DEBUG_FUNCPTR (gst_wavpack_dec_set_format);
123   base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_wavpack_dec_handle_frame);
124 }
125
126 static void
127 gst_wavpack_dec_reset (GstWavpackDec * dec)
128 {
129   dec->wv_id.buffer = NULL;
130   dec->wv_id.position = dec->wv_id.length = 0;
131
132   dec->channels = 0;
133   dec->channel_mask = 0;
134   dec->sample_rate = 0;
135   dec->depth = 0;
136 }
137
138 static void
139 gst_wavpack_dec_init (GstWavpackDec * dec)
140 {
141   dec->context = NULL;
142   dec->stream_reader = gst_wavpack_stream_reader_new ();
143
144   gst_wavpack_dec_reset (dec);
145 }
146
147 static void
148 gst_wavpack_dec_finalize (GObject * object)
149 {
150   GstWavpackDec *dec = GST_WAVPACK_DEC (object);
151
152   g_free (dec->stream_reader);
153   dec->stream_reader = NULL;
154
155   G_OBJECT_CLASS (parent_class)->finalize (object);
156 }
157
158 static gboolean
159 gst_wavpack_dec_start (GstAudioDecoder * dec)
160 {
161   GST_DEBUG_OBJECT (dec, "start");
162
163   /* never mind a few errors */
164   gst_audio_decoder_set_max_errors (dec, 16);
165   /* don't bother us with flushing */
166   gst_audio_decoder_set_drainable (dec, FALSE);
167   /* aim for some perfect timestamping */
168   gst_audio_decoder_set_tolerance (dec, 10 * GST_MSECOND);
169
170   return TRUE;
171 }
172
173 static gboolean
174 gst_wavpack_dec_stop (GstAudioDecoder * dec)
175 {
176   GstWavpackDec *wpdec = GST_WAVPACK_DEC (dec);
177
178   GST_DEBUG_OBJECT (dec, "stop");
179
180   if (wpdec->context) {
181     WavpackCloseFile (wpdec->context);
182     wpdec->context = NULL;
183   }
184
185   gst_wavpack_dec_reset (wpdec);
186
187   return TRUE;
188 }
189
190 static void
191 gst_wavpack_dec_negotiate (GstWavpackDec * dec)
192 {
193   GstAudioInfo info;
194   GstAudioFormat fmt;
195   GstAudioChannelPosition pos[64] = { GST_AUDIO_CHANNEL_POSITION_INVALID, };
196
197   /* arrange for 1, 2 or 4-byte width == depth output */
198   dec->width = dec->depth;
199   switch (dec->depth) {
200     case 8:
201       fmt = GST_AUDIO_FORMAT_S8;
202       break;
203     case 16:
204       fmt = _GST_AUDIO_FORMAT_NE (S16);
205       break;
206     case 24:
207     case 32:
208       fmt = _GST_AUDIO_FORMAT_NE (S32);
209       dec->width = 32;
210       break;
211     default:
212       g_assert_not_reached ();
213       break;
214   }
215
216   g_assert (dec->channel_mask != 0);
217
218   if (!gst_wavpack_get_channel_positions (dec->channels,
219           dec->channel_mask, pos))
220     GST_WARNING_OBJECT (dec, "Failed to set channel layout");
221
222   gst_audio_info_init (&info);
223   gst_audio_info_set_format (&info, fmt, dec->sample_rate, dec->channels, pos);
224
225   gst_audio_channel_positions_to_valid_order (info.position, info.channels);
226   gst_audio_get_channel_reorder_map (info.channels,
227       info.position, pos, dec->channel_reorder_map);
228
229   /* should always succeed */
230   gst_audio_decoder_set_output_format (GST_AUDIO_DECODER (dec), &info);
231 }
232
233 static gboolean
234 gst_wavpack_dec_set_format (GstAudioDecoder * bdec, GstCaps * caps)
235 {
236   /* pretty much nothing to do here,
237    * we'll parse it all from the stream and setup then */
238
239   return TRUE;
240 }
241
242 static void
243 gst_wavpack_dec_post_tags (GstWavpackDec * dec)
244 {
245   GstTagList *list;
246   GstFormat format_time = GST_FORMAT_TIME, format_bytes = GST_FORMAT_BYTES;
247   gint64 duration, size;
248
249   /* try to estimate the average bitrate */
250   if (gst_pad_peer_query_duration (GST_AUDIO_DECODER_SINK_PAD (dec),
251           format_bytes, &size) &&
252       gst_pad_peer_query_duration (GST_AUDIO_DECODER_SINK_PAD (dec),
253           format_time, &duration) && size > 0 && duration > 0) {
254     guint64 bitrate;
255
256     list = gst_tag_list_new_empty ();
257
258     bitrate = gst_util_uint64_scale (size, 8 * GST_SECOND, duration);
259     gst_tag_list_add (list, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
260         (guint) bitrate, NULL);
261
262     gst_element_post_message (GST_ELEMENT (dec),
263         gst_message_new_tag (GST_OBJECT (dec), list));
264   }
265 }
266
267 static GstFlowReturn
268 gst_wavpack_dec_handle_frame (GstAudioDecoder * bdec, GstBuffer * buf)
269 {
270   GstWavpackDec *dec;
271   GstBuffer *outbuf = NULL;
272   GstFlowReturn ret = GST_FLOW_OK;
273   WavpackHeader wph;
274   int32_t decoded, unpacked_size;
275   gboolean format_changed;
276   gint width, depth, i, j, max;
277   gint32 *dec_data = NULL;
278   guint8 *out_data;
279   GstMapInfo map, omap;
280
281   dec = GST_WAVPACK_DEC (bdec);
282
283   g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR);
284
285   gst_buffer_map (buf, &map, GST_MAP_READ);
286
287   /* check input, we only accept framed input with complete chunks */
288   if (map.size < sizeof (WavpackHeader))
289     goto input_not_framed;
290
291   if (!gst_wavpack_read_header (&wph, map.data))
292     goto invalid_header;
293
294   if (map.size < wph.ckSize + 4 * 1 + 4)
295     goto input_not_framed;
296
297   if (!(wph.flags & INITIAL_BLOCK))
298     goto input_not_framed;
299
300   dec->wv_id.buffer = map.data;
301   dec->wv_id.length = map.size;
302   dec->wv_id.position = 0;
303
304   /* create a new wavpack context if there is none yet but if there
305    * was already one (i.e. caps were set on the srcpad) check whether
306    * the new one has the same caps */
307   if (!dec->context) {
308     gchar error_msg[80];
309
310     dec->context = WavpackOpenFileInputEx (dec->stream_reader,
311         &dec->wv_id, NULL, error_msg, OPEN_STREAMING, 0);
312
313     /* expect this to work */
314     if (!dec->context) {
315       GST_WARNING_OBJECT (dec, "Couldn't decode buffer: %s", error_msg);
316       goto context_failed;
317     }
318   }
319
320   g_assert (dec->context != NULL);
321
322   format_changed =
323       (dec->sample_rate != WavpackGetSampleRate (dec->context)) ||
324       (dec->channels != WavpackGetNumChannels (dec->context)) ||
325       (dec->depth != WavpackGetBytesPerSample (dec->context) * 8) ||
326 #ifdef WAVPACK_OLD_API
327       (dec->channel_mask != dec->context->config.channel_mask);
328 #else
329       (dec->channel_mask != WavpackGetChannelMask (dec->context));
330 #endif
331
332   if (!gst_pad_has_current_caps (GST_AUDIO_DECODER_SRC_PAD (dec)) ||
333       format_changed) {
334     gint channel_mask;
335
336     dec->sample_rate = WavpackGetSampleRate (dec->context);
337     dec->channels = WavpackGetNumChannels (dec->context);
338     dec->depth = WavpackGetBytesPerSample (dec->context) * 8;
339
340 #ifdef WAVPACK_OLD_API
341     channel_mask = dec->context->config.channel_mask;
342 #else
343     channel_mask = WavpackGetChannelMask (dec->context);
344 #endif
345     if (channel_mask == 0)
346       channel_mask = gst_wavpack_get_default_channel_mask (dec->channels);
347
348     dec->channel_mask = channel_mask;
349
350     gst_wavpack_dec_negotiate (dec);
351
352     /* send GST_TAG_AUDIO_CODEC and GST_TAG_BITRATE tags before something
353      * is decoded or after the format has changed */
354     gst_wavpack_dec_post_tags (dec);
355   }
356
357   /* alloc output buffer */
358   dec_data = g_malloc (4 * wph.block_samples * dec->channels);
359
360   /* decode */
361   decoded = WavpackUnpackSamples (dec->context, dec_data, wph.block_samples);
362   if (decoded != wph.block_samples)
363     goto decode_error;
364
365   unpacked_size = (dec->width / 8) * wph.block_samples * dec->channels;
366   outbuf = gst_buffer_new_and_alloc (unpacked_size);
367
368   /* legacy; pass along offset, whatever that might entail */
369   GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buf);
370
371   gst_buffer_map (outbuf, &omap, GST_MAP_WRITE);
372   out_data = omap.data;
373
374   width = dec->width;
375   depth = dec->depth;
376   max = dec->channels * wph.block_samples;
377   if (width == 8) {
378     gint8 *outbuffer = (gint8 *) out_data;
379     gint *reorder_map = dec->channel_reorder_map;
380
381     for (i = 0; i < max; i += dec->channels) {
382       for (j = 0; j < dec->channels; j++)
383         *outbuffer++ = (gint8) (dec_data[i + reorder_map[j]]);
384     }
385   } else if (width == 16) {
386     gint16 *outbuffer = (gint16 *) out_data;
387     gint *reorder_map = dec->channel_reorder_map;
388
389     for (i = 0; i < max; i += dec->channels) {
390       for (j = 0; j < dec->channels; j++)
391         *outbuffer++ = (gint16) (dec_data[i + reorder_map[j]]);
392     }
393   } else if (dec->width == 32) {
394     gint32 *outbuffer = (gint32 *) out_data;
395     gint *reorder_map = dec->channel_reorder_map;
396
397     if (width != depth) {
398       for (i = 0; i < max; i += dec->channels) {
399         for (j = 0; j < dec->channels; j++)
400           *outbuffer++ =
401               (gint32) (dec_data[i + reorder_map[j]] << (width - depth));
402       }
403     } else {
404       for (i = 0; i < max; i += dec->channels) {
405         for (j = 0; j < dec->channels; j++)
406           *outbuffer++ = (gint32) (dec_data[i + reorder_map[j]]);
407       }
408     }
409   } else {
410     g_assert_not_reached ();
411   }
412
413   gst_buffer_unmap (outbuf, &omap);
414   gst_buffer_unmap (buf, &map);
415   buf = NULL;
416
417   g_free (dec_data);
418
419   ret = gst_audio_decoder_finish_frame (bdec, outbuf, 1);
420
421 out:
422   if (buf)
423     gst_buffer_unmap (buf, &map);
424
425   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
426     GST_DEBUG_OBJECT (dec, "flow: %s", gst_flow_get_name (ret));
427   }
428
429   return ret;
430
431 /* ERRORS */
432 input_not_framed:
433   {
434     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Expected framed input"));
435     ret = GST_FLOW_ERROR;
436     goto out;
437   }
438 invalid_header:
439   {
440     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Invalid wavpack header"));
441     ret = GST_FLOW_ERROR;
442     goto out;
443   }
444 context_failed:
445   {
446     GST_AUDIO_DECODER_ERROR (bdec, 1, LIBRARY, INIT, (NULL),
447         ("error creating Wavpack context"), ret);
448     goto out;
449   }
450 decode_error:
451   {
452     const gchar *reason = "unknown";
453
454     if (dec->context) {
455 #ifdef WAVPACK_OLD_API
456       reason = dec->context->error_message;
457 #else
458       reason = WavpackGetErrorMessage (dec->context);
459 #endif
460     } else {
461       reason = "couldn't create decoder context";
462     }
463     GST_AUDIO_DECODER_ERROR (bdec, 1, STREAM, DECODE, (NULL),
464         ("decoding error: %s", reason), ret);
465     g_free (dec_data);
466     if (ret == GST_FLOW_OK)
467       gst_audio_decoder_finish_frame (bdec, NULL, 1);
468     goto out;
469   }
470 }
471
472 gboolean
473 gst_wavpack_dec_plugin_init (GstPlugin * plugin)
474 {
475   if (!gst_element_register (plugin, "wavpackdec",
476           GST_RANK_PRIMARY, GST_TYPE_WAVPACK_DEC))
477     return FALSE;
478   GST_DEBUG_CATEGORY_INIT (gst_wavpack_dec_debug, "wavpackdec", 0,
479       "Wavpack decoder");
480   return TRUE;
481 }