]> git.sesse.net Git - ffmpeg/blob - libavformat/id3v2.c
avformat/id3v2: Check against max compression ratio before allocation
[ffmpeg] / libavformat / id3v2.c
1 /*
2  * Copyright (c) 2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * ID3v2 header parser
24  *
25  * Specifications available at:
26  * http://id3.org/Developer_Information
27  */
28
29 #include "config.h"
30
31 #if CONFIG_ZLIB
32 #include <zlib.h>
33 #endif
34
35 #include "libavutil/avstring.h"
36 #include "libavutil/bprint.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavcodec/png.h"
40 #include "avio_internal.h"
41 #include "internal.h"
42 #include "id3v1.h"
43 #include "id3v2.h"
44
45 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
46     { "TALB", "album"        },
47     { "TCOM", "composer"     },
48     { "TCON", "genre"        },
49     { "TCOP", "copyright"    },
50     { "TENC", "encoded_by"   },
51     { "TIT2", "title"        },
52     { "TLAN", "language"     },
53     { "TPE1", "artist"       },
54     { "TPE2", "album_artist" },
55     { "TPE3", "performer"    },
56     { "TPOS", "disc"         },
57     { "TPUB", "publisher"    },
58     { "TRCK", "track"        },
59     { "TSSE", "encoder"      },
60     { "USLT", "lyrics"       },
61     { 0 }
62 };
63
64 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
65     { "TCMP", "compilation"   },
66     { "TDRC", "date"          },
67     { "TDRL", "date"          },
68     { "TDEN", "creation_time" },
69     { "TSOA", "album-sort"    },
70     { "TSOP", "artist-sort"   },
71     { "TSOT", "title-sort"    },
72     { 0 }
73 };
74
75 static const AVMetadataConv id3v2_2_metadata_conv[] = {
76     { "TAL", "album"        },
77     { "TCO", "genre"        },
78     { "TCP", "compilation"  },
79     { "TT2", "title"        },
80     { "TEN", "encoded_by"   },
81     { "TP1", "artist"       },
82     { "TP2", "album_artist" },
83     { "TP3", "performer"    },
84     { "TRK", "track"        },
85     { 0 }
86 };
87
88 const char ff_id3v2_tags[][4] = {
89     "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
90     "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
91     "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
92     "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
93     { 0 },
94 };
95
96 const char ff_id3v2_4_tags[][4] = {
97     "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
98     "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
99     { 0 },
100 };
101
102 const char ff_id3v2_3_tags[][4] = {
103     "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
104     { 0 },
105 };
106
107 const char * const ff_id3v2_picture_types[21] = {
108     "Other",
109     "32x32 pixels 'file icon'",
110     "Other file icon",
111     "Cover (front)",
112     "Cover (back)",
113     "Leaflet page",
114     "Media (e.g. label side of CD)",
115     "Lead artist/lead performer/soloist",
116     "Artist/performer",
117     "Conductor",
118     "Band/Orchestra",
119     "Composer",
120     "Lyricist/text writer",
121     "Recording Location",
122     "During recording",
123     "During performance",
124     "Movie/video screen capture",
125     "A bright coloured fish",
126     "Illustration",
127     "Band/artist logotype",
128     "Publisher/Studio logotype",
129 };
130
131 const CodecMime ff_id3v2_mime_tags[] = {
132     { "image/gif",  AV_CODEC_ID_GIF   },
133     { "image/jpeg", AV_CODEC_ID_MJPEG },
134     { "image/jpg",  AV_CODEC_ID_MJPEG },
135     { "image/png",  AV_CODEC_ID_PNG   },
136     { "image/tiff", AV_CODEC_ID_TIFF  },
137     { "image/bmp",  AV_CODEC_ID_BMP   },
138     { "JPG",        AV_CODEC_ID_MJPEG }, /* ID3v2.2  */
139     { "PNG",        AV_CODEC_ID_PNG   }, /* ID3v2.2  */
140     { "",           AV_CODEC_ID_NONE  },
141 };
142
143 int ff_id3v2_match(const uint8_t *buf, const char *magic)
144 {
145     return  buf[0]         == magic[0] &&
146             buf[1]         == magic[1] &&
147             buf[2]         == magic[2] &&
148             buf[3]         != 0xff     &&
149             buf[4]         != 0xff     &&
150            (buf[6] & 0x80) == 0        &&
151            (buf[7] & 0x80) == 0        &&
152            (buf[8] & 0x80) == 0        &&
153            (buf[9] & 0x80) == 0;
154 }
155
156 int ff_id3v2_tag_len(const uint8_t *buf)
157 {
158     int len = ((buf[6] & 0x7f) << 21) +
159               ((buf[7] & 0x7f) << 14) +
160               ((buf[8] & 0x7f) << 7) +
161               (buf[9] & 0x7f) +
162               ID3v2_HEADER_SIZE;
163     if (buf[5] & 0x10)
164         len += ID3v2_HEADER_SIZE;
165     return len;
166 }
167
168 static unsigned int get_size(AVIOContext *s, int len)
169 {
170     int v = 0;
171     while (len--)
172         v = (v << 7) + (avio_r8(s) & 0x7F);
173     return v;
174 }
175
176 static unsigned int size_to_syncsafe(unsigned int size)
177 {
178     return (((size) & (0x7f <<  0)) >> 0) +
179            (((size) & (0x7f <<  8)) >> 1) +
180            (((size) & (0x7f << 16)) >> 2) +
181            (((size) & (0x7f << 24)) >> 3);
182 }
183
184 /* No real verification, only check that the tag consists of
185  * a combination of capital alpha-numerical characters */
186 static int is_tag(const char *buf, unsigned int len)
187 {
188     if (!len)
189         return 0;
190
191     while (len--)
192         if ((buf[len] < 'A' ||
193              buf[len] > 'Z') &&
194             (buf[len] < '0' ||
195              buf[len] > '9'))
196             return 0;
197
198     return 1;
199 }
200
201 /**
202  * Return 1 if the tag of length len at the given offset is valid, 0 if not, -1 on error
203  */
204 static int check_tag(AVIOContext *s, int offset, unsigned int len)
205 {
206     char tag[4];
207
208     if (len > 4 ||
209         avio_seek(s, offset, SEEK_SET) < 0 ||
210         avio_read(s, tag, len) < (int)len)
211         return -1;
212     else if (!AV_RB32(tag) || is_tag(tag, len))
213         return 1;
214
215     return 0;
216 }
217
218 /**
219  * Free GEOB type extra metadata.
220  */
221 static void free_geobtag(void *obj)
222 {
223     ID3v2ExtraMetaGEOB *geob = obj;
224     av_freep(&geob->mime_type);
225     av_freep(&geob->file_name);
226     av_freep(&geob->description);
227     av_freep(&geob->data);
228 }
229
230 /**
231  * Decode characters to UTF-8 according to encoding type. The decoded buffer is
232  * always null terminated. Stop reading when either *maxread bytes are read from
233  * pb or U+0000 character is found.
234  *
235  * @param dst Pointer where the address of the buffer with the decoded bytes is
236  * stored. Buffer must be freed by caller.
237  * @param maxread Pointer to maximum number of characters to read from the
238  * AVIOContext. After execution the value is decremented by the number of bytes
239  * actually read.
240  * @returns 0 if no error occurred, dst is uninitialized on error
241  */
242 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
243                       uint8_t **dst, int *maxread)
244 {
245     int ret;
246     uint8_t tmp;
247     uint32_t ch = 1;
248     int left = *maxread;
249     unsigned int (*get)(AVIOContext*) = avio_rb16;
250     AVIOContext *dynbuf;
251
252     if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
253         av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
254         return ret;
255     }
256
257     switch (encoding) {
258     case ID3v2_ENCODING_ISO8859:
259         while (left && ch) {
260             ch = avio_r8(pb);
261             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
262             left--;
263         }
264         break;
265
266     case ID3v2_ENCODING_UTF16BOM:
267         if ((left -= 2) < 0) {
268             av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
269             ffio_free_dyn_buf(&dynbuf);
270             *dst = NULL;
271             return AVERROR_INVALIDDATA;
272         }
273         switch (avio_rb16(pb)) {
274         case 0xfffe:
275             get = avio_rl16;
276         case 0xfeff:
277             break;
278         default:
279             av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
280             ffio_free_dyn_buf(&dynbuf);
281             *dst = NULL;
282             *maxread = left;
283             return AVERROR_INVALIDDATA;
284         }
285         // fall-through
286
287     case ID3v2_ENCODING_UTF16BE:
288         while ((left > 1) && ch) {
289             GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
290             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
291         }
292         if (left < 0)
293             left += 2;  /* did not read last char from pb */
294         break;
295
296     case ID3v2_ENCODING_UTF8:
297         while (left && ch) {
298             ch = avio_r8(pb);
299             avio_w8(dynbuf, ch);
300             left--;
301         }
302         break;
303     default:
304         av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
305     }
306
307     if (ch)
308         avio_w8(dynbuf, 0);
309
310     avio_close_dyn_buf(dynbuf, dst);
311     *maxread = left;
312
313     return 0;
314 }
315
316 /**
317  * Parse a text tag.
318  */
319 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen,
320                       AVDictionary **metadata, const char *key)
321 {
322     uint8_t *dst;
323     int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
324     unsigned genre;
325
326     if (taglen < 1)
327         return;
328
329     encoding = avio_r8(pb);
330     taglen--; /* account for encoding type byte */
331
332     if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
333         av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
334         return;
335     }
336
337     if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))                         &&
338         (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1) &&
339         genre <= ID3v1_GENRE_MAX) {
340         av_freep(&dst);
341         dst = av_strdup(ff_id3v1_genre_str[genre]);
342     } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
343         /* dst now contains the key, need to get value */
344         key = dst;
345         if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
346             av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
347             av_freep(&key);
348             return;
349         }
350         dict_flags |= AV_DICT_DONT_STRDUP_KEY;
351     } else if (!*dst)
352         av_freep(&dst);
353
354     if (dst)
355         av_dict_set(metadata, key, dst, dict_flags);
356 }
357
358 static void read_uslt(AVFormatContext *s, AVIOContext *pb, int taglen,
359                       AVDictionary **metadata)
360 {
361     uint8_t lang[4];
362     uint8_t *descriptor = NULL; // 'Content descriptor'
363     uint8_t *text;
364     char *key;
365     int encoding;
366     int ok = 0;
367
368     if (taglen < 1)
369         goto error;
370
371     encoding = avio_r8(pb);
372     taglen--;
373
374     if (avio_read(pb, lang, 3) < 3)
375         goto error;
376     lang[3] = '\0';
377     taglen -= 3;
378
379     if (decode_str(s, pb, encoding, &descriptor, &taglen) < 0)
380         goto error;
381
382     if (decode_str(s, pb, encoding, &text, &taglen) < 0)
383         goto error;
384
385     // FFmpeg does not support hierarchical metadata, so concatenate the keys.
386     key = av_asprintf("lyrics-%s%s%s", descriptor[0] ? (char *)descriptor : "",
387                                        descriptor[0] ? "-" : "",
388                                        lang);
389     if (!key) {
390         av_free(text);
391         goto error;
392     }
393
394     av_dict_set(metadata, key, text,
395                 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
396
397     ok = 1;
398 error:
399     if (!ok)
400         av_log(s, AV_LOG_ERROR, "Error reading lyrics, skipped\n");
401     av_free(descriptor);
402 }
403
404 /**
405  * Parse a comment tag.
406  */
407 static void read_comment(AVFormatContext *s, AVIOContext *pb, int taglen,
408                       AVDictionary **metadata)
409 {
410     const char *key = "comment";
411     uint8_t *dst;
412     int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
413     av_unused int language;
414
415     if (taglen < 4)
416         return;
417
418     encoding = avio_r8(pb);
419     language = avio_rl24(pb);
420     taglen -= 4;
421
422     if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
423         av_log(s, AV_LOG_ERROR, "Error reading comment frame, skipped\n");
424         return;
425     }
426
427     if (dst && !*dst)
428         av_freep(&dst);
429
430     if (dst) {
431         key = (const char *) dst;
432         dict_flags |= AV_DICT_DONT_STRDUP_KEY;
433     }
434
435     if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
436         av_log(s, AV_LOG_ERROR, "Error reading comment frame, skipped\n");
437         if (dict_flags & AV_DICT_DONT_STRDUP_KEY)
438             av_freep((void*)&key);
439         return;
440     }
441
442     if (dst)
443         av_dict_set(metadata, key, (const char *) dst, dict_flags);
444 }
445
446 /**
447  * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
448  */
449 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen,
450                          const char *tag, ID3v2ExtraMeta **extra_meta,
451                          int isv34)
452 {
453     ID3v2ExtraMetaGEOB *geob_data = NULL;
454     ID3v2ExtraMeta *new_extra     = NULL;
455     char encoding;
456     unsigned int len;
457
458     if (taglen < 1)
459         return;
460
461     new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
462     if (!new_extra) {
463         av_log(s, AV_LOG_ERROR, "Failed to alloc %"SIZE_SPECIFIER" bytes\n",
464                sizeof(ID3v2ExtraMeta));
465         return;
466     }
467
468     geob_data = &new_extra->data.geob;
469
470     /* read encoding type byte */
471     encoding = avio_r8(pb);
472     taglen--;
473
474     /* read MIME type (always ISO-8859) */
475     if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type,
476                    &taglen) < 0 ||
477         taglen <= 0)
478         goto fail;
479
480     /* read file name */
481     if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0 ||
482         taglen <= 0)
483         goto fail;
484
485     /* read content description */
486     if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0 ||
487         taglen < 0)
488         goto fail;
489
490     if (taglen) {
491         /* save encapsulated binary data */
492         geob_data->data = av_malloc(taglen);
493         if (!geob_data->data) {
494             av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
495             goto fail;
496         }
497         if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
498             av_log(s, AV_LOG_WARNING,
499                    "Error reading GEOB frame, data truncated.\n");
500         geob_data->datasize = len;
501     } else {
502         geob_data->data     = NULL;
503         geob_data->datasize = 0;
504     }
505
506     /* add data to the list */
507     new_extra->tag  = "GEOB";
508     new_extra->next = *extra_meta;
509     *extra_meta     = new_extra;
510
511     return;
512
513 fail:
514     av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
515     free_geobtag(geob_data);
516     av_free(new_extra);
517     return;
518 }
519
520 static int is_number(const char *str)
521 {
522     while (*str >= '0' && *str <= '9')
523         str++;
524     return !*str;
525 }
526
527 static AVDictionaryEntry *get_date_tag(AVDictionary *m, const char *tag)
528 {
529     AVDictionaryEntry *t;
530     if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
531         strlen(t->value) == 4 && is_number(t->value))
532         return t;
533     return NULL;
534 }
535
536 static void merge_date(AVDictionary **m)
537 {
538     AVDictionaryEntry *t;
539     char date[17] = { 0 };      // YYYY-MM-DD hh:mm
540
541     if (!(t = get_date_tag(*m, "TYER")) &&
542         !(t = get_date_tag(*m, "TYE")))
543         return;
544     av_strlcpy(date, t->value, 5);
545     av_dict_set(m, "TYER", NULL, 0);
546     av_dict_set(m, "TYE", NULL, 0);
547
548     if (!(t = get_date_tag(*m, "TDAT")) &&
549         !(t = get_date_tag(*m, "TDA")))
550         goto finish;
551     snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
552     av_dict_set(m, "TDAT", NULL, 0);
553     av_dict_set(m, "TDA", NULL, 0);
554
555     if (!(t = get_date_tag(*m, "TIME")) &&
556         !(t = get_date_tag(*m, "TIM")))
557         goto finish;
558     snprintf(date + 10, sizeof(date) - 10,
559              " %.2s:%.2s", t->value, t->value + 2);
560     av_dict_set(m, "TIME", NULL, 0);
561     av_dict_set(m, "TIM", NULL, 0);
562
563 finish:
564     if (date[0])
565         av_dict_set(m, "date", date, 0);
566 }
567
568 static void free_apic(void *obj)
569 {
570     ID3v2ExtraMetaAPIC *apic = obj;
571     av_buffer_unref(&apic->buf);
572     av_freep(&apic->description);
573 }
574
575 static void rstrip_spaces(char *buf)
576 {
577     size_t len = strlen(buf);
578     while (len > 0 && buf[len - 1] == ' ')
579         buf[--len] = 0;
580 }
581
582 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen,
583                       const char *tag, ID3v2ExtraMeta **extra_meta,
584                       int isv34)
585 {
586     int enc, pic_type;
587     char mimetype[64] = {0};
588     const CodecMime *mime     = ff_id3v2_mime_tags;
589     enum AVCodecID id         = AV_CODEC_ID_NONE;
590     ID3v2ExtraMetaAPIC *apic  = NULL;
591     ID3v2ExtraMeta *new_extra = NULL;
592     int64_t end               = avio_tell(pb) + taglen;
593
594     if (taglen <= 4 || (!isv34 && taglen <= 6))
595         goto fail;
596
597     new_extra = av_mallocz(sizeof(*new_extra));
598     if (!new_extra)
599         goto fail;
600
601     apic = &new_extra->data.apic;
602
603     enc = avio_r8(pb);
604     taglen--;
605
606     /* mimetype */
607     if (isv34) {
608         taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
609     } else {
610         if (avio_read(pb, mimetype, 3) < 0)
611             goto fail;
612
613         mimetype[3] = 0;
614         taglen    -= 3;
615     }
616
617     while (mime->id != AV_CODEC_ID_NONE) {
618         if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
619             id = mime->id;
620             break;
621         }
622         mime++;
623     }
624     if (id == AV_CODEC_ID_NONE) {
625         av_log(s, AV_LOG_WARNING,
626                "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
627         goto fail;
628     }
629     apic->id = id;
630
631     /* picture type */
632     pic_type = avio_r8(pb);
633     taglen--;
634     if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
635         av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
636                pic_type);
637         pic_type = 0;
638     }
639     apic->type = ff_id3v2_picture_types[pic_type];
640
641     /* description and picture data */
642     if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
643         av_log(s, AV_LOG_ERROR,
644                "Error decoding attached picture description.\n");
645         goto fail;
646     }
647
648     apic->buf = av_buffer_alloc(taglen + AV_INPUT_BUFFER_PADDING_SIZE);
649     if (!apic->buf || !taglen || avio_read(pb, apic->buf->data, taglen) != taglen)
650         goto fail;
651     memset(apic->buf->data + taglen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
652
653     new_extra->tag  = "APIC";
654     new_extra->next = *extra_meta;
655     *extra_meta     = new_extra;
656
657     // The description must be unique, and some ID3v2 tag writers add spaces
658     // to write several APIC entries with the same description.
659     rstrip_spaces(apic->description);
660
661     return;
662
663 fail:
664     if (apic)
665         free_apic(apic);
666     av_freep(&new_extra);
667     avio_seek(pb, end, SEEK_SET);
668 }
669
670 static void free_chapter(void *obj)
671 {
672     ID3v2ExtraMetaCHAP *chap = obj;
673     av_freep(&chap->element_id);
674     av_dict_free(&chap->meta);
675 }
676
677 static void read_chapter(AVFormatContext *s, AVIOContext *pb, int len, const char *ttag, ID3v2ExtraMeta **extra_meta, int isv34)
678 {
679     int taglen;
680     char tag[5];
681     ID3v2ExtraMeta *new_extra = NULL;
682     ID3v2ExtraMetaCHAP *chap  = NULL;
683
684     new_extra = av_mallocz(sizeof(*new_extra));
685     if (!new_extra)
686         return;
687
688     chap = &new_extra->data.chap;
689
690     if (decode_str(s, pb, 0, &chap->element_id, &len) < 0)
691         goto fail;
692
693     if (len < 16)
694         goto fail;
695
696     chap->start = avio_rb32(pb);
697     chap->end   = avio_rb32(pb);
698     avio_skip(pb, 8);
699
700     len -= 16;
701     while (len > 10) {
702         if (avio_read(pb, tag, 4) < 4)
703             goto fail;
704         tag[4] = 0;
705         taglen = avio_rb32(pb);
706         avio_skip(pb, 2);
707         len -= 10;
708         if (taglen < 0 || taglen > len)
709             goto fail;
710         if (tag[0] == 'T')
711             read_ttag(s, pb, taglen, &chap->meta, tag);
712         else
713             avio_skip(pb, taglen);
714         len -= taglen;
715     }
716
717     ff_metadata_conv(&chap->meta, NULL, ff_id3v2_34_metadata_conv);
718     ff_metadata_conv(&chap->meta, NULL, ff_id3v2_4_metadata_conv);
719
720     new_extra->tag  = "CHAP";
721     new_extra->next = *extra_meta;
722     *extra_meta     = new_extra;
723
724     return;
725
726 fail:
727     free_chapter(chap);
728     av_freep(&new_extra);
729 }
730
731 static void free_priv(void *obj)
732 {
733     ID3v2ExtraMetaPRIV *priv = obj;
734     av_freep(&priv->owner);
735     av_freep(&priv->data);
736 }
737
738 static void read_priv(AVFormatContext *s, AVIOContext *pb, int taglen,
739                       const char *tag, ID3v2ExtraMeta **extra_meta, int isv34)
740 {
741     ID3v2ExtraMeta *meta;
742     ID3v2ExtraMetaPRIV *priv;
743
744     meta = av_mallocz(sizeof(*meta));
745     if (!meta)
746         return;
747
748     priv = &meta->data.priv;
749
750     if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &priv->owner, &taglen) < 0)
751         goto fail;
752
753     priv->data = av_malloc(taglen);
754     if (!priv->data)
755         goto fail;
756
757     priv->datasize = taglen;
758
759     if (avio_read(pb, priv->data, priv->datasize) != priv->datasize)
760         goto fail;
761
762     meta->tag   = "PRIV";
763     meta->next  = *extra_meta;
764     *extra_meta = meta;
765
766     return;
767
768 fail:
769     free_priv(priv);
770     av_freep(&meta);
771 }
772
773 typedef struct ID3v2EMFunc {
774     const char *tag3;
775     const char *tag4;
776     void (*read)(AVFormatContext *s, AVIOContext *pb, int taglen,
777                  const char *tag, ID3v2ExtraMeta **extra_meta,
778                  int isv34);
779     void (*free)(void *obj);
780 } ID3v2EMFunc;
781
782 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
783     { "GEO", "GEOB", read_geobtag, free_geobtag },
784     { "PIC", "APIC", read_apic,    free_apic    },
785     { "CHAP","CHAP", read_chapter, free_chapter },
786     { "PRIV","PRIV", read_priv,    free_priv    },
787     { NULL }
788 };
789
790 /**
791  * Get the corresponding ID3v2EMFunc struct for a tag.
792  * @param isv34 Determines if v2.2 or v2.3/4 strings are used
793  * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
794  */
795 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
796 {
797     int i = 0;
798     while (id3v2_extra_meta_funcs[i].tag3) {
799         if (tag && !memcmp(tag,
800                     (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
801                              id3v2_extra_meta_funcs[i].tag3),
802                     (isv34 ? 4 : 3)))
803             return &id3v2_extra_meta_funcs[i];
804         i++;
805     }
806     return NULL;
807 }
808
809 static void id3v2_parse(AVIOContext *pb, AVDictionary **metadata,
810                         AVFormatContext *s, int len, uint8_t version,
811                         uint8_t flags, ID3v2ExtraMeta **extra_meta)
812 {
813     int isv34, unsync;
814     unsigned tlen;
815     char tag[5];
816     int64_t next, end = avio_tell(pb) + len;
817     int taghdrlen;
818     const char *reason = NULL;
819     AVIOContext pb_local;
820     AVIOContext *pbx;
821     unsigned char *buffer = NULL;
822     int buffer_size       = 0;
823     const ID3v2EMFunc *extra_func = NULL;
824     unsigned char *uncompressed_buffer = NULL;
825     av_unused int uncompressed_buffer_size = 0;
826     const char *comm_frame;
827
828     av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
829
830     switch (version) {
831     case 2:
832         if (flags & 0x40) {
833             reason = "compression";
834             goto error;
835         }
836         isv34     = 0;
837         taghdrlen = 6;
838         comm_frame = "COM";
839         break;
840
841     case 3:
842     case 4:
843         isv34     = 1;
844         taghdrlen = 10;
845         comm_frame = "COMM";
846         break;
847
848     default:
849         reason = "version";
850         goto error;
851     }
852
853     unsync = flags & 0x80;
854
855     if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
856         int extlen = get_size(pb, 4);
857         if (version == 4)
858             /* In v2.4 the length includes the length field we just read. */
859             extlen -= 4;
860
861         if (extlen < 0) {
862             reason = "invalid extended header length";
863             goto error;
864         }
865         avio_skip(pb, extlen);
866         len -= extlen + 4;
867         if (len < 0) {
868             reason = "extended header too long.";
869             goto error;
870         }
871     }
872
873     while (len >= taghdrlen) {
874         unsigned int tflags = 0;
875         int tunsync         = 0;
876         int tcomp           = 0;
877         int tencr           = 0;
878         unsigned long av_unused dlen;
879
880         if (isv34) {
881             if (avio_read(pb, tag, 4) < 4)
882                 break;
883             tag[4] = 0;
884             if (version == 3) {
885                 tlen = avio_rb32(pb);
886             } else {
887                 /* some encoders incorrectly uses v3 sizes instead of syncsafe ones
888                  * so check the next tag to see which one to use */
889                 tlen = avio_rb32(pb);
890                 if (tlen > 0x7f) {
891                     if (tlen < len) {
892                         int64_t cur = avio_tell(pb);
893
894                         if (ffio_ensure_seekback(pb, 2 /* tflags */ + tlen + 4 /* next tag */))
895                             break;
896
897                         if (check_tag(pb, cur + 2 + size_to_syncsafe(tlen), 4) == 1)
898                             tlen = size_to_syncsafe(tlen);
899                         else if (check_tag(pb, cur + 2 + tlen, 4) != 1)
900                             break;
901                         avio_seek(pb, cur, SEEK_SET);
902                     } else
903                         tlen = size_to_syncsafe(tlen);
904                 }
905             }
906             tflags  = avio_rb16(pb);
907             tunsync = tflags & ID3v2_FLAG_UNSYNCH;
908         } else {
909             if (avio_read(pb, tag, 3) < 3)
910                 break;
911             tag[3] = 0;
912             tlen   = avio_rb24(pb);
913         }
914         if (tlen > (1<<28))
915             break;
916         len -= taghdrlen + tlen;
917
918         if (len < 0)
919             break;
920
921         next = avio_tell(pb) + tlen;
922
923         if (!tlen) {
924             if (tag[0])
925                 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
926                        tag);
927             continue;
928         }
929
930         if (tflags & ID3v2_FLAG_DATALEN) {
931             if (tlen < 4)
932                 break;
933             dlen = avio_rb32(pb);
934             tlen -= 4;
935         } else
936             dlen = tlen;
937
938         tcomp = tflags & ID3v2_FLAG_COMPRESSION;
939         tencr = tflags & ID3v2_FLAG_ENCRYPTION;
940
941         /* skip encrypted tags and, if no zlib, compressed tags */
942         if (tencr || (!CONFIG_ZLIB && tcomp)) {
943             const char *type;
944             if (!tcomp)
945                 type = "encrypted";
946             else if (!tencr)
947                 type = "compressed";
948             else
949                 type = "encrypted and compressed";
950
951             av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
952             avio_skip(pb, tlen);
953         /* check for text tag or supported special meta tag */
954         } else if (tag[0] == 'T' ||
955                    !memcmp(tag, "USLT", 4) ||
956                    !strcmp(tag, comm_frame) ||
957                    (extra_meta &&
958                     (extra_func = get_extra_meta_func(tag, isv34)))) {
959             pbx = pb;
960
961             if (unsync || tunsync || tcomp) {
962                 av_fast_malloc(&buffer, &buffer_size, tlen);
963                 if (!buffer) {
964                     av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
965                     goto seek;
966                 }
967             }
968             if (unsync || tunsync) {
969                 uint8_t *b = buffer;
970                 uint8_t *t = buffer;
971                 uint8_t *end = t + tlen;
972
973                 if (avio_read(pb, buffer, tlen) != tlen) {
974                     av_log(s, AV_LOG_ERROR, "Failed to read tag data\n");
975                     goto seek;
976                 }
977
978                 while (t != end) {
979                     *b++ = *t++;
980                     if (t != end && t[-1] == 0xff && !t[0])
981                         t++;
982                 }
983
984                 ffio_init_context(&pb_local, buffer, b - buffer, 0, NULL, NULL, NULL,
985                                   NULL);
986                 tlen = b - buffer;
987                 pbx  = &pb_local; // read from sync buffer
988             }
989
990 #if CONFIG_ZLIB
991                 if (tcomp) {
992                     int err;
993
994                     av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
995
996                     if (tlen <= 0)
997                         goto seek;
998                     if (dlen / 32768 > tlen)
999                         goto seek;
1000
1001                     av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
1002                     if (!uncompressed_buffer) {
1003                         av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
1004                         goto seek;
1005                     }
1006
1007                     if (!(unsync || tunsync)) {
1008                         err = avio_read(pb, buffer, tlen);
1009                         if (err < 0) {
1010                             av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
1011                             goto seek;
1012                         }
1013                         tlen = err;
1014                     }
1015
1016                     err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
1017                     if (err != Z_OK) {
1018                         av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
1019                         goto seek;
1020                     }
1021                     ffio_init_context(&pb_local, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);
1022                     tlen = dlen;
1023                     pbx = &pb_local; // read from sync buffer
1024                 }
1025 #endif
1026             if (tag[0] == 'T')
1027                 /* parse text tag */
1028                 read_ttag(s, pbx, tlen, metadata, tag);
1029             else if (!memcmp(tag, "USLT", 4))
1030                 read_uslt(s, pbx, tlen, metadata);
1031             else if (!strcmp(tag, comm_frame))
1032                 read_comment(s, pbx, tlen, metadata);
1033             else
1034                 /* parse special meta tag */
1035                 extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);
1036         } else if (!tag[0]) {
1037             if (tag[1])
1038                 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
1039             avio_skip(pb, tlen);
1040             break;
1041         }
1042         /* Skip to end of tag */
1043 seek:
1044         avio_seek(pb, next, SEEK_SET);
1045     }
1046
1047     /* Footer preset, always 10 bytes, skip over it */
1048     if (version == 4 && flags & 0x10)
1049         end += 10;
1050
1051 error:
1052     if (reason)
1053         av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
1054                version, reason);
1055     avio_seek(pb, end, SEEK_SET);
1056     av_free(buffer);
1057     av_free(uncompressed_buffer);
1058     return;
1059 }
1060
1061 static void id3v2_read_internal(AVIOContext *pb, AVDictionary **metadata,
1062                                 AVFormatContext *s, const char *magic,
1063                                 ID3v2ExtraMeta **extra_meta, int64_t max_search_size)
1064 {
1065     int len, ret;
1066     uint8_t buf[ID3v2_HEADER_SIZE];
1067     int found_header;
1068     int64_t start, off;
1069
1070     if (max_search_size && max_search_size < ID3v2_HEADER_SIZE)
1071         return;
1072
1073     start = avio_tell(pb);
1074     do {
1075         /* save the current offset in case there's nothing to read/skip */
1076         off = avio_tell(pb);
1077         if (max_search_size && off - start >= max_search_size - ID3v2_HEADER_SIZE) {
1078             avio_seek(pb, off, SEEK_SET);
1079             break;
1080         }
1081
1082         ret = ffio_ensure_seekback(pb, ID3v2_HEADER_SIZE);
1083         if (ret >= 0)
1084             ret = avio_read(pb, buf, ID3v2_HEADER_SIZE);
1085         if (ret != ID3v2_HEADER_SIZE) {
1086             avio_seek(pb, off, SEEK_SET);
1087             break;
1088         }
1089         found_header = ff_id3v2_match(buf, magic);
1090         if (found_header) {
1091             /* parse ID3v2 header */
1092             len = ((buf[6] & 0x7f) << 21) |
1093                   ((buf[7] & 0x7f) << 14) |
1094                   ((buf[8] & 0x7f) << 7) |
1095                    (buf[9] & 0x7f);
1096             id3v2_parse(pb, metadata, s, len, buf[3], buf[5], extra_meta);
1097         } else {
1098             avio_seek(pb, off, SEEK_SET);
1099         }
1100     } while (found_header);
1101     ff_metadata_conv(metadata, NULL, ff_id3v2_34_metadata_conv);
1102     ff_metadata_conv(metadata, NULL, id3v2_2_metadata_conv);
1103     ff_metadata_conv(metadata, NULL, ff_id3v2_4_metadata_conv);
1104     merge_date(metadata);
1105 }
1106
1107 void ff_id3v2_read_dict(AVIOContext *pb, AVDictionary **metadata,
1108                         const char *magic, ID3v2ExtraMeta **extra_meta)
1109 {
1110     id3v2_read_internal(pb, metadata, NULL, magic, extra_meta, 0);
1111 }
1112
1113 void ff_id3v2_read(AVFormatContext *s, const char *magic,
1114                    ID3v2ExtraMeta **extra_meta, unsigned int max_search_size)
1115 {
1116     id3v2_read_internal(s->pb, &s->metadata, s, magic, extra_meta, max_search_size);
1117 }
1118
1119 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
1120 {
1121     ID3v2ExtraMeta *current = *extra_meta, *next;
1122     const ID3v2EMFunc *extra_func;
1123
1124     while (current) {
1125         if ((extra_func = get_extra_meta_func(current->tag, 1)))
1126             extra_func->free(&current->data);
1127         next = current->next;
1128         av_freep(&current);
1129         current = next;
1130     }
1131
1132     *extra_meta = NULL;
1133 }
1134
1135 int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
1136 {
1137     ID3v2ExtraMeta *cur;
1138
1139     for (cur = extra_meta; cur; cur = cur->next) {
1140         ID3v2ExtraMetaAPIC *apic;
1141         AVStream *st;
1142
1143         if (strcmp(cur->tag, "APIC"))
1144             continue;
1145         apic = &cur->data.apic;
1146
1147         if (!(st = avformat_new_stream(s, NULL)))
1148             return AVERROR(ENOMEM);
1149
1150         st->disposition      |= AV_DISPOSITION_ATTACHED_PIC;
1151         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1152         st->codecpar->codec_id   = apic->id;
1153
1154         if (AV_RB64(apic->buf->data) == PNGSIG)
1155             st->codecpar->codec_id = AV_CODEC_ID_PNG;
1156
1157         if (apic->description[0])
1158             av_dict_set(&st->metadata, "title", apic->description, 0);
1159
1160         av_dict_set(&st->metadata, "comment", apic->type, 0);
1161
1162         av_init_packet(&st->attached_pic);
1163         st->attached_pic.buf          = apic->buf;
1164         st->attached_pic.data         = apic->buf->data;
1165         st->attached_pic.size         = apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE;
1166         st->attached_pic.stream_index = st->index;
1167         st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
1168
1169         apic->buf = NULL;
1170     }
1171
1172     return 0;
1173 }
1174
1175 int ff_id3v2_parse_chapters(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
1176 {
1177     int ret = 0;
1178     ID3v2ExtraMeta *cur;
1179     AVRational time_base = {1, 1000};
1180     ID3v2ExtraMetaCHAP **chapters = NULL;
1181     int num_chapters = 0;
1182     int i;
1183
1184     // since extra_meta is a linked list where elements are prepended,
1185     // we need to reverse the order of chapters
1186     for (cur = extra_meta; cur; cur = cur->next) {
1187         ID3v2ExtraMetaCHAP *chap;
1188
1189         if (strcmp(cur->tag, "CHAP"))
1190             continue;
1191         chap = &cur->data.chap;
1192
1193         if ((ret = av_dynarray_add_nofree(&chapters, &num_chapters, chap)) < 0)
1194             goto end;
1195     }
1196
1197     for (i = 0; i < (num_chapters / 2); i++) {
1198         ID3v2ExtraMetaCHAP *right;
1199         int right_index;
1200
1201         right_index = (num_chapters - 1) - i;
1202         right = chapters[right_index];
1203
1204         chapters[right_index] = chapters[i];
1205         chapters[i] = right;
1206     }
1207
1208     for (i = 0; i < num_chapters; i++) {
1209         ID3v2ExtraMetaCHAP *chap;
1210         AVChapter *chapter;
1211
1212         chap = chapters[i];
1213         chapter = avpriv_new_chapter(s, i, time_base, chap->start, chap->end, chap->element_id);
1214         if (!chapter)
1215             continue;
1216
1217         if ((ret = av_dict_copy(&chapter->metadata, chap->meta, 0)) < 0)
1218             goto end;
1219     }
1220
1221 end:
1222     av_freep(&chapters);
1223     return ret;
1224 }
1225
1226 int ff_id3v2_parse_priv_dict(AVDictionary **metadata, ID3v2ExtraMeta *extra_meta)
1227 {
1228     ID3v2ExtraMeta *cur;
1229     int dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL;
1230
1231     for (cur = extra_meta; cur; cur = cur->next) {
1232         if (!strcmp(cur->tag, "PRIV")) {
1233             ID3v2ExtraMetaPRIV *priv = &cur->data.priv;
1234             AVBPrint bprint;
1235             char *escaped, *key;
1236             int i, ret;
1237
1238             if ((key = av_asprintf(ID3v2_PRIV_METADATA_PREFIX "%s", priv->owner)) == NULL) {
1239                 return AVERROR(ENOMEM);
1240             }
1241
1242             av_bprint_init(&bprint, priv->datasize + 1, AV_BPRINT_SIZE_UNLIMITED);
1243
1244             for (i = 0; i < priv->datasize; i++) {
1245                 if (priv->data[i] < 32 || priv->data[i] > 126 || priv->data[i] == '\\') {
1246                     av_bprintf(&bprint, "\\x%02x", priv->data[i]);
1247                 } else {
1248                     av_bprint_chars(&bprint, priv->data[i], 1);
1249                 }
1250             }
1251
1252             if ((ret = av_bprint_finalize(&bprint, &escaped)) < 0) {
1253                 av_free(key);
1254                 return ret;
1255             }
1256
1257             if ((ret = av_dict_set(metadata, key, escaped, dict_flags)) < 0) {
1258                 return ret;
1259             }
1260         }
1261     }
1262
1263     return 0;
1264 }
1265
1266 int ff_id3v2_parse_priv(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
1267 {
1268     return ff_id3v2_parse_priv_dict(&s->metadata, extra_meta);
1269 }