mp3enc.c
Go to the documentation of this file.
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"
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 {
40  if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
41  av_strlcpy(buf, tag->value, buf_size);
42  return !!tag;
43 }
44 
46 {
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;
87 
88  /* xing header */
89  int64_t xing_offset;
92  uint32_t want;
93  uint32_t seen;
94  uint32_t pos;
95  uint64_t bag[XING_NUM_BAGS];
98 
99  /* index of the audio stream */
101  /* number of attached pictures we still need to write */
103 
104  /* audio packets are queued here until we get all the attached pictures */
106 } MP3Context;
107 
108 static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
109 
110 /*
111  * Write an empty XING header and initialize respective data.
112  */
114 {
115  MP3Context *mp3 = s->priv_data;
116  AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;
117  int32_t header;
118  MPADecodeHeader mpah;
119  int srate_idx, i, channels;
120  int bitrate_idx;
121  int best_bitrate_idx;
122  int best_bitrate_error = INT_MAX;
123  int xing_offset;
124  int ver = 0;
125  int lsf, bytes_needed;
126 
127  if (!s->pb->seekable)
128  return;
129 
130  for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
131  const uint16_t base_freq = avpriv_mpa_freq_tab[i];
132 
133  if (codec->sample_rate == base_freq) ver = 0x3; // MPEG 1
134  else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
135  else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
136  else continue;
137 
138  srate_idx = i;
139  break;
140  }
141  if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
142  av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing "
143  "header.\n");
144  return;
145  }
146 
147  switch (codec->channels) {
148  case 1: channels = MPA_MONO; break;
149  case 2: channels = MPA_STEREO; break;
150  default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
151  "not writing Xing header.\n");
152  return;
153  }
154 
155  /* dummy MPEG audio header */
156  header = 0xff << 24; // sync
157  header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
158  header |= (srate_idx << 2) << 8;
159  header |= channels << 6;
160 
161  lsf = !((header & (1 << 20) && header & (1 << 19)));
162 
163  xing_offset = xing_offtbl[ver != 3][channels == 1];
164  bytes_needed = 4 // header
165  + xing_offset
166  + 4 // xing tag
167  + 4 // frames/size/toc flags
168  + 4 // frames
169  + 4 // size
170  + XING_TOC_SIZE; // toc
171 
172  for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
173  int bit_rate = 1000 * avpriv_mpa_bitrate_tab[lsf][3 - 1][bitrate_idx];
174  int error = FFABS(bit_rate - codec->bit_rate);
175 
176  if (error < best_bitrate_error){
177  best_bitrate_error = error;
178  best_bitrate_idx = bitrate_idx;
179  }
180  }
181 
182  for (bitrate_idx = best_bitrate_idx; bitrate_idx < 15; bitrate_idx++) {
183  int32_t mask = bitrate_idx << (4 + 8);
184  header |= mask;
185 
186  avpriv_mpegaudio_decode_header(&mpah, header);
187 
188  if (bytes_needed <= mpah.frame_size)
189  break;
190 
191  header &= ~mask;
192  }
193 
194  avio_wb32(s->pb, header);
195 
196  avpriv_mpegaudio_decode_header(&mpah, header);
197 
198  av_assert0(mpah.frame_size >= XING_MAX_SIZE);
199 
200  ffio_fill(s->pb, 0, xing_offset);
201  mp3->xing_offset = avio_tell(s->pb);
202  ffio_wfourcc(s->pb, "Xing");
203  avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames / size / TOC
204 
205  mp3->size = mpah.frame_size;
206  mp3->want = 1;
207 
208  avio_wb32(s->pb, 0); // frames
209  avio_wb32(s->pb, 0); // size
210 
211  // TOC
212  for (i = 0; i < XING_TOC_SIZE; i++)
213  avio_w8(s->pb, 255 * i / XING_TOC_SIZE);
214 
215  ffio_fill(s->pb, 0, mpah.frame_size - bytes_needed);
216 }
217 
218 /*
219  * Add a frame to XING data.
220  * Following lame's "VbrTag.c".
221  */
222 static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
223 {
224  int i;
225 
226  mp3->frames++;
227  mp3->seen++;
228  mp3->size += pkt->size;
229 
230  if (mp3->want == mp3->seen) {
231  mp3->bag[mp3->pos] = mp3->size;
232 
233  if (XING_NUM_BAGS == ++mp3->pos) {
234  /* shrink table to half size by throwing away each second bag. */
235  for (i = 1; i < XING_NUM_BAGS; i += 2)
236  mp3->bag[i / 2] = mp3->bag[i];
237 
238  /* double wanted amount per bag. */
239  mp3->want *= 2;
240  /* adjust current position to half of table size. */
241  mp3->pos = XING_NUM_BAGS / 2;
242  }
243 
244  mp3->seen = 0;
245  }
246 }
247 
249 {
250  MP3Context *mp3 = s->priv_data;
251 
252  if (mp3->xing_offset && pkt->size >= 4) {
253  MPADecodeHeader c;
254  uint32_t h;
255 
256  h = AV_RB32(pkt->data);
257  if (ff_mpa_check_header(h) == 0) {
259  if (!mp3->initial_bitrate)
260  mp3->initial_bitrate = c.bit_rate;
261  if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
262  mp3->has_variable_bitrate = 1;
263  }
264 
265  mp3_xing_add_frame(mp3, pkt);
266  }
267 
268  return ff_raw_write_packet(s, pkt);
269 }
270 
272 {
273  MP3Context *mp3 = s->priv_data;
274  AVPacketList *pktl;
275  int ret = 0, write = 1;
276 
277  ff_id3v2_finish(&mp3->id3, s->pb);
278  mp3_write_xing(s);
279 
280  while ((pktl = mp3->queue)) {
281  if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
282  write = 0;
283  av_free_packet(&pktl->pkt);
284  mp3->queue = pktl->next;
285  av_freep(&pktl);
286  }
287  mp3->queue_end = NULL;
288  return ret;
289 }
290 
292 {
293  MP3Context *mp3 = s->priv_data;
294  int i;
295 
296  /* replace "Xing" identification string with "Info" for CBR files. */
297  if (!mp3->has_variable_bitrate) {
298  avio_seek(s->pb, mp3->xing_offset, SEEK_SET);
299  ffio_wfourcc(s->pb, "Info");
300  }
301 
302  avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);
303  avio_wb32(s->pb, mp3->frames);
304  avio_wb32(s->pb, mp3->size);
305 
306  avio_w8(s->pb, 0); // first toc entry has to be zero.
307 
308  for (i = 1; i < XING_TOC_SIZE; ++i) {
309  int j = i * mp3->pos / XING_TOC_SIZE;
310  int seek_point = 256LL * mp3->bag[j] / mp3->size;
311  avio_w8(s->pb, FFMIN(seek_point, 255));
312  }
313 
314  avio_seek(s->pb, 0, SEEK_END);
315 }
316 
317 static int mp3_write_trailer(struct AVFormatContext *s)
318 {
319  uint8_t buf[ID3v1_TAG_SIZE];
320  MP3Context *mp3 = s->priv_data;
321 
322  if (mp3->pics_to_write) {
323  av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
324  "attached pictures.\n");
325  mp3_queue_flush(s);
326  }
327 
328  /* write the id3v1 tag */
329  if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
330  avio_write(s->pb, buf, ID3v1_TAG_SIZE);
331  }
332 
333  if (mp3->xing_offset)
334  mp3_update_xing(s);
335 
336  return 0;
337 }
338 
339 #if CONFIG_MP2_MUXER
340 AVOutputFormat ff_mp2_muxer = {
341  .name = "mp2",
342  .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
343  .mime_type = "audio/x-mpeg",
344  .extensions = "mp2,m2a",
345  .audio_codec = AV_CODEC_ID_MP2,
346  .video_codec = AV_CODEC_ID_NONE,
347  .write_packet = ff_raw_write_packet,
348  .flags = AVFMT_NOTIMESTAMPS,
349 };
350 #endif
351 
352 #if CONFIG_MP3_MUXER
353 
354 static const AVOption options[] = {
355  { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
356  offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
357  { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
358  offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
359  { NULL },
360 };
361 
362 static const AVClass mp3_muxer_class = {
363  .class_name = "MP3 muxer",
364  .item_name = av_default_item_name,
365  .option = options,
366  .version = LIBAVUTIL_VERSION_INT,
367 };
368 
369 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
370 {
371  MP3Context *mp3 = s->priv_data;
372 
373  if (pkt->stream_index == mp3->audio_stream_idx) {
374  if (mp3->pics_to_write) {
375  /* buffer audio packets until we get all the pictures */
376  AVPacketList *pktl = av_mallocz(sizeof(*pktl));
377  if (!pktl)
378  return AVERROR(ENOMEM);
379 
380  pktl->pkt = *pkt;
381  pkt->destruct = NULL;
382 
383  if (mp3->queue_end)
384  mp3->queue_end->next = pktl;
385  else
386  mp3->queue = pktl;
387  mp3->queue_end = pktl;
388  } else
389  return mp3_write_audio_packet(s, pkt);
390  } else {
391  int ret;
392 
393  /* warn only once for each stream */
394  if (s->streams[pkt->stream_index]->nb_frames == 1) {
395  av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
396  " ignoring.\n", pkt->stream_index);
397  }
398  if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
399  return 0;
400 
401  if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
402  return ret;
403  mp3->pics_to_write--;
404 
405  /* flush the buffered audio packets */
406  if (!mp3->pics_to_write &&
407  (ret = mp3_queue_flush(s)) < 0)
408  return ret;
409  }
410 
411  return 0;
412 }
413 
418 static int mp3_write_header(struct AVFormatContext *s)
419 {
420  MP3Context *mp3 = s->priv_data;
421  int ret, i;
422 
423  /* check the streams -- we want exactly one audio and arbitrary number of
424  * video (attached pictures) */
425  mp3->audio_stream_idx = -1;
426  for (i = 0; i < s->nb_streams; i++) {
427  AVStream *st = s->streams[i];
428  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
429  if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
430  av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
431  "audio stream is required.\n");
432  return AVERROR(EINVAL);
433  }
434  mp3->audio_stream_idx = i;
435  } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
436  av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
437  return AVERROR(EINVAL);
438  }
439  }
440  if (mp3->audio_stream_idx < 0) {
441  av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
442  return AVERROR(EINVAL);
443  }
444  mp3->pics_to_write = s->nb_streams - 1;
445 
447  ret = ff_id3v2_write_metadata(s, &mp3->id3);
448  if (ret < 0)
449  return ret;
450 
451  if (!mp3->pics_to_write) {
452  ff_id3v2_finish(&mp3->id3, s->pb);
453  mp3_write_xing(s);
454  }
455 
456  return 0;
457 }
458 
459 AVOutputFormat ff_mp3_muxer = {
460  .name = "mp3",
461  .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
462  .mime_type = "audio/x-mpeg",
463  .extensions = "mp3",
464  .priv_data_size = sizeof(MP3Context),
465  .audio_codec = AV_CODEC_ID_MP3,
466  .video_codec = AV_CODEC_ID_PNG,
467  .write_header = mp3_write_header,
468  .write_packet = mp3_write_packet,
470  .flags = AVFMT_NOTIMESTAMPS,
471  .priv_class = &mp3_muxer_class,
472 };
473 #endif