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., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, 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-1.0 -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-1.0 -v autoaudiosrc ! 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-1.0 -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-1.0 -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-1.0 -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 
61 #ifdef HAVE_CONFIG_H
62 #include "config.h"
63 #endif
64 
65 #include <string.h>
66 #include "gstlamemp3enc.h"
67 #include <gst/gst-i18n-plugin.h>
68 
69 /* lame < 3.98 */
70 #ifndef HAVE_LAME_SET_VBR_QUALITY
71 #define lame_set_VBR_quality(flags,q) lame_set_VBR_q((flags),(int)(q))
72 #endif
73 
74 GST_DEBUG_CATEGORY_STATIC (debug);
75 #define GST_CAT_DEFAULT debug
76 
77 /* elementfactory information */
78 
79 /* LAMEMP3ENC can do MPEG-1, MPEG-2, and MPEG-2.5, so it has 9 possible
80  * sample rates it supports */
81 static GstStaticPadTemplate gst_lamemp3enc_sink_template =
82     GST_STATIC_PAD_TEMPLATE ("sink",
83     GST_PAD_SINK,
84     GST_PAD_ALWAYS,
85     GST_STATIC_CAPS ("audio/x-raw, "
86         "format = (string) " GST_AUDIO_NE (S16) ", "
87         "layout = (string) interleaved, "
88         "rate = (int) { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 }, "
89         "channels = (int) 1; "
90         "audio/x-raw, "
91         "format = (string) " GST_AUDIO_NE (S16) ", "
92         "layout = (string) interleaved, "
93         "rate = (int) { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 }, "
94         "channels = (int) 2, " "channel-mask = (bitmask) 0x3")
95     );
96 
97 static GstStaticPadTemplate gst_lamemp3enc_src_template =
98 GST_STATIC_PAD_TEMPLATE ("src",
99     GST_PAD_SRC,
100     GST_PAD_ALWAYS,
101     GST_STATIC_CAPS ("audio/mpeg, "
102         "mpegversion = (int) 1, "
103         "layer = (int) 3, "
104         "rate = (int) { 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 }, "
105         "channels = (int) [ 1, 2 ]")
106     );
107 
108 /********** Define useful types for non-programmatic interfaces **********/
109 enum
110 {
111   LAMEMP3ENC_TARGET_QUALITY = 0,
112   LAMEMP3ENC_TARGET_BITRATE
113 };
114 
115 #define GST_TYPE_LAMEMP3ENC_TARGET (gst_lamemp3enc_target_get_type())
116 static GType
gst_lamemp3enc_target_get_type(void)117 gst_lamemp3enc_target_get_type (void)
118 {
119   static GType lame_target_type = 0;
120   static const GEnumValue lame_targets[] = {
121     {LAMEMP3ENC_TARGET_QUALITY, "Quality", "quality"},
122     {LAMEMP3ENC_TARGET_BITRATE, "Bitrate", "bitrate"},
123     {0, NULL, NULL}
124   };
125 
126   if (!lame_target_type) {
127     lame_target_type =
128         g_enum_register_static ("GstLameMP3EncTarget", lame_targets);
129   }
130   return lame_target_type;
131 }
132 
133 enum
134 {
135   LAMEMP3ENC_ENCODING_ENGINE_QUALITY_FAST = 0,
136   LAMEMP3ENC_ENCODING_ENGINE_QUALITY_STANDARD,
137   LAMEMP3ENC_ENCODING_ENGINE_QUALITY_HIGH
138 };
139 
140 #define GST_TYPE_LAMEMP3ENC_ENCODING_ENGINE_QUALITY (gst_lamemp3enc_encoding_engine_quality_get_type())
141 static GType
gst_lamemp3enc_encoding_engine_quality_get_type(void)142 gst_lamemp3enc_encoding_engine_quality_get_type (void)
143 {
144   static GType lame_encoding_engine_quality_type = 0;
145   static const GEnumValue lame_encoding_engine_quality[] = {
146     {0, "Fast", "fast"},
147     {1, "Standard", "standard"},
148     {2, "High", "high"},
149     {0, NULL, NULL}
150   };
151 
152   if (!lame_encoding_engine_quality_type) {
153     lame_encoding_engine_quality_type =
154         g_enum_register_static ("GstLameMP3EncEncodingEngineQuality",
155         lame_encoding_engine_quality);
156   }
157   return lame_encoding_engine_quality_type;
158 }
159 
160 /********** Standard stuff for signals and arguments **********/
161 
162 enum
163 {
164   ARG_0,
165   ARG_TARGET,
166   ARG_BITRATE,
167   ARG_CBR,
168   ARG_QUALITY,
169   ARG_ENCODING_ENGINE_QUALITY,
170   ARG_MONO
171 };
172 
173 #define DEFAULT_TARGET LAMEMP3ENC_TARGET_QUALITY
174 #define DEFAULT_BITRATE 128
175 #define DEFAULT_CBR FALSE
176 #define DEFAULT_QUALITY 4
177 #define DEFAULT_ENCODING_ENGINE_QUALITY LAMEMP3ENC_ENCODING_ENGINE_QUALITY_STANDARD
178 #define DEFAULT_MONO FALSE
179 
180 static gboolean gst_lamemp3enc_start (GstAudioEncoder * enc);
181 static gboolean gst_lamemp3enc_stop (GstAudioEncoder * enc);
182 static gboolean gst_lamemp3enc_set_format (GstAudioEncoder * enc,
183     GstAudioInfo * info);
184 static GstFlowReturn gst_lamemp3enc_handle_frame (GstAudioEncoder * enc,
185     GstBuffer * in_buf);
186 static void gst_lamemp3enc_flush (GstAudioEncoder * enc);
187 
188 static void gst_lamemp3enc_set_property (GObject * object, guint prop_id,
189     const GValue * value, GParamSpec * pspec);
190 static void gst_lamemp3enc_get_property (GObject * object, guint prop_id,
191     GValue * value, GParamSpec * pspec);
192 static gboolean gst_lamemp3enc_setup (GstLameMP3Enc * lame, GstTagList ** tags);
193 
194 #define gst_lamemp3enc_parent_class parent_class
195 G_DEFINE_TYPE (GstLameMP3Enc, gst_lamemp3enc, GST_TYPE_AUDIO_ENCODER);
196 
197 static void
gst_lamemp3enc_release_memory(GstLameMP3Enc * lame)198 gst_lamemp3enc_release_memory (GstLameMP3Enc * lame)
199 {
200   if (lame->lgf) {
201     lame_close (lame->lgf);
202     lame->lgf = NULL;
203   }
204 }
205 
206 static void
gst_lamemp3enc_finalize(GObject * obj)207 gst_lamemp3enc_finalize (GObject * obj)
208 {
209   gst_lamemp3enc_release_memory (GST_LAMEMP3ENC (obj));
210 
211   G_OBJECT_CLASS (parent_class)->finalize (obj);
212 }
213 
214 static void
gst_lamemp3enc_class_init(GstLameMP3EncClass * klass)215 gst_lamemp3enc_class_init (GstLameMP3EncClass * klass)
216 {
217   GObjectClass *gobject_class;
218   GstElementClass *gstelement_class;
219   GstAudioEncoderClass *base_class;
220 
221   gobject_class = (GObjectClass *) klass;
222   gstelement_class = (GstElementClass *) klass;
223   base_class = (GstAudioEncoderClass *) klass;
224 
225   gobject_class->set_property = gst_lamemp3enc_set_property;
226   gobject_class->get_property = gst_lamemp3enc_get_property;
227   gobject_class->finalize = gst_lamemp3enc_finalize;
228 
229   gst_element_class_add_static_pad_template (gstelement_class,
230       &gst_lamemp3enc_src_template);
231   gst_element_class_add_static_pad_template (gstelement_class,
232       &gst_lamemp3enc_sink_template);
233 
234   gst_element_class_set_static_metadata (gstelement_class,
235       "L.A.M.E. mp3 encoder", "Codec/Encoder/Audio",
236       "High-quality free MP3 encoder",
237       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
238 
239   base_class->start = GST_DEBUG_FUNCPTR (gst_lamemp3enc_start);
240   base_class->stop = GST_DEBUG_FUNCPTR (gst_lamemp3enc_stop);
241   base_class->set_format = GST_DEBUG_FUNCPTR (gst_lamemp3enc_set_format);
242   base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_lamemp3enc_handle_frame);
243   base_class->flush = GST_DEBUG_FUNCPTR (gst_lamemp3enc_flush);
244 
245   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_TARGET,
246       g_param_spec_enum ("target", "Target",
247           "Optimize for quality or bitrate", GST_TYPE_LAMEMP3ENC_TARGET,
248           DEFAULT_TARGET,
249           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
250   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BITRATE,
251       g_param_spec_int ("bitrate", "Bitrate (kb/s)",
252           "Bitrate in kbit/sec (Only valid if target is bitrate, for CBR one "
253           "of 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, "
254           "256 or 320)", 8, 320, DEFAULT_BITRATE,
255           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
256   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_CBR,
257       g_param_spec_boolean ("cbr", "CBR", "Enforce constant bitrate encoding "
258           "(Only valid if target is bitrate)", DEFAULT_CBR,
259           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
260   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_QUALITY,
261       g_param_spec_float ("quality", "Quality",
262           "VBR Quality from 0 to 10, 0 being the best "
263           "(Only valid if target is quality)", 0.0, 9.999,
264           DEFAULT_QUALITY,
265           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
266   g_object_class_install_property (G_OBJECT_CLASS (klass),
267       ARG_ENCODING_ENGINE_QUALITY, g_param_spec_enum ("encoding-engine-quality",
268           "Encoding Engine Quality", "Quality/speed of the encoding engine, "
269           "this does not affect the bitrate!",
270           GST_TYPE_LAMEMP3ENC_ENCODING_ENGINE_QUALITY,
271           DEFAULT_ENCODING_ENGINE_QUALITY,
272           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
273   g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_MONO,
274       g_param_spec_boolean ("mono", "Mono", "Enforce mono encoding",
275           DEFAULT_MONO,
276           G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
277 }
278 
279 static void
gst_lamemp3enc_init(GstLameMP3Enc * lame)280 gst_lamemp3enc_init (GstLameMP3Enc * lame)
281 {
282   GST_PAD_SET_ACCEPT_TEMPLATE (GST_AUDIO_ENCODER_SINK_PAD (lame));
283 }
284 
285 static gboolean
gst_lamemp3enc_start(GstAudioEncoder * enc)286 gst_lamemp3enc_start (GstAudioEncoder * enc)
287 {
288   GstLameMP3Enc *lame = GST_LAMEMP3ENC (enc);
289 
290   GST_DEBUG_OBJECT (lame, "start");
291 
292   if (!lame->adapter)
293     lame->adapter = gst_adapter_new ();
294   gst_adapter_clear (lame->adapter);
295 
296   return TRUE;
297 }
298 
299 static gboolean
gst_lamemp3enc_stop(GstAudioEncoder * enc)300 gst_lamemp3enc_stop (GstAudioEncoder * enc)
301 {
302   GstLameMP3Enc *lame = GST_LAMEMP3ENC (enc);
303 
304   GST_DEBUG_OBJECT (lame, "stop");
305 
306   if (lame->adapter) {
307     g_object_unref (lame->adapter);
308     lame->adapter = NULL;
309   }
310 
311   gst_lamemp3enc_release_memory (lame);
312   return TRUE;
313 }
314 
315 static gboolean
gst_lamemp3enc_set_format(GstAudioEncoder * enc,GstAudioInfo * info)316 gst_lamemp3enc_set_format (GstAudioEncoder * enc, GstAudioInfo * info)
317 {
318   GstLameMP3Enc *lame;
319   gint out_samplerate;
320   gint version;
321   GstCaps *othercaps;
322   GstClockTime latency;
323   GstTagList *tags = NULL;
324 
325   lame = GST_LAMEMP3ENC (enc);
326 
327   /* parameters already parsed for us */
328   lame->samplerate = GST_AUDIO_INFO_RATE (info);
329   lame->num_channels = GST_AUDIO_INFO_CHANNELS (info);
330 
331   /* but we might be asked to reconfigure, so reset */
332   gst_lamemp3enc_release_memory (lame);
333 
334   GST_DEBUG_OBJECT (lame, "setting up lame");
335   if (!gst_lamemp3enc_setup (lame, &tags))
336     goto setup_failed;
337 
338   out_samplerate = lame_get_out_samplerate (lame->lgf);
339   if (out_samplerate == 0)
340     goto zero_output_rate;
341   if (out_samplerate != lame->samplerate) {
342     GST_WARNING_OBJECT (lame,
343         "output samplerate %d is different from incoming samplerate %d",
344         out_samplerate, lame->samplerate);
345   }
346   lame->out_samplerate = out_samplerate;
347 
348   version = lame_get_version (lame->lgf);
349   if (version == 0)
350     version = 2;
351   else if (version == 1)
352     version = 1;
353   else if (version == 2)
354     version = 3;
355 
356   othercaps =
357       gst_caps_new_simple ("audio/mpeg",
358       "mpegversion", G_TYPE_INT, 1,
359       "mpegaudioversion", G_TYPE_INT, version,
360       "layer", G_TYPE_INT, 3,
361       "channels", G_TYPE_INT, lame->mono ? 1 : lame->num_channels,
362       "rate", G_TYPE_INT, out_samplerate, NULL);
363 
364   /* and use these caps */
365   gst_audio_encoder_set_output_format (GST_AUDIO_ENCODER (enc), othercaps);
366   gst_caps_unref (othercaps);
367 
368   /* base class feedback:
369    * - we will handle buffers, just hand us all available
370    * - report latency */
371   latency = gst_util_uint64_scale_int (lame_get_framesize (lame->lgf),
372       GST_SECOND, lame->samplerate);
373   gst_audio_encoder_set_latency (enc, latency, latency);
374 
375   if (tags) {
376     gst_audio_encoder_merge_tags (enc, tags, GST_TAG_MERGE_REPLACE);
377     gst_tag_list_unref (tags);
378   }
379 
380   return TRUE;
381 
382 zero_output_rate:
383   {
384     if (tags)
385       gst_tag_list_unref (tags);
386     GST_ELEMENT_ERROR (lame, LIBRARY, SETTINGS, (NULL),
387         ("LAME mp3 audio decided on a zero sample rate"));
388     return FALSE;
389   }
390 setup_failed:
391   {
392     GST_ELEMENT_ERROR (lame, LIBRARY, SETTINGS,
393         (_("Failed to configure LAME mp3 audio encoder. Check your encoding parameters.")), (NULL));
394     return FALSE;
395   }
396 }
397 
398 /* <php-emulation-mode>three underscores for ___rate is really really really
399  * private as opposed to one underscore<php-emulation-mode> */
400 /* call this MACRO outside of the NULL state so that we have a higher chance
401  * of actually having a pipeline and bus to get the message through */
402 
403 #define CHECK_AND_FIXUP_BITRATE(obj,param,rate)		 		  \
404 G_STMT_START {                                                            \
405   gint ___rate = rate;                                                    \
406   gint maxrate = 320;							  \
407   gint multiplier = 64;							  \
408   if (rate == 0) {                                                        \
409     ___rate = rate;                                                       \
410   } else if (rate <= 64) {				                  \
411     maxrate = 64; multiplier = 8;                                         \
412     if ((rate % 8) != 0) ___rate = GST_ROUND_UP_8 (rate); 		  \
413   } else if (rate <= 128) {						  \
414     maxrate = 128; multiplier = 16;                                       \
415     if ((rate % 16) != 0) ___rate = GST_ROUND_UP_16 (rate);               \
416   } else if (rate <= 256) {						  \
417     maxrate = 256; multiplier = 32;                                       \
418     if ((rate % 32) != 0) ___rate = GST_ROUND_UP_32 (rate);               \
419   } else if (rate <= 320) { 						  \
420     maxrate = 320; multiplier = 64;                                       \
421     if ((rate % 64) != 0) ___rate = GST_ROUND_UP_64 (rate);               \
422   }                                                                       \
423   if (___rate != rate) {                                                  \
424     GST_ELEMENT_WARNING (obj, LIBRARY, SETTINGS,			  \
425       (_("The requested bitrate %d kbit/s for property '%s' "             \
426        "is not allowed. "  					          \
427        "The bitrate was changed to %d kbit/s."), rate,		          \
428          param,  ___rate), 					          \
429        ("A bitrate below %d should be a multiple of %d.", 		  \
430           maxrate, multiplier));		  			  \
431     rate = ___rate;                                                       \
432   }                                                                       \
433 } G_STMT_END
434 
435 static void
gst_lamemp3enc_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)436 gst_lamemp3enc_set_property (GObject * object, guint prop_id,
437     const GValue * value, GParamSpec * pspec)
438 {
439   GstLameMP3Enc *lame;
440 
441   lame = GST_LAMEMP3ENC (object);
442 
443   switch (prop_id) {
444     case ARG_TARGET:
445       lame->target = g_value_get_enum (value);
446       break;
447     case ARG_BITRATE:
448       lame->bitrate = g_value_get_int (value);
449       break;
450     case ARG_CBR:
451       lame->cbr = g_value_get_boolean (value);
452       break;
453     case ARG_QUALITY:
454       lame->quality = g_value_get_float (value);
455       break;
456     case ARG_ENCODING_ENGINE_QUALITY:
457       lame->encoding_engine_quality = g_value_get_enum (value);
458       break;
459     case ARG_MONO:
460       lame->mono = g_value_get_boolean (value);
461       break;
462     default:
463       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
464       break;
465   }
466 }
467 
468 static void
gst_lamemp3enc_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)469 gst_lamemp3enc_get_property (GObject * object, guint prop_id, GValue * value,
470     GParamSpec * pspec)
471 {
472   GstLameMP3Enc *lame;
473 
474   lame = GST_LAMEMP3ENC (object);
475 
476   switch (prop_id) {
477     case ARG_TARGET:
478       g_value_set_enum (value, lame->target);
479       break;
480     case ARG_BITRATE:
481       g_value_set_int (value, lame->bitrate);
482       break;
483     case ARG_CBR:
484       g_value_set_boolean (value, lame->cbr);
485       break;
486     case ARG_QUALITY:
487       g_value_set_float (value, lame->quality);
488       break;
489     case ARG_ENCODING_ENGINE_QUALITY:
490       g_value_set_enum (value, lame->encoding_engine_quality);
491       break;
492     case ARG_MONO:
493       g_value_set_boolean (value, lame->mono);
494       break;
495     default:
496       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
497       break;
498   }
499 }
500 
501 /* **** credits go to mpegaudioparse **** */
502 
503 static const guint mp3types_bitrates[2][3][16] = {
504   {
505         {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,},
506         {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,},
507         {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,}
508       },
509   {
510         {0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,},
511         {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,},
512         {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,}
513       },
514 };
515 
516 static const guint mp3types_freqs[3][3] = { {44100, 48000, 32000},
517 {22050, 24000, 16000},
518 {11025, 12000, 8000}
519 };
520 
521 static inline guint
mp3_type_frame_length_from_header(GstLameMP3Enc * lame,guint32 header,guint * put_version,guint * put_layer,guint * put_channels,guint * put_bitrate,guint * put_samplerate,guint * put_mode,guint * put_crc)522 mp3_type_frame_length_from_header (GstLameMP3Enc * lame, guint32 header,
523     guint * put_version, guint * put_layer, guint * put_channels,
524     guint * put_bitrate, guint * put_samplerate, guint * put_mode,
525     guint * put_crc)
526 {
527   guint length;
528   gulong mode, samplerate, bitrate, layer, channels, padding, crc;
529   gulong version;
530   gint lsf, mpg25;
531 
532   if (header & (1 << 20)) {
533     lsf = (header & (1 << 19)) ? 0 : 1;
534     mpg25 = 0;
535   } else {
536     lsf = 1;
537     mpg25 = 1;
538   }
539 
540   version = 1 + lsf + mpg25;
541 
542   layer = 4 - ((header >> 17) & 0x3);
543 
544   crc = (header >> 16) & 0x1;
545 
546   bitrate = (header >> 12) & 0xF;
547   bitrate = mp3types_bitrates[lsf][layer - 1][bitrate] * 1000;
548   /* The caller has ensured we have a valid header, so bitrate can't be
549      zero here. */
550   g_assert (bitrate != 0);
551 
552   samplerate = (header >> 10) & 0x3;
553   samplerate = mp3types_freqs[lsf + mpg25][samplerate];
554 
555   padding = (header >> 9) & 0x1;
556 
557   mode = (header >> 6) & 0x3;
558   channels = (mode == 3) ? 1 : 2;
559 
560   switch (layer) {
561     case 1:
562       length = 4 * ((bitrate * 12) / samplerate + padding);
563       break;
564     case 2:
565       length = (bitrate * 144) / samplerate + padding;
566       break;
567     default:
568     case 3:
569       length = (bitrate * 144) / (samplerate << lsf) + padding;
570       break;
571   }
572 
573   GST_DEBUG_OBJECT (lame, "Calculated mp3 frame length of %u bytes", length);
574   GST_DEBUG_OBJECT (lame, "samplerate = %lu, bitrate = %lu, version = %lu, "
575       "layer = %lu, channels = %lu", samplerate, bitrate, version,
576       layer, channels);
577 
578   if (put_version)
579     *put_version = version;
580   if (put_layer)
581     *put_layer = layer;
582   if (put_channels)
583     *put_channels = channels;
584   if (put_bitrate)
585     *put_bitrate = bitrate;
586   if (put_samplerate)
587     *put_samplerate = samplerate;
588   if (put_mode)
589     *put_mode = mode;
590   if (put_crc)
591     *put_crc = crc;
592 
593   return length;
594 }
595 
596 static gboolean
mp3_sync_check(GstLameMP3Enc * lame,unsigned long head)597 mp3_sync_check (GstLameMP3Enc * lame, unsigned long head)
598 {
599   GST_DEBUG_OBJECT (lame, "checking mp3 header 0x%08lx", head);
600   /* if it's not a valid sync */
601   if ((head & 0xffe00000) != 0xffe00000) {
602     GST_WARNING_OBJECT (lame, "invalid sync");
603     return FALSE;
604   }
605   /* if it's an invalid MPEG version */
606   if (((head >> 19) & 3) == 0x1) {
607     GST_WARNING_OBJECT (lame, "invalid MPEG version: 0x%lx", (head >> 19) & 3);
608     return FALSE;
609   }
610   /* if it's an invalid layer */
611   if (!((head >> 17) & 3)) {
612     GST_WARNING_OBJECT (lame, "invalid layer: 0x%lx", (head >> 17) & 3);
613     return FALSE;
614   }
615   /* if it's an invalid bitrate */
616   if (((head >> 12) & 0xf) == 0x0) {
617     GST_WARNING_OBJECT (lame, "invalid bitrate: 0x%lx."
618         "Free format files are not supported yet", (head >> 12) & 0xf);
619     return FALSE;
620   }
621   if (((head >> 12) & 0xf) == 0xf) {
622     GST_WARNING_OBJECT (lame, "invalid bitrate: 0x%lx", (head >> 12) & 0xf);
623     return FALSE;
624   }
625   /* if it's an invalid samplerate */
626   if (((head >> 10) & 0x3) == 0x3) {
627     GST_WARNING_OBJECT (lame, "invalid samplerate: 0x%lx", (head >> 10) & 0x3);
628     return FALSE;
629   }
630 
631   if ((head & 0x3) == 0x2) {
632     /* Ignore this as there are some files with emphasis 0x2 that can
633      * be played fine. See BGO #537235 */
634     GST_WARNING_OBJECT (lame, "invalid emphasis: 0x%lx", head & 0x3);
635   }
636 
637   return TRUE;
638 }
639 
640 /* **** end mpegaudioparse **** */
641 
642 static GstFlowReturn
gst_lamemp3enc_finish_frames(GstLameMP3Enc * lame)643 gst_lamemp3enc_finish_frames (GstLameMP3Enc * lame)
644 {
645   gint av;
646   guint header;
647   GstFlowReturn result = GST_FLOW_OK;
648 
649   /* limited parsing, we don't expect to lose sync here */
650   while ((result == GST_FLOW_OK) &&
651       ((av = gst_adapter_available (lame->adapter)) > 4)) {
652     guint rate, version, layer, size;
653     GstBuffer *mp3_buf;
654     const guint8 *data;
655     guint samples_per_frame;
656 
657     data = gst_adapter_map (lame->adapter, 4);
658     header = GST_READ_UINT32_BE (data);
659     gst_adapter_unmap (lame->adapter);
660 
661     if (!mp3_sync_check (lame, header))
662       goto invalid_header;
663 
664     size = mp3_type_frame_length_from_header (lame, header, &version, &layer,
665         NULL, NULL, &rate, NULL, NULL);
666 
667     if (G_UNLIKELY (layer != 3 || rate != lame->out_samplerate)) {
668       GST_DEBUG_OBJECT (lame,
669           "unexpected mp3 header with rate %u, version %u, layer %u",
670           rate, version, layer);
671       goto invalid_header;
672     }
673 
674     if (size > av) {
675       /* pretty likely to occur when lame is holding back on us */
676       GST_LOG_OBJECT (lame, "frame size %u (> %d)", size, av);
677       break;
678     }
679 
680     /* Account for the internal resampling, finish frame really wants to
681      * know about the number of incoming samples
682      */
683     samples_per_frame = (version == 1) ? 1152 : 576;
684     samples_per_frame *= lame->samplerate;
685     samples_per_frame /= lame->out_samplerate;
686 
687     /* should be ok now */
688     mp3_buf = gst_adapter_take_buffer (lame->adapter, size);
689     /* number of samples for MPEG-1, layer 3 */
690     result = gst_audio_encoder_finish_frame (GST_AUDIO_ENCODER (lame),
691         mp3_buf, samples_per_frame);
692   }
693 
694 exit:
695   return result;
696 
697   /* ERRORS */
698 invalid_header:
699   {
700     GST_ELEMENT_ERROR (lame, STREAM, ENCODE,
701         ("invalid lame mp3 sync header %08X", header), (NULL));
702     result = GST_FLOW_ERROR;
703     goto exit;
704   }
705 }
706 
707 static GstFlowReturn
gst_lamemp3enc_flush_full(GstLameMP3Enc * lame,gboolean push)708 gst_lamemp3enc_flush_full (GstLameMP3Enc * lame, gboolean push)
709 {
710   GstBuffer *buf;
711   GstMapInfo map;
712   gint size;
713   GstFlowReturn result = GST_FLOW_OK;
714   gint av;
715 
716   if (!lame->lgf)
717     return GST_FLOW_OK;
718 
719   buf = gst_buffer_new_and_alloc (7200);
720   gst_buffer_map (buf, &map, GST_MAP_WRITE);
721   size = lame_encode_flush (lame->lgf, map.data, 7200);
722 
723   if (size > 0) {
724     gst_buffer_unmap (buf, &map);
725     gst_buffer_resize (buf, 0, size);
726     GST_DEBUG_OBJECT (lame, "collecting final %d bytes", size);
727     gst_adapter_push (lame->adapter, buf);
728   } else {
729     gst_buffer_unmap (buf, &map);
730     GST_DEBUG_OBJECT (lame, "no final packet (size=%d, push=%d)", size, push);
731     gst_buffer_unref (buf);
732     result = GST_FLOW_OK;
733   }
734 
735   if (push) {
736     result = gst_lamemp3enc_finish_frames (lame);
737   } else {
738     /* never mind */
739     gst_adapter_clear (lame->adapter);
740   }
741 
742   /* either way, we expect nothing left */
743   if ((av = gst_adapter_available (lame->adapter))) {
744     /* should this be more fatal ?? */
745     GST_WARNING_OBJECT (lame, "unparsed %d bytes left after flushing", av);
746     /* clean up anyway */
747     gst_adapter_clear (lame->adapter);
748   }
749 
750   return result;
751 }
752 
753 static void
gst_lamemp3enc_flush(GstAudioEncoder * enc)754 gst_lamemp3enc_flush (GstAudioEncoder * enc)
755 {
756   gst_lamemp3enc_flush_full (GST_LAMEMP3ENC (enc), FALSE);
757 }
758 
759 static GstFlowReturn
gst_lamemp3enc_handle_frame(GstAudioEncoder * enc,GstBuffer * in_buf)760 gst_lamemp3enc_handle_frame (GstAudioEncoder * enc, GstBuffer * in_buf)
761 {
762   GstLameMP3Enc *lame;
763   gint mp3_buffer_size, mp3_size;
764   GstBuffer *mp3_buf;
765   GstFlowReturn result;
766   gint num_samples;
767   GstMapInfo in_map, mp3_map;
768 
769   lame = GST_LAMEMP3ENC (enc);
770 
771   /* squeeze remaining and push */
772   if (G_UNLIKELY (in_buf == NULL))
773     return gst_lamemp3enc_flush_full (lame, TRUE);
774 
775   gst_buffer_map (in_buf, &in_map, GST_MAP_READ);
776 
777   num_samples = in_map.size / 2;
778 
779   /* allocate space for output */
780   mp3_buffer_size = 1.25 * num_samples + 7200;
781   mp3_buf = gst_buffer_new_allocate (NULL, mp3_buffer_size, NULL);
782   gst_buffer_map (mp3_buf, &mp3_map, GST_MAP_WRITE);
783 
784   /* lame seems to be too stupid to get mono interleaved going */
785   if (lame->num_channels == 1) {
786     mp3_size = lame_encode_buffer (lame->lgf,
787         (short int *) in_map.data,
788         (short int *) in_map.data, num_samples, mp3_map.data, mp3_buffer_size);
789   } else {
790     mp3_size = lame_encode_buffer_interleaved (lame->lgf,
791         (short int *) in_map.data,
792         num_samples / lame->num_channels, mp3_map.data, mp3_buffer_size);
793   }
794   gst_buffer_unmap (in_buf, &in_map);
795 
796   GST_LOG_OBJECT (lame, "encoded %" G_GSIZE_FORMAT " bytes of audio "
797       "to %d bytes of mp3", in_map.size, mp3_size);
798 
799   if (G_LIKELY (mp3_size > 0)) {
800     /* unfortunately lame does not provide frame delineated output,
801      * so collect output and parse into frames ... */
802     gst_buffer_unmap (mp3_buf, &mp3_map);
803     gst_buffer_resize (mp3_buf, 0, mp3_size);
804     gst_adapter_push (lame->adapter, mp3_buf);
805     result = gst_lamemp3enc_finish_frames (lame);
806   } else {
807     gst_buffer_unmap (mp3_buf, &mp3_map);
808     if (mp3_size < 0) {
809       /* eat error ? */
810       g_warning ("error %d", mp3_size);
811     }
812     gst_buffer_unref (mp3_buf);
813     result = GST_FLOW_OK;
814   }
815 
816   return result;
817 }
818 
819 /* set up the encoder state */
820 static gboolean
gst_lamemp3enc_setup(GstLameMP3Enc * lame,GstTagList ** tags)821 gst_lamemp3enc_setup (GstLameMP3Enc * lame, GstTagList ** tags)
822 {
823   gboolean res;
824 
825 #define CHECK_ERROR(command) G_STMT_START {\
826   if ((command) < 0) { \
827     GST_ERROR_OBJECT (lame, "setup failed: " G_STRINGIFY (command)); \
828     if (*tags) { \
829       gst_tag_list_unref (*tags); \
830       *tags = NULL; \
831     } \
832     return FALSE; \
833   } \
834 }G_STMT_END
835 
836   int retval;
837   GstCaps *allowed_caps;
838 
839   GST_DEBUG_OBJECT (lame, "starting setup");
840 
841   lame->lgf = lame_init ();
842 
843   if (lame->lgf == NULL)
844     return FALSE;
845 
846   *tags = gst_tag_list_new_empty ();
847 
848   /* copy the parameters over */
849   lame_set_in_samplerate (lame->lgf, lame->samplerate);
850 
851   /* let lame choose default samplerate unless outgoing sample rate is fixed */
852   allowed_caps = gst_pad_get_allowed_caps (GST_AUDIO_ENCODER_SRC_PAD (lame));
853 
854   if (allowed_caps != NULL) {
855     GstStructure *structure;
856     gint samplerate;
857 
858     structure = gst_caps_get_structure (allowed_caps, 0);
859 
860     if (gst_structure_get_int (structure, "rate", &samplerate)) {
861       GST_DEBUG_OBJECT (lame, "Setting sample rate to %d as fixed in src caps",
862           samplerate);
863       lame_set_out_samplerate (lame->lgf, samplerate);
864     } else {
865       GST_DEBUG_OBJECT (lame, "Letting lame choose sample rate");
866       lame_set_out_samplerate (lame->lgf, 0);
867     }
868     gst_caps_unref (allowed_caps);
869     allowed_caps = NULL;
870   } else {
871     GST_DEBUG_OBJECT (lame, "No peer yet, letting lame choose sample rate");
872     lame_set_out_samplerate (lame->lgf, 0);
873   }
874 
875   CHECK_ERROR (lame_set_num_channels (lame->lgf, lame->num_channels));
876   CHECK_ERROR (lame_set_bWriteVbrTag (lame->lgf, 0));
877 
878   if (lame->target == LAMEMP3ENC_TARGET_QUALITY) {
879     CHECK_ERROR (lame_set_VBR (lame->lgf, vbr_default));
880     CHECK_ERROR (lame_set_VBR_quality (lame->lgf, lame->quality));
881   } else {
882     if (lame->cbr) {
883       CHECK_AND_FIXUP_BITRATE (lame, "bitrate", lame->bitrate);
884       CHECK_ERROR (lame_set_VBR (lame->lgf, vbr_off));
885       CHECK_ERROR (lame_set_brate (lame->lgf, lame->bitrate));
886     } else {
887       CHECK_ERROR (lame_set_VBR (lame->lgf, vbr_abr));
888       CHECK_ERROR (lame_set_VBR_mean_bitrate_kbps (lame->lgf, lame->bitrate));
889     }
890     gst_tag_list_add (*tags, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
891         lame->bitrate * 1000, NULL);
892   }
893 
894   if (lame->encoding_engine_quality == LAMEMP3ENC_ENCODING_ENGINE_QUALITY_FAST)
895     CHECK_ERROR (lame_set_quality (lame->lgf, 7));
896   else if (lame->encoding_engine_quality ==
897       LAMEMP3ENC_ENCODING_ENGINE_QUALITY_HIGH)
898     CHECK_ERROR (lame_set_quality (lame->lgf, 2));
899   /* else default */
900 
901   if (lame->mono)
902     CHECK_ERROR (lame_set_mode (lame->lgf, MONO));
903 
904   /* initialize the lame encoder */
905   if ((retval = lame_init_params (lame->lgf)) >= 0) {
906     /* FIXME: it would be nice to print out the mode here */
907     GST_INFO
908         ("lame encoder setup (target %s, quality %f, bitrate %d, %d Hz, %d channels)",
909         (lame->target == LAMEMP3ENC_TARGET_QUALITY) ? "quality" : "bitrate",
910         lame->quality, lame->bitrate, lame->samplerate, lame->num_channels);
911     res = TRUE;
912   } else {
913     GST_ERROR_OBJECT (lame, "lame_init_params returned %d", retval);
914     res = FALSE;
915   }
916 
917   GST_DEBUG_OBJECT (lame, "done with setup");
918   return res;
919 #undef CHECK_ERROR
920 }
921 
922 gboolean
gst_lamemp3enc_register(GstPlugin * plugin)923 gst_lamemp3enc_register (GstPlugin * plugin)
924 {
925   GST_DEBUG_CATEGORY_INIT (debug, "lamemp3enc", 0, "lame mp3 encoder");
926 
927   if (!gst_element_register (plugin, "lamemp3enc", GST_RANK_PRIMARY,
928           GST_TYPE_LAMEMP3ENC))
929     return FALSE;
930 
931   return TRUE;
932 }
933