]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3enc.c
Check mp3 header before calling avpriv_mpegaudio_decode_header().
[ffmpeg] / libavformat / mp3enc.c
1 /*
2  * MP3 muxer
3  * Copyright (c) 2003 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "avformat.h"
23 #include "avio_internal.h"
24 #include "id3v1.h"
25 #include "id3v2.h"
26 #include "rawenc.h"
27 #include "libavutil/avstring.h"
28 #include "libavcodec/mpegaudio.h"
29 #include "libavcodec/mpegaudiodata.h"
30 #include "libavcodec/mpegaudiodecheader.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/dict.h"
34 #include "libavutil/avassert.h"
35
36 static int id3v1_set_string(AVFormatContext *s, const char *key,
37                             uint8_t *buf, int buf_size)
38 {
39     AVDictionaryEntry *tag;
40     if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
41         av_strlcpy(buf, tag->value, buf_size);
42     return !!tag;
43 }
44
45 static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
46 {
47     AVDictionaryEntry *tag;
48     int i, count = 0;
49
50     memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
51     buf[0] = 'T';
52     buf[1] = 'A';
53     buf[2] = 'G';
54     count += id3v1_set_string(s, "TIT2",    buf +  3, 30);       //title
55     count += id3v1_set_string(s, "TPE1",    buf + 33, 30);       //author|artist
56     count += id3v1_set_string(s, "TALB",    buf + 63, 30);       //album
57     count += id3v1_set_string(s, "TDRL",    buf + 93,  4);       //date
58     count += id3v1_set_string(s, "comment", buf + 97, 30);
59     if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
60         buf[125] = 0;
61         buf[126] = atoi(tag->value);
62         count++;
63     }
64     buf[127] = 0xFF; /* default to unknown genre */
65     if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
66         for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
67             if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
68                 buf[127] = i;
69                 count++;
70                 break;
71             }
72         }
73     }
74     return count;
75 }
76
77 #define XING_NUM_BAGS 400
78 #define XING_TOC_SIZE 100
79 // maximum size of the xing frame: offset/Xing/flags/frames/size/TOC
80 #define XING_MAX_SIZE (32 + 4 + 4 + 4 + 4 + XING_TOC_SIZE)
81
82 typedef struct MP3Context {
83     const AVClass *class;
84     ID3v2EncContext id3;
85     int id3v2_version;
86     int write_id3v1;
87     int write_xing;
88
89     /* xing header */
90     int64_t xing_offset;
91     int32_t frames;
92     int32_t size;
93     uint32_t want;
94     uint32_t seen;
95     uint32_t pos;
96     uint64_t bag[XING_NUM_BAGS];
97     int initial_bitrate;
98     int has_variable_bitrate;
99
100     /* index of the audio stream */
101     int audio_stream_idx;
102     /* number of attached pictures we still need to write */
103     int pics_to_write;
104
105     /* audio packets are queued here until we get all the attached pictures */
106     AVPacketList *queue, *queue_end;
107 } MP3Context;
108
109 static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
110
111 /*
112  * Write an empty XING header and initialize respective data.
113  */
114 static void mp3_write_xing(AVFormatContext *s)
115 {
116     MP3Context       *mp3 = s->priv_data;
117     AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;
118     int32_t        header;
119     MPADecodeHeader  mpah;
120     int srate_idx, i, channels;
121     int bitrate_idx;
122     int best_bitrate_idx;
123     int best_bitrate_error = INT_MAX;
124     int xing_offset;
125     int ver = 0;
126     int lsf, bytes_needed;
127
128     if (!s->pb->seekable || !mp3->write_xing)
129         return;
130
131     for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
132         const uint16_t base_freq = avpriv_mpa_freq_tab[i];
133
134         if      (codec->sample_rate == base_freq)     ver = 0x3; // MPEG 1
135         else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
136         else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
137         else continue;
138
139         srate_idx = i;
140         break;
141     }
142     if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
143         av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing "
144                "header.\n");
145         return;
146     }
147
148     switch (codec->channels) {
149     case 1:  channels = MPA_MONO;                                          break;
150     case 2:  channels = MPA_STEREO;                                        break;
151     default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
152                     "not writing Xing header.\n");
153              return;
154     }
155
156     /* dummy MPEG audio header */
157     header  =  0xff                                  << 24; // sync
158     header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
159     header |= (srate_idx << 2) << 8;
160     header |= channels << 6;
161
162     lsf = !((header & (1 << 20) && header & (1 << 19)));
163
164     xing_offset  = xing_offtbl[ver != 3][channels == 1];
165     bytes_needed = 4              // header
166                  + xing_offset
167                  + 4              // xing tag
168                  + 4              // frames/size/toc flags
169                  + 4              // frames
170                  + 4              // size
171                  + XING_TOC_SIZE; // toc
172
173     for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
174         int bit_rate = 1000 * avpriv_mpa_bitrate_tab[lsf][3 - 1][bitrate_idx];
175         int error    = FFABS(bit_rate - codec->bit_rate);
176
177         if (error < best_bitrate_error){
178             best_bitrate_error = error;
179             best_bitrate_idx   = bitrate_idx;
180         }
181     }
182
183     for (bitrate_idx = best_bitrate_idx; bitrate_idx < 15; bitrate_idx++) {
184         int32_t mask = bitrate_idx << (4 + 8);
185         header |= mask;
186
187         avpriv_mpegaudio_decode_header(&mpah, header);
188
189         if (bytes_needed <= mpah.frame_size)
190             break;
191
192         header &= ~mask;
193     }
194
195     avio_wb32(s->pb, header);
196
197     avpriv_mpegaudio_decode_header(&mpah, header);
198
199     av_assert0(mpah.frame_size >= XING_MAX_SIZE);
200
201     ffio_fill(s->pb, 0, xing_offset);
202     mp3->xing_offset = avio_tell(s->pb);
203     ffio_wfourcc(s->pb, "Xing");
204     avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames / size / TOC
205
206     mp3->size = mpah.frame_size;
207     mp3->want = 1;
208
209     avio_wb32(s->pb, 0);  // frames
210     avio_wb32(s->pb, 0);  // size
211
212     // TOC
213     for (i = 0; i < XING_TOC_SIZE; i++)
214         avio_w8(s->pb, 255 * i / XING_TOC_SIZE);
215
216     ffio_fill(s->pb, 0, mpah.frame_size - bytes_needed);
217 }
218
219 /*
220  * Add a frame to XING data.
221  * Following lame's "VbrTag.c".
222  */
223 static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
224 {
225     int i;
226
227     mp3->frames++;
228     mp3->seen++;
229     mp3->size += pkt->size;
230
231     if (mp3->want == mp3->seen) {
232         mp3->bag[mp3->pos] = mp3->size;
233
234         if (XING_NUM_BAGS == ++mp3->pos) {
235             /* shrink table to half size by throwing away each second bag. */
236             for (i = 1; i < XING_NUM_BAGS; i += 2)
237                 mp3->bag[i / 2] = mp3->bag[i];
238
239             /* double wanted amount per bag. */
240             mp3->want *= 2;
241             /* adjust current position to half of table size. */
242             mp3->pos = XING_NUM_BAGS / 2;
243         }
244
245         mp3->seen = 0;
246     }
247 }
248
249 static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
250 {
251     MP3Context  *mp3 = s->priv_data;
252
253     if (mp3->xing_offset && pkt->size >= 4) {
254         MPADecodeHeader c;
255         uint32_t h;
256
257         h = AV_RB32(pkt->data);
258         if (ff_mpa_check_header(h) == 0) {
259             avpriv_mpegaudio_decode_header(&c, h);
260             if (!mp3->initial_bitrate)
261                 mp3->initial_bitrate = c.bit_rate;
262             if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
263                 mp3->has_variable_bitrate = 1;
264         }
265
266         mp3_xing_add_frame(mp3, pkt);
267     }
268
269     return ff_raw_write_packet(s, pkt);
270 }
271
272 static int mp3_queue_flush(AVFormatContext *s)
273 {
274     MP3Context *mp3 = s->priv_data;
275     AVPacketList *pktl;
276     int ret = 0, write = 1;
277
278     ff_id3v2_finish(&mp3->id3, s->pb);
279     mp3_write_xing(s);
280
281     while ((pktl = mp3->queue)) {
282         if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
283             write = 0;
284         av_free_packet(&pktl->pkt);
285         mp3->queue = pktl->next;
286         av_freep(&pktl);
287     }
288     mp3->queue_end = NULL;
289     return ret;
290 }
291
292 static void mp3_update_xing(AVFormatContext *s)
293 {
294     MP3Context  *mp3 = s->priv_data;
295     int i;
296
297     /* replace "Xing" identification string with "Info" for CBR files. */
298     if (!mp3->has_variable_bitrate) {
299         avio_seek(s->pb, mp3->xing_offset, SEEK_SET);
300         ffio_wfourcc(s->pb, "Info");
301     }
302
303     avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);
304     avio_wb32(s->pb, mp3->frames);
305     avio_wb32(s->pb, mp3->size);
306
307     avio_w8(s->pb, 0);  // first toc entry has to be zero.
308
309     for (i = 1; i < XING_TOC_SIZE; ++i) {
310         int j = i * mp3->pos / XING_TOC_SIZE;
311         int seek_point = 256LL * mp3->bag[j] / mp3->size;
312         avio_w8(s->pb, FFMIN(seek_point, 255));
313     }
314
315     avio_seek(s->pb, 0, SEEK_END);
316 }
317
318 static int mp3_write_trailer(struct AVFormatContext *s)
319 {
320     uint8_t buf[ID3v1_TAG_SIZE];
321     MP3Context *mp3 = s->priv_data;
322
323     if (mp3->pics_to_write) {
324         av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
325                "attached pictures.\n");
326         mp3_queue_flush(s);
327     }
328
329     /* write the id3v1 tag */
330     if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
331         avio_write(s->pb, buf, ID3v1_TAG_SIZE);
332     }
333
334     if (mp3->xing_offset)
335         mp3_update_xing(s);
336
337     return 0;
338 }
339
340 #if CONFIG_MP2_MUXER
341 AVOutputFormat ff_mp2_muxer = {
342     .name              = "mp2",
343     .long_name         = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
344     .mime_type         = "audio/x-mpeg",
345     .extensions        = "mp2,m2a,mpa",
346     .audio_codec       = AV_CODEC_ID_MP2,
347     .video_codec       = AV_CODEC_ID_NONE,
348     .write_packet      = ff_raw_write_packet,
349     .flags             = AVFMT_NOTIMESTAMPS,
350 };
351 #endif
352
353 #if CONFIG_MP3_MUXER
354
355 static const AVOption options[] = {
356     { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
357       offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
358     { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
359       offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
360     { "write_xing",  "Write the Xing header containing file duration.",
361       offsetof(MP3Context, write_xing),  AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
362     { NULL },
363 };
364
365 static const AVClass mp3_muxer_class = {
366     .class_name     = "MP3 muxer",
367     .item_name      = av_default_item_name,
368     .option         = options,
369     .version        = LIBAVUTIL_VERSION_INT,
370 };
371
372 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
373 {
374     MP3Context *mp3 = s->priv_data;
375
376     if (pkt->stream_index == mp3->audio_stream_idx) {
377         if (mp3->pics_to_write) {
378             /* buffer audio packets until we get all the pictures */
379             AVPacketList *pktl = av_mallocz(sizeof(*pktl));
380             if (!pktl)
381                 return AVERROR(ENOMEM);
382
383             pktl->pkt     = *pkt;
384             pktl->pkt.buf = av_buffer_ref(pkt->buf);
385             if (!pktl->pkt.buf) {
386                 av_freep(&pktl);
387                 return AVERROR(ENOMEM);
388             }
389
390             if (mp3->queue_end)
391                 mp3->queue_end->next = pktl;
392             else
393                 mp3->queue = pktl;
394             mp3->queue_end = pktl;
395         } else
396             return mp3_write_audio_packet(s, pkt);
397     } else {
398         int ret;
399
400         /* warn only once for each stream */
401         if (s->streams[pkt->stream_index]->nb_frames == 1) {
402             av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
403                    " ignoring.\n", pkt->stream_index);
404         }
405         if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
406             return 0;
407
408         if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
409             return ret;
410         mp3->pics_to_write--;
411
412         /* flush the buffered audio packets */
413         if (!mp3->pics_to_write &&
414             (ret = mp3_queue_flush(s)) < 0)
415             return ret;
416     }
417
418     return 0;
419 }
420
421 /**
422  * Write an ID3v2 header at beginning of stream
423  */
424
425 static int mp3_write_header(struct AVFormatContext *s)
426 {
427     MP3Context  *mp3 = s->priv_data;
428     int ret, i;
429
430     if (mp3->id3v2_version      &&
431         mp3->id3v2_version != 3 &&
432         mp3->id3v2_version != 4) {
433         av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
434                "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
435         return AVERROR(EINVAL);
436     }
437
438     /* check the streams -- we want exactly one audio and arbitrary number of
439      * video (attached pictures) */
440     mp3->audio_stream_idx = -1;
441     for (i = 0; i < s->nb_streams; i++) {
442         AVStream *st = s->streams[i];
443         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
444             if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
445                 av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
446                        "audio stream is required.\n");
447                 return AVERROR(EINVAL);
448             }
449             mp3->audio_stream_idx = i;
450         } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
451             av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
452             return AVERROR(EINVAL);
453         }
454     }
455     if (mp3->audio_stream_idx < 0) {
456         av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
457         return AVERROR(EINVAL);
458     }
459     mp3->pics_to_write = s->nb_streams - 1;
460
461     if (mp3->pics_to_write && !mp3->id3v2_version) {
462         av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
463                "ID3v2 header is disabled.\n");
464         return AVERROR(EINVAL);
465     }
466
467     if (mp3->id3v2_version) {
468         ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
469         ret = ff_id3v2_write_metadata(s, &mp3->id3);
470         if (ret < 0)
471             return ret;
472     }
473
474     if (!mp3->pics_to_write) {
475         if (mp3->id3v2_version)
476             ff_id3v2_finish(&mp3->id3, s->pb);
477         mp3_write_xing(s);
478     }
479
480     return 0;
481 }
482
483 AVOutputFormat ff_mp3_muxer = {
484     .name              = "mp3",
485     .long_name         = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
486     .mime_type         = "audio/x-mpeg",
487     .extensions        = "mp3",
488     .priv_data_size    = sizeof(MP3Context),
489     .audio_codec       = AV_CODEC_ID_MP3,
490     .video_codec       = AV_CODEC_ID_PNG,
491     .write_header      = mp3_write_header,
492     .write_packet      = mp3_write_packet,
493     .write_trailer     = mp3_write_trailer,
494     .flags             = AVFMT_NOTIMESTAMPS,
495     .priv_class        = &mp3_muxer_class,
496 };
497 #endif