FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/mp3enc.c
Date: 2026-09-19 14:27:34
Exec Total Coverage
Lines: 261 361 72.3%
Functions: 12 14 85.7%
Branches: 130 219 59.4%

Line Branch Exec Source
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"
30 #include "libavcodec/mpegaudio.h"
31 #include "libavcodec/mpegaudiodata.h"
32 #include "libavcodec/mpegaudiodecheader.h"
33 #include "packet_internal.h"
34 #include "libavutil/intreadwrite.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/crc.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/replaygain.h"
41
42 static int id3v1_set_string(AVFormatContext *s, const char *key,
43 uint8_t *buf, int buf_size)
44 {
45 AVDictionaryEntry *tag;
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
52 static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
53 {
54 AVDictionaryEntry *tag;
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
100 typedef struct MP3Context {
101 const AVClass *class;
102 ID3v2EncContext id3;
103 AVIOContext *id3_pb;
104 int id3v2_version;
105 int write_id3v1;
106 int write_xing;
107
108 /* xing header */
109 // a buffer containing the whole XING/LAME frame
110 uint8_t *xing_frame;
111 int xing_frame_size;
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
117 int64_t xing_frame_offset;
118 // offset of the XING/INFO tag in the frame
119 int xing_offset;
120
121 int32_t frames;
122 int32_t size;
123 uint32_t want;
124 uint32_t seen;
125 uint32_t pos;
126 uint64_t bag[XING_NUM_BAGS];
127 int initial_bitrate;
128 int has_variable_bitrate;
129 MPADecodeHeader2 *hdr;
130 MPADecodeHeader2 *xing_header;
131 MPADecodeHeader2 *first_frame;
132 int delay;
133 int64_t padding;
134
135 /* index of the audio stream */
136 int audio_stream_idx;
137 /* number of attached pictures we still need to write */
138 int pics_to_write;
139
140 /* audio packets are queued here until we get all the attached pictures */
141 PacketList queue;
142 } MP3Context;
143
144 static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
145
146 /*
147 * Write an empty XING header and initialize respective data.
148 */
149 29 static int mp3_write_xing(AVFormatContext *s)
150 {
151 29 MP3Context *mp3 = s->priv_data;
152 29 AVCodecParameters *par = s->streams[mp3->audio_stream_idx]->codecpar;
153 29 AVDictionaryEntry *enc = av_dict_get(s->streams[mp3->audio_stream_idx]->metadata, "encoder", NULL, 0);
154 AVIOContext *dyn_ctx;
155 int32_t header;
156 int srate_idx, i, channels;
157 int bitrate_idx;
158 29 int best_bitrate_idx = -1;
159 29 int best_bitrate_error = INT_MAX;
160 int ret;
161 29 int ver = 0;
162 int bytes_needed;
163
164
3/4
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 2 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 27 times.
29 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) || !mp3->write_xing)
165 2 return 0;
166
167
1/2
✓ Branch 0 taken 49 times.
✗ Branch 1 not taken.
49 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++) {
168 49 const uint16_t base_freq = ff_mpa_freq_tab[i];
169
170
2/2
✓ Branch 0 taken 26 times.
✓ Branch 1 taken 23 times.
49 if (par->sample_rate == base_freq) ver = 0x3; // MPEG 1
171
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 23 times.
23 else if (par->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
172
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 22 times.
23 else if (par->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
173 22 else continue;
174
175 27 srate_idx = i;
176 27 break;
177 }
178
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
179 av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing header.\n");
180 return 0;
181 }
182
183
2/3
✓ Branch 0 taken 23 times.
✓ Branch 1 taken 4 times.
✗ Branch 2 not taken.
27 switch (par->ch_layout.nb_channels) {
184 23 case 1: channels = MPA_MONO; break;
185 4 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 27 header = 0xffU << 24; // sync
193 27 header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
194 27 header |= (srate_idx << 2) << 8;
195 27 header |= channels << 6;
196
197
2/2
✓ Branch 0 taken 378 times.
✓ Branch 1 taken 27 times.
405 for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
198 378 int bit_rate = 1000 * ff_mpa_bitrate_tab[ver != 3][3 - 1][bitrate_idx];
199 378 int error = FFABS(bit_rate - par->bit_rate);
200
201
2/2
✓ Branch 0 taken 158 times.
✓ Branch 1 taken 220 times.
378 if (error < best_bitrate_error) {
202 158 best_bitrate_error = error;
203 158 best_bitrate_idx = bitrate_idx;
204 }
205 }
206
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 av_assert0(best_bitrate_idx >= 0);
207
208 27 for (bitrate_idx = best_bitrate_idx; ; bitrate_idx++) {
209 29 int32_t mask = bitrate_idx << (4 + 8);
210
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
29 if (15 == bitrate_idx)
211 return 0;
212 29 header |= mask;
213
214 29 ret = avpriv_mpegaudio_decode_header2(&mp3->xing_header, header);
215
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
29 if (ret < 0)
216 return ret;
217 29 mp3->xing_offset = xing_offtbl[mp3->xing_header->lsf == 1][mp3->xing_header->nb_channels == 1] + 4;
218 29 bytes_needed = mp3->xing_offset + XING_SIZE;
219
220
2/2
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 2 times.
29 if (bytes_needed <= mp3->xing_header->frame_size)
221 27 break;
222
223 2 header &= ~mask;
224 }
225
226 27 ret = avio_open_dyn_buf(&dyn_ctx);
227
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 if (ret < 0)
228 return ret;
229
230 27 avio_wb32(dyn_ctx, header);
231
232 27 ffio_fill(dyn_ctx, 0, mp3->xing_offset - 4);
233 27 ffio_wfourcc(dyn_ctx, "Xing");
234 27 avio_wb32(dyn_ctx, 0x01 | 0x02 | 0x04 | 0x08); // frames / size / TOC / vbr scale
235
236 27 mp3->size = mp3->xing_header->frame_size;
237 27 mp3->want=1;
238 27 mp3->seen=0;
239 27 mp3->pos=0;
240
241 27 avio_wb32(dyn_ctx, 0); // frames
242 27 avio_wb32(dyn_ctx, 0); // size
243
244 // TOC
245
2/2
✓ Branch 0 taken 2700 times.
✓ Branch 1 taken 27 times.
2727 for (i = 0; i < XING_TOC_SIZE; i++)
246 2700 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 27 avio_wb32(dyn_ctx, 0);
251
252 // encoder short version string
253
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 24 times.
27 if (enc) {
254 3 uint8_t encoder_str[9] = { 0 };
255
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
3 if ( strlen(enc->value) > sizeof(encoder_str)
256 && !strcmp("Lavc libmp3lame", enc->value)) {
257 memcpy(encoder_str, "Lavf lame", 9);
258 } else
259
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 memcpy(encoder_str, enc->value, FFMIN(strlen(enc->value), sizeof(encoder_str)));
260
261 3 avio_write(dyn_ctx, encoder_str, sizeof(encoder_str));
262 } else
263 24 avio_write(dyn_ctx, "Lavf\0\0\0\0\0", 9);
264
265 27 avio_w8(dyn_ctx, 0); // tag revision 0 / unknown vbr method
266 27 avio_w8(dyn_ctx, 0); // unknown lowpass filter value
267 27 ffio_fill(dyn_ctx, 0, 8); // empty replaygain fields
268 27 avio_w8(dyn_ctx, 0); // unknown encoding flags
269 27 avio_w8(dyn_ctx, 0); // unknown abr/minimal bitrate
270 27 avio_wb24(dyn_ctx, 0); // empty encoder delay/padding
271
272 27 avio_w8(dyn_ctx, 0); // misc
273 27 avio_w8(dyn_ctx, 0); // mp3gain
274 27 avio_wb16(dyn_ctx, 0); // preset
275
276 // audio length and CRCs (will be updated later)
277 27 avio_wb32(dyn_ctx, 0); // music length
278 27 avio_wb16(dyn_ctx, 0); // music crc
279 27 avio_wb16(dyn_ctx, 0); // tag crc
280
281 27 ffio_fill(dyn_ctx, 0, mp3->xing_header->frame_size - bytes_needed);
282
283 27 mp3->xing_frame_size = avio_close_dyn_buf(dyn_ctx, &mp3->xing_frame);
284 27 mp3->xing_frame_offset = avio_tell(s->pb);
285 27 avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
286
287 27 mp3->audio_size = mp3->xing_frame_size;
288
289 27 return 0;
290 }
291
292 /*
293 * Add a frame to XING data.
294 * Following lame's "VbrTag.c".
295 */
296 2051 static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
297 {
298 int i;
299
300 2051 mp3->frames++;
301 2051 mp3->seen++;
302 2051 mp3->size += pkt->size;
303
304
2/2
✓ Branch 0 taken 1953 times.
✓ Branch 1 taken 98 times.
2051 if (mp3->want == mp3->seen) {
305 1953 mp3->bag[mp3->pos] = mp3->size;
306
307
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1952 times.
1953 if (XING_NUM_BAGS == ++mp3->pos) {
308 /* shrink table to half size by throwing away each second bag. */
309
2/2
✓ Branch 0 taken 200 times.
✓ Branch 1 taken 1 times.
201 for (i = 1; i < XING_NUM_BAGS; i += 2)
310 200 mp3->bag[i >> 1] = mp3->bag[i];
311
312 /* double wanted amount per bag. */
313 1 mp3->want *= 2;
314 /* adjust current position to half of table size. */
315 1 mp3->pos = XING_NUM_BAGS / 2;
316 }
317
318 1953 mp3->seen = 0;
319 }
320 2051 }
321
322 2093 static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
323 {
324 2093 MP3Context *mp3 = s->priv_data;
325
326
2/4
✓ Branch 0 taken 2093 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2093 times.
✗ Branch 3 not taken.
2093 if (pkt->data && pkt->size >= 4) {
327 int ret;
328 uint32_t h;
329
330 2093 h = AV_RB32(pkt->data);
331 2093 ret = avpriv_mpegaudio_decode_header2(&mp3->hdr, h);
332
1/2
✓ Branch 0 taken 2093 times.
✗ Branch 1 not taken.
2093 if (ret >= 0) {
333
2/2
✓ Branch 0 taken 29 times.
✓ Branch 1 taken 2064 times.
2093 if (!mp3->initial_bitrate)
334 29 mp3->initial_bitrate = mp3->hdr->bit_rate;
335
3/4
✓ Branch 0 taken 2093 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 140 times.
✓ Branch 3 taken 1953 times.
2093 if ((mp3->hdr->bit_rate == 0) || (mp3->initial_bitrate != mp3->hdr->bit_rate))
336 140 mp3->has_variable_bitrate = 1;
337
4/4
✓ Branch 0 taken 2051 times.
✓ Branch 1 taken 42 times.
✓ Branch 2 taken 27 times.
✓ Branch 3 taken 2024 times.
2093 if (mp3->xing_offset && !mp3->first_frame) {
338 27 const MPADecodeHeader2 *xing = mp3->xing_header;
339
340
1/2
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
27 if (mp3->hdr->layer != xing->layer ||
341
1/2
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
27 mp3->hdr->sample_rate != xing->sample_rate ||
342
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 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
350 27 ret = avpriv_mpegaudio_decode_header2(&mp3->first_frame, h);
351
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 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
2/2
✓ Branch 0 taken 2051 times.
✓ Branch 1 taken 42 times.
2093 if (mp3->xing_offset) {
380 2051 uint8_t *side_data = NULL;
381 size_t side_data_size;
382
383 2051 mp3_xing_add_frame(mp3, pkt);
384 2051 mp3->audio_size += pkt->size;
385 4102 mp3->audio_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE),
386 2051 mp3->audio_crc, pkt->data, pkt->size);
387
388 2051 side_data = av_packet_get_side_data(pkt,
389 AV_PKT_DATA_SKIP_SAMPLES,
390 &side_data_size);
391
3/4
✓ Branch 0 taken 15 times.
✓ Branch 1 taken 2036 times.
✓ Branch 2 taken 15 times.
✗ Branch 3 not taken.
2066 if (side_data && side_data_size >= 10) {
392 15 uint32_t discard_padding = AV_RL32(side_data + 4);
393 /* Padding longer than a frame is spread over several packets. */
394
2/2
✓ Branch 0 taken 7 times.
✓ Branch 1 taken 8 times.
15 mp3->padding = discard_padding ? mp3->padding + discard_padding : 0;
395
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 5 times.
15 if (!mp3->delay)
396
2/2
✓ Branch 0 taken 7 times.
✓ Branch 1 taken 3 times.
10 mp3->delay = FFMAX((int64_t)AV_RL32(side_data) - 528 - 1, 0);
397 } else {
398 2036 mp3->padding = 0;
399 }
400 }
401 }
402
403 2093 return ff_raw_write_packet(s, pkt);
404 }
405
406 29 static int mp3_finish_id3v2(AVFormatContext *s)
407 {
408 29 MP3Context *mp3 = s->priv_data;
409
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 27 times.
29 AVIOContext *pb = mp3->id3_pb ? mp3->id3_pb : s->pb;
410 29 uint8_t *buf = NULL;
411 int ret, size;
412
413 29 ff_id3v2_finish(&mp3->id3, pb, s->metadata_header_padding);
414 29 ret = pb->error;
415
416
2/2
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 2 times.
29 if (!mp3->id3_pb)
417 27 return ret;
418
419 2 size = avio_get_dyn_buf(mp3->id3_pb, &buf);
420 2 ret = mp3->id3_pb->error;
421
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 if (ret >= 0) {
422 2 avio_write(s->pb, buf, size);
423 2 ret = s->pb->error;
424 }
425 2 ffio_free_dyn_buf(&mp3->id3_pb);
426
427 2 return ret;
428 }
429
430 3 static int mp3_queue_flush(AVFormatContext *s)
431 {
432 3 MP3Context *mp3 = s->priv_data;
433 3 AVPacket *const pkt = ffformatcontext(s)->pkt;
434 3 int ret = 0, write = 1;
435
436 3 ret = mp3_finish_id3v2(s);
437
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 if (ret >= 0)
438 3 ret = mp3_write_xing(s);
439
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
3 if (ret < 0)
440 write = 0;
441
442
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 3 times.
6 while (mp3->queue.head) {
443 3 ff_packet_list_get(&mp3->queue, pkt);
444
2/4
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 3 times.
3 if (write && (ret = mp3_write_audio_packet(s, pkt)) < 0)
445 write = 0;
446 3 av_packet_unref(pkt);
447 }
448 3 return ret;
449 }
450
451 27 static void mp3_update_xing(AVFormatContext *s)
452 {
453 27 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 27 int64_t old_pos = avio_tell(s->pb);
460
461 /* replace "Xing" identification string with "Info" for CBR files. */
462
2/2
✓ Branch 0 taken 26 times.
✓ Branch 1 taken 1 times.
27 if (!mp3->has_variable_bitrate)
463 26 AV_WL32(mp3->xing_frame + mp3->xing_offset, MKTAG('I', 'n', 'f', 'o'));
464
465
1/2
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
27 if (mp3->first_frame) {
466 27 MPADecodeHeader2 *header = mp3->first_frame;
467
468 27 header->error_protection = mp3->xing_header->error_protection;
469 27 header->bitrate_index = mp3->xing_header->bitrate_index;
470 27 header->padding = mp3->xing_header->padding;
471 27 AV_WB32(mp3->xing_frame, ff_mpa_encode_header(header));
472 }
473
474 27 AV_WB32(mp3->xing_frame + mp3->xing_offset + 8, mp3->frames);
475 27 AV_WB32(mp3->xing_frame + mp3->xing_offset + 12, mp3->size);
476
477 27 toc = mp3->xing_frame + mp3->xing_offset + 16;
478 27 toc[0] = 0; // first toc entry has to be zero.
479
2/2
✓ Branch 0 taken 2673 times.
✓ Branch 1 taken 27 times.
2700 for (i = 1; i < XING_TOC_SIZE; ++i) {
480 2673 int j = i * mp3->pos / XING_TOC_SIZE;
481 2673 int seek_point = 256LL * mp3->bag[j] / mp3->size;
482 2673 toc[i] = FFMIN(seek_point, 255);
483 }
484
485 /* write replaygain */
486 27 sd = av_packet_side_data_get(s->streams[0]->codecpar->coded_side_data,
487 27 s->streams[0]->codecpar->nb_coded_side_data,
488 AV_PKT_DATA_REPLAYGAIN);
489
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
27 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
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 22 times.
27 if (mp3->padding)
513 5 mp3->padding += 528 + 1;
514
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 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
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 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 27 AV_WB24(mp3->xing_frame + mp3->xing_offset + 141, (mp3->delay << 12) + mp3->padding);
523
524 27 AV_WB32(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 8, mp3->audio_size);
525 27 AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 4, mp3->audio_crc);
526
527 27 tag_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE), 0, mp3->xing_frame, 190);
528 27 AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 2, tag_crc);
529
530 27 avio_seek(s->pb, mp3->xing_frame_offset, SEEK_SET);
531 27 avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
532 27 avio_seek(s->pb, old_pos, SEEK_SET);
533 27 }
534
535 29 static int mp3_write_trailer(struct AVFormatContext *s)
536 {
537 uint8_t buf[ID3v1_TAG_SIZE];
538 29 MP3Context *mp3 = s->priv_data;
539 int ret;
540
541
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
29 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
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
29 if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
550 avio_write(s->pb, buf, ID3v1_TAG_SIZE);
551 }
552
553
2/2
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 2 times.
29 if (mp3->xing_offset)
554 27 mp3_update_xing(s);
555
556 29 return 0;
557 }
558
559 24 static int query_codec(enum AVCodecID id, int std_compliance)
560 {
561 24 const CodecMime *cm= ff_id3v2_mime_tags;
562
563
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 24 times.
24 if (id == AV_CODEC_ID_MP3)
564 return 1;
565
566
1/2
✓ Branch 0 taken 120 times.
✗ Branch 1 not taken.
120 while(cm->id != AV_CODEC_ID_NONE) {
567
2/2
✓ Branch 0 taken 24 times.
✓ Branch 1 taken 96 times.
120 if(id == cm->id)
568 24 return MKTAG('A', 'P', 'I', 'C');
569 96 cm++;
570 }
571 return 0;
572 }
573
574 static 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
584 static 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
591 2098 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
592 {
593 2098 MP3Context *mp3 = s->priv_data;
594
595
2/2
✓ Branch 0 taken 2093 times.
✓ Branch 1 taken 5 times.
2098 if (pkt->stream_index == mp3->audio_stream_idx) {
596
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 2090 times.
2093 if (mp3->pics_to_write) {
597 /* buffer audio packets until we get all the pictures */
598 3 int ret = ff_packet_list_put(&mp3->queue, pkt, NULL, 0);
599
600
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
3 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;
605 return mp3_write_audio_packet(s, pkt);
606 }
607 } else
608 2090 return mp3_write_audio_packet(s, pkt);
609 } else {
610
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 4 times.
5 AVIOContext *pb = mp3->id3_pb ? mp3->id3_pb : s->pb;
611 int ret;
612
613 /* warn only once for each stream */
614
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 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
2/4
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 5 times.
5 if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
619 return 0;
620
621 5 ret = ff_id3v2_write_apic(s, pb, &mp3->id3, pkt);
622
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (ret < 0)
623 return ret;
624
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (pb->error < 0)
625 return pb->error;
626 5 mp3->pics_to_write--;
627
628 /* flush the buffered audio packets */
629
3/4
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 2 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 3 times.
8 if (!mp3->pics_to_write &&
630 3 (ret = mp3_queue_flush(s)) < 0)
631 return ret;
632 }
633
634 8 return 0;
635 }
636
637 /**
638 * Write an ID3v2 header at beginning of stream
639 */
640
641 29 static int mp3_init(struct AVFormatContext *s)
642 {
643 29 MP3Context *mp3 = s->priv_data;
644 int i;
645
646
1/2
✓ Branch 0 taken 29 times.
✗ Branch 1 not taken.
29 if (mp3->id3v2_version &&
647
2/2
✓ Branch 0 taken 26 times.
✓ Branch 1 taken 3 times.
29 mp3->id3v2_version != 3 &&
648
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 26 times.
26 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 29 mp3->audio_stream_idx = -1;
657
2/2
✓ Branch 0 taken 34 times.
✓ Branch 1 taken 29 times.
63 for (i = 0; i < s->nb_streams; i++) {
658 34 AVStream *st = s->streams[i];
659
2/2
✓ Branch 0 taken 29 times.
✓ Branch 1 taken 5 times.
34 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
660
2/4
✓ Branch 0 taken 29 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 29 times.
29 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 29 mp3->audio_stream_idx = i;
666
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 } 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
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
29 if (mp3->audio_stream_idx < 0) {
672 av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
673 return AVERROR(EINVAL);
674 }
675 29 mp3->pics_to_write = s->nb_streams - 1;
676
677
3/4
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 26 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 3 times.
29 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 29 return 0;
684 }
685
686 29 static int mp3_write_header(struct AVFormatContext *s)
687 {
688 29 MP3Context *mp3 = s->priv_data;
689 29 AVIOContext *pb = s->pb;
690 int ret;
691
692
1/2
✓ Branch 0 taken 29 times.
✗ Branch 1 not taken.
29 if (mp3->id3v2_version) {
693
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 27 times.
29 if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
694 2 ret = avio_open_dyn_buf(&mp3->id3_pb);
695
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2 times.
2 if (ret < 0)
696 return ret;
697 2 pb = mp3->id3_pb;
698 }
699
700 29 ff_id3v2_start(&mp3->id3, pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
701 29 ret = ff_id3v2_write_metadata(s, pb, &mp3->id3);
702
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
29 if (ret < 0)
703 return ret;
704
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 29 times.
29 if (pb->error < 0)
705 return pb->error;
706 }
707
708
2/2
✓ Branch 0 taken 26 times.
✓ Branch 1 taken 3 times.
29 if (!mp3->pics_to_write) {
709
2/4
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 26 times.
26 if (mp3->id3v2_version && (ret = mp3_finish_id3v2(s)) < 0)
710 return ret;
711 26 return mp3_write_xing(s);
712 }
713
714 3 return 0;
715 }
716
717 29 static void mp3_deinit(struct AVFormatContext *s)
718 {
719 29 MP3Context *mp3 = s->priv_data;
720
721 29 ff_packet_list_free(&mp3->queue);
722 29 ffio_free_dyn_buf(&mp3->id3_pb);
723 29 av_freep(&mp3->xing_frame);
724 29 av_freep(&mp3->hdr);
725 29 av_freep(&mp3->xing_header);
726 29 av_freep(&mp3->first_frame);
727 29 }
728
729 const FFOutputFormat ff_mp3_muxer = {
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 };
746