]> git.sesse.net Git - ffmpeg/blob - libavcodec/libmp3lame.c
Merge commit '79922d7237aba2b8c6abbd2e06a0c08e4f498ad4'
[ffmpeg] / libavcodec / libmp3lame.c
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
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/common.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/log.h"
33 #include "libavutil/opt.h"
34 #include "avcodec.h"
35 #include "audio_frame_queue.h"
36 #include "dsputil.h"
37 #include "internal.h"
38 #include "mpegaudio.h"
39 #include "mpegaudiodecheader.h"
40
41 #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.
42
43 typedef struct LAMEContext {
44     AVClass *class;
45     AVCodecContext *avctx;
46     lame_global_flags *gfp;
47     uint8_t buffer[BUFFER_SIZE];
48     int buffer_index;
49     int reservoir;
50     float *samples_flt[2];
51     AudioFrameQueue afq;
52     DSPContext dsp;
53 } LAMEContext;
54
55
56 static av_cold int mp3lame_encode_close(AVCodecContext *avctx)
57 {
58     LAMEContext *s = avctx->priv_data;
59
60 #if FF_API_OLD_ENCODE_AUDIO
61     av_freep(&avctx->coded_frame);
62 #endif
63     av_freep(&s->samples_flt[0]);
64     av_freep(&s->samples_flt[1]);
65
66     ff_af_queue_close(&s->afq);
67
68     lame_close(s->gfp);
69     return 0;
70 }
71
72 static av_cold int mp3lame_encode_init(AVCodecContext *avctx)
73 {
74     LAMEContext *s = avctx->priv_data;
75     int ret;
76
77     s->avctx = avctx;
78
79     /* initialize LAME and get defaults */
80     if ((s->gfp = lame_init()) == NULL)
81         return AVERROR(ENOMEM);
82
83
84     lame_set_num_channels(s->gfp, avctx->channels);
85     lame_set_mode(s->gfp, avctx->channels > 1 ? JOINT_STEREO : MONO);
86
87     /* sample rate */
88     lame_set_in_samplerate (s->gfp, avctx->sample_rate);
89     lame_set_out_samplerate(s->gfp, avctx->sample_rate);
90
91     /* algorithmic quality */
92     if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
93         lame_set_quality(s->gfp, 5);
94     else
95         lame_set_quality(s->gfp, avctx->compression_level);
96
97     /* rate control */
98     if (avctx->flags & CODEC_FLAG_QSCALE) {
99         lame_set_VBR(s->gfp, vbr_default);
100         lame_set_VBR_quality(s->gfp, avctx->global_quality / (float)FF_QP2LAMBDA);
101     } else {
102         if (avctx->bit_rate)
103             lame_set_brate(s->gfp, avctx->bit_rate / 1000);
104     }
105
106     /* do not get a Xing VBR header frame from LAME */
107     lame_set_bWriteVbrTag(s->gfp,0);
108
109     /* bit reservoir usage */
110     lame_set_disable_reservoir(s->gfp, !s->reservoir);
111
112     /* set specified parameters */
113     if (lame_init_params(s->gfp) < 0) {
114         ret = -1;
115         goto error;
116     }
117
118     /* get encoder delay */
119     avctx->delay = lame_get_encoder_delay(s->gfp) + 528 + 1;
120     ff_af_queue_init(avctx, &s->afq);
121
122     avctx->frame_size  = lame_get_framesize(s->gfp);
123
124 #if FF_API_OLD_ENCODE_AUDIO
125     avctx->coded_frame = avcodec_alloc_frame();
126     if (!avctx->coded_frame) {
127         ret = AVERROR(ENOMEM);
128         goto error;
129     }
130 #endif
131
132     /* allocate float sample buffers */
133     if (avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
134         int ch;
135         for (ch = 0; ch < avctx->channels; ch++) {
136             s->samples_flt[ch] = av_malloc(avctx->frame_size *
137                                            sizeof(*s->samples_flt[ch]));
138             if (!s->samples_flt[ch]) {
139                 ret = AVERROR(ENOMEM);
140                 goto error;
141             }
142         }
143     }
144
145     ff_dsputil_init(&s->dsp, avctx);
146
147     return 0;
148 error:
149     mp3lame_encode_close(avctx);
150     return ret;
151 }
152
153 #define ENCODE_BUFFER(func, buf_type, buf_name) do {                        \
154     lame_result = func(s->gfp,                                              \
155                        (const buf_type *)buf_name[0],                       \
156                        (const buf_type *)buf_name[1], frame->nb_samples,    \
157                        s->buffer + s->buffer_index,                         \
158                        BUFFER_SIZE - s->buffer_index);                      \
159 } while (0)
160
161 static int mp3lame_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
162                                 const AVFrame *frame, int *got_packet_ptr)
163 {
164     LAMEContext *s = avctx->priv_data;
165     MPADecodeHeader hdr;
166     int len, ret, ch;
167     int lame_result;
168
169     if (frame) {
170         switch (avctx->sample_fmt) {
171         case AV_SAMPLE_FMT_S16P:
172             ENCODE_BUFFER(lame_encode_buffer, int16_t, frame->data);
173             break;
174         case AV_SAMPLE_FMT_S32P:
175             ENCODE_BUFFER(lame_encode_buffer_int, int32_t, frame->data);
176             break;
177         case AV_SAMPLE_FMT_FLTP:
178             if (frame->linesize[0] < 4 * FFALIGN(frame->nb_samples, 8)) {
179                 av_log(avctx, AV_LOG_ERROR, "inadequate AVFrame plane padding\n");
180                 return AVERROR(EINVAL);
181             }
182             for (ch = 0; ch < avctx->channels; ch++) {
183                 s->dsp.vector_fmul_scalar(s->samples_flt[ch],
184                                           (const float *)frame->data[ch],
185                                           32768.0f,
186                                           FFALIGN(frame->nb_samples, 8));
187             }
188             ENCODE_BUFFER(lame_encode_buffer_float, float, s->samples_flt);
189             break;
190         default:
191             return AVERROR_BUG;
192         }
193     } else {
194         lame_result = lame_encode_flush(s->gfp, s->buffer + s->buffer_index,
195                                         BUFFER_SIZE - s->buffer_index);
196     }
197     if (lame_result < 0) {
198         if (lame_result == -1) {
199             av_log(avctx, AV_LOG_ERROR,
200                    "lame: output buffer too small (buffer index: %d, free bytes: %d)\n",
201                    s->buffer_index, BUFFER_SIZE - s->buffer_index);
202         }
203         return -1;
204     }
205     s->buffer_index += lame_result;
206
207     /* add current frame to the queue */
208     if (frame) {
209         if ((ret = ff_af_queue_add(&s->afq, frame) < 0))
210             return ret;
211     }
212
213     /* Move 1 frame from the LAME buffer to the output packet, if available.
214        We have to parse the first frame header in the output buffer to
215        determine the frame size. */
216     if (s->buffer_index < 4)
217         return 0;
218     if (avpriv_mpegaudio_decode_header(&hdr, AV_RB32(s->buffer))) {
219         av_log(avctx, AV_LOG_ERROR, "free format output not supported\n");
220         return -1;
221     }
222     len = hdr.frame_size;
223     av_dlog(avctx, "in:%d packet-len:%d index:%d\n", avctx->frame_size, len,
224             s->buffer_index);
225     if (len <= s->buffer_index) {
226         if ((ret = ff_alloc_packet2(avctx, avpkt, len)))
227             return ret;
228         memcpy(avpkt->data, s->buffer, len);
229         s->buffer_index -= len;
230         memmove(s->buffer, s->buffer + len, s->buffer_index);
231
232         /* Get the next frame pts/duration */
233         ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
234                            &avpkt->duration);
235
236         avpkt->size = len;
237         *got_packet_ptr = 1;
238     }
239     return 0;
240 }
241
242 #define OFFSET(x) offsetof(LAMEContext, x)
243 #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
244 static const AVOption options[] = {
245     { "reservoir", "Use bit reservoir.", OFFSET(reservoir), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, AE },
246     { NULL },
247 };
248
249 static const AVClass libmp3lame_class = {
250     .class_name = "libmp3lame encoder",
251     .item_name  = av_default_item_name,
252     .option     = options,
253     .version    = LIBAVUTIL_VERSION_INT,
254 };
255
256 static const AVCodecDefault libmp3lame_defaults[] = {
257     { "b",          "0" },
258     { NULL },
259 };
260
261 static const int libmp3lame_sample_rates[] = {
262     44100, 48000,  32000, 22050, 24000, 16000, 11025, 12000, 8000, 0
263 };
264
265 AVCodec ff_libmp3lame_encoder = {
266     .name                  = "libmp3lame",
267     .type                  = AVMEDIA_TYPE_AUDIO,
268     .id                    = AV_CODEC_ID_MP3,
269     .priv_data_size        = sizeof(LAMEContext),
270     .init                  = mp3lame_encode_init,
271     .encode2               = mp3lame_encode_frame,
272     .close                 = mp3lame_encode_close,
273     .capabilities          = CODEC_CAP_DELAY | CODEC_CAP_SMALL_LAST_FRAME,
274     .sample_fmts           = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P,
275                                                              AV_SAMPLE_FMT_FLTP,
276                                                              AV_SAMPLE_FMT_S16P,
277                                                              AV_SAMPLE_FMT_NONE },
278     .supported_samplerates = libmp3lame_sample_rates,
279     .channel_layouts       = (const uint64_t[]) { AV_CH_LAYOUT_MONO,
280                                                   AV_CH_LAYOUT_STEREO,
281                                                   0 },
282     .long_name             = NULL_IF_CONFIG_SMALL("libmp3lame MP3 (MPEG audio layer 3)"),
283     .priv_class            = &libmp3lame_class,
284     .defaults              = libmp3lame_defaults,
285 };