FFmpeg
Loading...
Searching...
No Matches
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 FFmpeg.
6 *
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 "mux.h"
27#include "rawenc.h"
28#include "libavutil/avstring.h"
29#include "libavutil/mem.h"
33#include "packet_internal.h"
35#include "libavutil/opt.h"
36#include "libavutil/dict.h"
37#include "libavutil/avassert.h"
38#include "libavutil/crc.h"
41
42static int id3v1_set_string(AVFormatContext *s, const char *key,
43 uint8_t *buf, int buf_size)
44{
46 if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
47 av_strlcpy(buf, tag->value, buf_size);
48 return !!tag;
49}
50
51// refer to: http://id3.org/ID3v1
52static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
53{
55 int i, count = 0;
56
57 memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
58 buf[0] = 'T';
59 buf[1] = 'A';
60 buf[2] = 'G';
61 /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */
62 count += id3v1_set_string(s, "TIT2", buf + 3, 30 + 1); //title
63 count += id3v1_set_string(s, "TPE1", buf + 33, 30 + 1); //author|artist
64 count += id3v1_set_string(s, "TALB", buf + 63, 30 + 1); //album
65 if ((tag = av_dict_get(s->metadata, "TYER", NULL, 0))) { //year
66 av_strlcpy(buf + 93, tag->value, 4 + 1);
67 count++;
68 } else if ((tag = av_dict_get(s->metadata, "TDRC", NULL, 0))) {
69 av_strlcpy(buf + 93, tag->value, 4 + 1);
70 count++;
71 } else if ((tag = av_dict_get(s->metadata, "TDAT", NULL, 0))) {
72 av_strlcpy(buf + 93, tag->value, 4 + 1);
73 count++;
74 }
75
76 count += id3v1_set_string(s, "comment", buf + 97, 30 + 1);
77 if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
78 buf[125] = 0;
79 buf[126] = atoi(tag->value);
80 count++;
81 }
82 buf[127] = 0xFF; /* default to unknown genre */
83 if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
84 for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
85 if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
86 buf[127] = i;
87 count++;
88 break;
89 }
90 }
91 }
92 return count;
93}
94
95#define XING_NUM_BAGS 400
96#define XING_TOC_SIZE 100
97// size of the XING/LAME data, starting from the Xing tag
98#define XING_SIZE 156
99
100typedef struct MP3Context {
101 const AVClass *class;
107
108 /* xing header */
109 // a buffer containing the whole XING/LAME frame
110 uint8_t *xing_frame;
112
113 AVCRC audio_crc; // CRC of the audio data
114 uint32_t audio_size; // total size of the audio data
115
116 // offset of the XING/LAME frame in the file
118 // offset of the XING/INFO tag in the frame
120
123 uint32_t want;
124 uint32_t seen;
125 uint32_t pos;
132 int delay;
134
135 /* index of the audio stream */
137 /* number of attached pictures we still need to write */
139
140 /* audio packets are queued here until we get all the attached pictures */
142} MP3Context;
143
144static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
145
146/*
147 * Write an empty XING header and initialize respective data.
148 */
150{
151 MP3Context *mp3 = s->priv_data;
152 AVCodecParameters *par = s->streams[mp3->audio_stream_idx]->codecpar;
153 AVDictionaryEntry *enc = av_dict_get(s->streams[mp3->audio_stream_idx]->metadata, "encoder", NULL, 0);
154 AVIOContext *dyn_ctx;
156 int srate_idx, i, channels;
157 int bitrate_idx;
158 int best_bitrate_idx = -1;
159 int best_bitrate_error = INT_MAX;
160 int ret;
161 int ver = 0;
162 int bytes_needed;
163
164 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) || !mp3->write_xing)
165 return 0;
166
167 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++) {
168 const uint16_t base_freq = ff_mpa_freq_tab[i];
169
170 if (par->sample_rate == base_freq) ver = 0x3; // MPEG 1
171 else if (par->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
172 else if (par->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
173 else continue;
174
175 srate_idx = i;
176 break;
177 }
179 av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing header.\n");
180 return 0;
181 }
182
183 switch (par->ch_layout.nb_channels) {
184 case 1: channels = MPA_MONO; break;
185 case 2: channels = MPA_STEREO; break;
186 default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
187 "not writing Xing header.\n");
188 return 0;
189 }
190
191 /* dummy MPEG audio header */
192 header = 0xffU << 24; // sync
193 header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
194 header |= (srate_idx << 2) << 8;
195 header |= channels << 6;
196
197 for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
198 int bit_rate = 1000 * ff_mpa_bitrate_tab[ver != 3][3 - 1][bitrate_idx];
199 int error = FFABS(bit_rate - par->bit_rate);
200
201 if (error < best_bitrate_error) {
202 best_bitrate_error = error;
203 best_bitrate_idx = bitrate_idx;
204 }
205 }
206 av_assert0(best_bitrate_idx >= 0);
207
208 for (bitrate_idx = best_bitrate_idx; ; bitrate_idx++) {
209 int32_t mask = bitrate_idx << (4 + 8);
210 if (15 == bitrate_idx)
211 return 0;
212 header |= mask;
213
215 if (ret < 0)
216 return ret;
217 mp3->xing_offset = xing_offtbl[mp3->xing_header->lsf == 1][mp3->xing_header->nb_channels == 1] + 4;
218 bytes_needed = mp3->xing_offset + XING_SIZE;
219
220 if (bytes_needed <= mp3->xing_header->frame_size)
221 break;
222
223 header &= ~mask;
224 }
225
226 ret = avio_open_dyn_buf(&dyn_ctx);
227 if (ret < 0)
228 return ret;
229
230 avio_wb32(dyn_ctx, header);
231
232 ffio_fill(dyn_ctx, 0, mp3->xing_offset - 4);
233 ffio_wfourcc(dyn_ctx, "Xing");
234 avio_wb32(dyn_ctx, 0x01 | 0x02 | 0x04 | 0x08); // frames / size / TOC / vbr scale
235
236 mp3->size = mp3->xing_header->frame_size;
237 mp3->want=1;
238 mp3->seen=0;
239 mp3->pos=0;
240
241 avio_wb32(dyn_ctx, 0); // frames
242 avio_wb32(dyn_ctx, 0); // size
243
244 // TOC
245 for (i = 0; i < XING_TOC_SIZE; i++)
246 avio_w8(dyn_ctx, (uint8_t)(255 * i / XING_TOC_SIZE));
247
248 // vbr quality
249 // we write it, because some (broken) tools always expect it to be present
250 avio_wb32(dyn_ctx, 0);
251
252 // encoder short version string
253 if (enc) {
254 uint8_t encoder_str[9] = { 0 };
255 if ( strlen(enc->value) > sizeof(encoder_str)
256 && !strcmp("Lavc libmp3lame", enc->value)) {
257 memcpy(encoder_str, "Lavf lame", 9);
258 } else
259 memcpy(encoder_str, enc->value, FFMIN(strlen(enc->value), sizeof(encoder_str)));
260
261 avio_write(dyn_ctx, encoder_str, sizeof(encoder_str));
262 } else
263 avio_write(dyn_ctx, "Lavf\0\0\0\0\0", 9);
264
265 avio_w8(dyn_ctx, 0); // tag revision 0 / unknown vbr method
266 avio_w8(dyn_ctx, 0); // unknown lowpass filter value
267 ffio_fill(dyn_ctx, 0, 8); // empty replaygain fields
268 avio_w8(dyn_ctx, 0); // unknown encoding flags
269 avio_w8(dyn_ctx, 0); // unknown abr/minimal bitrate
270 avio_wb24(dyn_ctx, 0); // empty encoder delay/padding
271
272 avio_w8(dyn_ctx, 0); // misc
273 avio_w8(dyn_ctx, 0); // mp3gain
274 avio_wb16(dyn_ctx, 0); // preset
275
276 // audio length and CRCs (will be updated later)
277 avio_wb32(dyn_ctx, 0); // music length
278 avio_wb16(dyn_ctx, 0); // music crc
279 avio_wb16(dyn_ctx, 0); // tag crc
280
281 ffio_fill(dyn_ctx, 0, mp3->xing_header->frame_size - bytes_needed);
282
283 mp3->xing_frame_size = avio_close_dyn_buf(dyn_ctx, &mp3->xing_frame);
284 mp3->xing_frame_offset = avio_tell(s->pb);
285 avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
286
287 mp3->audio_size = mp3->xing_frame_size;
288
289 return 0;
290}
291
292/*
293 * Add a frame to XING data.
294 * Following lame's "VbrTag.c".
295 */
297{
298 int i;
299
300 mp3->frames++;
301 mp3->seen++;
302 mp3->size += pkt->size;
303
304 if (mp3->want == mp3->seen) {
305 mp3->bag[mp3->pos] = mp3->size;
306
307 if (XING_NUM_BAGS == ++mp3->pos) {
308 /* shrink table to half size by throwing away each second bag. */
309 for (i = 1; i < XING_NUM_BAGS; i += 2)
310 mp3->bag[i >> 1] = mp3->bag[i];
311
312 /* double wanted amount per bag. */
313 mp3->want *= 2;
314 /* adjust current position to half of table size. */
315 mp3->pos = XING_NUM_BAGS / 2;
316 }
317
318 mp3->seen = 0;
319 }
320}
321
323{
324 MP3Context *mp3 = s->priv_data;
325
326 if (pkt->data && pkt->size >= 4) {
327 int ret;
328 uint32_t h;
329
330 h = AV_RB32(pkt->data);
332 if (ret >= 0) {
333 if (!mp3->initial_bitrate)
334 mp3->initial_bitrate = mp3->hdr->bit_rate;
335 if ((mp3->hdr->bit_rate == 0) || (mp3->initial_bitrate != mp3->hdr->bit_rate))
336 mp3->has_variable_bitrate = 1;
337 if (mp3->xing_offset && !mp3->first_frame) {
338 const MPADecodeHeader2 *xing = mp3->xing_header;
339
340 if (mp3->hdr->layer != xing->layer ||
341 mp3->hdr->sample_rate != xing->sample_rate ||
342 mp3->hdr->nb_channels != xing->nb_channels) {
343 av_log(s, AV_LOG_ERROR, "First audio frame (layer %d, %d Hz, %d channels) "
344 "does not match the stream (layer %d, %d Hz, %d channels).\n",
345 mp3->hdr->layer, mp3->hdr->sample_rate, mp3->hdr->nb_channels,
346 xing->layer, xing->sample_rate, xing->nb_channels);
347 return AVERROR_INVALIDDATA;
348 }
349
351 if (ret < 0)
352 return ret;
353 }
354 } else if (ret == AVERROR(ENOMEM)) {
355 return ret;
356 } else {
357 av_log(s, AV_LOG_WARNING, "Audio packet of size %d (starting with %08"PRIX32"...) "
358 "is invalid, writing it anyway.\n", pkt->size, h);
359 }
360
361#ifdef FILTER_VBR_HEADERS
362 /* filter out XING and INFO headers. */
363 int base = 4 + xing_offtbl[mp3->hdr->lsf == 1][mp3->hdr->nb_channels == 1];
364
365 if (base + 4 <= pkt->size) {
366 uint32_t v = AV_RB32(pkt->data + base);
367
368 if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
369 return 0;
370 }
371
372 /* filter out VBRI headers. */
373 base = 4 + 32;
374
375 if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
376 return 0;
377#endif
378
379 if (mp3->xing_offset) {
380 uint8_t *side_data = NULL;
381 size_t side_data_size;
382
384 mp3->audio_size += pkt->size;
386 mp3->audio_crc, pkt->data, pkt->size);
387
388 side_data = av_packet_get_side_data(pkt,
390 &side_data_size);
391 if (side_data && side_data_size >= 10) {
392 uint32_t discard_padding = AV_RL32(side_data + 4);
393 /* Padding longer than a frame is spread over several packets. */
394 mp3->padding = discard_padding ? mp3->padding + discard_padding : 0;
395 if (!mp3->delay)
396 mp3->delay = FFMAX((int64_t)AV_RL32(side_data) - 528 - 1, 0);
397 } else {
398 mp3->padding = 0;
399 }
400 }
401 }
402
403 return ff_raw_write_packet(s, pkt);
404}
405
407{
408 MP3Context *mp3 = s->priv_data;
409 AVIOContext *pb = mp3->id3_pb ? mp3->id3_pb : s->pb;
410 uint8_t *buf = NULL;
411 int ret, size;
412
413 ff_id3v2_finish(&mp3->id3, pb, s->metadata_header_padding);
414 ret = pb->error;
415
416 if (!mp3->id3_pb)
417 return ret;
418
419 size = avio_get_dyn_buf(mp3->id3_pb, &buf);
420 ret = mp3->id3_pb->error;
421 if (ret >= 0) {
422 avio_write(s->pb, buf, size);
423 ret = s->pb->error;
424 }
426
427 return ret;
428}
429
431{
432 MP3Context *mp3 = s->priv_data;
433 AVPacket *const pkt = ffformatcontext(s)->pkt;
434 int ret = 0, write = 1;
435
436 ret = mp3_finish_id3v2(s);
437 if (ret >= 0)
438 ret = mp3_write_xing(s);
439 if (ret < 0)
440 write = 0;
441
442 while (mp3->queue.head) {
444 if (write && (ret = mp3_write_audio_packet(s, pkt)) < 0)
445 write = 0;
447 }
448 return ret;
449}
450
452{
453 MP3Context *mp3 = s->priv_data;
454 const AVPacketSideData *sd;
455 AVReplayGain *rg;
456 uint16_t tag_crc;
457 uint8_t *toc;
458 int i;
459 int64_t old_pos = avio_tell(s->pb);
460
461 /* replace "Xing" identification string with "Info" for CBR files. */
462 if (!mp3->has_variable_bitrate)
463 AV_WL32(mp3->xing_frame + mp3->xing_offset, MKTAG('I', 'n', 'f', 'o'));
464
465 if (mp3->first_frame) {
467
468 header->error_protection = mp3->xing_header->error_protection;
469 header->bitrate_index = mp3->xing_header->bitrate_index;
470 header->padding = mp3->xing_header->padding;
472 }
473
474 AV_WB32(mp3->xing_frame + mp3->xing_offset + 8, mp3->frames);
475 AV_WB32(mp3->xing_frame + mp3->xing_offset + 12, mp3->size);
476
477 toc = mp3->xing_frame + mp3->xing_offset + 16;
478 toc[0] = 0; // first toc entry has to be zero.
479 for (i = 1; i < XING_TOC_SIZE; ++i) {
480 int j = i * mp3->pos / XING_TOC_SIZE;
481 int seek_point = 256LL * mp3->bag[j] / mp3->size;
482 toc[i] = FFMIN(seek_point, 255);
483 }
484
485 /* write replaygain */
486 sd = av_packet_side_data_get(s->streams[0]->codecpar->coded_side_data,
487 s->streams[0]->codecpar->nb_coded_side_data,
489 if (sd && sd->size >= sizeof(*rg)) {
490 uint16_t val;
491
492 rg = (AVReplayGain *)sd->data;
493 AV_WB32(mp3->xing_frame + mp3->xing_offset + 131,
494 av_rescale(rg->track_peak, 1 << 23, 100000));
495
496 if (rg->track_gain != INT32_MIN) {
497 val = FFABS(rg->track_gain / 10000) & ((1 << 9) - 1);
498 val |= (rg->track_gain < 0) << 9;
499 val |= 1 << 13;
500 AV_WB16(mp3->xing_frame + mp3->xing_offset + 135, val);
501 }
502
503 if (rg->album_gain != INT32_MIN) {
504 val = FFABS(rg->album_gain / 10000) & ((1 << 9) - 1);
505 val |= (rg->album_gain < 0) << 9;
506 val |= 1 << 14;
507 AV_WB16(mp3->xing_frame + mp3->xing_offset + 137, val);
508 }
509 }
510
511 /* write encoder delay/padding */
512 if (mp3->padding)
513 mp3->padding += 528 + 1;
514 if (mp3->delay >= 1 << 12) {
515 mp3->delay = (1 << 12) - 1;
516 av_log(s, AV_LOG_WARNING, "Too many samples of initial padding.\n");
517 }
518 if (mp3->padding >= 1 << 12) {
519 mp3->padding = (1 << 12) - 1;
520 av_log(s, AV_LOG_WARNING, "Too many samples of trailing padding.\n");
521 }
522 AV_WB24(mp3->xing_frame + mp3->xing_offset + 141, (mp3->delay << 12) + mp3->padding);
523
524 AV_WB32(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 8, mp3->audio_size);
525 AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 4, mp3->audio_crc);
526
527 tag_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE), 0, mp3->xing_frame, 190);
528 AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 2, tag_crc);
529
530 avio_seek(s->pb, mp3->xing_frame_offset, SEEK_SET);
531 avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
532 avio_seek(s->pb, old_pos, SEEK_SET);
533}
534
536{
537 uint8_t buf[ID3v1_TAG_SIZE];
538 MP3Context *mp3 = s->priv_data;
539 int ret;
540
541 if (mp3->pics_to_write) {
542 av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
543 "attached pictures.\n");
544 if ((ret = mp3_queue_flush(s)) < 0)
545 return ret;
546 }
547
548 /* write the id3v1 tag */
549 if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
550 avio_write(s->pb, buf, ID3v1_TAG_SIZE);
551 }
552
553 if (mp3->xing_offset)
555
556 return 0;
557}
558
559static int query_codec(enum AVCodecID id, int std_compliance)
560{
562
563 if (id == AV_CODEC_ID_MP3)
564 return 1;
565
566 while(cm->id != AV_CODEC_ID_NONE) {
567 if(id == cm->id)
568 return MKTAG('A', 'P', 'I', 'C');
569 cm++;
570 }
571 return 0;
572}
573
574static const AVOption options[] = {
575 { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
576 offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
577 { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
578 offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
579 { "write_xing", "Write the Xing header containing file duration.",
580 offsetof(MP3Context, write_xing), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
581 { NULL },
582};
583
584static const AVClass mp3_muxer_class = {
585 .class_name = "MP3 muxer",
586 .item_name = av_default_item_name,
587 .option = options,
588 .version = LIBAVUTIL_VERSION_INT,
589};
590
592{
593 MP3Context *mp3 = s->priv_data;
594
595 if (pkt->stream_index == mp3->audio_stream_idx) {
596 if (mp3->pics_to_write) {
597 /* buffer audio packets until we get all the pictures */
598 int ret = ff_packet_list_put(&mp3->queue, pkt, NULL, 0);
599
600 if (ret < 0) {
601 av_log(s, AV_LOG_WARNING, "Not enough memory to buffer audio. Skipping picture streams\n");
602 mp3->pics_to_write = 0;
603 if ((ret = mp3_queue_flush(s)) < 0)
604 return ret;
606 }
607 } else
609 } else {
610 AVIOContext *pb = mp3->id3_pb ? mp3->id3_pb : s->pb;
611 int ret;
612
613 /* warn only once for each stream */
614 if (s->streams[pkt->stream_index]->nb_frames == 1) {
615 av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
616 " ignoring.\n", pkt->stream_index);
617 }
618 if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
619 return 0;
620
621 ret = ff_id3v2_write_apic(s, pb, &mp3->id3, pkt);
622 if (ret < 0)
623 return ret;
624 if (pb->error < 0)
625 return pb->error;
626 mp3->pics_to_write--;
627
628 /* flush the buffered audio packets */
629 if (!mp3->pics_to_write &&
630 (ret = mp3_queue_flush(s)) < 0)
631 return ret;
632 }
633
634 return 0;
635}
636
637/**
638 * Write an ID3v2 header at beginning of stream
639 */
640
641static int mp3_init(struct AVFormatContext *s)
642{
643 MP3Context *mp3 = s->priv_data;
644 int i;
645
646 if (mp3->id3v2_version &&
647 mp3->id3v2_version != 3 &&
648 mp3->id3v2_version != 4) {
649 av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
650 "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
651 return AVERROR(EINVAL);
652 }
653
654 /* check the streams -- we want exactly one audio and arbitrary number of
655 * video (attached pictures) */
656 mp3->audio_stream_idx = -1;
657 for (i = 0; i < s->nb_streams; i++) {
658 AVStream *st = s->streams[i];
660 if (mp3->audio_stream_idx >= 0 || st->codecpar->codec_id != AV_CODEC_ID_MP3) {
661 av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
662 "audio stream is required.\n");
663 return AVERROR(EINVAL);
664 }
665 mp3->audio_stream_idx = i;
666 } else if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
667 av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
668 return AVERROR(EINVAL);
669 }
670 }
671 if (mp3->audio_stream_idx < 0) {
672 av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
673 return AVERROR(EINVAL);
674 }
675 mp3->pics_to_write = s->nb_streams - 1;
676
677 if (mp3->pics_to_write && !mp3->id3v2_version) {
678 av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
679 "ID3v2 header is disabled.\n");
680 return AVERROR(EINVAL);
681 }
682
683 return 0;
684}
685
687{
688 MP3Context *mp3 = s->priv_data;
689 AVIOContext *pb = s->pb;
690 int ret;
691
692 if (mp3->id3v2_version) {
693 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
694 ret = avio_open_dyn_buf(&mp3->id3_pb);
695 if (ret < 0)
696 return ret;
697 pb = mp3->id3_pb;
698 }
699
701 ret = ff_id3v2_write_metadata(s, pb, &mp3->id3);
702 if (ret < 0)
703 return ret;
704 if (pb->error < 0)
705 return pb->error;
706 }
707
708 if (!mp3->pics_to_write) {
709 if (mp3->id3v2_version && (ret = mp3_finish_id3v2(s)) < 0)
710 return ret;
711 return mp3_write_xing(s);
712 }
713
714 return 0;
715}
716
717static void mp3_deinit(struct AVFormatContext *s)
718{
719 MP3Context *mp3 = s->priv_data;
720
723 av_freep(&mp3->xing_frame);
724 av_freep(&mp3->hdr);
725 av_freep(&mp3->xing_header);
726 av_freep(&mp3->first_frame);
727}
728
730 .p.name = "mp3",
731 .p.long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
732 .p.mime_type = "audio/mpeg",
733 .p.extensions = "mp3",
734 .priv_data_size = sizeof(MP3Context),
735 .p.audio_codec = AV_CODEC_ID_MP3,
736 .p.video_codec = AV_CODEC_ID_PNG,
737 .init = mp3_init,
738 .write_header = mp3_write_header,
739 .write_packet = mp3_write_packet,
740 .write_trailer = mp3_write_trailer,
741 .deinit = mp3_deinit,
742 .query_codec = query_codec,
743 .p.flags = AVFMT_NOTIMESTAMPS,
744 .p.priv_class = &mp3_muxer_class,
745};
static double val(void *priv, double ch)
Definition aeval.c:77
const FFOutputFormat ff_mp3_muxer
Definition mp3enc.c:729
channels
Definition aptx.h:31
int32_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
Main libavformat public API header.
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition avformat.h:500
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition avio.h:41
void avio_w8(AVIOContext *s, int b)
Definition aviobuf.c:184
void avio_wb32(AVIOContext *s, unsigned int val)
Definition aviobuf.c:368
void avio_wb16(AVIOContext *s, unsigned int val)
Definition aviobuf.c:446
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:494
void avio_wb24(AVIOContext *s, unsigned int val)
Definition aviobuf.c:458
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition aviobuf.c:1369
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition aviobuf.c:206
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition aviobuf.c:1324
int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition aviobuf.c:1336
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition aviobuf.c:1397
static av_always_inline void ffio_wfourcc(AVIOContext *pb, const uint8_t *s)
void ffio_fill(AVIOContext *s, int b, int64_t count)
Definition aviobuf.c:192
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Public header for CRC hash function implementation.
static AVPacket * pkt
Public dictionary API.
#define cm
Definition dvbsubdec.c:40
const char * key
#define AV_OPT_FLAG_ENCODING_PARAM
A generic parameter which can be set by the user for muxing or encoding.
Definition opt.h:351
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition codec_id.h:47
@ AV_CODEC_ID_PNG
Definition codec_id.h:111
@ AV_CODEC_ID_NONE
Definition codec_id.h:48
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition codec_id.h:456
const AVPacketSideData * av_packet_side_data_get(const AVPacketSideData *sd, int nb_sd, enum AVPacketSideDataType type)
Get side information from a side data array.
Definition packet.c:570
@ AV_PKT_DATA_SKIP_SAMPLES
Recommends skipping the specified number of samples.
Definition packet.h:153
@ AV_PKT_DATA_REPLAYGAIN
This side data should be associated with an audio stream and contains ReplayGain information in form ...
Definition packet.h:96
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, size_t *size)
Get side information from packet.
Definition packet.c:252
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition crc.c:389
uint32_t AVCRC
Definition crc.h:46
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition crc.c:421
@ AV_CRC_16_ANSI_LE
Definition crc.h:54
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:60
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition avstring.c:85
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
const char *const ff_id3v1_genre_str[ID3v1_GENRE_MAX+1]
ID3v1 genres.
Definition id3v1.c:26
#define ID3v1_TAG_SIZE
Definition id3v1.h:27
#define ID3v1_GENRE_MAX
Definition id3v1.h:29
const CodecMime ff_id3v2_mime_tags[]
Definition id3v2.c:138
void ff_id3v2_start(ID3v2EncContext *id3, AVIOContext *pb, int id3v2_version, const char *magic)
Initialize an ID3v2 tag.
Definition id3v2enc.c:349
void ff_id3v2_finish(ID3v2EncContext *id3, AVIOContext *pb, int padding_bytes)
Finalize an opened ID3v2 tag.
Definition id3v2enc.c:556
#define ID3v2_DEFAULT_MAGIC
Default magic bytes for ID3v2 header: "ID3".
Definition id3v2.h:35
int ff_id3v2_write_apic(AVFormatContext *s, AVIOContext *pb, ID3v2EncContext *id3, AVPacket *pkt)
Write an attached picture from pkt into an ID3v2 tag.
Definition id3v2enc.c:498
int ff_id3v2_write_metadata(AVFormatContext *s, AVIOContext *pb, ID3v2EncContext *id3)
Convert and write all global metadata from s into an ID3v2 tag.
Definition id3v2enc.c:476
static int query_codec(enum AVCodecID id, int std_compliance)
Definition img2enc.c:361
#define AV_WB24(p, d)
#define AV_WB32(p, v)
#define AV_WL32(p, v)
#define AV_RL32(p)
#define AV_RB32(p)
#define AV_WB16(p, v)
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition internal.h:130
int ff_packet_list_get(PacketList *list, AVPacket *pkt)
Remove the oldest AVPacket in the list and return it.
Definition packet_list.c:89
void ff_packet_list_free(PacketList *list)
Wipe the list and unref all the packets in it.
int ff_packet_list_put(PacketList *list, AVPacket *pkt, int(*copy)(AVPacket *dst, const AVPacket *src), int flags)
Append an AVPacket to the list.
Definition packet_list.c:40
int ff_raw_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition rawenc.c:31
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
static const uint16_t mask[17]
Definition lzw.c:38
#define FFMIN(a, b)
Definition macros.h:49
#define MKTAG(a, b, c, d)
Definition macros.h:55
#define MKBETAG(a, b, c, d)
Definition macros.h:56
#define FFMAX(a, b)
Definition macros.h:47
Memory handling functions.
uint32_t tag
Definition movenc.c:2128
static void mp3_update_xing(AVFormatContext *s)
Definition mp3enc.c:451
static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
Definition mp3enc.c:322
static int mp3_queue_flush(AVFormatContext *s)
Definition mp3enc.c:430
static const AVClass mp3_muxer_class
Definition mp3enc.c:584
static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
Definition mp3enc.c:296
#define XING_NUM_BAGS
Definition mp3enc.c:95
static const uint8_t xing_offtbl[2][2]
Definition mp3enc.c:144
static int mp3_init(struct AVFormatContext *s)
Write an ID3v2 header at beginning of stream.
Definition mp3enc.c:641
static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
Definition mp3enc.c:52
static int query_codec(enum AVCodecID id, int std_compliance)
Definition mp3enc.c:559
static int mp3_write_xing(AVFormatContext *s)
Definition mp3enc.c:149
static void mp3_deinit(struct AVFormatContext *s)
Definition mp3enc.c:717
static int mp3_write_header(struct AVFormatContext *s)
Definition mp3enc.c:686
static int id3v1_set_string(AVFormatContext *s, const char *key, uint8_t *buf, int buf_size)
Definition mp3enc.c:42
static int mp3_finish_id3v2(AVFormatContext *s)
Definition mp3enc.c:406
#define XING_SIZE
Definition mp3enc.c:98
static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition mp3enc.c:591
#define XING_TOC_SIZE
Definition mp3enc.c:96
static int mp3_write_trailer(struct AVFormatContext *s)
Definition mp3enc.c:535
mpeg audio declarations for both encoder and decoder.
#define MPA_MONO
Definition mpegaudio.h:49
#define MPA_STEREO
Definition mpegaudio.h:46
mpeg audio layer common tables.
FF_VISIBILITY_PUSH_HIDDEN const uint16_t ff_mpa_bitrate_tab[2][3][15]
const uint16_t ff_mpa_freq_tab[3]
int avpriv_mpegaudio_decode_header2(MPADecodeHeader2 **phdr, uint32_t header)
Decode an MPEG audio header into *phdr, which is allocated if it is NULL.
MPEG Audio header decoder.
static uint32_t ff_mpa_encode_header(const MPADecodeHeader2 *s)
AVOptions.
static const uint8_t header[24]
Definition sdr2.c:68
#define FF_ARRAY_ELEMS(a)
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
This struct describes the properties of an encoded stream.
Definition codec_par.h:49
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
char * value
Definition dict.h:92
Format I/O context.
Definition avformat.h:1337
Bytestream IO Context.
Definition avio.h:160
int error
contains the error code or 0 if no error happened
Definition avio.h:239
AVOption.
Definition opt.h:428
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition packet.h:424
uint8_t * data
Definition packet.h:425
This structure stores compressed data.
Definition packet.h:580
ReplayGain information (see http://wiki.hydrogenaudio.org/index.php?title=ReplayGain_1....
Definition replaygain.h:29
uint32_t track_peak
Peak track amplitude, with 100000 representing full scale (but values may overflow).
Definition replaygain.h:39
int32_t track_gain
Track replay gain in microbels (divide by 100000 to get the value in dB).
Definition replaygain.h:34
int32_t album_gain
Same as track_gain, but for the whole album.
Definition replaygain.h:43
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
AVPacket * pkt
Used to hold temporary packets for the generic demuxing code.
Definition internal.h:111
ID3v2EncContext id3
Definition mp3enc.c:102
uint32_t want
Definition mp3enc.c:123
int pics_to_write
Definition mp3enc.c:138
uint64_t bag[XING_NUM_BAGS]
Definition mp3enc.c:126
int xing_frame_size
Definition mp3enc.c:111
int initial_bitrate
Definition mp3enc.c:127
uint32_t audio_size
Definition mp3enc.c:114
int64_t padding
Definition mp3enc.c:133
AVIOContext * id3_pb
Definition mp3enc.c:103
AVCRC audio_crc
Definition mp3enc.c:113
int id3v2_version
Definition mp3enc.c:104
int audio_stream_idx
Definition mp3enc.c:136
MPADecodeHeader2 * hdr
Definition mp3enc.c:129
PacketList queue
Definition mp3enc.c:141
MPADecodeHeader2 * xing_header
Definition mp3enc.c:130
int write_xing
Definition mp3enc.c:106
int xing_offset
Definition mp3enc.c:119
int32_t frames
Definition mp3enc.c:121
uint8_t * xing_frame
Definition mp3enc.c:110
int write_id3v1
Definition mp3enc.c:105
int64_t xing_frame_offset
Definition mp3enc.c:117
MPADecodeHeader2 * first_frame
Definition mp3enc.c:131
int has_variable_bitrate
Definition mp3enc.c:128
int32_t size
Definition mp3enc.c:122
uint32_t pos
Definition mp3enc.c:125
int delay
Definition mp3enc.c:132
uint32_t seen
Definition mp3enc.c:124
Same as MPADecodeHeader, plus the header fields that carry no decoding information.
PacketListEntry * head
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
int size
uint8_t base
Definition vp3data.h:128