]> git.sesse.net Git - ffmpeg/blob - libavcodec/libvorbis.c
Fix parser not to clobber has_b_frames when extradata is set.
[ffmpeg] / libavcodec / libvorbis.c
1 /*
2  * copyright (c) 2002 Mark Hills <mark@pogo.org.uk>
3  *
4  * This file is part of Libav.
5  *
6  * Libav 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  * Libav 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 Libav; 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;
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;
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 ((ret = vorbis_encode_setup_init(vi)))
116         goto error;
117
118     return 0;
119 error:
120     return vorbis_error_to_averror(ret);
121 }
122
123 /* How many bytes are needed for a buffer of length 'l' */
124 static int xiph_len(int l)
125 {
126     return 1 + l / 255 + l;
127 }
128
129 static av_cold int oggvorbis_encode_close(AVCodecContext *avccontext)
130 {
131     OggVorbisContext *context = avccontext->priv_data;
132 /*  ogg_packet op ; */
133
134     vorbis_analysis_wrote(&context->vd, 0);  /* notify vorbisenc this is EOF */
135
136     vorbis_block_clear(&context->vb);
137     vorbis_dsp_clear(&context->vd);
138     vorbis_info_clear(&context->vi);
139
140     av_freep(&avccontext->coded_frame);
141     av_freep(&avccontext->extradata);
142
143     return 0;
144 }
145
146 static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext)
147 {
148     OggVorbisContext *context = avccontext->priv_data;
149     ogg_packet header, header_comm, header_code;
150     uint8_t *p;
151     unsigned int offset;
152     int ret;
153
154     vorbis_info_init(&context->vi);
155     if ((ret = oggvorbis_init_encoder(&context->vi, avccontext))) {
156         av_log(avccontext, AV_LOG_ERROR, "oggvorbis_encode_init: init_encoder failed\n");
157         goto error;
158     }
159     if ((ret = vorbis_analysis_init(&context->vd, &context->vi))) {
160         ret = vorbis_error_to_averror(ret);
161         goto error;
162     }
163     if ((ret = vorbis_block_init(&context->vd, &context->vb))) {
164         ret = vorbis_error_to_averror(ret);
165         goto error;
166     }
167
168     vorbis_comment_init(&context->vc);
169     vorbis_comment_add_tag(&context->vc, "encoder", LIBAVCODEC_IDENT);
170
171     if ((ret = vorbis_analysis_headerout(&context->vd, &context->vc, &header,
172                                          &header_comm, &header_code))) {
173         ret = vorbis_error_to_averror(ret);
174         goto error;
175     }
176
177     avccontext->extradata_size =
178         1 + xiph_len(header.bytes) + xiph_len(header_comm.bytes) +
179         header_code.bytes;
180     p = avccontext->extradata =
181             av_malloc(avccontext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
182     if (!p) {
183         ret = AVERROR(ENOMEM);
184         goto error;
185     }
186     p[0]    = 2;
187     offset  = 1;
188     offset += av_xiphlacing(&p[offset], header.bytes);
189     offset += av_xiphlacing(&p[offset], header_comm.bytes);
190     memcpy(&p[offset], header.packet, header.bytes);
191     offset += header.bytes;
192     memcpy(&p[offset], header_comm.packet, header_comm.bytes);
193     offset += header_comm.bytes;
194     memcpy(&p[offset], header_code.packet, header_code.bytes);
195     offset += header_code.bytes;
196     assert(offset == avccontext->extradata_size);
197
198 #if 0
199     vorbis_block_clear(&context->vb);
200     vorbis_dsp_clear(&context->vd);
201     vorbis_info_clear(&context->vi);
202 #endif
203     vorbis_comment_clear(&context->vc);
204
205     avccontext->frame_size = OGGVORBIS_FRAME_SIZE;
206
207     avccontext->coded_frame = avcodec_alloc_frame();
208     if (!avccontext->coded_frame) {
209         ret = AVERROR(ENOMEM);
210         goto error;
211     }
212
213     return 0;
214 error:
215     oggvorbis_encode_close(avccontext);
216     return ret;
217 }
218
219 static int oggvorbis_encode_frame(AVCodecContext *avccontext,
220                                   unsigned char *packets,
221                                   int buf_size, void *data)
222 {
223     OggVorbisContext *context = avccontext->priv_data;
224     ogg_packet op;
225     signed short *audio = data;
226     int l;
227
228     if (data) {
229         const int samples = avccontext->frame_size;
230         float **buffer;
231         int c, channels = context->vi.channels;
232
233         buffer = vorbis_analysis_buffer(&context->vd, samples);
234         for (c = 0; c < channels; c++) {
235             int co = (channels > 8) ? c :
236                      ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
237             for (l = 0; l < samples; l++)
238                 buffer[c][l] = audio[l * channels + co] / 32768.f;
239         }
240         vorbis_analysis_wrote(&context->vd, samples);
241     } else {
242         if (!context->eof)
243             vorbis_analysis_wrote(&context->vd, 0);
244         context->eof = 1;
245     }
246
247     while (vorbis_analysis_blockout(&context->vd, &context->vb) == 1) {
248         vorbis_analysis(&context->vb, NULL);
249         vorbis_bitrate_addblock(&context->vb);
250
251         while (vorbis_bitrate_flushpacket(&context->vd, &op)) {
252             /* i'd love to say the following line is a hack, but sadly it's
253              * not, apparently the end of stream decision is in libogg. */
254             if (op.bytes == 1 && op.e_o_s)
255                 continue;
256             if (context->buffer_index + sizeof(ogg_packet) + op.bytes > BUFFER_SIZE) {
257                 av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.");
258                 return -1;
259             }
260             memcpy(context->buffer + context->buffer_index, &op, sizeof(ogg_packet));
261             context->buffer_index += sizeof(ogg_packet);
262             memcpy(context->buffer + context->buffer_index, op.packet, op.bytes);
263             context->buffer_index += op.bytes;
264 //            av_log(avccontext, AV_LOG_DEBUG, "e%d / %d\n", context->buffer_index, op.bytes);
265         }
266     }
267
268     l = 0;
269     if (context->buffer_index) {
270         ogg_packet *op2 = (ogg_packet *)context->buffer;
271         op2->packet = context->buffer + sizeof(ogg_packet);
272
273         l = op2->bytes;
274         avccontext->coded_frame->pts = ff_samples_to_time_base(avccontext,
275                                                                op2->granulepos);
276         //FIXME we should reorder the user supplied pts and not assume that they are spaced by 1/sample_rate
277
278         if (l > buf_size) {
279             av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.");
280             return -1;
281         }
282
283         memcpy(packets, op2->packet, l);
284         context->buffer_index -= l + sizeof(ogg_packet);
285         memmove(context->buffer, context->buffer + l + sizeof(ogg_packet), context->buffer_index);
286 //        av_log(avccontext, AV_LOG_DEBUG, "E%d\n", l);
287     }
288
289     return l;
290 }
291
292 AVCodec ff_libvorbis_encoder = {
293     .name           = "libvorbis",
294     .type           = AVMEDIA_TYPE_AUDIO,
295     .id             = CODEC_ID_VORBIS,
296     .priv_data_size = sizeof(OggVorbisContext),
297     .init           = oggvorbis_encode_init,
298     .encode         = oggvorbis_encode_frame,
299     .close          = oggvorbis_encode_close,
300     .capabilities   = CODEC_CAP_DELAY,
301     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE },
302     .long_name      = NULL_IF_CONFIG_SMALL("libvorbis Vorbis"),
303     .priv_class     = &class,
304 };