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