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