wavpack: use appropriate printf format for gsize
[platform/upstream/gstreamer.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., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:element-wavpackenc
24  *
25  * WavpackEnc encodes raw audio into a framed Wavpack stream.
26  * <ulink url="http://www.wavpack.com/">Wavpack</ulink> is an open-source
27  * audio codec that features both lossless and lossy encoding.
28  *
29  * <refsect2>
30  * <title>Example launch line</title>
31  * |[
32  * gst-launch-1.0 audiotestsrc num-buffers=500 ! audioconvert ! wavpackenc ! filesink location=sinewave.wv
33  * ]| This pipeline encodes audio from audiotestsrc into a Wavpack file. The audioconvert element is needed
34  * as the Wavpack encoder only accepts input with 32 bit width.
35  * |[
36  * gst-launch-1.0 cdda://1 ! audioconvert ! wavpackenc ! filesink location=track1.wv
37  * ]| This pipeline encodes audio from an audio CD into a Wavpack file using
38  * lossless encoding (the file output will be fairly large).
39  * |[
40  * gst-launch-1.0 cdda://1 ! audioconvert ! wavpackenc bitrate=128000 ! filesink location=track1.wv
41  * ]| This pipeline encodes audio from an audio CD into a Wavpack file using
42  * lossy encoding at a certain bitrate (the file will be fairly small).
43  * </refsect2>
44  */
45
46 /*
47  * TODO: - add 32 bit float mode. CONFIG_FLOAT_DATA
48  */
49
50 #include <string.h>
51 #include <gst/gst.h>
52 #include <glib/gprintf.h>
53
54 #include <wavpack/wavpack.h>
55 #include "gstwavpackenc.h"
56 #include "gstwavpackcommon.h"
57
58 static gboolean gst_wavpack_enc_start (GstAudioEncoder * enc);
59 static gboolean gst_wavpack_enc_stop (GstAudioEncoder * enc);
60 static gboolean gst_wavpack_enc_set_format (GstAudioEncoder * enc,
61     GstAudioInfo * info);
62 static GstFlowReturn gst_wavpack_enc_handle_frame (GstAudioEncoder * enc,
63     GstBuffer * in_buf);
64 static gboolean gst_wavpack_enc_sink_event (GstAudioEncoder * enc,
65     GstEvent * event);
66
67 static int gst_wavpack_enc_push_block (void *id, void *data, int32_t count);
68 static GstFlowReturn gst_wavpack_enc_drain (GstWavpackEnc * enc);
69
70 static void gst_wavpack_enc_set_property (GObject * object, guint prop_id,
71     const GValue * value, GParamSpec * pspec);
72 static void gst_wavpack_enc_get_property (GObject * object, guint prop_id,
73     GValue * value, GParamSpec * pspec);
74
75 enum
76 {
77   ARG_0,
78   ARG_MODE,
79   ARG_BITRATE,
80   ARG_BITSPERSAMPLE,
81   ARG_CORRECTION_MODE,
82   ARG_MD5,
83   ARG_EXTRA_PROCESSING,
84   ARG_JOINT_STEREO_MODE
85 };
86
87 GST_DEBUG_CATEGORY_STATIC (gst_wavpack_enc_debug);
88 #define GST_CAT_DEFAULT gst_wavpack_enc_debug
89
90 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
91     GST_PAD_SINK,
92     GST_PAD_ALWAYS,
93     GST_STATIC_CAPS ("audio/x-raw, "
94         "format = (string) " GST_AUDIO_NE (S32) ", "
95         "layout = (string) interleaved, "
96         "channels = (int) [ 1, 8 ], " "rate = (int) [ 6000, 192000 ]")
97     );
98
99 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
100     GST_PAD_SRC,
101     GST_PAD_ALWAYS,
102     GST_STATIC_CAPS ("audio/x-wavpack, "
103         "depth = (int) [ 1, 32 ], "
104         "channels = (int) [ 1, 8 ], "
105         "rate = (int) [ 6000, 192000 ], " "framed = (boolean) TRUE")
106     );
107
108 static GstStaticPadTemplate wvcsrc_factory = GST_STATIC_PAD_TEMPLATE ("wvcsrc",
109     GST_PAD_SRC,
110     GST_PAD_SOMETIMES,
111     GST_STATIC_CAPS ("audio/x-wavpack-correction, " "framed = (boolean) TRUE")
112     );
113
114 enum
115 {
116   GST_WAVPACK_ENC_MODE_VERY_FAST = 0,
117   GST_WAVPACK_ENC_MODE_FAST,
118   GST_WAVPACK_ENC_MODE_DEFAULT,
119   GST_WAVPACK_ENC_MODE_HIGH,
120   GST_WAVPACK_ENC_MODE_VERY_HIGH
121 };
122
123 #define GST_TYPE_WAVPACK_ENC_MODE (gst_wavpack_enc_mode_get_type ())
124 static GType
125 gst_wavpack_enc_mode_get_type (void)
126 {
127   static GType qtype = 0;
128
129   if (qtype == 0) {
130     static const GEnumValue values[] = {
131 #if 0
132       /* Very Fast Compression is not supported yet, but will be supported
133        * in future wavpack versions */
134       {GST_WAVPACK_ENC_MODE_VERY_FAST, "Very Fast Compression", "veryfast"},
135 #endif
136       {GST_WAVPACK_ENC_MODE_FAST, "Fast Compression", "fast"},
137       {GST_WAVPACK_ENC_MODE_DEFAULT, "Normal Compression", "normal"},
138       {GST_WAVPACK_ENC_MODE_HIGH, "High Compression", "high"},
139 #ifndef WAVPACK_OLD_API
140       {GST_WAVPACK_ENC_MODE_VERY_HIGH, "Very High Compression", "veryhigh"},
141 #endif
142       {0, NULL, NULL}
143     };
144
145     qtype = g_enum_register_static ("GstWavpackEncMode", values);
146   }
147   return qtype;
148 }
149
150 enum
151 {
152   GST_WAVPACK_CORRECTION_MODE_OFF = 0,
153   GST_WAVPACK_CORRECTION_MODE_ON,
154   GST_WAVPACK_CORRECTION_MODE_OPTIMIZED
155 };
156
157 #define GST_TYPE_WAVPACK_ENC_CORRECTION_MODE (gst_wavpack_enc_correction_mode_get_type ())
158 static GType
159 gst_wavpack_enc_correction_mode_get_type (void)
160 {
161   static GType qtype = 0;
162
163   if (qtype == 0) {
164     static const GEnumValue values[] = {
165       {GST_WAVPACK_CORRECTION_MODE_OFF, "Create no correction file", "off"},
166       {GST_WAVPACK_CORRECTION_MODE_ON, "Create correction file", "on"},
167       {GST_WAVPACK_CORRECTION_MODE_OPTIMIZED,
168           "Create optimized correction file", "optimized"},
169       {0, NULL, NULL}
170     };
171
172     qtype = g_enum_register_static ("GstWavpackEncCorrectionMode", values);
173   }
174   return qtype;
175 }
176
177 enum
178 {
179   GST_WAVPACK_JS_MODE_AUTO = 0,
180   GST_WAVPACK_JS_MODE_LEFT_RIGHT,
181   GST_WAVPACK_JS_MODE_MID_SIDE
182 };
183
184 #define GST_TYPE_WAVPACK_ENC_JOINT_STEREO_MODE (gst_wavpack_enc_joint_stereo_mode_get_type ())
185 static GType
186 gst_wavpack_enc_joint_stereo_mode_get_type (void)
187 {
188   static GType qtype = 0;
189
190   if (qtype == 0) {
191     static const GEnumValue values[] = {
192       {GST_WAVPACK_JS_MODE_AUTO, "auto", "auto"},
193       {GST_WAVPACK_JS_MODE_LEFT_RIGHT, "left/right", "leftright"},
194       {GST_WAVPACK_JS_MODE_MID_SIDE, "mid/side", "midside"},
195       {0, NULL, NULL}
196     };
197
198     qtype = g_enum_register_static ("GstWavpackEncJSMode", values);
199   }
200   return qtype;
201 }
202
203 #define gst_wavpack_enc_parent_class parent_class
204 G_DEFINE_TYPE (GstWavpackEnc, gst_wavpack_enc, GST_TYPE_AUDIO_ENCODER);
205
206 static void
207 gst_wavpack_enc_class_init (GstWavpackEncClass * klass)
208 {
209   GObjectClass *gobject_class = (GObjectClass *) klass;
210   GstElementClass *element_class = (GstElementClass *) (klass);
211   GstAudioEncoderClass *base_class = (GstAudioEncoderClass *) (klass);
212
213   /* add pad templates */
214   gst_element_class_add_pad_template (element_class,
215       gst_static_pad_template_get (&sink_factory));
216   gst_element_class_add_pad_template (element_class,
217       gst_static_pad_template_get (&src_factory));
218   gst_element_class_add_pad_template (element_class,
219       gst_static_pad_template_get (&wvcsrc_factory));
220
221   /* set element details */
222   gst_element_class_set_static_metadata (element_class, "Wavpack audio encoder",
223       "Codec/Encoder/Audio",
224       "Encodes audio with the Wavpack lossless/lossy audio codec",
225       "Sebastian Dröge <slomo@circular-chaos.org>");
226
227   /* set property handlers */
228   gobject_class->set_property = gst_wavpack_enc_set_property;
229   gobject_class->get_property = gst_wavpack_enc_get_property;
230
231   base_class->start = GST_DEBUG_FUNCPTR (gst_wavpack_enc_start);
232   base_class->stop = GST_DEBUG_FUNCPTR (gst_wavpack_enc_stop);
233   base_class->set_format = GST_DEBUG_FUNCPTR (gst_wavpack_enc_set_format);
234   base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_wavpack_enc_handle_frame);
235   base_class->sink_event = GST_DEBUG_FUNCPTR (gst_wavpack_enc_sink_event);
236
237   /* install all properties */
238   g_object_class_install_property (gobject_class, ARG_MODE,
239       g_param_spec_enum ("mode", "Encoding mode",
240           "Speed versus compression tradeoff.",
241           GST_TYPE_WAVPACK_ENC_MODE, GST_WAVPACK_ENC_MODE_DEFAULT,
242           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
243   g_object_class_install_property (gobject_class, ARG_BITRATE,
244       g_param_spec_uint ("bitrate", "Bitrate",
245           "Try to encode with this average bitrate (bits/sec). "
246           "This enables lossy encoding, values smaller than 24000 disable it again.",
247           0, 9600000, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
248   g_object_class_install_property (gobject_class, ARG_BITSPERSAMPLE,
249       g_param_spec_double ("bits-per-sample", "Bits per sample",
250           "Try to encode with this amount of bits per sample. "
251           "This enables lossy encoding, values smaller than 2.0 disable it again.",
252           0.0, 24.0, 0.0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
253   g_object_class_install_property (gobject_class, ARG_CORRECTION_MODE,
254       g_param_spec_enum ("correction-mode", "Correction stream mode",
255           "Use this mode for the correction stream. Only works in lossy mode!",
256           GST_TYPE_WAVPACK_ENC_CORRECTION_MODE, GST_WAVPACK_CORRECTION_MODE_OFF,
257           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
258   g_object_class_install_property (gobject_class, ARG_MD5,
259       g_param_spec_boolean ("md5", "MD5",
260           "Store MD5 hash of raw samples within the file.", FALSE,
261           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
262   g_object_class_install_property (gobject_class, ARG_EXTRA_PROCESSING,
263       g_param_spec_uint ("extra-processing", "Extra processing",
264           "Use better but slower filters for better compression/quality.",
265           0, 6, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
266   g_object_class_install_property (gobject_class, ARG_JOINT_STEREO_MODE,
267       g_param_spec_enum ("joint-stereo-mode", "Joint-Stereo mode",
268           "Use this joint-stereo mode.", GST_TYPE_WAVPACK_ENC_JOINT_STEREO_MODE,
269           GST_WAVPACK_JS_MODE_AUTO,
270           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
271 }
272
273 static void
274 gst_wavpack_enc_reset (GstWavpackEnc * enc)
275 {
276   /* close and free everything stream related if we already did something */
277   if (enc->wp_context) {
278     WavpackCloseFile (enc->wp_context);
279     enc->wp_context = NULL;
280   }
281   if (enc->wp_config) {
282     g_free (enc->wp_config);
283     enc->wp_config = NULL;
284   }
285   if (enc->first_block) {
286     g_free (enc->first_block);
287     enc->first_block = NULL;
288   }
289   enc->first_block_size = 0;
290   if (enc->md5_context) {
291     g_checksum_free (enc->md5_context);
292     enc->md5_context = NULL;
293   }
294   if (enc->pending_segment)
295     gst_event_unref (enc->pending_segment);
296   enc->pending_segment = NULL;
297
298   if (enc->pending_buffer) {
299     gst_buffer_unref (enc->pending_buffer);
300     enc->pending_buffer = NULL;
301     enc->pending_offset = 0;
302   }
303
304   /* reset the last returns to GST_FLOW_OK. This is only set to something else
305    * while WavpackPackSamples() or more specific gst_wavpack_enc_push_block()
306    * so not valid anymore */
307   enc->srcpad_last_return = enc->wvcsrcpad_last_return = GST_FLOW_OK;
308
309   /* reset stream information */
310   enc->samplerate = 0;
311   enc->depth = 0;
312   enc->channels = 0;
313   enc->channel_mask = 0;
314   enc->need_channel_remap = FALSE;
315
316   enc->timestamp_offset = GST_CLOCK_TIME_NONE;
317   enc->next_ts = GST_CLOCK_TIME_NONE;
318 }
319
320 static void
321 gst_wavpack_enc_init (GstWavpackEnc * enc)
322 {
323   GstAudioEncoder *benc = GST_AUDIO_ENCODER (enc);
324
325   /* initialize object attributes */
326   enc->wp_config = NULL;
327   enc->wp_context = NULL;
328   enc->first_block = NULL;
329   enc->md5_context = NULL;
330   gst_wavpack_enc_reset (enc);
331
332   enc->wv_id.correction = FALSE;
333   enc->wv_id.wavpack_enc = enc;
334   enc->wv_id.passthrough = FALSE;
335   enc->wvc_id.correction = TRUE;
336   enc->wvc_id.wavpack_enc = enc;
337   enc->wvc_id.passthrough = FALSE;
338
339   /* set default values of params */
340   enc->mode = GST_WAVPACK_ENC_MODE_DEFAULT;
341   enc->bitrate = 0;
342   enc->bps = 0.0;
343   enc->correction_mode = GST_WAVPACK_CORRECTION_MODE_OFF;
344   enc->md5 = FALSE;
345   enc->extra_processing = 0;
346   enc->joint_stereo_mode = GST_WAVPACK_JS_MODE_AUTO;
347
348   /* require perfect ts */
349   gst_audio_encoder_set_perfect_timestamp (benc, TRUE);
350 }
351
352
353 static gboolean
354 gst_wavpack_enc_start (GstAudioEncoder * enc)
355 {
356   GST_DEBUG_OBJECT (enc, "start");
357
358   return TRUE;
359 }
360
361 static gboolean
362 gst_wavpack_enc_stop (GstAudioEncoder * enc)
363 {
364   GstWavpackEnc *wpenc = GST_WAVPACK_ENC (enc);
365
366   GST_DEBUG_OBJECT (enc, "stop");
367   gst_wavpack_enc_reset (wpenc);
368
369   return TRUE;
370 }
371
372 static gboolean
373 gst_wavpack_enc_set_format (GstAudioEncoder * benc, GstAudioInfo * info)
374 {
375   GstWavpackEnc *enc = GST_WAVPACK_ENC (benc);
376   GstAudioChannelPosition *pos;
377   GstAudioChannelPosition opos[64] = { GST_AUDIO_CHANNEL_POSITION_INVALID, };
378   GstCaps *caps;
379   guint64 mask = 0;
380
381   /* we may be configured again, but that change should have cleanup context */
382   g_assert (enc->wp_context == NULL);
383
384   enc->channels = GST_AUDIO_INFO_CHANNELS (info);
385   enc->depth = GST_AUDIO_INFO_DEPTH (info);
386   enc->samplerate = GST_AUDIO_INFO_RATE (info);
387
388   pos = info->position;
389   g_assert (pos);
390
391   /* If one channel is NONE they'll be all undefined */
392   if (pos != NULL && pos[0] == GST_AUDIO_CHANNEL_POSITION_NONE) {
393     goto invalid_channels;
394   }
395
396   enc->channel_mask =
397       gst_wavpack_get_channel_mask_from_positions (pos, enc->channels);
398   enc->need_channel_remap =
399       gst_wavpack_set_channel_mapping (pos, enc->channels,
400       enc->channel_mapping);
401
402   /* wavpack caps hold gst mask, not wavpack mask */
403   gst_audio_channel_positions_to_mask (opos, enc->channels, FALSE, &mask);
404
405   /* set fixed src pad caps now that we know what we will get */
406   caps = gst_caps_new_simple ("audio/x-wavpack",
407       "channels", G_TYPE_INT, enc->channels,
408       "rate", G_TYPE_INT, enc->samplerate,
409       "depth", G_TYPE_INT, enc->depth, "framed", G_TYPE_BOOLEAN, TRUE, NULL);
410
411   if (mask)
412     gst_caps_set_simple (caps, "channel-mask", GST_TYPE_BITMASK, mask, NULL);
413
414   if (!gst_audio_encoder_set_output_format (benc, caps))
415     goto setting_src_caps_failed;
416
417   gst_caps_unref (caps);
418
419   /* no special feedback to base class; should provide all available samples */
420
421   return TRUE;
422
423   /* ERRORS */
424 setting_src_caps_failed:
425   {
426     GST_DEBUG_OBJECT (enc,
427         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
428     gst_caps_unref (caps);
429     return FALSE;
430   }
431 invalid_channels:
432   {
433     GST_DEBUG_OBJECT (enc, "input has invalid channel layout");
434     return FALSE;
435   }
436 }
437
438 static void
439 gst_wavpack_enc_set_wp_config (GstWavpackEnc * enc)
440 {
441   enc->wp_config = g_new0 (WavpackConfig, 1);
442   /* set general stream informations in the WavpackConfig */
443   enc->wp_config->bytes_per_sample = GST_ROUND_UP_8 (enc->depth) / 8;
444   enc->wp_config->bits_per_sample = enc->depth;
445   enc->wp_config->num_channels = enc->channels;
446   enc->wp_config->channel_mask = enc->channel_mask;
447   enc->wp_config->sample_rate = enc->samplerate;
448
449   /*
450    * Set parameters in WavpackConfig
451    */
452
453   /* Encoding mode */
454   switch (enc->mode) {
455 #if 0
456     case GST_WAVPACK_ENC_MODE_VERY_FAST:
457       enc->wp_config->flags |= CONFIG_VERY_FAST_FLAG;
458       enc->wp_config->flags |= CONFIG_FAST_FLAG;
459       break;
460 #endif
461     case GST_WAVPACK_ENC_MODE_FAST:
462       enc->wp_config->flags |= CONFIG_FAST_FLAG;
463       break;
464     case GST_WAVPACK_ENC_MODE_DEFAULT:
465       break;
466     case GST_WAVPACK_ENC_MODE_HIGH:
467       enc->wp_config->flags |= CONFIG_HIGH_FLAG;
468       break;
469 #ifndef WAVPACK_OLD_API
470     case GST_WAVPACK_ENC_MODE_VERY_HIGH:
471       enc->wp_config->flags |= CONFIG_HIGH_FLAG;
472       enc->wp_config->flags |= CONFIG_VERY_HIGH_FLAG;
473       break;
474 #endif
475   }
476
477   /* Bitrate, enables lossy mode */
478   if (enc->bitrate) {
479     enc->wp_config->flags |= CONFIG_HYBRID_FLAG;
480     enc->wp_config->flags |= CONFIG_BITRATE_KBPS;
481     enc->wp_config->bitrate = enc->bitrate / 1000.0;
482   } else if (enc->bps) {
483     enc->wp_config->flags |= CONFIG_HYBRID_FLAG;
484     enc->wp_config->bitrate = enc->bps;
485   }
486
487   /* Correction Mode, only in lossy mode */
488   if (enc->wp_config->flags & CONFIG_HYBRID_FLAG) {
489     if (enc->correction_mode > GST_WAVPACK_CORRECTION_MODE_OFF) {
490       GstCaps *caps = gst_caps_new_simple ("audio/x-wavpack-correction",
491           "framed", G_TYPE_BOOLEAN, TRUE, NULL);
492
493       enc->wvcsrcpad =
494           gst_pad_new_from_static_template (&wvcsrc_factory, "wvcsrc");
495
496       /* try to add correction src pad, don't set correction mode on failure */
497       GST_DEBUG_OBJECT (enc, "Adding correction pad with caps %"
498           GST_PTR_FORMAT, caps);
499       if (!gst_pad_set_caps (enc->wvcsrcpad, caps)) {
500         enc->correction_mode = 0;
501         GST_WARNING_OBJECT (enc, "setting correction caps failed");
502       } else {
503         gst_pad_use_fixed_caps (enc->wvcsrcpad);
504         gst_pad_set_active (enc->wvcsrcpad, TRUE);
505         gst_element_add_pad (GST_ELEMENT (enc), enc->wvcsrcpad);
506         enc->wp_config->flags |= CONFIG_CREATE_WVC;
507         if (enc->correction_mode == GST_WAVPACK_CORRECTION_MODE_OPTIMIZED) {
508           enc->wp_config->flags |= CONFIG_OPTIMIZE_WVC;
509         }
510       }
511       gst_caps_unref (caps);
512     }
513   } else {
514     if (enc->correction_mode > GST_WAVPACK_CORRECTION_MODE_OFF) {
515       enc->correction_mode = 0;
516       GST_WARNING_OBJECT (enc, "setting correction mode only has "
517           "any effect if a bitrate is provided.");
518     }
519   }
520   gst_element_no_more_pads (GST_ELEMENT (enc));
521
522   /* MD5, setup MD5 context */
523   if ((enc->md5) && !(enc->md5_context)) {
524     enc->wp_config->flags |= CONFIG_MD5_CHECKSUM;
525     enc->md5_context = g_checksum_new (G_CHECKSUM_MD5);
526   }
527
528   /* Extra encode processing */
529   if (enc->extra_processing) {
530     enc->wp_config->flags |= CONFIG_EXTRA_MODE;
531     enc->wp_config->xmode = enc->extra_processing;
532   }
533
534   /* Joint stereo mode */
535   switch (enc->joint_stereo_mode) {
536     case GST_WAVPACK_JS_MODE_AUTO:
537       break;
538     case GST_WAVPACK_JS_MODE_LEFT_RIGHT:
539       enc->wp_config->flags |= CONFIG_JOINT_OVERRIDE;
540       enc->wp_config->flags &= ~CONFIG_JOINT_STEREO;
541       break;
542     case GST_WAVPACK_JS_MODE_MID_SIDE:
543       enc->wp_config->flags |= (CONFIG_JOINT_OVERRIDE | CONFIG_JOINT_STEREO);
544       break;
545   }
546 }
547
548 static int
549 gst_wavpack_enc_push_block (void *id, void *data, int32_t count)
550 {
551   GstWavpackEncWriteID *wid = (GstWavpackEncWriteID *) id;
552   GstWavpackEnc *enc = GST_WAVPACK_ENC (wid->wavpack_enc);
553   GstFlowReturn *flow;
554   GstBuffer *buffer;
555   GstPad *pad;
556   guchar *block = (guchar *) data;
557   gint samples = 0;
558
559   pad = (wid->correction) ? enc->wvcsrcpad : GST_AUDIO_ENCODER_SRC_PAD (enc);
560   flow =
561       (wid->correction) ? &enc->
562       wvcsrcpad_last_return : &enc->srcpad_last_return;
563
564   buffer = gst_buffer_new_and_alloc (count);
565   gst_buffer_fill (buffer, 0, data, count);
566
567   if (count > sizeof (WavpackHeader) && memcmp (block, "wvpk", 4) == 0) {
568     /* if it's a Wavpack block set buffer timestamp and duration, etc */
569     WavpackHeader wph;
570
571     GST_LOG_OBJECT (enc, "got %d bytes of encoded wavpack %sdata",
572         count, (wid->correction) ? "correction " : "");
573
574     gst_wavpack_read_header (&wph, block);
575
576     /* Only set when pushing the first buffer again, in that case
577      * we don't want to delay the buffer or push newsegment events
578      */
579     if (!wid->passthrough) {
580       /* Only push complete blocks */
581       if (enc->pending_buffer == NULL) {
582         enc->pending_buffer = buffer;
583         enc->pending_offset = wph.block_index;
584       } else if (enc->pending_offset == wph.block_index) {
585         enc->pending_buffer = gst_buffer_append (enc->pending_buffer, buffer);
586       } else {
587         GST_ERROR ("Got incomplete block, dropping");
588         gst_buffer_unref (enc->pending_buffer);
589         enc->pending_buffer = buffer;
590         enc->pending_offset = wph.block_index;
591       }
592
593       if (!(wph.flags & FINAL_BLOCK))
594         return TRUE;
595
596       buffer = enc->pending_buffer;
597       enc->pending_buffer = NULL;
598       enc->pending_offset = 0;
599
600       /* only send segment on correction pad,
601        * regular pad is handled normally by baseclass */
602       if (wid->correction && enc->pending_segment) {
603         gst_pad_push_event (pad, enc->pending_segment);
604         enc->pending_segment = NULL;
605       }
606
607       if (wph.block_index == 0) {
608         /* save header for later reference, so we can re-send it later on
609          * EOS with fixed up values for total sample count etc. */
610         if (enc->first_block == NULL && !wid->correction) {
611           GstMapInfo map;
612
613           gst_buffer_map (buffer, &map, GST_MAP_READ);
614           enc->first_block = g_memdup (map.data, map.size);
615           enc->first_block_size = map.size;
616           gst_buffer_unmap (buffer, &map);
617         }
618       }
619     }
620     samples = wph.block_samples;
621
622     /* decorate buffer */
623     /* NOTE: this will get overwritten by baseclass, but stay for those
624      * that are pushed directly
625      * FIXME: add setting to baseclass to avoid overwriting it ?? */
626     GST_BUFFER_OFFSET (buffer) = wph.block_index;
627     GST_BUFFER_OFFSET_END (buffer) = wph.block_index + wph.block_samples;
628   } else {
629     /* if it's something else set no timestamp and duration on the buffer */
630     GST_DEBUG_OBJECT (enc, "got %d bytes of unknown data", count);
631   }
632
633   if (wid->correction || wid->passthrough) {
634     /* push the buffer and forward errors */
635     GST_DEBUG_OBJECT (enc, "pushing buffer with %" G_GSIZE_FORMAT " bytes",
636         gst_buffer_get_size (buffer));
637     *flow = gst_pad_push (pad, buffer);
638   } else {
639     GST_DEBUG_OBJECT (enc, "handing frame of %" G_GSIZE_FORMAT " bytes",
640         gst_buffer_get_size (buffer));
641     *flow = gst_audio_encoder_finish_frame (GST_AUDIO_ENCODER (enc), buffer,
642         samples);
643   }
644
645   if (*flow != GST_FLOW_OK) {
646     GST_WARNING_OBJECT (enc, "flow on %s:%s = %s",
647         GST_DEBUG_PAD_NAME (pad), gst_flow_get_name (*flow));
648     return FALSE;
649   }
650
651   return TRUE;
652 }
653
654 static void
655 gst_wavpack_enc_fix_channel_order (GstWavpackEnc * enc, gint32 * data,
656     gint nsamples)
657 {
658   gint i, j;
659   gint32 tmp[8];
660
661   for (i = 0; i < nsamples / enc->channels; i++) {
662     for (j = 0; j < enc->channels; j++) {
663       tmp[enc->channel_mapping[j]] = data[j];
664     }
665     for (j = 0; j < enc->channels; j++) {
666       data[j] = tmp[j];
667     }
668     data += enc->channels;
669   }
670 }
671
672 static GstFlowReturn
673 gst_wavpack_enc_handle_frame (GstAudioEncoder * benc, GstBuffer * buf)
674 {
675   GstWavpackEnc *enc = GST_WAVPACK_ENC (benc);
676   uint32_t sample_count;
677   GstFlowReturn ret;
678   GstMapInfo map;
679
680   /* base class ensures configuration */
681   g_return_val_if_fail (enc->depth != 0, GST_FLOW_NOT_NEGOTIATED);
682
683   /* reset the last returns to GST_FLOW_OK. This is only set to something else
684    * while WavpackPackSamples() or more specific gst_wavpack_enc_push_block()
685    * so not valid anymore */
686   enc->srcpad_last_return = enc->wvcsrcpad_last_return = GST_FLOW_OK;
687
688   if (G_UNLIKELY (!buf))
689     return gst_wavpack_enc_drain (enc);
690
691   sample_count = gst_buffer_get_size (buf) / 4;
692   GST_DEBUG_OBJECT (enc, "got %u raw samples", sample_count);
693
694   /* check if we already have a valid WavpackContext, otherwise make one */
695   if (!enc->wp_context) {
696     /* create raw context */
697     enc->wp_context =
698         WavpackOpenFileOutput (gst_wavpack_enc_push_block, &enc->wv_id,
699         (enc->correction_mode > 0) ? &enc->wvc_id : NULL);
700     if (!enc->wp_context)
701       goto context_failed;
702
703     /* set the WavpackConfig according to our parameters */
704     gst_wavpack_enc_set_wp_config (enc);
705
706     /* set the configuration to the context now that we know everything
707      * and initialize the encoder */
708     if (!WavpackSetConfiguration (enc->wp_context,
709             enc->wp_config, (uint32_t) (-1))
710         || !WavpackPackInit (enc->wp_context)) {
711       WavpackCloseFile (enc->wp_context);
712       goto config_failed;
713     }
714     GST_DEBUG_OBJECT (enc, "setup of encoding context successfull");
715   }
716
717   if (enc->need_channel_remap) {
718     buf = gst_buffer_make_writable (buf);
719     gst_buffer_map (buf, &map, GST_MAP_WRITE);
720     gst_wavpack_enc_fix_channel_order (enc, (gint32 *) map.data, sample_count);
721     gst_buffer_unmap (buf, &map);
722   }
723
724   gst_buffer_map (buf, &map, GST_MAP_READ);
725
726   /* if we want to append the MD5 sum to the stream update it here
727    * with the current raw samples */
728   if (enc->md5) {
729     g_checksum_update (enc->md5_context, map.data, map.size);
730   }
731
732   /* encode and handle return values from encoding */
733   if (WavpackPackSamples (enc->wp_context, (int32_t *) map.data,
734           sample_count / enc->channels)) {
735     GST_DEBUG_OBJECT (enc, "encoding samples successful");
736     gst_buffer_unmap (buf, &map);
737     ret = GST_FLOW_OK;
738   } else {
739     gst_buffer_unmap (buf, &map);
740     if ((enc->srcpad_last_return == GST_FLOW_OK) ||
741         (enc->wvcsrcpad_last_return == GST_FLOW_OK)) {
742       ret = GST_FLOW_OK;
743     } else if ((enc->srcpad_last_return == GST_FLOW_NOT_LINKED) &&
744         (enc->wvcsrcpad_last_return == GST_FLOW_NOT_LINKED)) {
745       ret = GST_FLOW_NOT_LINKED;
746     } else if ((enc->srcpad_last_return == GST_FLOW_FLUSHING) &&
747         (enc->wvcsrcpad_last_return == GST_FLOW_FLUSHING)) {
748       ret = GST_FLOW_FLUSHING;
749     } else {
750       goto encoding_failed;
751     }
752   }
753
754 exit:
755   return ret;
756
757   /* ERRORS */
758 encoding_failed:
759   {
760     GST_ELEMENT_ERROR (enc, LIBRARY, ENCODE, (NULL),
761         ("encoding samples failed"));
762     ret = GST_FLOW_ERROR;
763     goto exit;
764   }
765 config_failed:
766   {
767     GST_ELEMENT_ERROR (enc, LIBRARY, SETTINGS, (NULL),
768         ("error setting up wavpack encoding context"));
769     ret = GST_FLOW_ERROR;
770     goto exit;
771   }
772 context_failed:
773   {
774     GST_ELEMENT_ERROR (enc, LIBRARY, INIT, (NULL),
775         ("error creating Wavpack context"));
776     ret = GST_FLOW_ERROR;
777     goto exit;
778   }
779 }
780
781 static void
782 gst_wavpack_enc_rewrite_first_block (GstWavpackEnc * enc)
783 {
784   GstSegment segment;
785   gboolean ret;
786   GstQuery *query;
787   gboolean seekable = FALSE;
788
789   g_return_if_fail (enc);
790   g_return_if_fail (enc->first_block);
791
792   /* update the sample count in the first block */
793   WavpackUpdateNumSamples (enc->wp_context, enc->first_block);
794
795   /* try to seek to the beginning of the output */
796   query = gst_query_new_seeking (GST_FORMAT_BYTES);
797   if (gst_pad_peer_query (GST_AUDIO_ENCODER_SRC_PAD (enc), query)) {
798     GstFormat format;
799
800     gst_query_parse_seeking (query, &format, &seekable, NULL, NULL);
801     if (format != GST_FORMAT_BYTES)
802       seekable = FALSE;
803   } else {
804     GST_LOG_OBJECT (enc, "SEEKING query not handled");
805   }
806   gst_query_unref (query);
807
808   if (!seekable) {
809     GST_DEBUG_OBJECT (enc, "downstream not seekable; not rewriting");
810     return;
811   }
812
813   gst_segment_init (&segment, GST_FORMAT_BYTES);
814   ret = gst_pad_push_event (GST_AUDIO_ENCODER_SRC_PAD (enc),
815       gst_event_new_segment (&segment));
816   if (ret) {
817     /* try to rewrite the first block */
818     GST_DEBUG_OBJECT (enc, "rewriting first block ...");
819     enc->wv_id.passthrough = TRUE;
820     ret = gst_wavpack_enc_push_block (&enc->wv_id,
821         enc->first_block, enc->first_block_size);
822     enc->wv_id.passthrough = FALSE;
823     g_free (enc->first_block);
824     enc->first_block = NULL;
825   } else {
826     GST_WARNING_OBJECT (enc, "rewriting of first block failed. "
827         "Seeking to first block failed!");
828   }
829 }
830
831 static GstFlowReturn
832 gst_wavpack_enc_drain (GstWavpackEnc * enc)
833 {
834   if (!enc->wp_context)
835     return GST_FLOW_OK;
836
837   GST_DEBUG_OBJECT (enc, "draining");
838
839   /* Encode all remaining samples and flush them to the src pads */
840   WavpackFlushSamples (enc->wp_context);
841
842   /* Drop all remaining data, this is no complete block otherwise
843    * it would've been pushed already */
844   if (enc->pending_buffer) {
845     gst_buffer_unref (enc->pending_buffer);
846     enc->pending_buffer = NULL;
847     enc->pending_offset = 0;
848   }
849
850   /* write the MD5 sum if we have to write one */
851   if ((enc->md5) && (enc->md5_context)) {
852     guint8 md5_digest[16];
853     gsize digest_len = sizeof (md5_digest);
854
855     g_checksum_get_digest (enc->md5_context, md5_digest, &digest_len);
856     if (digest_len == sizeof (md5_digest)) {
857       WavpackStoreMD5Sum (enc->wp_context, md5_digest);
858       WavpackFlushSamples (enc->wp_context);
859     } else
860       GST_WARNING_OBJECT (enc, "Calculating MD5 digest failed");
861   }
862
863   /* Try to rewrite the first frame with the correct sample number */
864   if (enc->first_block)
865     gst_wavpack_enc_rewrite_first_block (enc);
866
867   /* close the context if not already happened */
868   if (enc->wp_context) {
869     WavpackCloseFile (enc->wp_context);
870     enc->wp_context = NULL;
871   }
872
873   return GST_FLOW_OK;
874 }
875
876 static gboolean
877 gst_wavpack_enc_sink_event (GstAudioEncoder * benc, GstEvent * event)
878 {
879   GstWavpackEnc *enc = GST_WAVPACK_ENC (benc);
880
881   GST_DEBUG_OBJECT (enc, "Received %s event on sinkpad",
882       GST_EVENT_TYPE_NAME (event));
883
884   switch (GST_EVENT_TYPE (event)) {
885     case GST_EVENT_SEGMENT:
886       if (enc->wp_context) {
887         GST_WARNING_OBJECT (enc, "got NEWSEGMENT after encoding "
888             "already started");
889       }
890       /* peek and hold NEWSEGMENT events for sending on correction pad */
891       if (enc->pending_segment)
892         gst_event_unref (enc->pending_segment);
893       enc->pending_segment = gst_event_ref (event);
894       break;
895     default:
896       break;
897   }
898
899   /* baseclass handles rest */
900   return GST_AUDIO_ENCODER_CLASS (parent_class)->sink_event (benc, event);
901 }
902
903 static void
904 gst_wavpack_enc_set_property (GObject * object, guint prop_id,
905     const GValue * value, GParamSpec * pspec)
906 {
907   GstWavpackEnc *enc = GST_WAVPACK_ENC (object);
908
909   switch (prop_id) {
910     case ARG_MODE:
911       enc->mode = g_value_get_enum (value);
912       break;
913     case ARG_BITRATE:{
914       guint val = g_value_get_uint (value);
915
916       if ((val >= 24000) && (val <= 9600000)) {
917         enc->bitrate = val;
918         enc->bps = 0.0;
919       } else {
920         enc->bitrate = 0;
921         enc->bps = 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         enc->bps = val;
930         enc->bitrate = 0;
931       } else {
932         enc->bps = 0.0;
933         enc->bitrate = 0;
934       }
935       break;
936     }
937     case ARG_CORRECTION_MODE:
938       enc->correction_mode = g_value_get_enum (value);
939       break;
940     case ARG_MD5:
941       enc->md5 = g_value_get_boolean (value);
942       break;
943     case ARG_EXTRA_PROCESSING:
944       enc->extra_processing = g_value_get_uint (value);
945       break;
946     case ARG_JOINT_STEREO_MODE:
947       enc->joint_stereo_mode = g_value_get_enum (value);
948       break;
949     default:
950       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
951       break;
952   }
953 }
954
955 static void
956 gst_wavpack_enc_get_property (GObject * object, guint prop_id, GValue * value,
957     GParamSpec * pspec)
958 {
959   GstWavpackEnc *enc = GST_WAVPACK_ENC (object);
960
961   switch (prop_id) {
962     case ARG_MODE:
963       g_value_set_enum (value, enc->mode);
964       break;
965     case ARG_BITRATE:
966       if (enc->bps == 0.0) {
967         g_value_set_uint (value, enc->bitrate);
968       } else {
969         g_value_set_uint (value, 0);
970       }
971       break;
972     case ARG_BITSPERSAMPLE:
973       if (enc->bitrate == 0) {
974         g_value_set_double (value, enc->bps);
975       } else {
976         g_value_set_double (value, 0.0);
977       }
978       break;
979     case ARG_CORRECTION_MODE:
980       g_value_set_enum (value, enc->correction_mode);
981       break;
982     case ARG_MD5:
983       g_value_set_boolean (value, enc->md5);
984       break;
985     case ARG_EXTRA_PROCESSING:
986       g_value_set_uint (value, enc->extra_processing);
987       break;
988     case ARG_JOINT_STEREO_MODE:
989       g_value_set_enum (value, enc->joint_stereo_mode);
990       break;
991     default:
992       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
993       break;
994   }
995 }
996
997 gboolean
998 gst_wavpack_enc_plugin_init (GstPlugin * plugin)
999 {
1000   if (!gst_element_register (plugin, "wavpackenc",
1001           GST_RANK_NONE, GST_TYPE_WAVPACK_ENC))
1002     return FALSE;
1003
1004   GST_DEBUG_CATEGORY_INIT (gst_wavpack_enc_debug, "wavpackenc", 0,
1005       "Wavpack encoder");
1006
1007   return TRUE;
1008 }