• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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 <strings.h>
00023 #include "avformat.h"
00024 #include "id3v1.h"
00025 #include "id3v2.h"
00026 #include "rawenc.h"
00027 #include "libavutil/avstring.h"
00028 #include "libavutil/intreadwrite.h"
00029 #include "libavutil/opt.h"
00030 #include "libavcodec/mpegaudio.h"
00031 #include "libavcodec/mpegaudiodata.h"
00032 #include "libavcodec/mpegaudiodecheader.h"
00033 #include "libavformat/avio_internal.h"
00034 #include "libavutil/dict.h"
00035 
00036 static int id3v1_set_string(AVFormatContext *s, const char *key,
00037                             uint8_t *buf, int buf_size)
00038 {
00039     AVDictionaryEntry *tag;
00040     if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
00041         av_strlcpy(buf, tag->value, buf_size);
00042     return !!tag;
00043 }
00044 
00045 static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
00046 {
00047     AVDictionaryEntry *tag;
00048     int i, count = 0;
00049 
00050     memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
00051     buf[0] = 'T';
00052     buf[1] = 'A';
00053     buf[2] = 'G';
00054     /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */
00055     count += id3v1_set_string(s, "TIT2",    buf +  3, 30 + 1);       //title
00056     count += id3v1_set_string(s, "TPE1",    buf + 33, 30 + 1);       //author|artist
00057     count += id3v1_set_string(s, "TALB",    buf + 63, 30 + 1);       //album
00058     count += id3v1_set_string(s, "TDRL",    buf + 93,  4 + 1);       //date
00059     count += id3v1_set_string(s, "comment", buf + 97, 30 + 1);
00060     if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
00061         buf[125] = 0;
00062         buf[126] = atoi(tag->value);
00063         count++;
00064     }
00065     buf[127] = 0xFF; /* default to unknown genre */
00066     if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
00067         for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
00068             if (!strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
00069                 buf[127] = i;
00070                 count++;
00071                 break;
00072             }
00073         }
00074     }
00075     return count;
00076 }
00077 
00078 /* simple formats */
00079 
00080 static void id3v2_put_size(AVFormatContext *s, int size)
00081 {
00082     avio_w8(s->pb, size >> 21 & 0x7f);
00083     avio_w8(s->pb, size >> 14 & 0x7f);
00084     avio_w8(s->pb, size >> 7  & 0x7f);
00085     avio_w8(s->pb, size       & 0x7f);
00086 }
00087 
00088 static int string_is_ascii(const uint8_t *str)
00089 {
00090     while (*str && *str < 128) str++;
00091     return !*str;
00092 }
00093 
00099 static int id3v2_put_ttag(AVFormatContext *s, const char *str1, const char *str2,
00100                           uint32_t tag, enum ID3v2Encoding enc)
00101 {
00102     int len;
00103     uint8_t *pb;
00104     int (*put)(AVIOContext*, const char*);
00105     AVIOContext *dyn_buf;
00106     if (avio_open_dyn_buf(&dyn_buf) < 0)
00107         return AVERROR(ENOMEM);
00108 
00109     /* check if the strings are ASCII-only and use UTF16 only if
00110      * they're not */
00111     if (enc == ID3v2_ENCODING_UTF16BOM && string_is_ascii(str1) &&
00112         (!str2 || string_is_ascii(str2)))
00113         enc = ID3v2_ENCODING_ISO8859;
00114 
00115     avio_w8(dyn_buf, enc);
00116     if (enc == ID3v2_ENCODING_UTF16BOM) {
00117         avio_wl16(dyn_buf, 0xFEFF);      /* BOM */
00118         put = avio_put_str16le;
00119     } else
00120         put = avio_put_str;
00121 
00122     put(dyn_buf, str1);
00123     if (str2)
00124         put(dyn_buf, str2);
00125     len = avio_close_dyn_buf(dyn_buf, &pb);
00126 
00127     avio_wb32(s->pb, tag);
00128     id3v2_put_size(s, len);
00129     avio_wb16(s->pb, 0);
00130     avio_write(s->pb, pb, len);
00131 
00132     av_freep(&pb);
00133     return len + ID3v2_HEADER_SIZE;
00134 }
00135 
00136 static int mp2_write_trailer(struct AVFormatContext *s)
00137 {
00138     uint8_t buf[ID3v1_TAG_SIZE];
00139 
00140     /* write the id3v1 tag */
00141     if (id3v1_create_tag(s, buf) > 0) {
00142         avio_write(s->pb, buf, ID3v1_TAG_SIZE);
00143         avio_flush(s->pb);
00144     }
00145     return 0;
00146 }
00147 
00148 #if CONFIG_MP2_MUXER
00149 AVOutputFormat ff_mp2_muxer = {
00150     "mp2",
00151     NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
00152     "audio/x-mpeg",
00153     "mp2,m2a",
00154     0,
00155     CODEC_ID_MP2,
00156     CODEC_ID_NONE,
00157     NULL,
00158     ff_raw_write_packet,
00159     mp2_write_trailer,
00160 };
00161 #endif
00162 
00163 #if CONFIG_MP3_MUXER
00164 #define VBR_NUM_BAGS 400
00165 #define VBR_TOC_SIZE 100
00166 typedef struct MP3Context {
00167     const AVClass *class;
00168     int id3v2_version;
00169     int64_t frames_offset;
00170     int32_t frames;
00171     int32_t size;
00172     uint32_t want;
00173     uint32_t seen;
00174     uint32_t pos;
00175     uint64_t bag[VBR_NUM_BAGS];
00176 } MP3Context;
00177 
00178 static const AVOption options[] = {
00179     { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
00180       offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
00181     { NULL },
00182 };
00183 
00184 static const AVClass mp3_muxer_class = {
00185     .class_name     = "MP3 muxer",
00186     .item_name      = av_default_item_name,
00187     .option         = options,
00188     .version        = LIBAVUTIL_VERSION_INT,
00189 };
00190 
00191 static int id3v2_check_write_tag(AVFormatContext *s, AVDictionaryEntry *t, const char table[][4],
00192                                  enum ID3v2Encoding enc)
00193 {
00194     uint32_t tag;
00195     int i;
00196 
00197     if (t->key[0] != 'T' || strlen(t->key) != 4)
00198         return -1;
00199     tag = AV_RB32(t->key);
00200     for (i = 0; *table[i]; i++)
00201         if (tag == AV_RB32(table[i]))
00202             return id3v2_put_ttag(s, t->value, NULL, tag, enc);
00203     return -1;
00204 }
00205 
00206 static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
00207 
00208 /*
00209  * Write an empty XING header and initialize respective data.
00210  */
00211 static int mp3_write_xing(AVFormatContext *s)
00212 {
00213     AVCodecContext   *codec = s->streams[0]->codec;
00214     MP3Context       *mp3 = s->priv_data;
00215     int              bitrate_idx = 3;
00216     int64_t          xing_offset;
00217     int32_t          mask, header;
00218     MPADecodeHeader  c;
00219     int              srate_idx, i, channels;
00220     int              needed;
00221 
00222     for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
00223         if (ff_mpa_freq_tab[i] == codec->sample_rate) {
00224             srate_idx = i;
00225             break;
00226         }
00227     if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
00228         av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
00229         return -1;
00230     }
00231 
00232     switch (codec->channels) {
00233     case 1:  channels = MPA_MONO;                                          break;
00234     case 2:  channels = MPA_STEREO;                                        break;
00235     default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
00236     }
00237 
00238     /* dummy MPEG audio header */
00239     header  =  0xff                                  << 24; // sync
00240     header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
00241     header |= (srate_idx << 2) <<  8;
00242     header |= channels << 6;
00243 
00244     for (;;) {
00245         if (15 == bitrate_idx)
00246             return -1;
00247 
00248         mask = (bitrate_idx << 4) <<  8;
00249         header |= mask;
00250         ff_mpegaudio_decode_header(&c, header);
00251         xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
00252         needed = 4              // header
00253                + xing_offset
00254                + 4              // xing tag
00255                + 4              // frames/size/toc flags
00256                + 4              // frames
00257                + 4              // size
00258                + VBR_TOC_SIZE;  // toc
00259 
00260         if (needed <= c.frame_size)
00261             break;
00262 
00263         header &= ~mask;
00264         ++bitrate_idx;
00265     }
00266 
00267     avio_wb32(s->pb, header);
00268     ffio_fill(s->pb, 0, xing_offset);
00269     avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
00270     avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames/size/toc
00271 
00272     mp3->frames_offset = avio_tell(s->pb);
00273     mp3->size = c.frame_size;
00274     mp3->want=1;
00275     mp3->seen=0;
00276     mp3->pos=0;
00277 
00278     avio_wb32(s->pb, 0);  // frames
00279     avio_wb32(s->pb, 0);  // size
00280 
00281     // toc
00282     for (i = 0; i < VBR_TOC_SIZE; ++i)
00283         avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
00284 
00285     ffio_fill(s->pb, 0, c.frame_size - needed);
00286     avio_flush(s->pb);
00287 
00288     return 0;
00289 }
00290 
00291 /*
00292  * Add a frame to XING data.
00293  * Following lame's "VbrTag.c".
00294  */
00295 static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
00296 {
00297     MP3Context  *mp3 = s->priv_data;
00298     int i;
00299 
00300     ++mp3->frames;
00301     mp3->size += pkt->size;
00302 
00303     if (mp3->want == ++mp3->seen) {
00304         mp3->bag[mp3->pos] = mp3->size;
00305 
00306         if (VBR_NUM_BAGS == ++mp3->pos) {
00307             /* shrink table to half size by throwing away each second bag. */
00308             for (i = 1; i < VBR_NUM_BAGS; i += 2)
00309                 mp3->bag[i >> 1] = mp3->bag[i];
00310 
00311             /* double wanted amount per bag. */
00312             mp3->want <<= 1;
00313             /* adjust current position to half of table size. */
00314             mp3->pos >>= 1;
00315         }
00316 
00317         mp3->seen = 0;
00318     }
00319 }
00320 
00321 static void mp3_fix_xing(AVFormatContext *s)
00322 {
00323     MP3Context  *mp3 = s->priv_data;
00324     int i;
00325 
00326     avio_flush(s->pb);
00327     avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
00328     avio_wb32(s->pb, mp3->frames);
00329     avio_wb32(s->pb, mp3->size);
00330 
00331     avio_w8(s->pb, 0);  // first toc entry has to be zero.
00332 
00333     for (i = 1; i < VBR_TOC_SIZE; ++i) {
00334         int j = i * mp3->pos / VBR_TOC_SIZE;
00335         int seek_point = 256LL * mp3->bag[j] / mp3->size;
00336         avio_w8(s->pb, FFMIN(seek_point, 255));
00337     }
00338 
00339     avio_flush(s->pb);
00340     avio_seek(s->pb, 0, SEEK_END);
00341 }
00342 
00347 static int mp3_write_header(struct AVFormatContext *s)
00348 {
00349     MP3Context  *mp3 = s->priv_data;
00350     AVDictionaryEntry *t = NULL;
00351     int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
00352                                                     ID3v2_ENCODING_UTF8;
00353     int64_t size_pos, cur_pos;
00354 
00355     avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
00356     avio_w8(s->pb, 0);
00357     avio_w8(s->pb, 0); /* flags */
00358 
00359     /* reserve space for size */
00360     size_pos = avio_tell(s->pb);
00361     avio_wb32(s->pb, 0);
00362 
00363     ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
00364     if (mp3->id3v2_version == 4)
00365         ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
00366 
00367     while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) {
00368         int ret;
00369 
00370         if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
00371             totlen += ret;
00372             continue;
00373         }
00374         if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
00375                                                ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
00376             totlen += ret;
00377             continue;
00378         }
00379 
00380         /* unknown tag, write as TXXX frame */
00381         if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
00382             return ret;
00383         totlen += ret;
00384     }
00385 
00386     cur_pos = avio_tell(s->pb);
00387     avio_seek(s->pb, size_pos, SEEK_SET);
00388     id3v2_put_size(s, totlen);
00389     avio_seek(s->pb, cur_pos, SEEK_SET);
00390 
00391     if (s->pb->seekable)
00392         mp3_write_xing(s);
00393 
00394     return 0;
00395 }
00396 
00397 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
00398 {
00399     if (! pkt || ! pkt->data || pkt->size < 4)
00400         return ff_raw_write_packet(s, pkt);
00401     else {
00402         MP3Context  *mp3 = s->priv_data;
00403 #ifdef FILTER_VBR_HEADERS
00404         MPADecodeHeader c;
00405         int base;
00406 
00407         ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
00408 
00409         /* filter out XING and INFO headers. */
00410         base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
00411 
00412         if (base + 4 <= pkt->size) {
00413             uint32_t v = AV_RB32(pkt->data + base);
00414 
00415             if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
00416                 return 0;
00417         }
00418 
00419         /* filter out VBRI headers. */
00420         base = 4 + 32;
00421 
00422         if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
00423             return 0;
00424 #endif
00425 
00426         if (mp3->frames_offset)
00427             mp3_xing_add_frame(s, pkt);
00428 
00429         return ff_raw_write_packet(s, pkt);
00430     }
00431 }
00432 
00433 static int mp3_write_trailer(AVFormatContext *s)
00434 {
00435     MP3Context  *mp3 = s->priv_data;
00436     int ret=mp2_write_trailer(s);
00437 
00438     if (ret < 0)
00439         return ret;
00440 
00441     if (mp3->frames_offset)
00442         mp3_fix_xing(s);
00443 
00444     return 0;
00445 }
00446 
00447 AVOutputFormat ff_mp3_muxer = {
00448     "mp3",
00449     NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
00450     "audio/x-mpeg",
00451     "mp3",
00452     sizeof(MP3Context),
00453     CODEC_ID_MP3,
00454     CODEC_ID_NONE,
00455     mp3_write_header,
00456     mp3_write_packet,
00457     mp3_write_trailer,
00458     AVFMT_NOTIMESTAMPS,
00459     .priv_class = &mp3_muxer_class,
00460 };
00461 #endif

Generated on Wed Apr 11 2012 07:31:36 for FFmpeg by  doxygen 1.7.1