configure.ac: Check for wavpack version and define WAVPACK_OLD_API if necessary.
[platform/upstream/gst-plugins-good.git] / ext / wavpack / gstwavpackenc.c
1 /* GStreamer Wavpack encoder plugin
2  * Copyright (c) 2006 Sebastian Dröge <slomo@circular-chaos.org>
3  *
4  * gstwavpackdec.c: Wavpack audio encoder
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /*
23  * TODO: - add multichannel handling. channel_mask is:
24  *                  front left
25  *                  front right
26  *                  center
27  *                  LFE
28  *                  back left
29  *                  back right
30  *                  front left center
31  *                  front right center
32  *                  back left
33  *                  back center
34  *                  side left
35  *                  side right
36  *                  ...
37  *        - add 32 bit float mode. CONFIG_FLOAT_DATA
38  */
39
40 #include <string.h>
41 #include <gst/gst.h>
42 #include <glib/gprintf.h>
43
44 #include <wavpack/wavpack.h>
45 #include "gstwavpackenc.h"
46 #include "gstwavpackcommon.h"
47 #include "md5.h"
48
49 static GstFlowReturn gst_wavpack_enc_chain (GstPad * pad, GstBuffer * buffer);
50 static gboolean gst_wavpack_enc_sink_set_caps (GstPad * pad, GstCaps * caps);
51 static int gst_wavpack_enc_push_block (void *id, void *data, int32_t count);
52 static gboolean gst_wavpack_enc_sink_event (GstPad * pad, GstEvent * event);
53 static GstStateChangeReturn gst_wavpack_enc_change_state (GstElement * element,
54     GstStateChange transition);
55 static void gst_wavpack_enc_finalize (GObject * object);
56 static void gst_wavpack_enc_set_property (GObject * object, guint prop_id,
57     const GValue * value, GParamSpec * pspec);
58 static void gst_wavpack_enc_get_property (GObject * object, guint prop_id,
59     GValue * value, GParamSpec * pspec);
60
61 enum
62 {
63   ARG_0,
64   ARG_MODE,
65   ARG_BITRATE,
66   ARG_BITSPERSAMPLE,
67   ARG_CORRECTION_MODE,
68   ARG_MD5,
69   ARG_EXTRA_PROCESSING,
70   ARG_JOINT_STEREO_MODE,
71 };
72
73 GST_DEBUG_CATEGORY_STATIC (gst_wavpack_enc_debug);
74 #define GST_CAT_DEFAULT gst_wavpack_enc_debug
75
76 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
77     GST_PAD_SINK,
78     GST_PAD_ALWAYS,
79     GST_STATIC_CAPS ("audio/x-raw-int, "
80         "width = (int) 32, "
81         "depth = (int) 32, "
82         "endianness = (int) LITTLE_ENDIAN, "
83         "channels = (int) [ 1, 2 ], "
84         "rate = (int) [ 6000, 192000 ]," "signed = (boolean) TRUE;"
85         "audio/x-raw-int, "
86         "width = (int) 24, "
87         "depth = (int) 24, "
88         "endianness = (int) LITTLE_ENDIAN, "
89         "channels = (int) [ 1, 2 ], "
90         "rate = (int) [ 6000, 192000 ]," "signed = (boolean) TRUE;"
91         "audio/x-raw-int, "
92         "width = (int) 16, "
93         "depth = (int) 16, "
94         "endianness = (int) LITTLE_ENDIAN, "
95         "channels = (int) [ 1, 2 ], "
96         "rate = (int) [ 6000, 192000 ]," "signed = (boolean) TRUE;"
97         "audio/x-raw-int, "
98         "width = (int) 8, "
99         "depth = (int) 8, "
100         "endianness = (int) LITTLE_ENDIAN, "
101         "channels = (int) [ 1, 2 ], "
102         "rate = (int) [ 6000, 192000 ]," "signed = (boolean) TRUE")
103     );
104
105 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
106     GST_PAD_SRC,
107     GST_PAD_ALWAYS,
108     GST_STATIC_CAPS ("audio/x-wavpack, "
109         "width = (int) { 8, 16, 24, 32 }, "
110         "channels = (int) [ 1, 2 ], "
111         "rate = (int) [ 6000, 192000 ], " "framed = (boolean) FALSE")
112     );
113
114 static GstStaticPadTemplate wvcsrc_factory = GST_STATIC_PAD_TEMPLATE ("wvcsrc",
115     GST_PAD_SRC,
116     GST_PAD_SOMETIMES,
117     GST_STATIC_CAPS ("audio/x-wavpack-correction, " "framed = (boolean) FALSE")
118     );
119
120 #define DEFAULT_MODE 1
121 #define GST_TYPE_WAVPACK_ENC_MODE (gst_wavpack_enc_mode_get_type ())
122 static GType
123 gst_wavpack_enc_mode_get_type (void)
124 {
125   static GType qtype = 0;
126
127   if (qtype == 0) {
128     static const GEnumValue values[] = {
129       {0, "Fast Compression", "0"},
130       {1, "Default", "1"},
131       {2, "High Compression", "2"},
132       {0, NULL, NULL}
133     };
134
135     qtype = g_enum_register_static ("GstWavpackEncMode", values);
136   }
137   return qtype;
138 }
139
140 #define DEFAULT_CORRECTION_MODE 0
141 #define GST_TYPE_WAVPACK_ENC_CORRECTION_MODE (gst_wavpack_enc_correction_mode_get_type ())
142 static GType
143 gst_wavpack_enc_correction_mode_get_type (void)
144 {
145   static GType qtype = 0;
146
147   if (qtype == 0) {
148     static const GEnumValue values[] = {
149       {0, "Create no correction file (default)", "0"},
150       {1, "Create correction file", "1"},
151       {2, "Create optimized correction file", "2"},
152       {0, NULL, NULL}
153     };
154
155     qtype = g_enum_register_static ("GstWavpackEncCorrectionMode", values);
156   }
157   return qtype;
158 }
159
160 #define DEFAULT_JS_MODE 0
161 #define GST_TYPE_WAVPACK_ENC_JOINT_STEREO_MODE (gst_wavpack_enc_joint_stereo_mode_get_type ())
162 static GType
163 gst_wavpack_enc_joint_stereo_mode_get_type (void)
164 {
165   static GType qtype = 0;
166
167   if (qtype == 0) {
168     static const GEnumValue values[] = {
169       {0, "auto (default)", "0"},
170       {1, "left/right", "1"},
171       {2, "mid/side", "2"},
172       {0, NULL, NULL}
173     };
174
175     qtype = g_enum_register_static ("GstWavpackEncJSMode", values);
176   }
177   return qtype;
178 }
179
180 GST_BOILERPLATE (GstWavpackEnc, gst_wavpack_enc, GstElement, GST_TYPE_ELEMENT);
181
182 static void
183 gst_wavpack_enc_base_init (gpointer klass)
184 {
185   static GstElementDetails element_details = {
186     "Wavpack audio encoder",
187     "Codec/Encoder/Audio",
188     "Encodes audio with the Wavpack lossless/lossy audio codec",
189     "Sebastian Dröge <slomo@circular-chaos.org>"
190   };
191   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
192
193   /* add pad templates */
194   gst_element_class_add_pad_template (element_class,
195       gst_static_pad_template_get (&sink_factory));
196   gst_element_class_add_pad_template (element_class,
197       gst_static_pad_template_get (&src_factory));
198   gst_element_class_add_pad_template (element_class,
199       gst_static_pad_template_get (&wvcsrc_factory));
200
201   /* set element details */
202   gst_element_class_set_details (element_class, &element_details);
203 }
204
205
206 static void
207 gst_wavpack_enc_class_init (GstWavpackEncClass * klass)
208 {
209   GObjectClass *gobject_class = (GObjectClass *) klass;
210   GstElementClass *gstelement_class = (GstElementClass *) klass;
211
212   parent_class = g_type_class_peek_parent (klass);
213
214   /* set state change handler */
215   gstelement_class->change_state =
216       GST_DEBUG_FUNCPTR (gst_wavpack_enc_change_state);
217   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_wavpack_enc_finalize);
218
219   /* set property handlers */
220   gobject_class->set_property =
221       GST_DEBUG_FUNCPTR (gst_wavpack_enc_set_property);
222   gobject_class->get_property =
223       GST_DEBUG_FUNCPTR (gst_wavpack_enc_get_property);
224
225   /* install all properties */
226   g_object_class_install_property (gobject_class, ARG_MODE,
227       g_param_spec_enum ("mode", "Encoding mode",
228           "Speed versus compression tradeoff.",
229           GST_TYPE_WAVPACK_ENC_MODE, DEFAULT_MODE, G_PARAM_READWRITE));
230   g_object_class_install_property (gobject_class, ARG_BITRATE,
231       g_param_spec_double ("bitrate", "Bitrate",
232           "Try to encode with this average bitrate (bits/sec). "
233           "This enables lossy encoding! A value smaller than 24000.0 disables this.",
234           0.0, 9600000.0, 0.0, G_PARAM_READWRITE));
235   g_object_class_install_property (gobject_class, ARG_BITSPERSAMPLE,
236       g_param_spec_double ("bits-per-sample", "Bits per sample",
237           "Try to encode with this amount of bits per sample. "
238           "This enables lossy encoding! A value smaller than 2.0 disables this.",
239           0.0, 24.0, 0.0, G_PARAM_READWRITE));
240   g_object_class_install_property (gobject_class, ARG_CORRECTION_MODE,
241       g_param_spec_enum ("correction_mode", "Correction file mode",
242           "Use this mode for correction file creation. Only works in lossy mode!",
243           GST_TYPE_WAVPACK_ENC_CORRECTION_MODE, DEFAULT_CORRECTION_MODE,
244           G_PARAM_READWRITE));
245   g_object_class_install_property (gobject_class, ARG_MD5,
246       g_param_spec_boolean ("md5", "MD5",
247           "Store MD5 hash of raw samples within the file.", FALSE,
248           G_PARAM_READWRITE));
249   g_object_class_install_property (gobject_class, ARG_EXTRA_PROCESSING,
250       g_param_spec_boolean ("extra_processing", "Extra processing",
251           "Extra encode processing.", FALSE, G_PARAM_READWRITE));
252   g_object_class_install_property (gobject_class, ARG_JOINT_STEREO_MODE,
253       g_param_spec_enum ("joint_stereo_mode", "Joint-Stereo mode",
254           "Use this joint-stereo mode.", GST_TYPE_WAVPACK_ENC_JOINT_STEREO_MODE,
255           DEFAULT_JS_MODE, G_PARAM_READWRITE));
256 }
257
258 static void
259 gst_wavpack_enc_init (GstWavpackEnc * wavpack_enc, GstWavpackEncClass * gclass)
260 {
261   GstElementClass *klass = GST_ELEMENT_GET_CLASS (wavpack_enc);
262
263   /* setup sink pad, add handlers */
264   wavpack_enc->sinkpad =
265       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
266           "sink"), "sink");
267   gst_pad_set_setcaps_function (wavpack_enc->sinkpad,
268       GST_DEBUG_FUNCPTR (gst_wavpack_enc_sink_set_caps));
269   gst_pad_set_chain_function (wavpack_enc->sinkpad,
270       GST_DEBUG_FUNCPTR (gst_wavpack_enc_chain));
271   gst_pad_set_event_function (wavpack_enc->sinkpad,
272       GST_DEBUG_FUNCPTR (gst_wavpack_enc_sink_event));
273   gst_element_add_pad (GST_ELEMENT (wavpack_enc), wavpack_enc->sinkpad);
274
275   /* setup src pad */
276   wavpack_enc->srcpad =
277       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
278           "src"), "src");
279   gst_element_add_pad (GST_ELEMENT (wavpack_enc), wavpack_enc->srcpad);
280
281   /* initialize object attributes */
282   wavpack_enc->wp_config = NULL;
283   wavpack_enc->wp_context = NULL;
284   wavpack_enc->first_block = NULL;
285   wavpack_enc->first_block_size = 0;
286   wavpack_enc->md5_context = NULL;
287   wavpack_enc->samplerate = 0;
288   wavpack_enc->width = 0;
289   wavpack_enc->channels = 0;
290
291   wavpack_enc->wv_id = (write_id *) g_malloc0 (sizeof (write_id));
292   wavpack_enc->wv_id->correction = FALSE;
293   wavpack_enc->wv_id->wavpack_enc = wavpack_enc;
294   wavpack_enc->wvc_id = (write_id *) g_malloc0 (sizeof (write_id));
295   wavpack_enc->wvc_id->correction = TRUE;
296   wavpack_enc->wvc_id->wavpack_enc = wavpack_enc;
297
298   /* set default values of params */
299   wavpack_enc->mode = 1;
300   wavpack_enc->bitrate = 0.0;
301   wavpack_enc->correction_mode = 0;
302   wavpack_enc->md5 = FALSE;
303   wavpack_enc->extra_processing = FALSE;
304   wavpack_enc->joint_stereo_mode = 0;
305 }
306
307 static void
308 gst_wavpack_enc_finalize (GObject * object)
309 {
310   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (object);
311
312   /* free the blockout helpers */
313   g_free (wavpack_enc->wv_id);
314   g_free (wavpack_enc->wvc_id);
315
316   G_OBJECT_CLASS (parent_class)->finalize (object);
317 }
318
319 static gboolean
320 gst_wavpack_enc_sink_set_caps (GstPad * pad, GstCaps * caps)
321 {
322   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (gst_pad_get_parent (pad));
323   GstStructure *structure = gst_caps_get_structure (caps, 0);
324   int depth = 0;
325
326   /* check caps and put relevant parts into our object attributes */
327   if ((!gst_structure_get_int (structure, "channels", &wavpack_enc->channels))
328       || (!gst_structure_get_int (structure, "rate", &wavpack_enc->samplerate))
329       || (!gst_structure_get_int (structure, "width", &wavpack_enc->width))
330       || (!(gst_structure_get_int (structure, "depth", &depth))
331           || depth != wavpack_enc->width)) {
332     GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, INIT, (NULL),
333         ("got invalid caps: %", GST_PTR_FORMAT, caps));
334     gst_object_unref (wavpack_enc);
335     return FALSE;
336   }
337
338   /* set fixed src pad caps now that we know what we will get */
339   caps = gst_caps_new_simple ("audio/x-wavpack",
340       "channels", G_TYPE_INT, wavpack_enc->channels,
341       "rate", G_TYPE_INT, wavpack_enc->samplerate,
342       "width", G_TYPE_INT, wavpack_enc->width,
343       "framed", G_TYPE_BOOLEAN, TRUE, NULL);
344
345   if (!gst_pad_set_caps (wavpack_enc->srcpad, caps)) {
346     GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, INIT, (NULL),
347         ("setting caps failed: %", GST_PTR_FORMAT, caps));
348     gst_caps_unref (caps);
349     gst_object_unref (wavpack_enc);
350     return FALSE;
351   }
352   gst_pad_use_fixed_caps (wavpack_enc->srcpad);
353
354   gst_caps_unref (caps);
355   gst_object_unref (wavpack_enc);
356   return TRUE;
357 }
358
359 static void
360 gst_wavpack_enc_set_wp_config (GstWavpackEnc * wavpack_enc)
361 {
362   wavpack_enc->wp_config = (WavpackConfig *) g_malloc0 (sizeof (WavpackConfig));
363   /* set general stream informations in the WavpackConfig */
364   wavpack_enc->wp_config->bytes_per_sample = (wavpack_enc->width + 7) >> 3;
365   wavpack_enc->wp_config->bits_per_sample = wavpack_enc->width;
366   wavpack_enc->wp_config->num_channels = wavpack_enc->channels;
367
368   /* TODO: handle more than 2 channels correctly! */
369   if (wavpack_enc->channels == 1) {
370     wavpack_enc->wp_config->channel_mask = 0x4;
371   } else if (wavpack_enc->channels == 2) {
372     wavpack_enc->wp_config->channel_mask = 0x2 | 0x1;
373   }
374   wavpack_enc->wp_config->sample_rate = wavpack_enc->samplerate;
375
376   /*
377    * Set parameters in WavpackConfig
378    */
379
380   /* Encoding mode */
381   switch (wavpack_enc->mode) {
382     case 0:
383       wavpack_enc->wp_config->flags |= CONFIG_FAST_FLAG;
384       break;
385     case 1:                    /* default */
386       break;
387     case 2:
388       wavpack_enc->wp_config->flags |= CONFIG_HIGH_FLAG;
389       break;
390   }
391
392   /* Bitrate, enables lossy mode */
393   if (wavpack_enc->bitrate >= 2.0) {
394     wavpack_enc->wp_config->flags |= CONFIG_HYBRID_FLAG;
395     if (wavpack_enc->bitrate >= 24000.0) {
396       wavpack_enc->wp_config->bitrate = wavpack_enc->bitrate / 1000.0;
397       wavpack_enc->wp_config->flags |= CONFIG_BITRATE_KBPS;
398     } else {
399       wavpack_enc->wp_config->bitrate = wavpack_enc->bitrate;
400     }
401   }
402
403   /* Correction Mode, only in lossy mode */
404   if (wavpack_enc->wp_config->flags & CONFIG_HYBRID_FLAG) {
405     if (wavpack_enc->correction_mode > 0) {
406       wavpack_enc->wvcsrcpad =
407           gst_pad_new_from_template (gst_element_class_get_pad_template
408           (GST_ELEMENT_GET_CLASS (wavpack_enc), "wvcsrc"), "wvcsrc");
409
410       /* try to add correction src pad, don't set correction mode on failure */
411       GstCaps *caps = gst_caps_new_simple ("audio/x-wavpack-correction",
412           "framed", G_TYPE_BOOLEAN, FALSE, NULL);
413
414       gst_element_no_more_pads (GST_ELEMENT (wavpack_enc));
415
416       if (!gst_pad_set_caps (wavpack_enc->wvcsrcpad, caps)) {
417         wavpack_enc->correction_mode = 0;
418         GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, INIT, (NULL),
419             ("setting correction caps failed: %", GST_PTR_FORMAT, caps));
420       } else {
421         gst_pad_use_fixed_caps (wavpack_enc->wvcsrcpad);
422
423         if (gst_element_add_pad (GST_ELEMENT (wavpack_enc),
424                 wavpack_enc->wvcsrcpad)) {
425
426           wavpack_enc->wp_config->flags |= CONFIG_CREATE_WVC;
427           if (wavpack_enc->correction_mode == 2) {
428             wavpack_enc->wp_config->flags |= CONFIG_OPTIMIZE_WVC;
429           }
430         } else {
431           wavpack_enc->correction_mode = 0;
432           GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, INIT, (NULL),
433               ("add correction pad failed. no correction file will be created."));
434         }
435         gst_caps_unref (caps);
436       }
437     }
438   } else {
439     if (wavpack_enc->correction_mode > 0) {
440       wavpack_enc->correction_mode = 0;
441       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, SETTINGS, (NULL),
442           ("settings correction mode only has effect if a bitrate is provided."));
443     }
444   }
445   gst_element_no_more_pads (GST_ELEMENT (wavpack_enc));
446
447   /* MD5, setup MD5 context */
448   if ((wavpack_enc->md5) && !(wavpack_enc->md5_context)) {
449     wavpack_enc->wp_config->flags |= CONFIG_MD5_CHECKSUM;
450     wavpack_enc->md5_context = (MD5_CTX *) g_malloc0 (sizeof (MD5_CTX));
451     MD5Init (wavpack_enc->md5_context);
452   }
453
454   /* Extra encode processing */
455   if (wavpack_enc->extra_processing) {
456     wavpack_enc->wp_config->flags |= CONFIG_EXTRA_MODE;
457   }
458
459   /* Joint stereo mode */
460   switch (wavpack_enc->joint_stereo_mode) {
461     case 0:                    /* default */
462       break;
463     case 1:
464       wavpack_enc->wp_config->flags |= CONFIG_JOINT_OVERRIDE;
465       wavpack_enc->wp_config->flags &= ~CONFIG_JOINT_STEREO;
466       break;
467     case 2:
468       wavpack_enc->wp_config->flags |=
469           (CONFIG_JOINT_OVERRIDE | CONFIG_JOINT_STEREO);
470       break;
471   }
472 }
473
474 static int32_t *
475 gst_wavpack_enc_format_samples (const uchar * src_data, uint32_t sample_count,
476     guint width)
477 {
478   int32_t *data = (int32_t *) g_malloc0 (sizeof (int32_t) * sample_count);
479
480   /* put all samples into an int32_t*, no matter what
481    * width we have and convert them from little endian
482    * to host byte order */
483
484   switch (width) {
485       int i;
486
487     case 8:
488       for (i = 0; i < sample_count; i++)
489         data[i] = (int32_t) (int8_t) src_data[i];
490       break;
491     case 16:
492       for (i = 0; i < sample_count; i++)
493         data[i] = (int32_t) src_data[2 * i]
494             | ((int32_t) (int8_t) src_data[2 * i + 1] << 8);
495       break;
496     case 24:
497       for (i = 0; i < sample_count; i++)
498         data[i] = (int32_t) src_data[3 * i]
499             | ((int32_t) src_data[3 * i + 1] << 8)
500             | ((int32_t) (int8_t) src_data[3 * i + 2] << 16);
501       break;
502     case 32:
503       for (i = 0; i < sample_count; i++)
504         data[i] = (int32_t) src_data[4 * i]
505             | ((int32_t) src_data[4 * i + 1] << 8)
506             | ((int32_t) src_data[4 * i + 2] << 16)
507             | ((int32_t) (int8_t) src_data[4 * i + 3] << 24);
508       break;
509   }
510
511   return data;
512 }
513
514 static int
515 gst_wavpack_enc_push_block (void *id, void *data, int32_t count)
516 {
517   write_id *wid = (write_id *) id;
518   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (wid->wavpack_enc);
519   GstFlowReturn ret;
520   GstBuffer *buffer;
521   guchar *block = (guchar *) data;
522
523   if (wid->correction == FALSE) {
524     /* we got something that should be pushed to the (non-correction) src pad */
525
526     /* try to allocate a buffer, compatible with the pad, fail otherwise */
527     ret = gst_pad_alloc_buffer_and_set_caps (wavpack_enc->srcpad,
528         GST_BUFFER_OFFSET_NONE, count, GST_PAD_CAPS (wavpack_enc->srcpad),
529         &buffer);
530     if (ret != GST_FLOW_OK) {
531       wavpack_enc->srcpad_last_return = ret;
532       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
533           ("Dropped one block (%d bytes) of encoded data while allocating buffer! Reason: '%s'\n",
534               count, gst_flow_get_name (ret)));
535       return FALSE;
536     }
537
538     g_memmove (GST_BUFFER_DATA (buffer), block, count);
539
540     if ((block[0] == 'w') && (block[1] == 'v') && (block[2] == 'p')
541         && (block[3] == 'k')) {
542       /* if it's a Wavpack block set buffer timestamp and duration, etc */
543       WavpackHeader wph;
544
545       GST_DEBUG ("got %d bytes of encoded wavpack data", count);
546       gst_wavpack_read_header (&wph, block);
547
548       /* if it's the first wavpack block save it for later reference
549        * i.e. sample count correction and send a NEW_SEGMENT event */
550       if (wph.block_index == 0) {
551         GstEvent *event = gst_event_new_new_segment (FALSE,
552             1.0, GST_FORMAT_BYTES, 0, GST_BUFFER_OFFSET_NONE, 0);
553
554         gst_pad_push_event (wavpack_enc->srcpad, event);
555         wavpack_enc->first_block = g_malloc0 (count);
556         g_memmove (wavpack_enc->first_block, block, count);
557         wavpack_enc->first_block_size = count;
558       }
559
560       /* set buffer timestamp, duration, offset, offset_end from
561        * the wavpack header */
562       GST_BUFFER_TIMESTAMP (buffer) =
563           gst_util_uint64_scale_int (GST_SECOND, wph.block_index,
564           wavpack_enc->samplerate);
565       GST_BUFFER_DURATION (buffer) =
566           gst_util_uint64_scale_int (GST_SECOND, wph.block_samples,
567           wavpack_enc->samplerate);
568       GST_BUFFER_OFFSET (buffer) = wph.block_index;
569       GST_BUFFER_OFFSET_END (buffer) = wph.block_index + wph.block_samples;
570     } else {
571       /* if it's something else set no timestamp and duration on the buffer */
572       GST_DEBUG ("got %d bytes of unknown data", count);
573
574       GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
575       GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
576     }
577
578     /* push the buffer and forward errors */
579     ret = gst_pad_push (wavpack_enc->srcpad, buffer);
580     wavpack_enc->srcpad_last_return = ret;
581     if (ret == GST_FLOW_OK) {
582       return TRUE;
583     } else {
584       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
585           ("Dropped one block (%d bytes) of encoded data while pushing! Reason: '%s'\n",
586               count, gst_flow_get_name (ret)));
587       return FALSE;
588     }
589   } else if (wid->correction == TRUE) {
590     /* we got something that should be pushed to the correction src pad */
591
592     /* is the correction pad linked? */
593     if (!gst_pad_is_linked (wavpack_enc->wvcsrcpad)) {
594       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
595           ("Dropped one block (%d bytes) of encoded correction data because of unlinked pad",
596               count));
597       wavpack_enc->wvcsrcpad_last_return = GST_FLOW_NOT_LINKED;
598       return FALSE;
599     }
600
601     /* try to allocate a buffer, compatible with the pad, fail otherwise */
602     ret = gst_pad_alloc_buffer_and_set_caps (wavpack_enc->wvcsrcpad,
603         GST_BUFFER_OFFSET_NONE, count,
604         GST_PAD_CAPS (wavpack_enc->wvcsrcpad), &buffer);
605     if (ret != GST_FLOW_OK) {
606       wavpack_enc->wvcsrcpad_last_return = ret;
607       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
608           ("Dropped one block (%d bytes) of encoded correction data while allocating buffer! Reason: '%s'\n",
609               count, gst_flow_get_name (ret)));
610       return FALSE;
611     }
612
613     g_memmove (GST_BUFFER_DATA (buffer), block, count);
614
615     if ((block[0] == 'w') && (block[1] == 'v') && (block[2] == 'p')
616         && (block[3] == 'k')) {
617       /* if it's a Wavpack block set buffer timestamp and duration, etc */
618       WavpackHeader wph;
619
620       GST_DEBUG ("got %d bytes of encoded wavpack correction data", count);
621       gst_wavpack_read_header (&wph, block);
622
623       /* if it's the first wavpack block send a NEW_SEGMENT
624        * event */
625       if (wph.block_index == 0) {
626         GstEvent *event = gst_event_new_new_segment (FALSE,
627             1.0, GST_FORMAT_BYTES, 0, GST_BUFFER_OFFSET_NONE, 0);
628
629         gst_pad_push_event (wavpack_enc->wvcsrcpad, event);
630       }
631
632       /* set buffer timestamp, duration, offset, offset_end from
633        * the wavpack header */
634       GST_BUFFER_TIMESTAMP (buffer) =
635           gst_util_uint64_scale_int (GST_SECOND, wph.block_index,
636           wavpack_enc->samplerate);
637       GST_BUFFER_DURATION (buffer) =
638           gst_util_uint64_scale_int (GST_SECOND, wph.block_samples,
639           wavpack_enc->samplerate);
640       GST_BUFFER_OFFSET (buffer) = wph.block_index;
641       GST_BUFFER_OFFSET_END (buffer) = wph.block_index + wph.block_samples;
642     } else {
643       /* if it's something else set no timestamp and duration on the buffer */
644       GST_DEBUG ("got %d bytes of unknown data", count);
645
646       GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
647       GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
648     }
649
650     /* push the buffer and forward errors */
651     ret = gst_pad_push (wavpack_enc->wvcsrcpad, buffer);
652     wavpack_enc->wvcsrcpad_last_return = ret;
653     if (ret == GST_FLOW_OK)
654       return TRUE;
655     else {
656       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
657           ("Dropped one block (%d bytes) of encoded correction data while pushing! Reason: '%s'\n",
658               count, gst_flow_get_name (ret)));
659       return FALSE;
660     }
661   } else {
662     /* (correction != TRUE) && (correction != FALSE), wtf? ignore this */
663     g_assert_not_reached ();
664     return TRUE;
665   }
666 }
667
668 static GstFlowReturn
669 gst_wavpack_enc_chain (GstPad * pad, GstBuffer * buf)
670 {
671   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (gst_pad_get_parent (pad));
672   uint32_t sample_count =
673       GST_BUFFER_SIZE (buf) / ((wavpack_enc->width + 7) >> 3);
674   int32_t *data;
675   GstFlowReturn ret;
676
677   /* reset the last returns to GST_FLOW_OK. This is only set to something else
678    * while WavpackPackSamples() or more specific gst_wavpack_enc_push_block()
679    * so not valid anymore */
680   wavpack_enc->srcpad_last_return = wavpack_enc->wvcsrcpad_last_return =
681       GST_FLOW_OK;
682
683   GST_DEBUG ("got %u raw samples", sample_count);
684
685   /* check if we already have a valid WavpackContext, otherwise make one */
686   if (!wavpack_enc->wp_context) {
687     /* create raw context */
688     wavpack_enc->wp_context =
689         WavpackOpenFileOutput (gst_wavpack_enc_push_block, wavpack_enc->wv_id,
690         (wavpack_enc->correction_mode > 0) ? wavpack_enc->wvc_id : NULL);
691     if (!wavpack_enc->wp_context) {
692       GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, INIT, (NULL),
693           ("error creating Wavpack context"));
694       gst_object_unref (wavpack_enc);
695       gst_buffer_unref (buf);
696       return GST_FLOW_ERROR;
697     }
698
699     /* set the WavpackConfig according to our parameters */
700     gst_wavpack_enc_set_wp_config (wavpack_enc);
701
702     /* set the configuration to the context now that we know everything
703      * and initialize the encoder */
704     if (!WavpackSetConfiguration (wavpack_enc->wp_context,
705             wavpack_enc->wp_config, (uint32_t) (-1))
706         || !WavpackPackInit (wavpack_enc->wp_context)) {
707       GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, SETTINGS, (NULL),
708           ("error setting up wavpack encoding context"));
709       WavpackCloseFile (wavpack_enc->wp_context);
710       gst_object_unref (wavpack_enc);
711       gst_buffer_unref (buf);
712       return GST_FLOW_ERROR;
713     }
714     GST_DEBUG ("setup of encoding context successfull");
715   }
716
717   /* if we want to append the MD5 sum to the stream update it here
718    * with the current raw samples */
719   if (wavpack_enc->md5) {
720     MD5Update (wavpack_enc->md5_context, GST_BUFFER_DATA (buf),
721         GST_BUFFER_SIZE (buf));
722   }
723
724   /* put all samples into an int32_t*, no matter what
725    * width we have and convert them from little endian
726    * to host byte order */
727   data =
728       gst_wavpack_enc_format_samples (GST_BUFFER_DATA (buf), sample_count,
729       wavpack_enc->width);
730
731   gst_buffer_unref (buf);
732
733   /* encode and handle return values from encoding */
734   if (WavpackPackSamples (wavpack_enc->wp_context, data,
735           sample_count / wavpack_enc->channels)) {
736     GST_DEBUG ("encoding samples successfull");
737     ret = GST_FLOW_OK;
738   } else {
739     if ((wavpack_enc->srcpad_last_return == GST_FLOW_RESEND) ||
740         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_RESEND)) {
741       ret = GST_FLOW_RESEND;
742     } else if ((wavpack_enc->srcpad_last_return == GST_FLOW_OK) ||
743         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_OK)) {
744       ret = GST_FLOW_OK;
745     } else if ((wavpack_enc->srcpad_last_return == GST_FLOW_NOT_LINKED) &&
746         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_NOT_LINKED)) {
747       ret = GST_FLOW_NOT_LINKED;
748     } else if ((wavpack_enc->srcpad_last_return == GST_FLOW_WRONG_STATE) &&
749         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_WRONG_STATE)) {
750       ret = GST_FLOW_WRONG_STATE;
751     } else {
752       GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, ENCODE, (NULL),
753           ("encoding samples failed"));
754       ret = GST_FLOW_ERROR;
755     }
756   }
757
758   g_free (data);
759   gst_object_unref (wavpack_enc);
760   return ret;
761 }
762
763 static void
764 gst_wavpack_enc_rewrite_first_block (GstWavpackEnc * wavpack_enc)
765 {
766   GstEvent *event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
767       0, GST_BUFFER_OFFSET_NONE, 0);
768   gboolean ret;
769
770   g_return_if_fail (wavpack_enc);
771   g_return_if_fail (wavpack_enc->first_block);
772
773   /* update the sample count in the first block */
774   WavpackUpdateNumSamples (wavpack_enc->wp_context, wavpack_enc->first_block);
775
776   /* try to seek to the beginning of the output */
777   ret = gst_pad_push_event (wavpack_enc->srcpad, event);
778   if (ret) {
779     /* try to rewrite the first block */
780     ret = gst_wavpack_enc_push_block (wavpack_enc->wv_id,
781         wavpack_enc->first_block, wavpack_enc->first_block_size);
782     if (ret) {
783       GST_DEBUG ("rewriting of first block succeeded!");
784     } else {
785       GST_ELEMENT_WARNING (wavpack_enc, RESOURCE, WRITE, (NULL),
786           ("rewriting of first block failed while pushing!"));
787     }
788   } else {
789     GST_ELEMENT_WARNING (wavpack_enc, RESOURCE, SEEK, (NULL),
790         ("rewriting of first block failed. Seeking to first block failed!"));
791   }
792 }
793
794 static gboolean
795 gst_wavpack_enc_sink_event (GstPad * pad, GstEvent * event)
796 {
797   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (gst_pad_get_parent (pad));
798   gboolean ret = TRUE;
799
800   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
801
802   switch (GST_EVENT_TYPE (event)) {
803     case GST_EVENT_EOS:
804       /* Encode all remaining samples and flush them to the src pads */
805       WavpackFlushSamples (wavpack_enc->wp_context);
806
807       /* write the MD5 sum if we have to write one */
808       if ((wavpack_enc->md5) && (wavpack_enc->md5_context)) {
809         guchar md5_digest[16];
810
811         MD5Final (md5_digest, wavpack_enc->md5_context);
812         WavpackStoreMD5Sum (wavpack_enc->wp_context, md5_digest);
813       }
814
815       /* Try to rewrite the first frame with the correct sample number */
816       if (wavpack_enc->first_block)
817         gst_wavpack_enc_rewrite_first_block (wavpack_enc);
818
819       /* close the context if not already happened */
820       if (wavpack_enc->wp_context) {
821         WavpackCloseFile (wavpack_enc->wp_context);
822         wavpack_enc->wp_context = NULL;
823       }
824
825       ret = gst_pad_event_default (pad, event);
826       break;
827     case GST_EVENT_NEWSEGMENT:
828       if (wavpack_enc->wp_context) {
829         GST_ELEMENT_WARNING (wavpack_enc, RESOURCE, SEEK, (NULL),
830             ("got NEWSEGMENT after encoding already started"));
831       }
832       /* drop NEWSEGMENT events, we create our own when pushing
833        * the first buffer to the pads */
834       gst_event_unref (event);
835       ret = TRUE;
836       break;
837     default:
838       ret = gst_pad_event_default (pad, event);
839       break;
840   }
841
842   gst_object_unref (wavpack_enc);
843   return ret;
844 }
845
846 static GstStateChangeReturn
847 gst_wavpack_enc_change_state (GstElement * element, GstStateChange transition)
848 {
849   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
850   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (element);
851
852   switch (transition) {
853     case GST_STATE_CHANGE_NULL_TO_READY:
854       /* set the last returned GstFlowReturns of the two pads to GST_FLOW_OK
855        * as they're only set to something else in WavpackPackSamples() or more
856        * specific gst_wavpack_enc_push_block() and nothing happened there yet */
857       wavpack_enc->srcpad_last_return = wavpack_enc->wvcsrcpad_last_return =
858           GST_FLOW_OK;
859     case GST_STATE_CHANGE_READY_TO_PAUSED:
860     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
861     default:
862       break;
863   }
864
865   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
866
867   switch (transition) {
868     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
869       break;
870     case GST_STATE_CHANGE_PAUSED_TO_READY:
871       /* close and free everything stream related */
872       if (wavpack_enc->wp_context) {
873         WavpackCloseFile (wavpack_enc->wp_context);
874         wavpack_enc->wp_context = NULL;
875       }
876       if (wavpack_enc->wp_config) {
877         g_free (wavpack_enc->wp_config);
878         wavpack_enc->wp_config = NULL;
879       }
880       if (wavpack_enc->first_block) {
881         g_free (wavpack_enc->first_block);
882         wavpack_enc->first_block = NULL;
883         wavpack_enc->first_block_size = 0;
884       }
885       if (wavpack_enc->md5_context) {
886         g_free (wavpack_enc->md5_context);
887         wavpack_enc->md5_context = NULL;
888       }
889
890       /* reset the last returns to GST_FLOW_OK. This is only set to something else
891        * while WavpackPackSamples() or more specific gst_wavpack_enc_push_block()
892        * so not valid anymore */
893       wavpack_enc->srcpad_last_return = wavpack_enc->wvcsrcpad_last_return =
894           GST_FLOW_OK;
895       break;
896     case GST_STATE_CHANGE_READY_TO_NULL:
897       break;
898     default:
899       break;
900   }
901
902   return ret;
903 }
904
905 static void
906 gst_wavpack_enc_set_property (GObject * object, guint prop_id,
907     const GValue * value, GParamSpec * pspec)
908 {
909   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (object);
910
911   switch (prop_id) {
912     case ARG_MODE:
913       wavpack_enc->mode = g_value_get_enum (value);
914       break;
915     case ARG_BITRATE:{
916       gdouble val = g_value_get_double (value);
917
918       if ((val >= 24000.0) && (val <= 9600000.0)) {
919         wavpack_enc->bitrate = val;
920       } else {
921         wavpack_enc->bitrate = 0.0;
922       }
923       break;
924     }
925     case ARG_BITSPERSAMPLE:{
926       gdouble val = g_value_get_double (value);
927
928       if ((val >= 2.0) && (val <= 24.0)) {
929         wavpack_enc->bitrate = val;
930       } else {
931         wavpack_enc->bitrate = 0.0;
932       }
933       break;
934     }
935     case ARG_CORRECTION_MODE:
936       wavpack_enc->correction_mode = g_value_get_enum (value);
937       break;
938     case ARG_MD5:
939       wavpack_enc->md5 = g_value_get_boolean (value);
940       break;
941     case ARG_EXTRA_PROCESSING:
942       wavpack_enc->extra_processing = g_value_get_boolean (value);
943       break;
944     case ARG_JOINT_STEREO_MODE:
945       wavpack_enc->joint_stereo_mode = g_value_get_enum (value);
946       break;
947     default:
948       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
949       break;
950   }
951 }
952
953 static void
954 gst_wavpack_enc_get_property (GObject * object, guint prop_id, GValue * value,
955     GParamSpec * pspec)
956 {
957   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (object);
958
959   switch (prop_id) {
960     case ARG_MODE:
961       g_value_set_enum (value, wavpack_enc->mode);
962       break;
963     case ARG_BITRATE:
964       if (wavpack_enc->bitrate >= 24000.0) {
965         g_value_set_double (value, wavpack_enc->bitrate);
966       } else {
967         g_value_set_double (value, 0.0);
968       }
969       break;
970     case ARG_BITSPERSAMPLE:
971       if (wavpack_enc->bitrate <= 24.0) {
972         g_value_set_double (value, wavpack_enc->bitrate);
973       } else {
974         g_value_set_double (value, 0.0);
975       }
976       break;
977     case ARG_CORRECTION_MODE:
978       g_value_set_enum (value, wavpack_enc->correction_mode);
979       break;
980     case ARG_MD5:
981       g_value_set_boolean (value, wavpack_enc->md5);
982       break;
983     case ARG_EXTRA_PROCESSING:
984       g_value_set_boolean (value, wavpack_enc->extra_processing);
985       break;
986     case ARG_JOINT_STEREO_MODE:
987       g_value_set_enum (value, wavpack_enc->joint_stereo_mode);
988       break;
989     default:
990       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
991       break;
992   }
993 }
994
995 gboolean
996 gst_wavpack_enc_plugin_init (GstPlugin * plugin)
997 {
998   if (!gst_element_register (plugin, "wavpackenc",
999           GST_RANK_NONE, GST_TYPE_WAVPACK_ENC))
1000     return FALSE;
1001
1002   GST_DEBUG_CATEGORY_INIT (gst_wavpack_enc_debug, "wavpackenc", 0,
1003       "wavpack encoder");
1004
1005   return TRUE;
1006 }