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