]> git.sesse.net Git - ffmpeg/blob - libavcodec/libvorbis.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / libvorbis.c
1 /*
2  * copyright (c) 2002 Mark Hills <mark@pogo.org.uk>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg 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  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Ogg Vorbis codec support via libvorbisenc.
24  * @author Mark Hills <mark@pogo.org.uk>
25  */
26
27 #include <vorbis/vorbisenc.h>
28
29 #include "libavutil/opt.h"
30 #include "avcodec.h"
31 #include "bytestream.h"
32 #include "internal.h"
33 #include "vorbis.h"
34
35 #undef NDEBUG
36 #include <assert.h>
37
38 #define OGGVORBIS_FRAME_SIZE 64
39
40 #define BUFFER_SIZE (1024 * 64)
41
42 typedef struct OggVorbisContext {
43     AVClass *av_class;
44     vorbis_info vi;
45     vorbis_dsp_state vd;
46     vorbis_block vb;
47     uint8_t buffer[BUFFER_SIZE];
48     int buffer_index;
49     int eof;
50
51     /* decoder */
52     vorbis_comment vc;
53     ogg_packet op;
54
55     double iblock;
56 } OggVorbisContext;
57
58 static const AVOption options[] = {
59     { "iblock", "Sets the impulse block bias", offsetof(OggVorbisContext, iblock), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -15, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
60     { NULL }
61 };
62 static const AVClass class = { "libvorbis", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
63
64 static int vorbis_error_to_averror(int ov_err)
65 {
66     switch (ov_err) {
67     case OV_EFAULT: return AVERROR_BUG;
68     case OV_EINVAL: return AVERROR(EINVAL);
69     case OV_EIMPL:  return AVERROR(EINVAL);
70     default:        return AVERROR_UNKNOWN;
71     }
72 }
73
74 static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avccontext)
75 {
76     OggVorbisContext *context = avccontext->priv_data;
77     double cfreq;
78     int ret;
79
80     if (avccontext->flags & CODEC_FLAG_QSCALE) {
81         /* variable bitrate */
82         float q = avccontext->global_quality / (float)FF_QP2LAMBDA;
83         if ((ret = vorbis_encode_setup_vbr(vi, avccontext->channels,
84                                            avccontext->sample_rate,
85                                            q / 10.0)))
86             goto error;
87     } else {
88         int minrate = avccontext->rc_min_rate > 0 ? avccontext->rc_min_rate : -1;
89         int maxrate = avccontext->rc_min_rate > 0 ? avccontext->rc_max_rate : -1;
90
91         /* constant bitrate */
92         if ((ret = vorbis_encode_setup_managed(vi, avccontext->channels,
93                                                avccontext->sample_rate, minrate,
94                                                avccontext->bit_rate, maxrate)))
95             goto error;
96
97         /* variable bitrate by estimate, disable slow rate management */
98         if (minrate == -1 && maxrate == -1)
99             if ((ret = vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL)))
100                 goto error; /* should not happen */
101     }
102
103     /* cutoff frequency */
104     if (avccontext->cutoff > 0) {
105         cfreq = avccontext->cutoff / 1000.0;
106         if ((ret = vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &cfreq)))
107             goto error; /* should not happen */
108     }
109
110     if (context->iblock) {
111         if ((ret = vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &context->iblock)))
112             goto error;
113     }
114
115     if (avccontext->channels == 3 &&
116             avccontext->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
117         avccontext->channels == 4 &&
118             avccontext->channel_layout != AV_CH_LAYOUT_2_2 &&
119             avccontext->channel_layout != AV_CH_LAYOUT_QUAD ||
120         avccontext->channels == 5 &&
121             avccontext->channel_layout != AV_CH_LAYOUT_5POINT0 &&
122             avccontext->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
123         avccontext->channels == 6 &&
124             avccontext->channel_layout != AV_CH_LAYOUT_5POINT1 &&
125             avccontext->channel_layout != AV_CH_LAYOUT_5POINT1_BACK ||
126         avccontext->channels == 7 &&
127             avccontext->channel_layout != (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER) ||
128         avccontext->channels == 8 &&
129             avccontext->channel_layout != AV_CH_LAYOUT_7POINT1) {
130         if (avccontext->channel_layout) {
131             char name[32];
132             av_get_channel_layout_string(name, sizeof(name), avccontext->channels,
133                                          avccontext->channel_layout);
134             av_log(avccontext, AV_LOG_ERROR, "%s not supported by Vorbis: "
135                                              "output stream will have incorrect "
136                                              "channel layout.\n", name);
137         } else {
138             av_log(avccontext, AV_LOG_WARNING, "No channel layout specified. The encoder "
139                                                "will use Vorbis channel layout for "
140                                                "%d channels.\n", avccontext->channels);
141         }
142     }
143
144     if ((ret = vorbis_encode_setup_init(vi)))
145         goto error;
146
147     return 0;
148 error:
149     return vorbis_error_to_averror(ret);
150 }
151
152 /* How many bytes are needed for a buffer of length 'l' */
153 static int xiph_len(int l)
154 {
155     return 1 + l / 255 + l;
156 }
157
158 static av_cold int oggvorbis_encode_close(AVCodecContext *avccontext)
159 {
160     OggVorbisContext *context = avccontext->priv_data;
161 /*  ogg_packet op ; */
162
163     vorbis_analysis_wrote(&context->vd, 0);  /* notify vorbisenc this is EOF */
164
165     vorbis_block_clear(&context->vb);
166     vorbis_dsp_clear(&context->vd);
167     vorbis_info_clear(&context->vi);
168
169     av_freep(&avccontext->coded_frame);
170     av_freep(&avccontext->extradata);
171
172     return 0;
173 }
174
175 static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext)
176 {
177     OggVorbisContext *context = avccontext->priv_data;
178     ogg_packet header, header_comm, header_code;
179     uint8_t *p;
180     unsigned int offset;
181     int ret;
182
183     vorbis_info_init(&context->vi);
184     if ((ret = oggvorbis_init_encoder(&context->vi, avccontext))) {
185         av_log(avccontext, AV_LOG_ERROR, "oggvorbis_encode_init: init_encoder failed\n");
186         goto error;
187     }
188     if ((ret = vorbis_analysis_init(&context->vd, &context->vi))) {
189         ret = vorbis_error_to_averror(ret);
190         goto error;
191     }
192     if ((ret = vorbis_block_init(&context->vd, &context->vb))) {
193         ret = vorbis_error_to_averror(ret);
194         goto error;
195     }
196
197     vorbis_comment_init(&context->vc);
198     vorbis_comment_add_tag(&context->vc, "encoder", LIBAVCODEC_IDENT);
199
200     if ((ret = vorbis_analysis_headerout(&context->vd, &context->vc, &header,
201                                          &header_comm, &header_code))) {
202         ret = vorbis_error_to_averror(ret);
203         goto error;
204     }
205
206     avccontext->extradata_size =
207         1 + xiph_len(header.bytes) + xiph_len(header_comm.bytes) +
208         header_code.bytes;
209     p = avccontext->extradata =
210             av_malloc(avccontext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
211     if (!p) {
212         ret = AVERROR(ENOMEM);
213         goto error;
214     }
215     p[0]    = 2;
216     offset  = 1;
217     offset += av_xiphlacing(&p[offset], header.bytes);
218     offset += av_xiphlacing(&p[offset], header_comm.bytes);
219     memcpy(&p[offset], header.packet, header.bytes);
220     offset += header.bytes;
221     memcpy(&p[offset], header_comm.packet, header_comm.bytes);
222     offset += header_comm.bytes;
223     memcpy(&p[offset], header_code.packet, header_code.bytes);
224     offset += header_code.bytes;
225     assert(offset == avccontext->extradata_size);
226
227 #if 0
228     vorbis_block_clear(&context->vb);
229     vorbis_dsp_clear(&context->vd);
230     vorbis_info_clear(&context->vi);
231 #endif
232     vorbis_comment_clear(&context->vc);
233
234     avccontext->frame_size = OGGVORBIS_FRAME_SIZE;
235
236     avccontext->coded_frame = avcodec_alloc_frame();
237     if (!avccontext->coded_frame) {
238         ret = AVERROR(ENOMEM);
239         goto error;
240     }
241
242     return 0;
243 error:
244     oggvorbis_encode_close(avccontext);
245     return ret;
246 }
247
248 static int oggvorbis_encode_frame(AVCodecContext *avccontext,
249                                   unsigned char *packets,
250                                   int buf_size, void *data)
251 {
252     OggVorbisContext *context = avccontext->priv_data;
253     ogg_packet op;
254     signed short *audio = data;
255     int l;
256
257     if (data) {
258         const int samples = avccontext->frame_size;
259         float **buffer;
260         int c, channels = context->vi.channels;
261
262         buffer = vorbis_analysis_buffer(&context->vd, samples);
263         for (c = 0; c < channels; c++) {
264             int co = (channels > 8) ? c :
265                      ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
266             for (l = 0; l < samples; l++)
267                 buffer[c][l] = audio[l * channels + co] / 32768.f;
268         }
269         vorbis_analysis_wrote(&context->vd, samples);
270     } else {
271         if (!context->eof)
272             vorbis_analysis_wrote(&context->vd, 0);
273         context->eof = 1;
274     }
275
276     while (vorbis_analysis_blockout(&context->vd, &context->vb) == 1) {
277         vorbis_analysis(&context->vb, NULL);
278         vorbis_bitrate_addblock(&context->vb);
279
280         while (vorbis_bitrate_flushpacket(&context->vd, &op)) {
281             /* i'd love to say the following line is a hack, but sadly it's
282              * not, apparently the end of stream decision is in libogg. */
283             if (op.bytes == 1 && op.e_o_s)
284                 continue;
285             if (context->buffer_index + sizeof(ogg_packet) + op.bytes > BUFFER_SIZE) {
286                 av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.\n");
287                 return AVERROR(EINVAL);
288             }
289             memcpy(context->buffer + context->buffer_index, &op, sizeof(ogg_packet));
290             context->buffer_index += sizeof(ogg_packet);
291             memcpy(context->buffer + context->buffer_index, op.packet, op.bytes);
292             context->buffer_index += op.bytes;
293 //            av_log(avccontext, AV_LOG_DEBUG, "e%d / %d\n", context->buffer_index, op.bytes);
294         }
295     }
296
297     l = 0;
298     if (context->buffer_index) {
299         ogg_packet *op2 = (ogg_packet *)context->buffer;
300         op2->packet = context->buffer + sizeof(ogg_packet);
301
302         l = op2->bytes;
303         avccontext->coded_frame->pts = ff_samples_to_time_base(avccontext,
304                                                                op2->granulepos);
305         //FIXME we should reorder the user supplied pts and not assume that they are spaced by 1/sample_rate
306
307         if (l > buf_size) {
308             av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.\n");
309             return AVERROR(EINVAL);
310         }
311
312         memcpy(packets, op2->packet, l);
313         context->buffer_index -= l + sizeof(ogg_packet);
314         memmove(context->buffer, context->buffer + l + sizeof(ogg_packet), context->buffer_index);
315 //        av_log(avccontext, AV_LOG_DEBUG, "E%d\n", l);
316     }
317
318     return l;
319 }
320
321 AVCodec ff_libvorbis_encoder = {
322     .name           = "libvorbis",
323     .type           = AVMEDIA_TYPE_AUDIO,
324     .id             = CODEC_ID_VORBIS,
325     .priv_data_size = sizeof(OggVorbisContext),
326     .init           = oggvorbis_encode_init,
327     .encode         = oggvorbis_encode_frame,
328     .close          = oggvorbis_encode_close,
329     .capabilities   = CODEC_CAP_DELAY,
330     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE },
331     .long_name      = NULL_IF_CONFIG_SMALL("libvorbis Vorbis"),
332     .priv_class     = &class,
333 };