libavformat/mp3enc.c
Go to the documentation of this file.
00001 /*
00002  * MP3 muxer
00003  * Copyright (c) 2003 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "avformat.h"
00023 #include "avio_internal.h"
00024 #include "id3v1.h"
00025 #include "id3v2.h"
00026 #include "rawenc.h"
00027 #include "libavutil/avstring.h"
00028 #include "libavcodec/mpegaudio.h"
00029 #include "libavcodec/mpegaudiodata.h"
00030 #include "libavcodec/mpegaudiodecheader.h"
00031 #include "libavutil/intreadwrite.h"
00032 #include "libavutil/opt.h"
00033 #include "libavcodec/mpegaudio.h"
00034 #include "libavcodec/mpegaudiodata.h"
00035 #include "libavcodec/mpegaudiodecheader.h"
00036 #include "libavformat/avio_internal.h"
00037 #include "libavutil/dict.h"
00038 
00039 static int id3v1_set_string(AVFormatContext *s, const char *key,
00040                             uint8_t *buf, int buf_size)
00041 {
00042     AVDictionaryEntry *tag;
00043     if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
00044         av_strlcpy(buf, tag->value, buf_size);
00045     return !!tag;
00046 }
00047 
00048 static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
00049 {
00050     AVDictionaryEntry *tag;
00051     int i, count = 0;
00052 
00053     memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
00054     buf[0] = 'T';
00055     buf[1] = 'A';
00056     buf[2] = 'G';
00057     /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */
00058     count += id3v1_set_string(s, "TIT2",    buf +  3, 30 + 1);       //title
00059     count += id3v1_set_string(s, "TPE1",    buf + 33, 30 + 1);       //author|artist
00060     count += id3v1_set_string(s, "TALB",    buf + 63, 30 + 1);       //album
00061     count += id3v1_set_string(s, "TDRL",    buf + 93,  4 + 1);       //date
00062     count += id3v1_set_string(s, "comment", buf + 97, 30 + 1);
00063     if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
00064         buf[125] = 0;
00065         buf[126] = atoi(tag->value);
00066         count++;
00067     }
00068     buf[127] = 0xFF; /* default to unknown genre */
00069     if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
00070         for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
00071             if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
00072                 buf[127] = i;
00073                 count++;
00074                 break;
00075             }
00076         }
00077     }
00078     return count;
00079 }
00080 
00081 #define VBR_NUM_BAGS 400
00082 #define VBR_TOC_SIZE 100
00083 
00084 typedef struct MP3Context {
00085     const AVClass *class;
00086     int id3v2_version;
00087     int write_id3v1;
00088     int64_t frames_offset;
00089     int32_t frames;
00090     int32_t size;
00091     uint32_t want;
00092     uint32_t seen;
00093     uint32_t pos;
00094     uint64_t bag[VBR_NUM_BAGS];
00095 } MP3Context;
00096 
00097 static int mp2_write_trailer(struct AVFormatContext *s)
00098 {
00099     uint8_t buf[ID3v1_TAG_SIZE];
00100     MP3Context *mp3 = s->priv_data;
00101 
00102     /* write the id3v1 tag */
00103     if (mp3 && mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
00104         avio_write(s->pb, buf, ID3v1_TAG_SIZE);
00105     }
00106 
00107     /* write number of frames */
00108     if (mp3 && mp3->frames_offset) {
00109         avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
00110         avio_wb32(s->pb, s->streams[0]->nb_frames);
00111         avio_seek(s->pb, 0, SEEK_END);
00112     }
00113 
00114     avio_flush(s->pb);
00115 
00116     return 0;
00117 }
00118 
00119 #if CONFIG_MP2_MUXER
00120 AVOutputFormat ff_mp2_muxer = {
00121     .name              = "mp2",
00122     .long_name         = NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
00123     .mime_type         = "audio/x-mpeg",
00124     .extensions        = "mp2,m2a",
00125     .audio_codec       = CODEC_ID_MP2,
00126     .video_codec       = CODEC_ID_NONE,
00127     .write_packet      = ff_raw_write_packet,
00128     .write_trailer     = mp2_write_trailer,
00129     .flags             = AVFMT_NOTIMESTAMPS,
00130 };
00131 #endif
00132 
00133 #if CONFIG_MP3_MUXER
00134 
00135 static const AVOption options[] = {
00136     { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
00137       offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
00138     { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
00139       offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
00140     { NULL },
00141 };
00142 
00143 static const AVClass mp3_muxer_class = {
00144     .class_name     = "MP3 muxer",
00145     .item_name      = av_default_item_name,
00146     .option         = options,
00147     .version        = LIBAVUTIL_VERSION_INT,
00148 };
00149 
00150 static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
00151 
00152 /*
00153  * Write an empty XING header and initialize respective data.
00154  */
00155 static int mp3_write_xing(AVFormatContext *s)
00156 {
00157     AVCodecContext   *codec = s->streams[0]->codec;
00158     MP3Context       *mp3 = s->priv_data;
00159     int              bitrate_idx;
00160     int              best_bitrate_idx;
00161     int              best_bitrate_error= INT_MAX;
00162     int64_t          xing_offset;
00163     int32_t          header, mask;
00164     MPADecodeHeader  c;
00165     int              srate_idx, i, channels;
00166     int              needed;
00167 
00168     for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++)
00169         if (avpriv_mpa_freq_tab[i] == codec->sample_rate) {
00170             srate_idx = i;
00171             break;
00172         }
00173     if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
00174         av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
00175         return -1;
00176     }
00177 
00178     switch (codec->channels) {
00179     case 1:  channels = MPA_MONO;                                          break;
00180     case 2:  channels = MPA_STEREO;                                        break;
00181     default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
00182     }
00183 
00184     /* dummy MPEG audio header */
00185     header  =  0xff                                  << 24; // sync
00186     header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
00187     header |= (srate_idx << 2) <<  8;
00188     header |= channels << 6;
00189 
00190     for (bitrate_idx=1; bitrate_idx<15; bitrate_idx++) {
00191         int error;
00192         avpriv_mpegaudio_decode_header(&c, header | (bitrate_idx << (4+8)));
00193         error= FFABS(c.bit_rate - codec->bit_rate);
00194         if(error < best_bitrate_error){
00195             best_bitrate_error= error;
00196             best_bitrate_idx  = bitrate_idx;
00197         }
00198     }
00199 
00200     for (bitrate_idx= best_bitrate_idx;; bitrate_idx++) {
00201         if (15 == bitrate_idx)
00202             return -1;
00203         mask = bitrate_idx << (4+8);
00204         header |= mask;
00205         avpriv_mpegaudio_decode_header(&c, header);
00206         xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
00207         needed = 4              // header
00208                + xing_offset
00209                + 4              // xing tag
00210                + 4              // frames/size/toc flags
00211                + 4              // frames
00212                + 4              // size
00213                + VBR_TOC_SIZE;  // toc
00214 
00215         if (needed <= c.frame_size)
00216             break;
00217         header &= ~mask;
00218     }
00219 
00220     avio_wb32(s->pb, header);
00221     ffio_fill(s->pb, 0, xing_offset);
00222     avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
00223     avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames/size/toc
00224 
00225     mp3->frames_offset = avio_tell(s->pb);
00226     mp3->size = c.frame_size;
00227     mp3->want=1;
00228     mp3->seen=0;
00229     mp3->pos=0;
00230 
00231     avio_wb32(s->pb, 0);  // frames
00232     avio_wb32(s->pb, 0);  // size
00233 
00234     // toc
00235     for (i = 0; i < VBR_TOC_SIZE; ++i)
00236         avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
00237 
00238     ffio_fill(s->pb, 0, c.frame_size - needed);
00239     avio_flush(s->pb);
00240 
00241     return 0;
00242 }
00243 
00244 /*
00245  * Add a frame to XING data.
00246  * Following lame's "VbrTag.c".
00247  */
00248 static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
00249 {
00250     MP3Context  *mp3 = s->priv_data;
00251     int i;
00252 
00253     ++mp3->frames;
00254     mp3->size += pkt->size;
00255 
00256     if (mp3->want == ++mp3->seen) {
00257         mp3->bag[mp3->pos] = mp3->size;
00258 
00259         if (VBR_NUM_BAGS == ++mp3->pos) {
00260             /* shrink table to half size by throwing away each second bag. */
00261             for (i = 1; i < VBR_NUM_BAGS; i += 2)
00262                 mp3->bag[i >> 1] = mp3->bag[i];
00263 
00264             /* double wanted amount per bag. */
00265             mp3->want <<= 1;
00266             /* adjust current position to half of table size. */
00267             mp3->pos >>= 1;
00268         }
00269 
00270         mp3->seen = 0;
00271     }
00272 }
00273 
00274 static void mp3_fix_xing(AVFormatContext *s)
00275 {
00276     MP3Context  *mp3 = s->priv_data;
00277     int i;
00278 
00279     avio_flush(s->pb);
00280     avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
00281     avio_wb32(s->pb, mp3->frames);
00282     avio_wb32(s->pb, mp3->size);
00283 
00284     avio_w8(s->pb, 0);  // first toc entry has to be zero.
00285 
00286     for (i = 1; i < VBR_TOC_SIZE; ++i) {
00287         int j = i * mp3->pos / VBR_TOC_SIZE;
00288         int seek_point = 256LL * mp3->bag[j] / mp3->size;
00289         avio_w8(s->pb, FFMIN(seek_point, 255));
00290     }
00291 
00292     avio_flush(s->pb);
00293     avio_seek(s->pb, 0, SEEK_END);
00294 }
00295 
00300 static int mp3_write_header(struct AVFormatContext *s)
00301 {
00302     MP3Context  *mp3 = s->priv_data;
00303     int ret;
00304 
00305     ret = ff_id3v2_write(s, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
00306     if (ret < 0)
00307         return ret;
00308 
00309     if (s->pb->seekable)
00310         mp3_write_xing(s);
00311 
00312     return 0;
00313 }
00314 
00315 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
00316 {
00317     if (! pkt || ! pkt->data || pkt->size < 4)
00318         return ff_raw_write_packet(s, pkt);
00319     else {
00320         MP3Context  *mp3 = s->priv_data;
00321 #ifdef FILTER_VBR_HEADERS
00322         MPADecodeHeader c;
00323         int base;
00324 
00325         ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
00326 
00327         /* filter out XING and INFO headers. */
00328         base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
00329 
00330         if (base + 4 <= pkt->size) {
00331             uint32_t v = AV_RB32(pkt->data + base);
00332 
00333             if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
00334                 return 0;
00335         }
00336 
00337         /* filter out VBRI headers. */
00338         base = 4 + 32;
00339 
00340         if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
00341             return 0;
00342 #endif
00343 
00344         if (mp3->frames_offset)
00345             mp3_xing_add_frame(s, pkt);
00346 
00347         return ff_raw_write_packet(s, pkt);
00348     }
00349 }
00350 
00351 static int mp3_write_trailer(AVFormatContext *s)
00352 {
00353     MP3Context  *mp3 = s->priv_data;
00354     int ret=mp2_write_trailer(s);
00355 
00356     if (ret < 0)
00357         return ret;
00358 
00359     if (mp3->frames_offset)
00360         mp3_fix_xing(s);
00361 
00362     return 0;
00363 }
00364 
00365 AVOutputFormat ff_mp3_muxer = {
00366     .name              = "mp3",
00367     .long_name         = NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
00368     .mime_type         = "audio/x-mpeg",
00369     .extensions        = "mp3",
00370     .priv_data_size    = sizeof(MP3Context),
00371     .audio_codec       = CODEC_ID_MP3,
00372     .video_codec       = CODEC_ID_NONE,
00373     .write_header      = mp3_write_header,
00374     .write_packet      = mp3_write_packet,
00375     .write_trailer     = mp3_write_trailer,
00376     .flags             = AVFMT_NOTIMESTAMPS,
00377     .priv_class = &mp3_muxer_class,
00378 };
00379 #endif