3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/avstring.h"
23 #include "libavutil/dict.h"
24 #include "libavutil/intreadwrite.h"
25 #include "avio_internal.h"
30 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
32 { "TCOM", "composer" },
34 { "TCOP", "copyright" },
35 { "TENC", "encoded_by" },
37 { "TLAN", "language" },
39 { "TPE2", "album_artist" },
40 { "TPE3", "performer" },
42 { "TPUB", "publisher" },
44 { "TSSE", "encoder" },
48 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
51 { "TDEN", "creation_time" },
52 { "TSOA", "album-sort" },
53 { "TSOP", "artist-sort" },
54 { "TSOT", "title-sort" },
58 static const AVMetadataConv id3v2_2_metadata_conv[] = {
62 { "TEN", "encoded_by" },
64 { "TP2", "album_artist" },
65 { "TP3", "performer" },
70 const char ff_id3v2_tags[][4] = {
71 "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
72 "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
73 "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
74 "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
78 const char ff_id3v2_4_tags[][4] = {
79 "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
80 "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
84 const char ff_id3v2_3_tags[][4] = {
85 "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
89 const char *ff_id3v2_picture_types[21] = {
91 "32x32 pixels 'file icon'",
96 "Media (e.g. label side of CD)",
97 "Lead artist/lead performer/soloist",
102 "Lyricist/text writer",
103 "Recording Location",
105 "During performance",
106 "Movie/video screen capture",
107 "A bright coloured fish",
109 "Band/artist logotype",
110 "Publisher/Studio logotype",
113 const CodecMime ff_id3v2_mime_tags[] = {
114 { "image/gif", AV_CODEC_ID_GIF },
115 { "image/jpeg", AV_CODEC_ID_MJPEG },
116 { "image/jpg", AV_CODEC_ID_MJPEG },
117 { "image/png", AV_CODEC_ID_PNG },
118 { "image/tiff", AV_CODEC_ID_TIFF },
119 { "image/bmp", AV_CODEC_ID_BMP },
120 { "JPG", AV_CODEC_ID_MJPEG }, /* ID3v2.2 */
121 { "PNG", AV_CODEC_ID_PNG }, /* ID3v2.2 */
122 { "", AV_CODEC_ID_NONE },
125 int ff_id3v2_match(const uint8_t *buf, const char *magic)
127 return buf[0] == magic[0] &&
128 buf[1] == magic[1] &&
129 buf[2] == magic[2] &&
132 (buf[6] & 0x80) == 0 &&
133 (buf[7] & 0x80) == 0 &&
134 (buf[8] & 0x80) == 0 &&
135 (buf[9] & 0x80) == 0;
138 int ff_id3v2_tag_len(const uint8_t *buf)
140 int len = ((buf[6] & 0x7f) << 21) +
141 ((buf[7] & 0x7f) << 14) +
142 ((buf[8] & 0x7f) << 7) +
146 len += ID3v2_HEADER_SIZE;
150 static unsigned int get_size(AVIOContext *s, int len)
154 v = (v << 7) + (avio_r8(s) & 0x7F);
159 * Free GEOB type extra metadata.
161 static void free_geobtag(void *obj)
163 ID3v2ExtraMetaGEOB *geob = obj;
164 av_free(geob->mime_type);
165 av_free(geob->file_name);
166 av_free(geob->description);
172 * Decode characters to UTF-8 according to encoding type. The decoded buffer is
173 * always null terminated. Stop reading when either *maxread bytes are read from
174 * pb or U+0000 character is found.
176 * @param dst Pointer where the address of the buffer with the decoded bytes is
177 * stored. Buffer must be freed by caller.
178 * @param maxread Pointer to maximum number of characters to read from the
179 * AVIOContext. After execution the value is decremented by the number of bytes
181 * @returns 0 if no error occurred, dst is uninitialized on error
183 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
184 uint8_t **dst, int *maxread)
190 unsigned int (*get)(AVIOContext*) = avio_rb16;
193 if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
194 av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
199 case ID3v2_ENCODING_ISO8859:
202 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
207 case ID3v2_ENCODING_UTF16BOM:
208 if ((left -= 2) < 0) {
209 av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
210 ffio_free_dyn_buf(&dynbuf);
212 return AVERROR_INVALIDDATA;
214 switch (avio_rb16(pb)) {
220 av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
221 ffio_free_dyn_buf(&dynbuf);
224 return AVERROR_INVALIDDATA;
228 case ID3v2_ENCODING_UTF16BE:
229 while ((left > 1) && ch) {
230 GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
231 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
234 left += 2; /* did not read last char from pb */
237 case ID3v2_ENCODING_UTF8:
245 av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
251 avio_close_dyn_buf(dynbuf, dst);
260 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen,
264 int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
270 encoding = avio_r8(pb);
271 taglen--; /* account for encoding type byte */
273 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
274 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
278 if (!(strcmp(key, "TCON") && strcmp(key, "TCO")) &&
279 (sscanf(dst, "(%u)", &genre) == 1 || sscanf(dst, "%u", &genre) == 1) &&
280 genre <= ID3v1_GENRE_MAX) {
282 dst = av_strdup(ff_id3v1_genre_str[genre]);
283 } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
284 /* dst now contains the key, need to get value */
286 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
287 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
291 dict_flags |= AV_DICT_DONT_STRDUP_KEY;
296 av_dict_set(&s->metadata, key, dst, dict_flags);
300 * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
302 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen,
303 const char *tag, ID3v2ExtraMeta **extra_meta,
306 ID3v2ExtraMetaGEOB *geob_data = NULL;
307 ID3v2ExtraMeta *new_extra = NULL;
314 geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
316 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n",
317 sizeof(ID3v2ExtraMetaGEOB));
321 new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
323 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n",
324 sizeof(ID3v2ExtraMeta));
328 /* read encoding type byte */
329 encoding = avio_r8(pb);
332 /* read MIME type (always ISO-8859) */
333 if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type,
339 if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0 ||
343 /* read content description */
344 if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0 ||
349 /* save encapsulated binary data */
350 geob_data->data = av_malloc(taglen);
351 if (!geob_data->data) {
352 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
355 if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
356 av_log(s, AV_LOG_WARNING,
357 "Error reading GEOB frame, data truncated.\n");
358 geob_data->datasize = len;
360 geob_data->data = NULL;
361 geob_data->datasize = 0;
364 /* add data to the list */
365 new_extra->tag = "GEOB";
366 new_extra->data = geob_data;
367 new_extra->next = *extra_meta;
368 *extra_meta = new_extra;
373 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
374 free_geobtag(geob_data);
379 static int is_number(const char *str)
381 while (*str >= '0' && *str <= '9')
386 static AVDictionaryEntry *get_date_tag(AVDictionary *m, const char *tag)
388 AVDictionaryEntry *t;
389 if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
390 strlen(t->value) == 4 && is_number(t->value))
395 static void merge_date(AVDictionary **m)
397 AVDictionaryEntry *t;
398 char date[17] = { 0 }; // YYYY-MM-DD hh:mm
400 if (!(t = get_date_tag(*m, "TYER")) &&
401 !(t = get_date_tag(*m, "TYE")))
403 av_strlcpy(date, t->value, 5);
404 av_dict_set(m, "TYER", NULL, 0);
405 av_dict_set(m, "TYE", NULL, 0);
407 if (!(t = get_date_tag(*m, "TDAT")) &&
408 !(t = get_date_tag(*m, "TDA")))
410 snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
411 av_dict_set(m, "TDAT", NULL, 0);
412 av_dict_set(m, "TDA", NULL, 0);
414 if (!(t = get_date_tag(*m, "TIME")) &&
415 !(t = get_date_tag(*m, "TIM")))
417 snprintf(date + 10, sizeof(date) - 10,
418 " %.2s:%.2s", t->value, t->value + 2);
419 av_dict_set(m, "TIME", NULL, 0);
420 av_dict_set(m, "TIM", NULL, 0);
424 av_dict_set(m, "date", date, 0);
427 static void free_apic(void *obj)
429 ID3v2ExtraMetaAPIC *apic = obj;
430 av_buffer_unref(&apic->buf);
431 av_freep(&apic->description);
435 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen,
436 const char *tag, ID3v2ExtraMeta **extra_meta,
441 const CodecMime *mime = ff_id3v2_mime_tags;
442 enum AVCodecID id = AV_CODEC_ID_NONE;
443 ID3v2ExtraMetaAPIC *apic = NULL;
444 ID3v2ExtraMeta *new_extra = NULL;
445 int64_t end = avio_tell(pb) + taglen;
447 if (taglen <= 4 || (!isv34 && taglen <= 6))
450 new_extra = av_mallocz(sizeof(*new_extra));
451 apic = av_mallocz(sizeof(*apic));
452 if (!new_extra || !apic)
460 taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
462 avio_read(pb, mimetype, 3);
467 while (mime->id != AV_CODEC_ID_NONE) {
468 if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
474 if (id == AV_CODEC_ID_NONE) {
475 av_log(s, AV_LOG_WARNING,
476 "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
482 pic_type = avio_r8(pb);
484 if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
485 av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
489 apic->type = ff_id3v2_picture_types[pic_type];
491 /* description and picture data */
492 if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
493 av_log(s, AV_LOG_ERROR,
494 "Error decoding attached picture description.\n");
498 apic->buf = av_buffer_alloc(taglen + AV_INPUT_BUFFER_PADDING_SIZE);
499 if (!apic->buf || avio_read(pb, apic->buf->data, taglen) != taglen)
501 memset(apic->buf->data + taglen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
503 new_extra->tag = "APIC";
504 new_extra->data = apic;
505 new_extra->next = *extra_meta;
506 *extra_meta = new_extra;
513 av_freep(&new_extra);
514 avio_seek(pb, end, SEEK_SET);
517 typedef struct ID3v2EMFunc {
520 void (*read)(AVFormatContext *s, AVIOContext *pb, int taglen,
521 const char *tag, ID3v2ExtraMeta **extra_meta,
523 void (*free)(void *obj);
526 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
527 { "GEO", "GEOB", read_geobtag, free_geobtag },
528 { "PIC", "APIC", read_apic, free_apic },
533 * Get the corresponding ID3v2EMFunc struct for a tag.
534 * @param isv34 Determines if v2.2 or v2.3/4 strings are used
535 * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
537 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
540 while (id3v2_extra_meta_funcs[i].tag3) {
542 (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
543 id3v2_extra_meta_funcs[i].tag3),
545 return &id3v2_extra_meta_funcs[i];
551 static void id3v2_parse(AVFormatContext *s, int len, uint8_t version,
552 uint8_t flags, ID3v2ExtraMeta **extra_meta)
554 int isv34, tlen, unsync;
556 int64_t next, end = avio_tell(s->pb) + len;
558 const char *reason = NULL;
561 unsigned char *buffer = NULL;
563 const ID3v2EMFunc *extra_func;
568 reason = "compression";
586 unsync = flags & 0x80;
588 if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
589 int extlen = get_size(s->pb, 4);
591 /* In v2.4 the length includes the length field we just read. */
595 reason = "invalid extended header length";
598 avio_skip(s->pb, extlen);
601 while (len >= taghdrlen) {
602 unsigned int tflags = 0;
606 avio_read(s->pb, tag, 4);
609 tlen = avio_rb32(s->pb);
611 tlen = get_size(s->pb, 4);
612 tflags = avio_rb16(s->pb);
613 tunsync = tflags & ID3v2_FLAG_UNSYNCH;
615 avio_read(s->pb, tag, 3);
617 tlen = avio_rb24(s->pb);
619 if (tlen < 0 || tlen > len - taghdrlen) {
620 av_log(s, AV_LOG_WARNING,
621 "Invalid size in frame %s, skipping the rest of tag.\n",
625 len -= taghdrlen + tlen;
626 next = avio_tell(s->pb) + tlen;
630 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
635 if (tflags & ID3v2_FLAG_DATALEN) {
640 if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
641 av_log(s, AV_LOG_WARNING,
642 "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
643 avio_skip(s->pb, tlen);
644 /* check for text tag or supported special meta tag */
645 } else if (tag[0] == 'T' ||
647 (extra_func = get_extra_meta_func(tag, isv34)))) {
648 if (unsync || tunsync) {
649 int64_t end = avio_tell(s->pb) + tlen;
651 av_fast_malloc(&buffer, &buffer_size, tlen);
653 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
657 while (avio_tell(s->pb) < end && !s->pb->eof_reached) {
658 *b++ = avio_r8(s->pb);
659 if (*(b - 1) == 0xff && avio_tell(s->pb) < end - 1 &&
660 !s->pb->eof_reached ) {
661 uint8_t val = avio_r8(s->pb);
662 *b++ = val ? val : avio_r8(s->pb);
665 ffio_init_context(&pb, buffer, b - buffer, 0, NULL, NULL, NULL,
668 pbx = &pb; // read from sync buffer
670 pbx = s->pb; // read straight from input
674 read_ttag(s, pbx, tlen, tag);
676 /* parse special meta tag */
677 extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);
678 } else if (!tag[0]) {
680 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
681 avio_skip(s->pb, tlen);
684 /* Skip to end of tag */
686 avio_seek(s->pb, next, SEEK_SET);
689 /* Footer preset, always 10 bytes, skip over it */
690 if (version == 4 && flags & 0x10)
695 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
697 avio_seek(s->pb, end, SEEK_SET);
702 void ff_id3v2_read(AVFormatContext *s, const char *magic,
703 ID3v2ExtraMeta **extra_meta)
706 uint8_t buf[ID3v2_HEADER_SIZE];
711 /* save the current offset in case there's nothing to read/skip */
712 off = avio_tell(s->pb);
713 ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
714 if (ret != ID3v2_HEADER_SIZE)
716 found_header = ff_id3v2_match(buf, magic);
718 /* parse ID3v2 header */
719 len = ((buf[6] & 0x7f) << 21) |
720 ((buf[7] & 0x7f) << 14) |
721 ((buf[8] & 0x7f) << 7) |
723 id3v2_parse(s, len, buf[3], buf[5], extra_meta);
725 avio_seek(s->pb, off, SEEK_SET);
727 } while (found_header);
728 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
729 ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
730 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
731 merge_date(&s->metadata);
734 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
736 ID3v2ExtraMeta *current = *extra_meta, *next;
737 const ID3v2EMFunc *extra_func;
740 if ((extra_func = get_extra_meta_func(current->tag, 1)))
741 extra_func->free(current->data);
742 next = current->next;
748 int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
752 for (cur = *extra_meta; cur; cur = cur->next) {
753 ID3v2ExtraMetaAPIC *apic;
756 if (strcmp(cur->tag, "APIC"))
760 if (!(st = avformat_new_stream(s, NULL)))
761 return AVERROR(ENOMEM);
763 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
764 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
765 st->codecpar->codec_id = apic->id;
767 if (apic->description[0])
768 av_dict_set(&st->metadata, "title", apic->description, 0);
770 av_dict_set(&st->metadata, "comment", apic->type, 0);
772 av_init_packet(&st->attached_pic);
773 st->attached_pic.buf = apic->buf;
774 st->attached_pic.data = apic->buf->data;
775 st->attached_pic.size = apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE;
776 st->attached_pic.stream_index = st->index;
777 st->attached_pic.flags |= AV_PKT_FLAG_KEY;