282d9f698776dfcf54c5f054917bc41776ed76e2
[platform/upstream/gst-plugins-good.git] / ext / lame / gstlamemp3enc.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  * Copyright (C) <2004> Wim Taymans <wim@fluendo.com>
4  * Copyright (C) <2005> Thomas Vander Stichele <thomas at apestaart dot org>
5  * Copyright (C) <2009> Sebastian Dröge <sebastian.droege@collabora.co.uk>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:element-lamemp3enc
25  * @see_also: lame, mad, vorbisenc
26  *
27  * This element encodes raw integer audio into an MPEG-1 layer 3 (MP3) stream.
28  * Note that <ulink url="http://en.wikipedia.org/wiki/MP3">MP3</ulink> is not
29  * a free format, there are licensing and patent issues to take into
30  * consideration. See <ulink url="http://www.vorbis.com/">Ogg/Vorbis</ulink>
31  * for a royalty free (and often higher quality) alternative.
32  *
33  * <refsect2>
34  * <title>Output sample rate</title>
35  * If no fixed output sample rate is negotiated on the element's src pad,
36  * the element will choose an optimal sample rate to resample to internally.
37  * For example, a 16-bit 44.1 KHz mono audio stream encoded at 48 kbit will
38  * get resampled to 32 KHz.  Use filter caps on the src pad to force a
39  * particular sample rate.
40  * </refsect2>
41  * <refsect2>
42  * <title>Example pipelines</title>
43  * |[
44  * gst-launch -v audiotestsrc wave=sine num-buffers=100 ! audioconvert ! lamemp3enc ! filesink location=sine.mp3
45  * ]| Encode a test sine signal to MP3.
46  * |[
47  * gst-launch -v alsasrc ! audioconvert ! lamemp3enc target=bitrate bitrate=192 ! filesink location=alsasrc.mp3
48  * ]| Record from a sound card using ALSA and encode to MP3 with an average bitrate of 192kbps
49  * |[
50  * gst-launch -v filesrc location=music.wav ! decodebin ! audioconvert ! audioresample ! lamemp3enc target=quality quality=0 ! id3v2mux ! filesink location=music.mp3
51  * ]| Transcode from a .wav file to MP3 (the id3v2mux element is optional) with best VBR quality
52  * |[
53  * gst-launch -v cdda://5 ! audioconvert ! lamemp3enc target=bitrate cbr=true bitrate=192 ! filesink location=track5.mp3
54  * ]| Encode Audio CD track 5 to MP3 with a constant bitrate of 192kbps
55  * |[
56  * gst-launch -v audiotestsrc num-buffers=10 ! audio/x-raw,rate=44100,channels=1 ! lamemp3enc target=bitrate cbr=true bitrate=48 ! filesink location=test.mp3
57  * ]| Encode to a fixed sample rate
58  * </refsect2>
59  *
60  * Since: 0.10.12
61  */
62
63 #ifdef HAVE_CONFIG_H
64 #include "config.h"
65 #endif
66
67 #include <string.h>
68 #include "gstlamemp3enc.h"
69 #include <gst/gst-i18n-plugin.h>
70
71 /* lame < 3.98 */
72 #ifndef HAVE_LAME_SET_VBR_QUALITY
73 #define lame_set_VBR_quality(flags,q) lame_set_VBR_q((flags),(int)(q))
74 #endif
75
76 GST_DEBUG_CATEGORY_STATIC (debug);
77 #define GST_CAT_DEFAULT debug
78
79 /* elementfactory information */
80
81 /* LAMEMP3ENC can do MPEG-1, MPEG-2, and MPEG-2.5, so it has 9 possible
82  * sample rates it supports */
83 static GstStaticPadTemplate gst_lamemp3enc_sink_template =
84 GST_STATIC_PAD_TEMPLATE ("sink",
85     GST_PAD_SINK,
86     GST_PAD_ALWAYS,
87     GST_STATIC_CAPS ("audio/x-raw, "
88         "format = (string) " GST_AUDIO_NE (S16) ", "
89         "rate = (int) { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 }, "
90         "channels = (int) [ 1, 2 ]")
91     );
92
93 static GstStaticPadTemplate gst_lamemp3enc_src_template =
94 GST_STATIC_PAD_TEMPLATE ("src",
95     GST_PAD_SRC,
96     GST_PAD_ALWAYS,
97     GST_STATIC_CAPS ("audio/mpeg, "
98         "mpegversion = (int) 1, "
99         "layer = (int) 3, "
100         "rate = (int) { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 }, "
101         "channels = (int) [ 1, 2 ]")
102     );
103
104 /********** Define useful types for non-programmatic interfaces **********/
105 enum
106 {
107   LAMEMP3ENC_TARGET_QUALITY = 0,
108   LAMEMP3ENC_TARGET_BITRATE
109 };
110
111 #define GST_TYPE_LAMEMP3ENC_TARGET (gst_lamemp3enc_target_get_type())
112 static GType
113 gst_lamemp3enc_target_get_type (void)
114 {
115   static GType lame_target_type = 0;
116   static GEnumValue lame_targets[] = {
117     {LAMEMP3ENC_TARGET_QUALITY, "Quality", "quality"},
118     {LAMEMP3ENC_TARGET_BITRATE, "Bitrate", "bitrate"},
119     {0, NULL, NULL}
120   };
121
122   if (!lame_target_type) {
123     lame_target_type =
124         g_enum_register_static ("GstLameMP3EncTarget", lame_targets);
125   }
126   return lame_target_type;
127 }
128
129 enum
130 {
131   LAMEMP3ENC_ENCODING_ENGINE_QUALITY_FAST = 0,
132   LAMEMP3ENC_ENCODING_ENGINE_QUALITY_STANDARD,
133   LAMEMP3ENC_ENCODING_ENGINE_QUALITY_HIGH
134 };
135
136 #define GST_TYPE_LAMEMP3ENC_ENCODING_ENGINE_QUALITY (gst_lamemp3enc_encoding_engine_quality_get_type())
137 static GType
138 gst_lamemp3enc_encoding_engine_quality_get_type (void)
139 {
140   static GType lame_encoding_engine_quality_type = 0;
141   static GEnumValue lame_encoding_engine_quality[] = {
142     {0, "Fast", "fast"},
143     {1, "Standard", "standard"},
144     {2, "High", "high"},
145     {0, NULL, NULL}
146   };
147
148   if (!lame_encoding_engine_quality_type) {
149     lame_encoding_engine_quality_type =
150         g_enum_register_static ("GstLameMP3EncEncodingEngineQuality",
151         lame_encoding_engine_quality);
152   }
153   return lame_encoding_engine_quality_type;
154 }
155
156 /********** Standard stuff for signals and arguments **********/
157
158 enum
159 {
160   ARG_0,
161   ARG_TARGET,
162   ARG_BITRATE,
163   ARG_CBR,
164   ARG_QUALITY,
165   ARG_ENCODING_ENGINE_QUALITY,
166   ARG_MONO
167 };
168
169 #define DEFAULT_TARGET LAMEMP3ENC_TARGET_QUALITY
170 #define DEFAULT_BITRATE 128
171 #define DEFAULT_CBR FALSE
172 #define DEFAULT_QUALITY 4
173 #define DEFAULT_ENCODING_ENGINE_QUALITY LAMEMP3ENC_ENCODING_ENGINE_QUALITY_STANDARD
174 #define DEFAULT_MONO FALSE
175
176 static gboolean gst_lamemp3enc_start (GstAudioEncoder * enc);
177 static gboolean gst_lamemp3enc_stop (GstAudioEncoder * enc);
178 static gboolean gst_lamemp3enc_set_format (GstAudioEncoder * enc,
179     GstAudioInfo * info);
180 static GstFlowReturn gst_lamemp3enc_handle_frame (GstAudioEncoder * enc,
181     GstBuffer * in_buf);
182 static void gst_lamemp3enc_flush (GstAudioEncoder * enc);
183
184 static void gst_lamemp3enc_set_property (GObject * object, guint prop_id,
185     const GValue * value, GParamSpec * pspec);
186 static void gst_lamemp3enc_get_property (GObject * object, guint prop_id,
187     GValue * value, GParamSpec * pspec);
188 static gboolean gst_lamemp3enc_setup (GstLameMP3Enc * lame, GstTagList ** tags);
189
190 #define gst_lamemp3enc_parent_class parent_class
191 G_DEFINE_TYPE (GstLameMP3Enc, gst_lamemp3enc, GST_TYPE_AUDIO_ENCODER);
192
193 static void
194 gst_lamemp3enc_release_memory (GstLameMP3Enc * lame)
195 {
196   if (lame->lgf) {
197     lame_close (lame->lgf);
198     lame->lgf = NULL;
199   }
200 }
201
202 static void
203 gst_lamemp3enc_finalize (GObject * obj)
204 {
205   gst_lamemp3enc_release_memory (GST_LAMEMP3ENC (obj));
206
207   G_OBJECT_CLASS (parent_class)->finalize (obj);
208 }
209
210 static void
211 gst_lamemp3enc_class_init (GstLameMP3EncClass * klass)
212 {
213   GObjectClass *gobject_class;
214   GstElementClass *gstelement_class;
215   GstAudioEncoderClass *base_class;
216
217   gobject_class = (GObjectClass *) klass;
218   gstelement_class = (GstElementClass *) klass;
219   base_class = (GstAudioEncoderClass *) klass;
220
221   gobject_class->set_property = gst_lamemp3enc_set_property;
222   gobject_class->get_property = gst_lamemp3enc_get_property;
223   gobject_class->finalize = gst_lamemp3enc_finalize;
224
225   gst_element_class_add_pad_template (gstelement_class,
226       gst_static_pad_template_get (&gst_lamemp3enc_src_template));
227   gst_element_class_add_pad_template (gstelement_class,
228       gst_static_pad_template_get (&gst_lamemp3enc_sink_template));
229
230   gst_element_class_set_details_simple (gstelement_class,
231       "L.A.M.E. mp3 encoder", "Codec/Encoder/Audio",
232       "High-quality free MP3 encoder",
233       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
234
235   base_class->start = GST_DEBUG_FUNCPTR (gst_lamemp3enc_start);
236   base_class->stop = GST_DEBUG_FUNCPTR (gst_lamemp3enc_stop);
237   base_class->set_format = GST_DEBUG_FUNCPTR (gst_lamemp3enc_set_format);
238   base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_lamemp3enc_handle_frame);
239   base_class->flush = GST_DEBUG_FUNCPTR (gst_lamemp3enc_flush);
240
241   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_TARGET,
242       g_param_spec_enum ("target", "Target",
243           "Optimize for quality or bitrate", GST_TYPE_LAMEMP3ENC_TARGET,
244           DEFAULT_TARGET,
245           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
246   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BITRATE,
247       g_param_spec_int ("bitrate", "Bitrate (kb/s)",
248           "Bitrate in kbit/sec (Only valid if target is bitrate, for CBR one "
249           "of 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, "
250           "256 or 320)", 8, 320, DEFAULT_BITRATE,
251           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
252   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CBR,
253       g_param_spec_boolean ("cbr", "CBR", "Enforce constant bitrate encoding "
254           "(Only valid if target is bitrate)", DEFAULT_CBR,
255           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
256   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_QUALITY,
257       g_param_spec_float ("quality", "Quality",
258           "VBR Quality from 0 to 10, 0 being the best "
259           "(Only valid if target is quality)", 0.0, 9.999,
260           DEFAULT_QUALITY,
261           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
262   g_object_class_install_property (G_OBJECT_CLASS (klass),
263       ARG_ENCODING_ENGINE_QUALITY, g_param_spec_enum ("encoding-engine-quality",
264           "Encoding Engine Quality", "Quality/speed of the encoding engine, "
265           "this does not affect the bitrate!",
266           GST_TYPE_LAMEMP3ENC_ENCODING_ENGINE_QUALITY,
267           DEFAULT_ENCODING_ENGINE_QUALITY,
268           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
269   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_MONO,
270       g_param_spec_boolean ("mono", "Mono", "Enforce mono encoding",
271           DEFAULT_MONO,
272           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
273 }
274
275 static void
276 gst_lamemp3enc_init (GstLameMP3Enc * lame)
277 {
278 }
279
280 static gboolean
281 gst_lamemp3enc_start (GstAudioEncoder * enc)
282 {
283   GstLameMP3Enc *lame = GST_LAMEMP3ENC (enc);
284
285   GST_DEBUG_OBJECT (lame, "start");
286   return TRUE;
287 }
288
289 static gboolean
290 gst_lamemp3enc_stop (GstAudioEncoder * enc)
291 {
292   GstLameMP3Enc *lame = GST_LAMEMP3ENC (enc);
293
294   GST_DEBUG_OBJECT (lame, "stop");
295
296   gst_lamemp3enc_release_memory (lame);
297   return TRUE;
298 }
299
300 static gboolean
301 gst_lamemp3enc_set_format (GstAudioEncoder * enc, GstAudioInfo * info)
302 {
303   GstLameMP3Enc *lame;
304   gint out_samplerate;
305   gint version;
306   GstCaps *othercaps;
307   GstClockTime latency;
308   GstTagList *tags = NULL;
309
310   lame = GST_LAMEMP3ENC (enc);
311
312   /* parameters already parsed for us */
313   lame->samplerate = GST_AUDIO_INFO_RATE (info);
314   lame->num_channels = GST_AUDIO_INFO_CHANNELS (info);
315
316   /* but we might be asked to reconfigure, so reset */
317   gst_lamemp3enc_release_memory (lame);
318
319   GST_DEBUG_OBJECT (lame, "setting up lame");
320   if (!gst_lamemp3enc_setup (lame, &tags))
321     goto setup_failed;
322
323   out_samplerate = lame_get_out_samplerate (lame->lgf);
324   if (out_samplerate == 0)
325     goto zero_output_rate;
326   if (out_samplerate != lame->samplerate) {
327     GST_WARNING_OBJECT (lame,
328         "output samplerate %d is different from incoming samplerate %d",
329         out_samplerate, lame->samplerate);
330   }
331
332   version = lame_get_version (lame->lgf);
333   if (version == 0)
334     version = 2;
335   else if (version == 1)
336     version = 1;
337   else if (version == 2)
338     version = 3;
339
340   othercaps =
341       gst_caps_new_simple ("audio/mpeg",
342       "mpegversion", G_TYPE_INT, 1,
343       "mpegaudioversion", G_TYPE_INT, version,
344       "layer", G_TYPE_INT, 3,
345       "channels", G_TYPE_INT, lame->mono ? 1 : lame->num_channels,
346       "rate", G_TYPE_INT, out_samplerate, NULL);
347
348   /* and use these caps */
349   gst_pad_set_caps (GST_AUDIO_ENCODER_SRC_PAD (enc), othercaps);
350   gst_caps_unref (othercaps);
351
352   /* base class feedback:
353    * - we will handle buffers, just hand us all available
354    * - report latency */
355   latency = gst_util_uint64_scale_int (lame_get_framesize (lame->lgf),
356       GST_SECOND, lame->samplerate);
357   gst_audio_encoder_set_latency (enc, latency, latency);
358
359   if (tags)
360     gst_audio_encoder_merge_tags (enc, tags, GST_TAG_MERGE_REPLACE);
361
362   return TRUE;
363
364 zero_output_rate:
365   {
366     if (tags)
367       gst_tag_list_free (tags);
368     GST_ELEMENT_ERROR (lame, LIBRARY, SETTINGS, (NULL),
369         ("LAME mp3 audio decided on a zero sample rate"));
370     return FALSE;
371   }
372 setup_failed:
373   {
374     GST_ELEMENT_ERROR (lame, LIBRARY, SETTINGS,
375         (_("Failed to configure LAME mp3 audio encoder. Check your encoding parameters.")), (NULL));
376     return FALSE;
377   }
378 }
379
380 /* <php-emulation-mode>three underscores for ___rate is really really really
381  * private as opposed to one underscore<php-emulation-mode> */
382 /* call this MACRO outside of the NULL state so that we have a higher chance
383  * of actually having a pipeline and bus to get the message through */
384
385 #define CHECK_AND_FIXUP_BITRATE(obj,param,rate)                           \
386 G_STMT_START {                                                            \
387   gint ___rate = rate;                                                    \
388   gint maxrate = 320;                                                     \
389   gint multiplier = 64;                                                   \
390   if (rate == 0) {                                                        \
391     ___rate = rate;                                                       \
392   } else if (rate <= 64) {                                                \
393     maxrate = 64; multiplier = 8;                                         \
394     if ((rate % 8) != 0) ___rate = GST_ROUND_UP_8 (rate);                 \
395   } else if (rate <= 128) {                                               \
396     maxrate = 128; multiplier = 16;                                       \
397     if ((rate % 16) != 0) ___rate = GST_ROUND_UP_16 (rate);               \
398   } else if (rate <= 256) {                                               \
399     maxrate = 256; multiplier = 32;                                       \
400     if ((rate % 32) != 0) ___rate = GST_ROUND_UP_32 (rate);               \
401   } else if (rate <= 320) {                                               \
402     maxrate = 320; multiplier = 64;                                       \
403     if ((rate % 64) != 0) ___rate = GST_ROUND_UP_64 (rate);               \
404   }                                                                       \
405   if (___rate != rate) {                                                  \
406     GST_ELEMENT_WARNING (obj, LIBRARY, SETTINGS,                          \
407       (_("The requested bitrate %d kbit/s for property '%s' "             \
408        "is not allowed. "                                                 \
409        "The bitrate was changed to %d kbit/s."), rate,                    \
410          param,  ___rate),                                                \
411        ("A bitrate below %d should be a multiple of %d.",                 \
412           maxrate, multiplier));                                          \
413     rate = ___rate;                                                       \
414   }                                                                       \
415 } G_STMT_END
416
417 static void
418 gst_lamemp3enc_set_property (GObject * object, guint prop_id,
419     const GValue * value, GParamSpec * pspec)
420 {
421   GstLameMP3Enc *lame;
422
423   lame = GST_LAMEMP3ENC (object);
424
425   switch (prop_id) {
426     case ARG_TARGET:
427       lame->target = g_value_get_enum (value);
428       break;
429     case ARG_BITRATE:
430       lame->bitrate = g_value_get_int (value);
431       break;
432     case ARG_CBR:
433       lame->cbr = g_value_get_boolean (value);
434       break;
435     case ARG_QUALITY:
436       lame->quality = g_value_get_float (value);
437       break;
438     case ARG_ENCODING_ENGINE_QUALITY:
439       lame->encoding_engine_quality = g_value_get_enum (value);
440       break;
441     case ARG_MONO:
442       lame->mono = g_value_get_boolean (value);
443       break;
444     default:
445       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
446       break;
447   }
448 }
449
450 static void
451 gst_lamemp3enc_get_property (GObject * object, guint prop_id, GValue * value,
452     GParamSpec * pspec)
453 {
454   GstLameMP3Enc *lame;
455
456   lame = GST_LAMEMP3ENC (object);
457
458   switch (prop_id) {
459     case ARG_TARGET:
460       g_value_set_enum (value, lame->target);
461       break;
462     case ARG_BITRATE:
463       g_value_set_int (value, lame->bitrate);
464       break;
465     case ARG_CBR:
466       g_value_set_boolean (value, lame->cbr);
467       break;
468     case ARG_QUALITY:
469       g_value_set_float (value, lame->quality);
470       break;
471     case ARG_ENCODING_ENGINE_QUALITY:
472       g_value_set_enum (value, lame->encoding_engine_quality);
473       break;
474     case ARG_MONO:
475       g_value_set_boolean (value, lame->mono);
476       break;
477     default:
478       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
479       break;
480   }
481 }
482
483 static GstFlowReturn
484 gst_lamemp3enc_flush_full (GstLameMP3Enc * lame, gboolean push)
485 {
486   GstBuffer *buf;
487   gint size;
488   guint8 *data;
489   GstFlowReturn result = GST_FLOW_OK;
490
491   if (!lame->lgf)
492     return GST_FLOW_OK;
493
494   buf = gst_buffer_new_and_alloc (7200);
495   data = gst_buffer_map (buf, NULL, NULL, GST_MAP_WRITE);
496   size = lame_encode_flush (lame->lgf, data, 7200);
497
498   if (size > 0) {
499     gst_buffer_unmap (buf, data, size);
500     if (push) {
501       GST_DEBUG_OBJECT (lame, "pushing final packet of %u bytes", size);
502       result =
503           gst_audio_encoder_finish_frame (GST_AUDIO_ENCODER (lame), buf, -1);
504     }
505   } else {
506     gst_buffer_unmap (buf, data, 0);
507     GST_DEBUG_OBJECT (lame, "no final packet (size=%d, push=%d)", size, push);
508     gst_buffer_unref (buf);
509     result = GST_FLOW_OK;
510   }
511   return result;
512 }
513
514 static void
515 gst_lamemp3enc_flush (GstAudioEncoder * enc)
516 {
517   gst_lamemp3enc_flush_full (GST_LAMEMP3ENC (enc), FALSE);
518 }
519
520 static GstFlowReturn
521 gst_lamemp3enc_handle_frame (GstAudioEncoder * enc, GstBuffer * in_buf)
522 {
523   GstLameMP3Enc *lame;
524   guchar *mp3_data;
525   gint mp3_buffer_size, mp3_size;
526   GstBuffer *mp3_buf;
527   GstFlowReturn result;
528   gint num_samples;
529   guint8 *data;
530   gsize size;
531
532   lame = GST_LAMEMP3ENC (enc);
533
534   /* squeeze remaining and push */
535   if (G_UNLIKELY (in_buf == NULL))
536     return gst_lamemp3enc_flush_full (lame, TRUE);
537
538   data = gst_buffer_map (in_buf, &size, NULL, GST_MAP_READ);
539
540   num_samples = size / 2;
541
542   /* allocate space for output */
543   mp3_buffer_size = 1.25 * num_samples + 7200;
544   mp3_buf = gst_buffer_new_allocate (NULL, mp3_buffer_size, 0);
545   mp3_data = gst_buffer_map (mp3_buf, NULL, NULL, GST_MAP_WRITE);
546
547   /* lame seems to be too stupid to get mono interleaved going */
548   if (lame->num_channels == 1) {
549     mp3_size = lame_encode_buffer (lame->lgf,
550         (short int *) data,
551         (short int *) data, num_samples, mp3_data, mp3_buffer_size);
552   } else {
553     mp3_size = lame_encode_buffer_interleaved (lame->lgf,
554         (short int *) data,
555         num_samples / lame->num_channels, mp3_data, mp3_buffer_size);
556   }
557   gst_buffer_unmap (in_buf, data, size);
558
559   GST_LOG_OBJECT (lame, "encoded %" G_GSIZE_FORMAT " bytes of audio "
560       "to %d bytes of mp3", size, mp3_size);
561
562   if (G_LIKELY (mp3_size > 0)) {
563     gst_buffer_unmap (mp3_buf, mp3_data, mp3_size);
564     result = gst_audio_encoder_finish_frame (enc, mp3_buf, -1);
565   } else {
566     gst_buffer_unmap (mp3_buf, mp3_data, 0);
567     if (mp3_size < 0) {
568       /* eat error ? */
569       g_warning ("error %d", mp3_size);
570     }
571     gst_buffer_unref (mp3_buf);
572     result = GST_FLOW_OK;
573   }
574
575   return result;
576 }
577
578 /* set up the encoder state */
579 static gboolean
580 gst_lamemp3enc_setup (GstLameMP3Enc * lame, GstTagList ** tags)
581 {
582   gboolean res;
583
584 #define CHECK_ERROR(command) G_STMT_START {\
585   if ((command) < 0) { \
586     GST_ERROR_OBJECT (lame, "setup failed: " G_STRINGIFY (command)); \
587     if (*tags) { \
588       gst_tag_list_free (*tags); \
589       *tags = NULL; \
590     } \
591     return FALSE; \
592   } \
593 }G_STMT_END
594
595   int retval;
596   GstCaps *allowed_caps;
597
598   GST_DEBUG_OBJECT (lame, "starting setup");
599
600   lame->lgf = lame_init ();
601
602   if (lame->lgf == NULL)
603     return FALSE;
604
605   *tags = gst_tag_list_new_empty ();
606
607   /* copy the parameters over */
608   lame_set_in_samplerate (lame->lgf, lame->samplerate);
609
610   /* let lame choose default samplerate unless outgoing sample rate is fixed */
611   allowed_caps = gst_pad_get_allowed_caps (GST_AUDIO_ENCODER_SRC_PAD (lame));
612
613   if (allowed_caps != NULL) {
614     GstStructure *structure;
615     gint samplerate;
616
617     structure = gst_caps_get_structure (allowed_caps, 0);
618
619     if (gst_structure_get_int (structure, "rate", &samplerate)) {
620       GST_DEBUG_OBJECT (lame, "Setting sample rate to %d as fixed in src caps",
621           samplerate);
622       lame_set_out_samplerate (lame->lgf, samplerate);
623     } else {
624       GST_DEBUG_OBJECT (lame, "Letting lame choose sample rate");
625       lame_set_out_samplerate (lame->lgf, 0);
626     }
627     gst_caps_unref (allowed_caps);
628     allowed_caps = NULL;
629   } else {
630     GST_DEBUG_OBJECT (lame, "No peer yet, letting lame choose sample rate");
631     lame_set_out_samplerate (lame->lgf, 0);
632   }
633
634   CHECK_ERROR (lame_set_num_channels (lame->lgf, lame->num_channels));
635   CHECK_ERROR (lame_set_bWriteVbrTag (lame->lgf, 0));
636
637   if (lame->target == LAMEMP3ENC_TARGET_QUALITY) {
638     CHECK_ERROR (lame_set_VBR (lame->lgf, vbr_default));
639     CHECK_ERROR (lame_set_VBR_quality (lame->lgf, lame->quality));
640   } else {
641     if (lame->cbr) {
642       CHECK_AND_FIXUP_BITRATE (lame, "bitrate", lame->bitrate);
643       CHECK_ERROR (lame_set_VBR (lame->lgf, vbr_off));
644       CHECK_ERROR (lame_set_brate (lame->lgf, lame->bitrate));
645     } else {
646       CHECK_ERROR (lame_set_VBR (lame->lgf, vbr_abr));
647       CHECK_ERROR (lame_set_VBR_mean_bitrate_kbps (lame->lgf, lame->bitrate));
648     }
649     gst_tag_list_add (*tags, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
650         lame->bitrate * 1000, NULL);
651   }
652
653   if (lame->encoding_engine_quality == LAMEMP3ENC_ENCODING_ENGINE_QUALITY_FAST)
654     CHECK_ERROR (lame_set_quality (lame->lgf, 7));
655   else if (lame->encoding_engine_quality ==
656       LAMEMP3ENC_ENCODING_ENGINE_QUALITY_HIGH)
657     CHECK_ERROR (lame_set_quality (lame->lgf, 2));
658   /* else default */
659
660   if (lame->mono)
661     CHECK_ERROR (lame_set_mode (lame->lgf, MONO));
662
663   /* initialize the lame encoder */
664   if ((retval = lame_init_params (lame->lgf)) >= 0) {
665     /* FIXME: it would be nice to print out the mode here */
666     GST_INFO
667         ("lame encoder setup (target %s, quality %f, bitrate %d, %d Hz, %d channels)",
668         (lame->target == LAMEMP3ENC_TARGET_QUALITY) ? "quality" : "bitrate",
669         lame->quality, lame->bitrate, lame->samplerate, lame->num_channels);
670     res = TRUE;
671   } else {
672     GST_ERROR_OBJECT (lame, "lame_init_params returned %d", retval);
673     res = FALSE;
674   }
675
676   GST_DEBUG_OBJECT (lame, "done with setup");
677   return res;
678 #undef CHECK_ERROR
679 }
680
681 gboolean
682 gst_lamemp3enc_register (GstPlugin * plugin)
683 {
684   GST_DEBUG_CATEGORY_INIT (debug, "lamemp3enc", 0, "lame mp3 encoder");
685
686   if (!gst_element_register (plugin, "lamemp3enc", GST_RANK_PRIMARY,
687           GST_TYPE_LAMEMP3ENC))
688     return FALSE;
689
690   return TRUE;
691 }