libavcodec/libvorbis.c
Go to the documentation of this file.
00001 /*
00002  * copyright (c) 2002 Mark Hills <mark@pogo.org.uk>
00003  *
00004  * This file is part of FFmpeg.
00005  *
00006  * FFmpeg is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * FFmpeg is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with FFmpeg; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00027 #include <vorbis/vorbisenc.h>
00028 
00029 #include "libavutil/opt.h"
00030 #include "avcodec.h"
00031 #include "bytestream.h"
00032 #include "vorbis.h"
00033 #include "libavutil/mathematics.h"
00034 
00035 #undef NDEBUG
00036 #include <assert.h>
00037 
00038 #define OGGVORBIS_FRAME_SIZE 64
00039 
00040 #define BUFFER_SIZE (1024 * 64)
00041 
00042 typedef struct OggVorbisContext {
00043     AVClass *av_class;
00044     vorbis_info vi;
00045     vorbis_dsp_state vd;
00046     vorbis_block vb;
00047     uint8_t buffer[BUFFER_SIZE];
00048     int buffer_index;
00049     int eof;
00050 
00051     /* decoder */
00052     vorbis_comment vc;
00053     ogg_packet op;
00054 
00055     double iblock;
00056 } OggVorbisContext;
00057 
00058 static const AVOption options[] = {
00059     { "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 },
00060     { NULL }
00061 };
00062 static const AVClass class = { "libvorbis", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
00063 
00064 static const char * error(int oggerr, int *averr)
00065 {
00066     switch (oggerr) {
00067         case OV_EFAULT: *averr = AVERROR(EFAULT); return "internal error";
00068         case OV_EIMPL:  *averr = AVERROR(EINVAL); return "not supported";
00069         case OV_EINVAL: *averr = AVERROR(EINVAL); return "invalid request";
00070         default:        *averr = AVERROR(EINVAL); return "unknown error";
00071     }
00072 }
00073 
00074 static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avccontext)
00075 {
00076     OggVorbisContext *context = avccontext->priv_data;
00077     double cfreq;
00078     int r;
00079 
00080     if (avccontext->flags & CODEC_FLAG_QSCALE) {
00081         /* variable bitrate */
00082         float quality = avccontext->global_quality / (float)FF_QP2LAMBDA;
00083         r = vorbis_encode_setup_vbr(vi, avccontext->channels,
00084                                     avccontext->sample_rate,
00085                                     quality / 10.0);
00086         if (r) {
00087             av_log(avccontext, AV_LOG_ERROR,
00088                    "Unable to set quality to %g: %s\n", quality, error(r, &r));
00089             return r;
00090         }
00091     } else {
00092         int minrate = avccontext->rc_min_rate > 0 ? avccontext->rc_min_rate : -1;
00093         int maxrate = avccontext->rc_min_rate > 0 ? avccontext->rc_max_rate : -1;
00094 
00095         /* constant bitrate */
00096         r = vorbis_encode_setup_managed(vi, avccontext->channels,
00097                                         avccontext->sample_rate, minrate,
00098                                         avccontext->bit_rate, maxrate);
00099         if (r) {
00100             av_log(avccontext, AV_LOG_ERROR,
00101                    "Unable to set CBR to %d: %s\n", avccontext->bit_rate,
00102                    error(r, &r));
00103             return r;
00104         }
00105 
00106         /* variable bitrate by estimate, disable slow rate management */
00107         if (minrate == -1 && maxrate == -1)
00108             if (vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, NULL))
00109                 return AVERROR(EINVAL); /* should not happen */
00110     }
00111 
00112     /* cutoff frequency */
00113     if (avccontext->cutoff > 0) {
00114         cfreq = avccontext->cutoff / 1000.0;
00115         if (vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &cfreq))
00116             return AVERROR(EINVAL); /* should not happen */
00117     }
00118 
00119     if (context->iblock) {
00120         vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &context->iblock);
00121     }
00122 
00123     if (avccontext->channels == 3 &&
00124             avccontext->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
00125         avccontext->channels == 4 &&
00126             avccontext->channel_layout != AV_CH_LAYOUT_2_2 &&
00127             avccontext->channel_layout != AV_CH_LAYOUT_QUAD ||
00128         avccontext->channels == 5 &&
00129             avccontext->channel_layout != AV_CH_LAYOUT_5POINT0 &&
00130             avccontext->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
00131         avccontext->channels == 6 &&
00132             avccontext->channel_layout != AV_CH_LAYOUT_5POINT1 &&
00133             avccontext->channel_layout != AV_CH_LAYOUT_5POINT1_BACK ||
00134         avccontext->channels == 7 &&
00135             avccontext->channel_layout != (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER) ||
00136         avccontext->channels == 8 &&
00137             avccontext->channel_layout != AV_CH_LAYOUT_7POINT1) {
00138         if (avccontext->channel_layout) {
00139             char name[32];
00140             av_get_channel_layout_string(name, sizeof(name), avccontext->channels,
00141                                          avccontext->channel_layout);
00142             av_log(avccontext, AV_LOG_ERROR, "%s not supported by Vorbis: "
00143                                              "output stream will have incorrect "
00144                                              "channel layout.\n", name);
00145         } else {
00146             av_log(avccontext, AV_LOG_WARNING, "No channel layout specified. The encoder "
00147                                                "will use Vorbis channel layout for "
00148                                                "%d channels.\n", avccontext->channels);
00149         }
00150     }
00151 
00152     return vorbis_encode_setup_init(vi);
00153 }
00154 
00155 /* How many bytes are needed for a buffer of length 'l' */
00156 static int xiph_len(int l)
00157 {
00158     return 1 + l / 255 + l;
00159 }
00160 
00161 static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext)
00162 {
00163     OggVorbisContext *context = avccontext->priv_data;
00164     ogg_packet header, header_comm, header_code;
00165     uint8_t *p;
00166     unsigned int offset;
00167     int r;
00168 
00169     vorbis_info_init(&context->vi);
00170     r = oggvorbis_init_encoder(&context->vi, avccontext);
00171     if (r < 0) {
00172         av_log(avccontext, AV_LOG_ERROR, "oggvorbis_encode_init failed\n");
00173         return r;
00174     }
00175     vorbis_analysis_init(&context->vd, &context->vi);
00176     vorbis_block_init(&context->vd, &context->vb);
00177 
00178     vorbis_comment_init(&context->vc);
00179     vorbis_comment_add_tag(&context->vc, "encoder", LIBAVCODEC_IDENT);
00180 
00181     vorbis_analysis_headerout(&context->vd, &context->vc, &header,
00182                               &header_comm, &header_code);
00183 
00184     avccontext->extradata_size =
00185         1 + xiph_len(header.bytes) + xiph_len(header_comm.bytes) +
00186         header_code.bytes;
00187     p = avccontext->extradata =
00188             av_malloc(avccontext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
00189     p[0]    = 2;
00190     offset  = 1;
00191     offset += av_xiphlacing(&p[offset], header.bytes);
00192     offset += av_xiphlacing(&p[offset], header_comm.bytes);
00193     memcpy(&p[offset], header.packet, header.bytes);
00194     offset += header.bytes;
00195     memcpy(&p[offset], header_comm.packet, header_comm.bytes);
00196     offset += header_comm.bytes;
00197     memcpy(&p[offset], header_code.packet, header_code.bytes);
00198     offset += header_code.bytes;
00199     assert(offset == avccontext->extradata_size);
00200 
00201 #if 0
00202     vorbis_block_clear(&context->vb);
00203     vorbis_dsp_clear(&context->vd);
00204     vorbis_info_clear(&context->vi);
00205 #endif
00206     vorbis_comment_clear(&context->vc);
00207 
00208     avccontext->frame_size = OGGVORBIS_FRAME_SIZE;
00209 
00210     avccontext->coded_frame = avcodec_alloc_frame();
00211     avccontext->coded_frame->key_frame = 1;
00212 
00213     return 0;
00214 }
00215 
00216 static int oggvorbis_encode_frame(AVCodecContext *avccontext,
00217                                   unsigned char *packets,
00218                                   int buf_size, void *data)
00219 {
00220     OggVorbisContext *context = avccontext->priv_data;
00221     ogg_packet op;
00222     signed short *audio = data;
00223     int l;
00224 
00225     if (data) {
00226         const int samples = avccontext->frame_size;
00227         float **buffer;
00228         int c, channels = context->vi.channels;
00229 
00230         buffer = vorbis_analysis_buffer(&context->vd, samples);
00231         for (c = 0; c < channels; c++) {
00232             int co = (channels > 8) ? c :
00233                      ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];
00234             for (l = 0; l < samples; l++)
00235                 buffer[c][l] = audio[l * channels + co] / 32768.f;
00236         }
00237         vorbis_analysis_wrote(&context->vd, samples);
00238     } else {
00239         if (!context->eof)
00240             vorbis_analysis_wrote(&context->vd, 0);
00241         context->eof = 1;
00242     }
00243 
00244     while (vorbis_analysis_blockout(&context->vd, &context->vb) == 1) {
00245         vorbis_analysis(&context->vb, NULL);
00246         vorbis_bitrate_addblock(&context->vb);
00247 
00248         while (vorbis_bitrate_flushpacket(&context->vd, &op)) {
00249             /* i'd love to say the following line is a hack, but sadly it's
00250              * not, apparently the end of stream decision is in libogg. */
00251             if (op.bytes == 1 && op.e_o_s)
00252                 continue;
00253             if (context->buffer_index + sizeof(ogg_packet) + op.bytes > BUFFER_SIZE) {
00254                 av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.\n");
00255                 return AVERROR(EINVAL);
00256             }
00257             memcpy(context->buffer + context->buffer_index, &op, sizeof(ogg_packet));
00258             context->buffer_index += sizeof(ogg_packet);
00259             memcpy(context->buffer + context->buffer_index, op.packet, op.bytes);
00260             context->buffer_index += op.bytes;
00261 //            av_log(avccontext, AV_LOG_DEBUG, "e%d / %d\n", context->buffer_index, op.bytes);
00262         }
00263     }
00264 
00265     l = 0;
00266     if (context->buffer_index) {
00267         ogg_packet *op2 = (ogg_packet *)context->buffer;
00268         op2->packet = context->buffer + sizeof(ogg_packet);
00269 
00270         l = op2->bytes;
00271         avccontext->coded_frame->pts = av_rescale_q(op2->granulepos, (AVRational) { 1, avccontext->sample_rate }, avccontext->time_base);
00272         //FIXME we should reorder the user supplied pts and not assume that they are spaced by 1/sample_rate
00273 
00274         if (l > buf_size) {
00275             av_log(avccontext, AV_LOG_ERROR, "libvorbis: buffer overflow.\n");
00276             return AVERROR(EINVAL);
00277         }
00278 
00279         memcpy(packets, op2->packet, l);
00280         context->buffer_index -= l + sizeof(ogg_packet);
00281         memmove(context->buffer, context->buffer + l + sizeof(ogg_packet), context->buffer_index);
00282 //        av_log(avccontext, AV_LOG_DEBUG, "E%d\n", l);
00283     }
00284 
00285     return l;
00286 }
00287 
00288 static av_cold int oggvorbis_encode_close(AVCodecContext *avccontext)
00289 {
00290     OggVorbisContext *context = avccontext->priv_data;
00291 /*  ogg_packet op ; */
00292 
00293     vorbis_analysis_wrote(&context->vd, 0);  /* notify vorbisenc this is EOF */
00294 
00295     vorbis_block_clear(&context->vb);
00296     vorbis_dsp_clear(&context->vd);
00297     vorbis_info_clear(&context->vi);
00298 
00299     av_freep(&avccontext->coded_frame);
00300     av_freep(&avccontext->extradata);
00301 
00302     return 0;
00303 }
00304 
00305 AVCodec ff_libvorbis_encoder = {
00306     .name           = "libvorbis",
00307     .type           = AVMEDIA_TYPE_AUDIO,
00308     .id             = CODEC_ID_VORBIS,
00309     .priv_data_size = sizeof(OggVorbisContext),
00310     .init           = oggvorbis_encode_init,
00311     .encode         = oggvorbis_encode_frame,
00312     .close          = oggvorbis_encode_close,
00313     .capabilities   = CODEC_CAP_DELAY,
00314     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE },
00315     .long_name      = NULL_IF_CONFIG_SMALL("libvorbis Vorbis"),
00316     .priv_class     = &class,
00317 };