OSDN Git Service

rtpdec: Don't pass non-const pointers to fmtp attribute parsing functions
[android-x86/external-ffmpeg.git] / 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 #include "libavutil/crc.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/replaygain.h"
38
39 static int id3v1_set_string(AVFormatContext *s, const char *key,
40                             uint8_t *buf, int buf_size)
41 {
42     AVDictionaryEntry *tag;
43     if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
44         av_strlcpy(buf, tag->value, buf_size);
45     return !!tag;
46 }
47
48 static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
49 {
50     AVDictionaryEntry *tag;
51     int i, count = 0;
52
53     memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
54     buf[0] = 'T';
55     buf[1] = 'A';
56     buf[2] = 'G';
57     count += id3v1_set_string(s, "TIT2",    buf +  3, 30);       //title
58     count += id3v1_set_string(s, "TPE1",    buf + 33, 30);       //author|artist
59     count += id3v1_set_string(s, "TALB",    buf + 63, 30);       //album
60     count += id3v1_set_string(s, "TDRL",    buf + 93,  4);       //date
61     count += id3v1_set_string(s, "comment", buf + 97, 30);
62     if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
63         buf[125] = 0;
64         buf[126] = atoi(tag->value);
65         count++;
66     }
67     buf[127] = 0xFF; /* default to unknown genre */
68     if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
69         for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
70             if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
71                 buf[127] = i;
72                 count++;
73                 break;
74             }
75         }
76     }
77     return count;
78 }
79
80 #define XING_NUM_BAGS 400
81 #define XING_TOC_SIZE 100
82 // size of the XING/LAME data, starting from the Xing tag
83 #define XING_SIZE 156
84
85 typedef struct MP3Context {
86     const AVClass *class;
87     ID3v2EncContext id3;
88     int id3v2_version;
89     int write_id3v1;
90     int write_xing;
91
92     /* xing header */
93     // a buffer containing the whole XING/LAME frame
94     uint8_t *xing_frame;
95     int      xing_frame_size;
96
97     AVCRC    audio_crc;     // CRC of the audio data
98     uint32_t audio_size;    // total size of the audio data
99
100     // offset of the XING/LAME frame in the file
101     int64_t  xing_frame_offset;
102     // offset of the XING/INFO tag in the frame
103     int xing_offset;
104
105     int32_t frames;
106     int32_t size;
107     uint32_t want;
108     uint32_t seen;
109     uint32_t pos;
110     uint64_t bag[XING_NUM_BAGS];
111     int initial_bitrate;
112     int has_variable_bitrate;
113
114     /* index of the audio stream */
115     int audio_stream_idx;
116     /* number of attached pictures we still need to write */
117     int pics_to_write;
118
119     /* audio packets are queued here until we get all the attached pictures */
120     AVPacketList *queue, *queue_end;
121 } MP3Context;
122
123 static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
124
125 /*
126  * Write an empty XING header and initialize respective data.
127  */
128 static void mp3_write_xing(AVFormatContext *s)
129 {
130     MP3Context       *mp3 = s->priv_data;
131     AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;
132     AVDictionaryEntry *enc = av_dict_get(s->streams[mp3->audio_stream_idx]->metadata, "encoder", NULL, 0);
133     AVIOContext *dyn_ctx;
134     int32_t        header;
135     MPADecodeHeader  mpah;
136     int srate_idx, i, channels;
137     int bitrate_idx;
138     int best_bitrate_idx;
139     int best_bitrate_error = INT_MAX;
140     int ret;
141     int ver = 0;
142     int lsf, bytes_needed;
143
144     if (!s->pb->seekable || !mp3->write_xing)
145         return;
146
147     for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
148         const uint16_t base_freq = avpriv_mpa_freq_tab[i];
149
150         if      (codec->sample_rate == base_freq)     ver = 0x3; // MPEG 1
151         else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
152         else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
153         else continue;
154
155         srate_idx = i;
156         break;
157     }
158     if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
159         av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing "
160                "header.\n");
161         return;
162     }
163
164     switch (codec->channels) {
165     case 1:  channels = MPA_MONO;                                          break;
166     case 2:  channels = MPA_STEREO;                                        break;
167     default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
168                     "not writing Xing header.\n");
169              return;
170     }
171
172     /* dummy MPEG audio header */
173     header  =  0xff                                  << 24; // sync
174     header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
175     header |= (srate_idx << 2) << 8;
176     header |= channels << 6;
177
178     lsf = !((header & (1 << 20) && header & (1 << 19)));
179
180     mp3->xing_offset = xing_offtbl[ver != 3][channels == 1] + 4;
181     bytes_needed     = mp3->xing_offset + XING_SIZE;
182
183     for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
184         int bit_rate = 1000 * avpriv_mpa_bitrate_tab[lsf][3 - 1][bitrate_idx];
185         int error    = FFABS(bit_rate - codec->bit_rate);
186
187         if (error < best_bitrate_error){
188             best_bitrate_error = error;
189             best_bitrate_idx   = bitrate_idx;
190         }
191     }
192
193     for (bitrate_idx = best_bitrate_idx; bitrate_idx < 15; bitrate_idx++) {
194         int32_t mask = bitrate_idx << (4 + 8);
195         header |= mask;
196
197         avpriv_mpegaudio_decode_header(&mpah, header);
198
199         if (bytes_needed <= mpah.frame_size)
200             break;
201
202         header &= ~mask;
203     }
204
205     ret = avio_open_dyn_buf(&dyn_ctx);
206     if (ret < 0)
207         return;
208
209     avio_wb32(dyn_ctx, header);
210
211     avpriv_mpegaudio_decode_header(&mpah, header);
212
213     av_assert0(mpah.frame_size >= bytes_needed);
214
215     ffio_fill(dyn_ctx, 0, mp3->xing_offset - 4);
216     ffio_wfourcc(dyn_ctx, "Xing");
217     avio_wb32(dyn_ctx, 0x01 | 0x02 | 0x04 | 0x08);  // frames / size / TOC / vbr scale
218
219     mp3->size = mpah.frame_size;
220     mp3->want = 1;
221
222     avio_wb32(dyn_ctx, 0);  // frames
223     avio_wb32(dyn_ctx, 0);  // size
224
225     // TOC
226     for (i = 0; i < XING_TOC_SIZE; i++)
227         avio_w8(dyn_ctx, 255 * i / XING_TOC_SIZE);
228
229     // vbr quality
230     // we write it, because some (broken) tools always expect it to be present
231     avio_wb32(dyn_ctx, 0);
232
233     // encoder short version string
234     if (enc) {
235         uint8_t encoder_str[9] = { 0 };
236         memcpy(encoder_str, enc->value, FFMIN(strlen(enc->value), sizeof(encoder_str)));
237         avio_write(dyn_ctx, encoder_str, sizeof(encoder_str));
238     } else
239         ffio_fill(dyn_ctx, 0, 9);
240
241     avio_w8(dyn_ctx, 0);      // tag revision 0 / unknown vbr method
242     avio_w8(dyn_ctx, 0);      // unknown lowpass filter value
243     ffio_fill(dyn_ctx, 0, 8); // empty replaygain fields
244     avio_w8(dyn_ctx, 0);      // unknown encoding flags
245     avio_w8(dyn_ctx, 0);      // unknown abr/minimal bitrate
246
247     // encoder delay
248     if (codec->initial_padding >= 1 << 12) {
249         av_log(s, AV_LOG_WARNING, "Too many samples of initial padding.\n");
250         avio_wb24(dyn_ctx, 0);
251     } else {
252         avio_wb24(dyn_ctx, codec->initial_padding << 12);
253     }
254
255     avio_w8(dyn_ctx,   0); // misc
256     avio_w8(dyn_ctx,   0); // mp3gain
257     avio_wb16(dyn_ctx, 0); // preset
258
259     // audio length and CRCs (will be updated later)
260     avio_wb32(dyn_ctx, 0); // music length
261     avio_wb16(dyn_ctx, 0); // music crc
262     avio_wb16(dyn_ctx, 0); // tag crc
263
264     ffio_fill(dyn_ctx, 0, mpah.frame_size - bytes_needed);
265
266     mp3->xing_frame_size   = avio_close_dyn_buf(dyn_ctx, &mp3->xing_frame);
267     mp3->xing_frame_offset = avio_tell(s->pb);
268     avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
269
270     mp3->audio_size = mp3->xing_frame_size;
271 }
272
273 /*
274  * Add a frame to XING data.
275  * Following lame's "VbrTag.c".
276  */
277 static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
278 {
279     int i;
280
281     mp3->frames++;
282     mp3->seen++;
283     mp3->size += pkt->size;
284
285     if (mp3->want == mp3->seen) {
286         mp3->bag[mp3->pos] = mp3->size;
287
288         if (XING_NUM_BAGS == ++mp3->pos) {
289             /* shrink table to half size by throwing away each second bag. */
290             for (i = 1; i < XING_NUM_BAGS; i += 2)
291                 mp3->bag[i / 2] = mp3->bag[i];
292
293             /* double wanted amount per bag. */
294             mp3->want *= 2;
295             /* adjust current position to half of table size. */
296             mp3->pos = XING_NUM_BAGS / 2;
297         }
298
299         mp3->seen = 0;
300     }
301 }
302
303 static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
304 {
305     MP3Context  *mp3 = s->priv_data;
306
307     if (mp3->xing_offset && pkt->size >= 4) {
308         MPADecodeHeader c;
309         uint32_t h;
310
311         h = AV_RB32(pkt->data);
312         if (ff_mpa_check_header(h) == 0) {
313             avpriv_mpegaudio_decode_header(&c, h);
314             if (!mp3->initial_bitrate)
315                 mp3->initial_bitrate = c.bit_rate;
316             if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
317                 mp3->has_variable_bitrate = 1;
318         }
319
320         mp3_xing_add_frame(mp3, pkt);
321
322         if (mp3->xing_offset) {
323             mp3->audio_size += pkt->size;
324             mp3->audio_crc   = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE),
325                                       mp3->audio_crc, pkt->data, pkt->size);
326         }
327     }
328
329     return ff_raw_write_packet(s, pkt);
330 }
331
332 static int mp3_queue_flush(AVFormatContext *s)
333 {
334     MP3Context *mp3 = s->priv_data;
335     AVPacketList *pktl;
336     int ret = 0, write = 1;
337
338     ff_id3v2_finish(&mp3->id3, s->pb);
339     mp3_write_xing(s);
340
341     while ((pktl = mp3->queue)) {
342         if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
343             write = 0;
344         av_free_packet(&pktl->pkt);
345         mp3->queue = pktl->next;
346         av_freep(&pktl);
347     }
348     mp3->queue_end = NULL;
349     return ret;
350 }
351
352 static void mp3_update_xing(AVFormatContext *s)
353 {
354     MP3Context  *mp3 = s->priv_data;
355     AVReplayGain *rg;
356     uint16_t tag_crc;
357     uint8_t *toc;
358     int i, rg_size;
359
360     /* replace "Xing" identification string with "Info" for CBR files. */
361     if (!mp3->has_variable_bitrate)
362         AV_WL32(mp3->xing_frame + mp3->xing_offset, MKTAG('I', 'n', 'f', 'o'));
363
364     AV_WB32(mp3->xing_frame + mp3->xing_offset + 8,  mp3->frames);
365     AV_WB32(mp3->xing_frame + mp3->xing_offset + 12, mp3->size);
366
367     toc    = mp3->xing_frame + mp3->xing_offset + 16;
368     toc[0] = 0;  // first toc entry has to be zero.
369     for (i = 1; i < XING_TOC_SIZE; ++i) {
370         int j = i * mp3->pos / XING_TOC_SIZE;
371         int seek_point = 256LL * mp3->bag[j] / mp3->size;
372         toc[i] = FFMIN(seek_point, 255);
373     }
374
375     /* write replaygain */
376     rg = (AVReplayGain*)av_stream_get_side_data(s->streams[0], AV_PKT_DATA_REPLAYGAIN,
377                                                 &rg_size);
378     if (rg && rg_size >= sizeof(*rg)) {
379         uint16_t val;
380
381         AV_WB32(mp3->xing_frame + mp3->xing_offset + 131,
382                 av_rescale(rg->track_peak, 1 << 23, 100000));
383
384         if (rg->track_gain != INT32_MIN) {
385             val  = FFABS(rg->track_gain / 10000) & ((1 << 9) - 1);
386             val |= (rg->track_gain < 0) << 9;
387             val |= 1 << 13;
388             AV_WB16(mp3->xing_frame + mp3->xing_offset + 135, val);
389         }
390
391         if (rg->album_gain != INT32_MIN) {
392             val  = FFABS(rg->album_gain / 10000) & ((1 << 9) - 1);
393             val |= (rg->album_gain < 0) << 9;
394             val |= 1 << 14;
395             AV_WB16(mp3->xing_frame + mp3->xing_offset + 137, val);
396         }
397     }
398
399     AV_WB32(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 8, mp3->audio_size);
400     AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 4, mp3->audio_crc);
401
402     tag_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE), 0, mp3->xing_frame, 190);
403     AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 2, tag_crc);
404
405     avio_seek(s->pb,  mp3->xing_frame_offset, SEEK_SET);
406     avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
407     avio_seek(s->pb, 0, SEEK_END);
408 }
409
410 static int mp3_write_trailer(struct AVFormatContext *s)
411 {
412     uint8_t buf[ID3v1_TAG_SIZE];
413     MP3Context *mp3 = s->priv_data;
414
415     if (mp3->pics_to_write) {
416         av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
417                "attached pictures.\n");
418         mp3_queue_flush(s);
419     }
420
421     /* write the id3v1 tag */
422     if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
423         avio_write(s->pb, buf, ID3v1_TAG_SIZE);
424     }
425
426     if (mp3->xing_offset)
427         mp3_update_xing(s);
428
429     av_freep(&mp3->xing_frame);
430
431     return 0;
432 }
433
434 #if CONFIG_MP2_MUXER
435 AVOutputFormat ff_mp2_muxer = {
436     .name              = "mp2",
437     .long_name         = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
438     .mime_type         = "audio/mpeg",
439     .extensions        = "mp2,m2a,mpa",
440     .audio_codec       = AV_CODEC_ID_MP2,
441     .video_codec       = AV_CODEC_ID_NONE,
442     .write_packet      = ff_raw_write_packet,
443     .flags             = AVFMT_NOTIMESTAMPS,
444 };
445 #endif
446
447 #if CONFIG_MP3_MUXER
448
449 static const AVOption options[] = {
450     { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
451       offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
452     { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
453       offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
454     { "write_xing",  "Write the Xing header containing file duration.",
455       offsetof(MP3Context, write_xing),  AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
456     { NULL },
457 };
458
459 static const AVClass mp3_muxer_class = {
460     .class_name     = "MP3 muxer",
461     .item_name      = av_default_item_name,
462     .option         = options,
463     .version        = LIBAVUTIL_VERSION_INT,
464 };
465
466 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
467 {
468     MP3Context *mp3 = s->priv_data;
469
470     if (pkt->stream_index == mp3->audio_stream_idx) {
471         if (mp3->pics_to_write) {
472             /* buffer audio packets until we get all the pictures */
473             AVPacketList *pktl = av_mallocz(sizeof(*pktl));
474             if (!pktl)
475                 return AVERROR(ENOMEM);
476
477             pktl->pkt     = *pkt;
478             pktl->pkt.buf = av_buffer_ref(pkt->buf);
479             if (!pktl->pkt.buf) {
480                 av_freep(&pktl);
481                 return AVERROR(ENOMEM);
482             }
483
484             if (mp3->queue_end)
485                 mp3->queue_end->next = pktl;
486             else
487                 mp3->queue = pktl;
488             mp3->queue_end = pktl;
489         } else
490             return mp3_write_audio_packet(s, pkt);
491     } else {
492         int ret;
493
494         /* warn only once for each stream */
495         if (s->streams[pkt->stream_index]->nb_frames == 1) {
496             av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
497                    " ignoring.\n", pkt->stream_index);
498         }
499         if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
500             return 0;
501
502         if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
503             return ret;
504         mp3->pics_to_write--;
505
506         /* flush the buffered audio packets */
507         if (!mp3->pics_to_write &&
508             (ret = mp3_queue_flush(s)) < 0)
509             return ret;
510     }
511
512     return 0;
513 }
514
515 /**
516  * Write an ID3v2 header at beginning of stream
517  */
518
519 static int mp3_write_header(struct AVFormatContext *s)
520 {
521     MP3Context  *mp3 = s->priv_data;
522     int ret, i;
523
524     if (mp3->id3v2_version      &&
525         mp3->id3v2_version != 3 &&
526         mp3->id3v2_version != 4) {
527         av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
528                "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
529         return AVERROR(EINVAL);
530     }
531
532     /* check the streams -- we want exactly one audio and arbitrary number of
533      * video (attached pictures) */
534     mp3->audio_stream_idx = -1;
535     for (i = 0; i < s->nb_streams; i++) {
536         AVStream *st = s->streams[i];
537         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
538             if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
539                 av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
540                        "audio stream is required.\n");
541                 return AVERROR(EINVAL);
542             }
543             mp3->audio_stream_idx = i;
544         } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
545             av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
546             return AVERROR(EINVAL);
547         }
548     }
549     if (mp3->audio_stream_idx < 0) {
550         av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
551         return AVERROR(EINVAL);
552     }
553     mp3->pics_to_write = s->nb_streams - 1;
554
555     if (mp3->pics_to_write && !mp3->id3v2_version) {
556         av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
557                "ID3v2 header is disabled.\n");
558         return AVERROR(EINVAL);
559     }
560
561     if (mp3->id3v2_version) {
562         ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
563         ret = ff_id3v2_write_metadata(s, &mp3->id3);
564         if (ret < 0)
565             return ret;
566     }
567
568     if (!mp3->pics_to_write) {
569         if (mp3->id3v2_version)
570             ff_id3v2_finish(&mp3->id3, s->pb);
571         mp3_write_xing(s);
572     }
573
574     return 0;
575 }
576
577 AVOutputFormat ff_mp3_muxer = {
578     .name              = "mp3",
579     .long_name         = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
580     .mime_type         = "audio/mpeg",
581     .extensions        = "mp3",
582     .priv_data_size    = sizeof(MP3Context),
583     .audio_codec       = AV_CODEC_ID_MP3,
584     .video_codec       = AV_CODEC_ID_PNG,
585     .write_header      = mp3_write_header,
586     .write_packet      = mp3_write_packet,
587     .write_trailer     = mp3_write_trailer,
588     .flags             = AVFMT_NOTIMESTAMPS,
589     .priv_class        = &mp3_muxer_class,
590 };
591 #endif