FFmpeg
Loading...
Searching...
No Matches
libmp3lame.c
Go to the documentation of this file.
1/*
2 * Interface to libmp3lame for mp3 encoding
3 * Copyright (c) 2002 Lennert Buytenhek <buytenh@gnu.org>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg 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 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
23 * @file
24 * Interface to libmp3lame for mp3 encoding.
25 */
26
27#include <lame/lame.h>
28
30#include "libavutil/common.h"
31#include "libavutil/float_dsp.h"
33#include "libavutil/log.h"
34#include "libavutil/mem.h"
35#include "libavutil/opt.h"
36#include "avcodec.h"
37#include "audio_frame_queue.h"
38#include "codec_internal.h"
39#include "encode.h"
40#include "mpegaudio.h"
41#include "mpegaudiodecheader.h"
42
43#define BUFFER_SIZE (7200 + 2 * MPA_FRAME_SIZE + MPA_FRAME_SIZE / 4+1000) // FIXME: Buffer size to small? Adding 1000 to make up for it.
44
62
63
65{
66 if (!s->buffer || s->buffer_size - s->buffer_index < BUFFER_SIZE) {
67 int new_size = s->buffer_index + 2 * BUFFER_SIZE, err;
68
69 ff_dlog(s->avctx, "resizing output buffer: %d -> %d\n", s->buffer_size,
70 new_size);
71 if ((err = av_reallocp(&s->buffer, new_size)) < 0) {
72 s->buffer_size = s->buffer_index = 0;
73 return err;
74 }
75 s->buffer_size = new_size;
76 }
77 return 0;
78}
79
81{
82 LAMEContext *s = avctx->priv_data;
83
84 av_freep(&s->samples_flt[0]);
85 av_freep(&s->samples_flt[1]);
86 av_freep(&s->buffer);
87 av_freep(&s->fdsp);
88
89 ff_af_queue_close(&s->afq);
90
91 lame_close(s->gfp);
92 return 0;
93}
94
96{
97 LAMEContext *s = avctx->priv_data;
98 int ret;
99
100 s->avctx = avctx;
101
102 /* initialize LAME and get defaults */
103 if (!(s->gfp = lame_init()))
104 return AVERROR(ENOMEM);
105
106
107 lame_set_num_channels(s->gfp, avctx->ch_layout.nb_channels);
108 lame_set_mode(s->gfp, avctx->ch_layout.nb_channels > 1 ?
109 s->joint_stereo ? JOINT_STEREO : STEREO : MONO);
110
111 /* sample rate */
112 lame_set_in_samplerate (s->gfp, avctx->sample_rate);
113 lame_set_out_samplerate(s->gfp, avctx->sample_rate);
114
115 /* algorithmic quality */
117 lame_set_quality(s->gfp, avctx->compression_level);
118
119 /* rate control */
120 if (avctx->flags & AV_CODEC_FLAG_QSCALE) { // VBR
121 lame_set_VBR(s->gfp, vbr_default);
122 lame_set_VBR_quality(s->gfp, avctx->global_quality / (float)FF_QP2LAMBDA);
123 } else {
124 if (avctx->bit_rate) {
125 if (s->abr) { // ABR
126 lame_set_VBR(s->gfp, vbr_abr);
127 lame_set_VBR_mean_bitrate_kbps(s->gfp, avctx->bit_rate / 1000);
128 } else // CBR
129 lame_set_brate(s->gfp, avctx->bit_rate / 1000);
130 }
131 }
132
133 /* lowpass cutoff frequency */
134 if (avctx->cutoff)
135 lame_set_lowpassfreq(s->gfp, avctx->cutoff);
136
137 /* do not get a Xing VBR header frame from LAME */
138 lame_set_bWriteVbrTag(s->gfp,0);
139
140 /* bit reservoir usage */
141 lame_set_disable_reservoir(s->gfp, !s->reservoir);
142
143 /* copyright flag */
144 lame_set_copyright(s->gfp, s->copyright);
145
146 /* original flag */
147 lame_set_original(s->gfp, s->original);
148
149 /* set specified parameters */
150 if (lame_init_params(s->gfp) < 0) {
151 ret = AVERROR_EXTERNAL;
152 goto error;
153 }
154
155 /* get encoder delay */
156 avctx->initial_padding = lame_get_encoder_delay(s->gfp) + 528 + 1;
157 ff_af_queue_init(avctx, &s->afq);
158
159 avctx->frame_size = lame_get_framesize(s->gfp);
160
161 /* allocate float sample buffers */
162 if (avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
163 int ch;
164 for (ch = 0; ch < avctx->ch_layout.nb_channels; ch++) {
165 s->samples_flt[ch] = av_malloc_array(avctx->frame_size,
166 sizeof(*s->samples_flt[ch]));
167 if (!s->samples_flt[ch]) {
168 ret = AVERROR(ENOMEM);
169 goto error;
170 }
171 }
172 }
173
174 ret = realloc_buffer(s);
175 if (ret < 0)
176 goto error;
177
179 if (!s->fdsp) {
180 ret = AVERROR(ENOMEM);
181 goto error;
182 }
183
184
185 return 0;
186error:
188 return ret;
189}
190
191#define ENCODE_BUFFER(func, buf_type, buf_name) do { \
192 lame_result = func(s->gfp, \
193 (const buf_type *)buf_name[0], \
194 (const buf_type *)buf_name[1], frame->nb_samples, \
195 s->buffer + s->buffer_index, \
196 s->buffer_size - s->buffer_index); \
197} while (0)
198
200 const AVFrame *frame, int *got_packet_ptr)
201{
202 LAMEContext *s = avctx->priv_data;
203 MPADecodeHeader hdr;
204 int len, ret, ch;
205 int lame_result;
206 uint32_t h;
207
208 if (frame) {
209 switch (avctx->sample_fmt) {
211 ENCODE_BUFFER(lame_encode_buffer, int16_t, frame->data);
212 break;
214 ENCODE_BUFFER(lame_encode_buffer_int, int32_t, frame->data);
215 break;
217 if (frame->linesize[0] < 4 * FFALIGN(frame->nb_samples, 8)) {
218 av_log(avctx, AV_LOG_ERROR, "inadequate AVFrame plane padding\n");
219 return AVERROR(EINVAL);
220 }
221 for (ch = 0; ch < avctx->ch_layout.nb_channels; ch++) {
222 s->fdsp->vector_fmul_scalar(s->samples_flt[ch],
223 (const float *)frame->data[ch],
224 32768.0f,
225 FFALIGN(frame->nb_samples, 8));
226 }
227 ENCODE_BUFFER(lame_encode_buffer_float, float, s->samples_flt);
228 break;
229 default:
230 return AVERROR_BUG;
231 }
232 } else if (!s->afq.frame_alloc) {
233 lame_result = 0;
234 } else {
235 lame_result = lame_encode_flush(s->gfp, s->buffer + s->buffer_index,
236 s->buffer_size - s->buffer_index);
237 }
238 if (lame_result < 0) {
239 if (lame_result == -1) {
240 av_log(avctx, AV_LOG_ERROR,
241 "lame: output buffer too small (buffer index: %d, free bytes: %d)\n",
242 s->buffer_index, s->buffer_size - s->buffer_index);
243 }
244 return AVERROR(ENOMEM);
245 }
246 s->buffer_index += lame_result;
247 ret = realloc_buffer(s);
248 if (ret < 0) {
249 av_log(avctx, AV_LOG_ERROR, "error reallocating output buffer\n");
250 return ret;
251 }
252
253 /* add current frame to the queue */
254 if (frame) {
255 if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
256 return ret;
257 }
258
259 /* Move 1 frame from the LAME buffer to the output packet, if available.
260 We have to parse the first frame header in the output buffer to
261 determine the frame size. */
262 if (s->buffer_index < 4)
263 return 0;
264 h = AV_RB32(s->buffer);
265
267 if (ret < 0) {
268 av_log(avctx, AV_LOG_ERROR, "Invalid mp3 header at start of buffer\n");
269 return AVERROR_BUG;
270 } else if (ret) {
271 av_log(avctx, AV_LOG_ERROR, "free format output not supported\n");
272 return AVERROR_INVALIDDATA;
273 }
274 len = hdr.frame_size;
275 ff_dlog(avctx, "in:%d packet-len:%d index:%d\n", avctx->frame_size, len,
276 s->buffer_index);
277 if (len <= s->buffer_index) {
278 if ((ret = ff_get_encode_buffer(avctx, avpkt, len, 0)) < 0)
279 return ret;
280 memcpy(avpkt->data, s->buffer, len);
281 s->buffer_index -= len;
282 memmove(s->buffer, s->buffer + len, s->buffer_index);
283
284 /* Get the next frame pts/duration */
285 ret = ff_af_queue_remove(&s->afq, avctx->frame_size, avpkt);
286 if (ret < 0)
287 return ret;
288
289 *got_packet_ptr = 1;
290 }
291 return 0;
292}
293
294#define OFFSET(x) offsetof(LAMEContext, x)
295#define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
296static const AVOption options[] = {
297 { "reservoir", "use bit reservoir", OFFSET(reservoir), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, AE },
298 { "joint_stereo", "use joint stereo", OFFSET(joint_stereo), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, AE },
299 { "abr", "use ABR", OFFSET(abr), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AE },
300 { "copyright", "set copyright flag", OFFSET(copyright), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AE},
301 { "original", "set original flag", OFFSET(original), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, AE},
302 { NULL },
303};
304
305static const AVClass libmp3lame_class = {
306 .class_name = "libmp3lame encoder",
307 .item_name = av_default_item_name,
308 .option = options,
309 .version = LIBAVUTIL_VERSION_INT,
310};
311
313 { "b", "0" },
314 { NULL },
315};
316
317static const int libmp3lame_sample_rates[] = {
318 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000, 0
319};
320
322 .p.name = "libmp3lame",
323 CODEC_LONG_NAME("libmp3lame MP3 (MPEG audio layer 3)"),
324 .p.type = AVMEDIA_TYPE_AUDIO,
325 .p.id = AV_CODEC_ID_MP3,
326 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
328 .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE,
329 .priv_data_size = sizeof(LAMEContext),
332 .close = mp3lame_encode_close,
336 .p.priv_class = &libmp3lame_class,
337 .defaults = libmp3lame_defaults,
338 .p.wrapper_name = "libmp3lame",
339};
#define AE
Definition alacenc.c:622
const FFCodec ff_libmp3lame_encoder
Definition libmp3lame.c:321
#define JOINT_STEREO
Definition atrac3.c:59
av_cold void ff_af_queue_close(AudioFrameQueue *afq)
Close AudioFrameQueue.
av_cold void ff_af_queue_init(AVCodecContext *avctx, AudioFrameQueue *afq)
Initialize AudioFrameQueue.
int ff_af_queue_remove(AudioFrameQueue *afq, int nb_samples, AVPacket *pkt)
Remove frame(s) from the queue.
int ff_af_queue_add(AudioFrameQueue *afq, const AVFrame *f)
Add a frame to the queue.
int32_t
Libavcodec external API header.
#define FF_COMPRESSION_DEFAULT
Definition avcodec.h:1242
#define s(width, name)
Definition cbs_vp9.c:198
Public libavutil channel layout APIs header.
#define CODEC_SAMPLERATES_ARRAY(array)
#define CODEC_CH_LAYOUTS(...)
#define FF_CODEC_CAP_NOT_INIT_THREADSAFE
The codec is not known to be init-threadsafe (i.e.
#define FF_CODEC_ENCODE_CB(func)
#define CODEC_LONG_NAME(str)
#define CODEC_SAMPLEFMTS(...)
common internal and external API header
#define STEREO
Definition cook.c:65
#define MONO
Definition cook.c:64
#define NULL
Definition coverity.c:32
static AVFrame * frame
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:608
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition encode.c:106
#define BUFFER_SIZE
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition avcodec.h:322
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition codec.h:79
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition codec.h:49
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition avcodec.h:213
#define AV_CODEC_CAP_SMALL_LAST_FRAME
Codec can be fed a final frame with a smaller size.
Definition codec.h:84
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition codec_id.h:454
#define AV_CHANNEL_LAYOUT_STEREO
#define AV_CHANNEL_LAYOUT_MONO
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition mem.c:188
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AV_SAMPLE_FMT_FLTP
float, planar
Definition samplefmt.h:66
@ AV_SAMPLE_FMT_S16P
signed 16 bits, planar
Definition samplefmt.h:64
@ AV_SAMPLE_FMT_S32P
signed 32 bits, planar
Definition samplefmt.h:65
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define AV_RB32(p)
#define av_cold
Definition attributes.h:117
av_cold AVFloatDSPContext * avpriv_float_dsp_alloc(int bit_exact)
Allocate a float DSP context.
Definition float_dsp.c:135
static av_cold int mp3lame_encode_init(AVCodecContext *avctx)
Definition libmp3lame.c:95
#define ENCODE_BUFFER(func, buf_type, buf_name)
Definition libmp3lame.c:191
static const int libmp3lame_sample_rates[]
Definition libmp3lame.c:317
static const FFCodecDefault libmp3lame_defaults[]
Definition libmp3lame.c:312
static av_cold int mp3lame_encode_close(AVCodecContext *avctx)
Definition libmp3lame.c:80
static int mp3lame_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr)
Definition libmp3lame.c:199
static int realloc_buffer(LAMEContext *s)
Definition libmp3lame.c:64
#define OFFSET(x)
Definition libmp3lame.c:294
static const AVClass libmp3lame_class
Definition libmp3lame.c:305
#define FFALIGN(x, a)
Definition macros.h:78
Memory handling functions.
mpeg audio declarations for both encoder and decoder.
int avpriv_mpegaudio_decode_header(MPADecodeHeader *s, uint32_t header)
MPEG Audio header decoder.
AVOptions.
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
AVChannelLayout ch_layout
Audio channel layout.
Definition avcodec.h:1055
enum AVSampleFormat sample_fmt
audio sample format
Definition avcodec.h:1047
int global_quality
Global quality for codecs which cannot change it per frame.
Definition avcodec.h:1235
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
int initial_padding
Audio only.
Definition avcodec.h:1114
int sample_rate
samples per second
Definition avcodec.h:1040
int compression_level
Definition avcodec.h:1241
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
int cutoff
Audio cutoff bandwidth (0 means "automatic")
Definition avcodec.h:1082
int frame_size
Number of samples per channel in an audio frame.
Definition avcodec.h:1068
void * priv_data
Definition avcodec.h:470
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
uint8_t * data
Definition packet.h:603
float * samples_flt[2]
Definition libmp3lame.c:56
AVFloatDSPContext * fdsp
Definition libmp3lame.c:58
lame_global_flags * gfp
Definition libmp3lame.c:48
AudioFrameQueue afq
Definition libmp3lame.c:57
AVCodecContext * avctx
Definition libmp3lame.c:47
int buffer_index
Definition libmp3lame.c:50
int buffer_size
Definition libmp3lame.c:51
int joint_stereo
Definition libmp3lame.c:53
uint8_t * buffer
Definition libmp3lame.c:49
#define av_malloc_array(a, b)
#define ff_dlog(a,...)
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
int len