bc060f20c11e96ff05a799ec82abe46e404c6987
[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_dispose (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->dispose = GST_DEBUG_FUNCPTR (gst_wavpack_enc_dispose);
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),
274       GST_DEBUG_FUNCPTR (wavpack_enc->sinkpad));
275
276   /* setup src pad */
277   wavpack_enc->srcpad =
278       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
279           "src"), "src");
280   gst_element_add_pad (GST_ELEMENT (wavpack_enc),
281       GST_DEBUG_FUNCPTR (wavpack_enc->srcpad));
282
283   /* initialize object attributes */
284   wavpack_enc->wp_config = NULL;
285   wavpack_enc->wp_context = NULL;
286   wavpack_enc->first_block = NULL;
287   wavpack_enc->first_block_size = 0;
288   wavpack_enc->md5_context = NULL;
289   wavpack_enc->samplerate = 0;
290   wavpack_enc->width = 0;
291   wavpack_enc->channels = 0;
292
293   wavpack_enc->wv_id = (write_id *) g_malloc0 (sizeof (write_id));
294   wavpack_enc->wv_id->correction = FALSE;
295   wavpack_enc->wv_id->wavpack_enc = wavpack_enc;
296   wavpack_enc->wvc_id = (write_id *) g_malloc0 (sizeof (write_id));
297   wavpack_enc->wvc_id->correction = TRUE;
298   wavpack_enc->wvc_id->wavpack_enc = wavpack_enc;
299
300   /* set default values of params */
301   wavpack_enc->mode = 1;
302   wavpack_enc->bitrate = 0.0;
303   wavpack_enc->correction_mode = 0;
304   wavpack_enc->md5 = FALSE;
305   wavpack_enc->extra_processing = FALSE;
306   wavpack_enc->joint_stereo_mode = 0;
307 }
308
309 static void
310 gst_wavpack_enc_dispose (GObject * object)
311 {
312   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (object);
313
314   /* free the blockout helpers */
315   g_free (wavpack_enc->wv_id);
316   g_free (wavpack_enc->wvc_id);
317
318   G_OBJECT_CLASS (parent_class)->dispose (object);
319 }
320
321 static gboolean
322 gst_wavpack_enc_sink_set_caps (GstPad * pad, GstCaps * caps)
323 {
324   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (gst_pad_get_parent (pad));
325   GstStructure *structure = gst_caps_get_structure (caps, 0);
326   int depth = 0;
327
328   /* check caps and put relevant parts into our object attributes */
329   if ((!gst_structure_get_int (structure, "channels", &wavpack_enc->channels))
330       || (!gst_structure_get_int (structure, "rate", &wavpack_enc->samplerate))
331       || (!gst_structure_get_int (structure, "width", &wavpack_enc->width))
332       || (!(gst_structure_get_int (structure, "depth", &depth))
333           || depth != wavpack_enc->width)) {
334     GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, INIT, (NULL),
335         ("got invalid caps: %", GST_PTR_FORMAT, caps));
336     gst_object_unref (wavpack_enc);
337     return FALSE;
338   }
339
340   /* set fixed src pad caps now that we know what we will get */
341   caps = gst_caps_new_simple ("audio/x-wavpack",
342       "channels", G_TYPE_INT, wavpack_enc->channels,
343       "rate", G_TYPE_INT, wavpack_enc->samplerate,
344       "width", G_TYPE_INT, wavpack_enc->width,
345       "framed", G_TYPE_BOOLEAN, TRUE, NULL);
346
347   if (!gst_pad_set_caps (wavpack_enc->srcpad, caps)) {
348     GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, INIT, (NULL),
349         ("setting caps failed: %", GST_PTR_FORMAT, caps));
350     gst_caps_unref (caps);
351     gst_object_unref (wavpack_enc);
352     return FALSE;
353   }
354   gst_pad_use_fixed_caps (wavpack_enc->srcpad);
355
356   gst_caps_unref (caps);
357   gst_object_unref (wavpack_enc);
358   return TRUE;
359 }
360
361 static void
362 gst_wavpack_enc_set_wp_config (GstWavpackEnc * wavpack_enc)
363 {
364   wavpack_enc->wp_config = (WavpackConfig *) g_malloc0 (sizeof (WavpackConfig));
365   /* set general stream informations in the WavpackConfig */
366   wavpack_enc->wp_config->bytes_per_sample = (wavpack_enc->width + 7) >> 3;
367   wavpack_enc->wp_config->bits_per_sample = wavpack_enc->width;
368   wavpack_enc->wp_config->num_channels = wavpack_enc->channels;
369
370   /* TODO: handle more than 2 channels correctly! */
371   if (wavpack_enc->channels == 1) {
372     wavpack_enc->wp_config->channel_mask = 0x4;
373   } else if (wavpack_enc->channels == 2) {
374     wavpack_enc->wp_config->channel_mask = 0x2 | 0x1;
375   }
376   wavpack_enc->wp_config->sample_rate = wavpack_enc->samplerate;
377
378   /*
379    * Set parameters in WavpackConfig
380    */
381
382   /* Encoding mode */
383   switch (wavpack_enc->mode) {
384     case 0:
385       wavpack_enc->wp_config->flags |= CONFIG_FAST_FLAG;
386       break;
387     case 1:                    /* default */
388       break;
389     case 2:
390       wavpack_enc->wp_config->flags |= CONFIG_HIGH_FLAG;
391       break;
392   }
393
394   /* Bitrate, enables lossy mode */
395   if (wavpack_enc->bitrate >= 2.0) {
396     wavpack_enc->wp_config->flags |= CONFIG_HYBRID_FLAG;
397     if (wavpack_enc->bitrate >= 24000.0) {
398       wavpack_enc->wp_config->bitrate = wavpack_enc->bitrate / 1000.0;
399       wavpack_enc->wp_config->flags |= CONFIG_BITRATE_KBPS;
400     } else {
401       wavpack_enc->wp_config->bitrate = wavpack_enc->bitrate;
402     }
403   }
404
405   /* Correction Mode, only in lossy mode */
406   if (wavpack_enc->wp_config->flags & CONFIG_HYBRID_FLAG) {
407     if (wavpack_enc->correction_mode > 0) {
408       wavpack_enc->wvcsrcpad =
409           gst_pad_new_from_template (gst_element_class_get_pad_template
410           (GST_ELEMENT_GET_CLASS (wavpack_enc), "wvcsrc"), "wvcsrc");
411
412       /* try to add correction src pad, don't set correction mode on failure */
413       if (gst_element_add_pad (GST_ELEMENT (wavpack_enc),
414               GST_DEBUG_FUNCPTR (wavpack_enc->wvcsrcpad))) {
415         GstCaps *caps = gst_caps_new_simple ("audio/x-wavpack-correction",
416             "framed", G_TYPE_BOOLEAN, FALSE, NULL);
417
418         gst_element_no_more_pads (GST_ELEMENT (wavpack_enc));
419
420         if (!gst_pad_set_caps (wavpack_enc->wvcsrcpad, caps)) {
421           wavpack_enc->correction_mode = 0;
422           GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, INIT, (NULL),
423               ("setting correction caps failed: %", GST_PTR_FORMAT, caps));
424         } else {
425           gst_pad_use_fixed_caps (wavpack_enc->wvcsrcpad);
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         }
431         gst_caps_unref (caps);
432       } else {
433         wavpack_enc->correction_mode = 0;
434         GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, INIT, (NULL),
435             ("add correction pad failed. no correction file will be created."));
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
446   /* MD5, setup MD5 context */
447   if ((wavpack_enc->md5) && !(wavpack_enc->md5_context)) {
448     wavpack_enc->wp_config->flags |= CONFIG_MD5_CHECKSUM;
449     wavpack_enc->md5_context = (MD5_CTX *) g_malloc0 (sizeof (MD5_CTX));
450     MD5Init (wavpack_enc->md5_context);
451   }
452
453   /* Extra encode processing */
454   if (wavpack_enc->extra_processing) {
455     wavpack_enc->wp_config->flags |= CONFIG_EXTRA_MODE;
456   }
457
458   /* Joint stereo mode */
459   switch (wavpack_enc->joint_stereo_mode) {
460     case 0:                    /* default */
461       break;
462     case 1:
463       wavpack_enc->wp_config->flags |= CONFIG_JOINT_OVERRIDE;
464       wavpack_enc->wp_config->flags &= ~CONFIG_JOINT_STEREO;
465       break;
466     case 2:
467       wavpack_enc->wp_config->flags |=
468           (CONFIG_JOINT_OVERRIDE | CONFIG_JOINT_STEREO);
469       break;
470   }
471 }
472
473 static int32_t *
474 gst_wavpack_enc_format_samples (const uchar * src_data, uint32_t sample_count,
475     guint width)
476 {
477   int32_t *data = (int32_t *) g_malloc0 (sizeof (int32_t) * sample_count);
478
479   /* put all samples into an int32_t*, no matter what
480    * width we have and convert them from little endian
481    * to host byte order */
482
483   switch (width) {
484       int i;
485
486     case 8:
487       for (i = 0; i < sample_count; i++)
488         data[i] = (int32_t) (int8_t) src_data[i];
489       break;
490     case 16:
491       for (i = 0; i < sample_count; i++)
492         data[i] = (int32_t) src_data[2 * i]
493             | ((int32_t) (int8_t) src_data[2 * i + 1] << 8);
494       break;
495     case 24:
496       for (i = 0; i < sample_count; i++)
497         data[i] = (int32_t) src_data[3 * i]
498             | ((int32_t) src_data[3 * i + 1] << 8)
499             | ((int32_t) (int8_t) src_data[3 * i + 2] << 16);
500       break;
501     case 32:
502       for (i = 0; i < sample_count; i++)
503         data[i] = (int32_t) src_data[4 * i]
504             | ((int32_t) src_data[4 * i + 1] << 8)
505             | ((int32_t) src_data[4 * i + 2] << 16)
506             | ((int32_t) (int8_t) src_data[4 * i + 3] << 24);
507       break;
508   }
509
510   return data;
511 }
512
513 static int
514 gst_wavpack_enc_push_block (void *id, void *data, int32_t count)
515 {
516   write_id *wid = (write_id *) id;
517   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (wid->wavpack_enc);
518   GstFlowReturn ret;
519   GstBuffer *buffer;
520   guchar *block = (guchar *) data;
521
522   if (wid->correction == FALSE) {
523     /* we got something that should be pushed to the (non-correction) src pad */
524
525     /* try to allocate a buffer, compatible with the pad, fail otherwise */
526     ret = gst_pad_alloc_buffer_and_set_caps (wavpack_enc->srcpad,
527         GST_BUFFER_OFFSET_NONE, count, GST_PAD_CAPS (wavpack_enc->srcpad),
528         &buffer);
529     if (ret != GST_FLOW_OK) {
530       wavpack_enc->srcpad_last_return = ret;
531       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
532           ("Dropped one block (%d bytes) of encoded data while allocating buffer! Reason: '%s'\n",
533               count, gst_flow_get_name (ret)));
534       return FALSE;
535     }
536
537     g_memmove (GST_BUFFER_DATA (buffer), block, count);
538
539     if ((block[0] == 'w') && (block[1] == 'v') && (block[2] == 'p')
540         && (block[3] == 'k')) {
541       /* if it's a Wavpack block set buffer timestamp and duration, etc */
542       WavpackHeader wph;
543
544       GST_DEBUG ("got %d bytes of encoded wavpack data", count);
545       gst_wavpack_read_header (&wph, block);
546
547       /* if it's the first wavpack block save it for later reference
548        * i.e. sample count correction and send a NEW_SEGMENT event */
549       if (wph.block_index == 0) {
550         GstEvent *event = gst_event_new_new_segment (FALSE,
551             1.0, GST_FORMAT_BYTES, 0, GST_BUFFER_OFFSET_NONE, 0);
552
553         gst_pad_push_event (wavpack_enc->srcpad, event);
554         wavpack_enc->first_block = g_malloc0 (count);
555         g_memmove (wavpack_enc->first_block, block, count);
556         wavpack_enc->first_block_size = count;
557       }
558
559       /* set buffer timestamp, duration, offset, offset_end from
560        * the wavpack header */
561       GST_BUFFER_TIMESTAMP (buffer) =
562           gst_util_uint64_scale_int (GST_SECOND, wph.block_index,
563           wavpack_enc->samplerate);
564       GST_BUFFER_DURATION (buffer) =
565           gst_util_uint64_scale_int (GST_SECOND, wph.block_samples,
566           wavpack_enc->samplerate);
567       GST_BUFFER_OFFSET (buffer) = wph.block_index;
568       GST_BUFFER_OFFSET_END (buffer) = wph.block_index + wph.block_samples;
569     } else {
570       /* if it's something else set no timestamp and duration on the buffer */
571       GST_DEBUG ("got %d bytes of unknown data", count);
572
573       GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
574       GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
575     }
576
577     /* push the buffer and forward errors */
578     ret = gst_pad_push (wavpack_enc->srcpad, buffer);
579     wavpack_enc->srcpad_last_return = ret;
580     if (ret == GST_FLOW_OK) {
581       return TRUE;
582     } else {
583       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
584           ("Dropped one block (%d bytes) of encoded data while pushing! Reason: '%s'\n",
585               count, gst_flow_get_name (ret)));
586       return FALSE;
587     }
588   } else if (wid->correction == TRUE) {
589     /* we got something that should be pushed to the correction src pad */
590
591     /* is the correction pad linked? */
592     if (!gst_pad_is_linked (wavpack_enc->wvcsrcpad)) {
593       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
594           ("Dropped one block (%d bytes) of encoded correction data because of unlinked pad",
595               count));
596       wavpack_enc->wvcsrcpad_last_return = GST_FLOW_NOT_LINKED;
597       return FALSE;
598     }
599
600     /* try to allocate a buffer, compatible with the pad, fail otherwise */
601     ret = gst_pad_alloc_buffer_and_set_caps (wavpack_enc->wvcsrcpad,
602         GST_BUFFER_OFFSET_NONE, count,
603         GST_PAD_CAPS (wavpack_enc->wvcsrcpad), &buffer);
604     if (ret != GST_FLOW_OK) {
605       wavpack_enc->wvcsrcpad_last_return = ret;
606       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
607           ("Dropped one block (%d bytes) of encoded correction data while allocating buffer! Reason: '%s'\n",
608               count, gst_flow_get_name (ret)));
609       return FALSE;
610     }
611
612     g_memmove (GST_BUFFER_DATA (buffer), block, count);
613
614     if ((block[0] == 'w') && (block[1] == 'v') && (block[2] == 'p')
615         && (block[3] == 'k')) {
616       /* if it's a Wavpack block set buffer timestamp and duration, etc */
617       WavpackHeader wph;
618
619       GST_DEBUG ("got %d bytes of encoded wavpack correction data", count);
620       gst_wavpack_read_header (&wph, block);
621
622       /* if it's the first wavpack block send a NEW_SEGMENT
623        * event */
624       if (wph.block_index == 0) {
625         GstEvent *event = gst_event_new_new_segment (FALSE,
626             1.0, GST_FORMAT_BYTES, 0, GST_BUFFER_OFFSET_NONE, 0);
627
628         gst_pad_push_event (wavpack_enc->wvcsrcpad, event);
629       }
630
631       /* set buffer timestamp, duration, offset, offset_end from
632        * the wavpack header */
633       GST_BUFFER_TIMESTAMP (buffer) =
634           gst_util_uint64_scale_int (GST_SECOND, wph.block_index,
635           wavpack_enc->samplerate);
636       GST_BUFFER_DURATION (buffer) =
637           gst_util_uint64_scale_int (GST_SECOND, wph.block_samples,
638           wavpack_enc->samplerate);
639       GST_BUFFER_OFFSET (buffer) = wph.block_index;
640       GST_BUFFER_OFFSET_END (buffer) = wph.block_index + wph.block_samples;
641     } else {
642       /* if it's something else set no timestamp and duration on the buffer */
643       GST_DEBUG ("got %d bytes of unknown data", count);
644
645       GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
646       GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
647     }
648
649     /* push the buffer and forward errors */
650     ret = gst_pad_push (wavpack_enc->wvcsrcpad, buffer);
651     wavpack_enc->wvcsrcpad_last_return = ret;
652     if (ret == GST_FLOW_OK)
653       return TRUE;
654     else {
655       GST_ELEMENT_WARNING (wavpack_enc, LIBRARY, ENCODE, (NULL),
656           ("Dropped one block (%d bytes) of encoded correction data while pushing! Reason: '%s'\n",
657               count, gst_flow_get_name (ret)));
658       return FALSE;
659     }
660   } else {
661     /* (correction != TRUE) && (correction != FALSE), wtf? ignore this */
662     g_assert_not_reached ();
663     return TRUE;
664   }
665 }
666
667 static GstFlowReturn
668 gst_wavpack_enc_chain (GstPad * pad, GstBuffer * buf)
669 {
670   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (gst_pad_get_parent (pad));
671   uint32_t sample_count =
672       GST_BUFFER_SIZE (buf) / ((wavpack_enc->width + 7) >> 3);
673   int32_t *data;
674   GstFlowReturn ret;
675
676   /* reset the last returns to GST_FLOW_OK. This is only set to something else
677    * while WavpackPackSamples() or more specific gst_wavpack_enc_push_block()
678    * so not valid anymore */
679   wavpack_enc->srcpad_last_return = wavpack_enc->wvcsrcpad_last_return =
680       GST_FLOW_OK;
681
682   GST_DEBUG ("got %u raw samples", sample_count);
683
684   /* check if we already have a valid WavpackContext, otherwise make one */
685   if (!wavpack_enc->wp_context) {
686     /* create raw context */
687     wavpack_enc->wp_context =
688         WavpackOpenFileOutput (gst_wavpack_enc_push_block, wavpack_enc->wv_id,
689         (wavpack_enc->correction_mode > 0) ? wavpack_enc->wvc_id : NULL);
690     if (!wavpack_enc->wp_context) {
691       GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, INIT, (NULL),
692           ("error creating Wavpack context"));
693       gst_object_unref (wavpack_enc);
694       gst_buffer_unref (buf);
695       return GST_FLOW_ERROR;
696     }
697
698     /* set the WavpackConfig according to our parameters */
699     gst_wavpack_enc_set_wp_config (wavpack_enc);
700
701     /* set the configuration to the context now that we know everything
702      * and initialize the encoder */
703     if (!WavpackSetConfiguration (wavpack_enc->wp_context,
704             wavpack_enc->wp_config, (uint32_t) (-1))
705         || !WavpackPackInit (wavpack_enc->wp_context)) {
706       GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, SETTINGS, (NULL),
707           ("error setting up wavpack encoding context"));
708       WavpackCloseFile (wavpack_enc->wp_context);
709       gst_object_unref (wavpack_enc);
710       gst_buffer_unref (buf);
711       return GST_FLOW_ERROR;
712     }
713     GST_DEBUG ("setup of encoding context successfull");
714   }
715
716   /* if we want to append the MD5 sum to the stream update it here
717    * with the current raw samples */
718   if (wavpack_enc->md5) {
719     MD5Update (wavpack_enc->md5_context, GST_BUFFER_DATA (buf),
720         GST_BUFFER_SIZE (buf));
721   }
722
723   /* put all samples into an int32_t*, no matter what
724    * width we have and convert them from little endian
725    * to host byte order */
726   data =
727       gst_wavpack_enc_format_samples (GST_BUFFER_DATA (buf), sample_count,
728       wavpack_enc->width);
729
730   gst_buffer_unref (buf);
731
732   /* encode and handle return values from encoding */
733   if (WavpackPackSamples (wavpack_enc->wp_context, data,
734           sample_count / wavpack_enc->channels)) {
735     GST_DEBUG ("encoding samples successfull");
736     ret = GST_FLOW_OK;
737   } else {
738     if ((wavpack_enc->srcpad_last_return == GST_FLOW_RESEND) ||
739         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_RESEND)) {
740       ret = GST_FLOW_RESEND;
741     } else if ((wavpack_enc->srcpad_last_return == GST_FLOW_OK) ||
742         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_OK)) {
743       ret = GST_FLOW_OK;
744     } else if ((wavpack_enc->srcpad_last_return == GST_FLOW_NOT_LINKED) &&
745         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_NOT_LINKED)) {
746       ret = GST_FLOW_NOT_LINKED;
747     } else if ((wavpack_enc->srcpad_last_return == GST_FLOW_WRONG_STATE) &&
748         (wavpack_enc->wvcsrcpad_last_return == GST_FLOW_WRONG_STATE)) {
749       ret = GST_FLOW_WRONG_STATE;
750     } else {
751       GST_ELEMENT_ERROR (wavpack_enc, LIBRARY, ENCODE, (NULL),
752           ("encoding samples failed"));
753       ret = GST_FLOW_ERROR;
754     }
755   }
756
757   g_free (data);
758   gst_object_unref (wavpack_enc);
759   return ret;
760 }
761
762 static void
763 gst_wavpack_enc_rewrite_first_block (GstWavpackEnc * wavpack_enc)
764 {
765   GstEvent *event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
766       0, GST_BUFFER_OFFSET_NONE, 0);
767   gboolean ret;
768
769   g_return_if_fail (wavpack_enc);
770   g_return_if_fail (wavpack_enc->first_block);
771
772   /* update the sample count in the first block */
773   WavpackUpdateNumSamples (wavpack_enc->wp_context, wavpack_enc->first_block);
774
775   /* try to seek to the beginning of the output */
776   ret = gst_pad_push_event (wavpack_enc->srcpad, event);
777   if (ret) {
778     /* try to rewrite the first block */
779     ret = gst_wavpack_enc_push_block (wavpack_enc->wv_id,
780         wavpack_enc->first_block, wavpack_enc->first_block_size);
781     if (ret) {
782       GST_DEBUG ("rewriting of first block succeeded!");
783     } else {
784       GST_ELEMENT_WARNING (wavpack_enc, RESOURCE, WRITE, (NULL),
785           ("rewriting of first block failed while pushing!"));
786     }
787   } else {
788     GST_ELEMENT_WARNING (wavpack_enc, RESOURCE, SEEK, (NULL),
789         ("rewriting of first block failed. Seeking to first block failed!"));
790   }
791 }
792
793 static gboolean
794 gst_wavpack_enc_sink_event (GstPad * pad, GstEvent * event)
795 {
796   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (gst_pad_get_parent (pad));
797   gboolean ret = TRUE;
798
799   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
800
801   switch (GST_EVENT_TYPE (event)) {
802     case GST_EVENT_EOS:
803       /* Encode all remaining samples and flush them to the src pads */
804       WavpackFlushSamples (wavpack_enc->wp_context);
805
806       /* write the MD5 sum if we have to write one */
807       if ((wavpack_enc->md5) && (wavpack_enc->md5_context)) {
808         guchar md5_digest[16];
809
810         MD5Final (md5_digest, wavpack_enc->md5_context);
811         WavpackStoreMD5Sum (wavpack_enc->wp_context, md5_digest);
812       }
813
814       /* Try to rewrite the first frame with the correct sample number */
815       if (wavpack_enc->first_block)
816         gst_wavpack_enc_rewrite_first_block (wavpack_enc);
817
818       /* close the context if not already happened */
819       if (wavpack_enc->wp_context) {
820         WavpackCloseFile (wavpack_enc->wp_context);
821         wavpack_enc->wp_context = NULL;
822       }
823
824       ret = gst_pad_event_default (pad, event);
825       break;
826     case GST_EVENT_NEWSEGMENT:
827       if (wavpack_enc->wp_context) {
828         GST_ELEMENT_WARNING (wavpack_enc, RESOURCE, SEEK, (NULL),
829             ("got NEWSEGMENT after encoding already started"));
830       }
831       /* drop NEWSEGMENT events, we create our own when pushing
832        * the first buffer to the pads */
833       gst_event_unref (event);
834       ret = TRUE;
835       break;
836     default:
837       ret = gst_pad_event_default (pad, event);
838       break;
839   }
840
841   gst_object_unref (wavpack_enc);
842   return ret;
843 }
844
845 static GstStateChangeReturn
846 gst_wavpack_enc_change_state (GstElement * element, GstStateChange transition)
847 {
848   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
849   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (element);
850
851   switch (transition) {
852     case GST_STATE_CHANGE_NULL_TO_READY:
853       /* set the last returned GstFlowReturns of the two pads to GST_FLOW_OK
854        * as they're only set to something else in WavpackPackSamples() or more
855        * specific gst_wavpack_enc_push_block() and nothing happened there yet */
856       wavpack_enc->srcpad_last_return = wavpack_enc->wvcsrcpad_last_return =
857           GST_FLOW_OK;
858     case GST_STATE_CHANGE_READY_TO_PAUSED:
859     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
860     default:
861       break;
862   }
863
864   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
865
866   switch (transition) {
867     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
868       break;
869     case GST_STATE_CHANGE_PAUSED_TO_READY:
870       /* close and free everything stream related */
871       if (wavpack_enc->wp_context) {
872         WavpackCloseFile (wavpack_enc->wp_context);
873         wavpack_enc->wp_context = NULL;
874       }
875       if (wavpack_enc->wp_config) {
876         g_free (wavpack_enc->wp_config);
877         wavpack_enc->wp_config = NULL;
878       }
879       if (wavpack_enc->first_block) {
880         g_free (wavpack_enc->first_block);
881         wavpack_enc->first_block = NULL;
882         wavpack_enc->first_block_size = 0;
883       }
884       if (wavpack_enc->md5_context) {
885         g_free (wavpack_enc->md5_context);
886         wavpack_enc->md5_context = NULL;
887       }
888
889       /* reset the last returns to GST_FLOW_OK. This is only set to something else
890        * while WavpackPackSamples() or more specific gst_wavpack_enc_push_block()
891        * so not valid anymore */
892       wavpack_enc->srcpad_last_return = wavpack_enc->wvcsrcpad_last_return =
893           GST_FLOW_OK;
894       break;
895     case GST_STATE_CHANGE_READY_TO_NULL:
896       break;
897     default:
898       break;
899   }
900
901   return ret;
902 }
903
904 static void
905 gst_wavpack_enc_set_property (GObject * object, guint prop_id,
906     const GValue * value, GParamSpec * pspec)
907 {
908   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (object);
909
910   switch (prop_id) {
911     case ARG_MODE:
912       wavpack_enc->mode = g_value_get_enum (value);
913       break;
914     case ARG_BITRATE:{
915       gdouble val = g_value_get_double (value);
916
917       if ((val >= 24000.0) && (val <= 9600000.0)) {
918         wavpack_enc->bitrate = val;
919       } else {
920         wavpack_enc->bitrate = 0.0;
921       }
922       break;
923     }
924     case ARG_BITSPERSAMPLE:{
925       gdouble val = g_value_get_double (value);
926
927       if ((val >= 2.0) && (val <= 24.0)) {
928         wavpack_enc->bitrate = val;
929       } else {
930         wavpack_enc->bitrate = 0.0;
931       }
932       break;
933     }
934     case ARG_CORRECTION_MODE:
935       wavpack_enc->correction_mode = g_value_get_enum (value);
936       break;
937     case ARG_MD5:
938       wavpack_enc->md5 = g_value_get_boolean (value);
939       break;
940     case ARG_EXTRA_PROCESSING:
941       wavpack_enc->extra_processing = g_value_get_boolean (value);
942       break;
943     case ARG_JOINT_STEREO_MODE:
944       wavpack_enc->joint_stereo_mode = g_value_get_enum (value);
945       break;
946     default:
947       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
948       break;
949   }
950 }
951
952 static void
953 gst_wavpack_enc_get_property (GObject * object, guint prop_id, GValue * value,
954     GParamSpec * pspec)
955 {
956   GstWavpackEnc *wavpack_enc = GST_WAVPACK_ENC (object);
957
958   switch (prop_id) {
959     case ARG_MODE:
960       g_value_set_enum (value, wavpack_enc->mode);
961       break;
962     case ARG_BITRATE:
963       if (wavpack_enc->bitrate >= 24000.0) {
964         g_value_set_double (value, wavpack_enc->bitrate);
965       } else {
966         g_value_set_double (value, 0.0);
967       }
968       break;
969     case ARG_BITSPERSAMPLE:
970       if (wavpack_enc->bitrate <= 24.0) {
971         g_value_set_double (value, wavpack_enc->bitrate);
972       } else {
973         g_value_set_double (value, 0.0);
974       }
975       break;
976     case ARG_CORRECTION_MODE:
977       g_value_set_enum (value, wavpack_enc->correction_mode);
978       break;
979     case ARG_MD5:
980       g_value_set_boolean (value, wavpack_enc->md5);
981       break;
982     case ARG_EXTRA_PROCESSING:
983       g_value_set_boolean (value, wavpack_enc->extra_processing);
984       break;
985     case ARG_JOINT_STEREO_MODE:
986       g_value_set_enum (value, wavpack_enc->joint_stereo_mode);
987       break;
988     default:
989       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
990       break;
991   }
992 }
993
994 gboolean
995 gst_wavpack_enc_plugin_init (GstPlugin * plugin)
996 {
997   if (!gst_element_register (plugin, "wavpackenc",
998           GST_RANK_NONE, GST_TYPE_WAVPACK_ENC))
999     return FALSE;
1000
1001   GST_DEBUG_CATEGORY_INIT (gst_wavpack_enc_debug, "wavpackenc", 0,
1002       "wavpack encoder");
1003
1004   return TRUE;
1005 }