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
24 #include "libavutil/avstring.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/dict.h"
27 #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"},
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"},
71 const char ff_id3v2_tags[][4] = {
72 "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
73 "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
74 "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
75 "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
79 const char ff_id3v2_4_tags[][4] = {
80 "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
81 "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
85 const char ff_id3v2_3_tags[][4] = {
86 "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
90 const char *ff_id3v2_picture_types[21] = {
92 "32x32 pixels 'file icon'",
97 "Media (e.g. label side of CD)",
98 "Lead artist/lead performer/soloist",
103 "Lyricist/text writer",
104 "Recording Location",
106 "During performance",
107 "Movie/video screen capture",
108 "A bright coloured fish",
110 "Band/artist logotype",
111 "Publisher/Studio logotype",
114 const CodecMime ff_id3v2_mime_tags[] = {
115 {"image/gif" , CODEC_ID_GIF},
116 {"image/jpeg", CODEC_ID_MJPEG},
117 {"image/png" , CODEC_ID_PNG},
118 {"image/tiff", CODEC_ID_TIFF},
122 int ff_id3v2_match(const uint8_t *buf, const char * magic)
124 return buf[0] == magic[0] &&
125 buf[1] == magic[1] &&
126 buf[2] == magic[2] &&
129 (buf[6] & 0x80) == 0 &&
130 (buf[7] & 0x80) == 0 &&
131 (buf[8] & 0x80) == 0 &&
132 (buf[9] & 0x80) == 0;
135 int ff_id3v2_tag_len(const uint8_t * buf)
137 int len = ((buf[6] & 0x7f) << 21) +
138 ((buf[7] & 0x7f) << 14) +
139 ((buf[8] & 0x7f) << 7) +
143 len += ID3v2_HEADER_SIZE;
147 static unsigned int get_size(AVIOContext *s, int len)
151 v = (v << 7) + (avio_r8(s) & 0x7F);
156 * Free GEOB type extra metadata.
158 static void free_geobtag(void *obj)
160 ID3v2ExtraMetaGEOB *geob = obj;
161 av_free(geob->mime_type);
162 av_free(geob->file_name);
163 av_free(geob->description);
169 * Decode characters to UTF-8 according to encoding type. The decoded buffer is
170 * always null terminated. Stop reading when either *maxread bytes are read from
171 * pb or U+0000 character is found.
173 * @param dst Pointer where the address of the buffer with the decoded bytes is
174 * stored. Buffer must be freed by caller.
175 * @param maxread Pointer to maximum number of characters to read from the
176 * AVIOContext. After execution the value is decremented by the number of bytes
178 * @returns 0 if no error occurred, dst is uninitialized on error
180 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
181 uint8_t **dst, int *maxread)
187 unsigned int (*get)(AVIOContext*) = avio_rb16;
190 if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
191 av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
197 case ID3v2_ENCODING_ISO8859:
200 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
205 case ID3v2_ENCODING_UTF16BOM:
206 if ((left -= 2) < 0) {
207 av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
208 avio_close_dyn_buf(dynbuf, dst);
210 return AVERROR_INVALIDDATA;
212 switch (avio_rb16(pb)) {
218 av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
219 avio_close_dyn_buf(dynbuf, dst);
222 return AVERROR_INVALIDDATA;
226 case ID3v2_ENCODING_UTF16BE:
227 while ((left > 1) && ch) {
228 GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
229 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
232 left += 2; /* did not read last char from pb */
235 case ID3v2_ENCODING_UTF8:
243 av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
249 avio_close_dyn_buf(dynbuf, dst);
258 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
261 int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
267 encoding = avio_r8(pb);
268 taglen--; /* account for encoding type byte */
270 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
271 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
275 if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
276 && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
277 && genre <= ID3v1_GENRE_MAX) {
279 dst = ff_id3v1_genre_str[genre];
280 } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
281 /* dst now contains the key, need to get value */
283 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
284 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
288 dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
291 dict_flags |= AV_DICT_DONT_STRDUP_VAL;
294 av_dict_set(&s->metadata, key, dst, dict_flags);
298 * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
300 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
302 ID3v2ExtraMetaGEOB *geob_data = NULL;
303 ID3v2ExtraMeta *new_extra = NULL;
310 geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
312 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
316 new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
318 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
322 /* read encoding type byte */
323 encoding = avio_r8(pb);
326 /* read MIME type (always ISO-8859) */
327 if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
332 if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
336 /* read content description */
337 if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
342 /* save encapsulated binary data */
343 geob_data->data = av_malloc(taglen);
344 if (!geob_data->data) {
345 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
348 if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
349 av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
350 geob_data->datasize = len;
352 geob_data->data = NULL;
353 geob_data->datasize = 0;
356 /* add data to the list */
357 new_extra->tag = "GEOB";
358 new_extra->data = geob_data;
359 new_extra->next = *extra_meta;
360 *extra_meta = new_extra;
365 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
366 free_geobtag(geob_data);
371 static int is_number(const char *str)
373 while (*str >= '0' && *str <= '9') str++;
377 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
379 AVDictionaryEntry *t;
380 if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
381 strlen(t->value) == 4 && is_number(t->value))
386 static void merge_date(AVDictionary **m)
388 AVDictionaryEntry *t;
389 char date[17] = {0}; // YYYY-MM-DD hh:mm
391 if (!(t = get_date_tag(*m, "TYER")) &&
392 !(t = get_date_tag(*m, "TYE")))
394 av_strlcpy(date, t->value, 5);
395 av_dict_set(m, "TYER", NULL, 0);
396 av_dict_set(m, "TYE", NULL, 0);
398 if (!(t = get_date_tag(*m, "TDAT")) &&
399 !(t = get_date_tag(*m, "TDA")))
401 snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
402 av_dict_set(m, "TDAT", NULL, 0);
403 av_dict_set(m, "TDA", NULL, 0);
405 if (!(t = get_date_tag(*m, "TIME")) &&
406 !(t = get_date_tag(*m, "TIM")))
408 snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
409 av_dict_set(m, "TIME", NULL, 0);
410 av_dict_set(m, "TIM", NULL, 0);
414 av_dict_set(m, "date", date, 0);
417 static void free_apic(void *obj)
419 ID3v2ExtraMetaAPIC *apic = obj;
420 av_freep(&apic->data);
421 av_freep(&apic->description);
425 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
429 const CodecMime *mime = ff_id3v2_mime_tags;
430 enum CodecID id = CODEC_ID_NONE;
431 ID3v2ExtraMetaAPIC *apic = NULL;
432 ID3v2ExtraMeta *new_extra = NULL;
433 int64_t end = avio_tell(pb) + taglen;
438 new_extra = av_mallocz(sizeof(*new_extra));
439 apic = av_mallocz(sizeof(*apic));
440 if (!new_extra || !apic)
447 taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
448 while (mime->id != CODEC_ID_NONE) {
449 if (!strncmp(mime->str, mimetype, sizeof(mimetype))) {
455 if (id == CODEC_ID_NONE) {
456 av_log(s, AV_LOG_WARNING, "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
462 pic_type = avio_r8(pb);
464 if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
465 av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n", pic_type);
468 apic->type = ff_id3v2_picture_types[pic_type];
470 /* description and picture data */
471 if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
472 av_log(s, AV_LOG_ERROR, "Error decoding attached picture description.\n");
477 apic->data = av_malloc(taglen);
478 if (!apic->data || avio_read(pb, apic->data, taglen) != taglen)
481 new_extra->tag = "APIC";
482 new_extra->data = apic;
483 new_extra->next = *extra_meta;
484 *extra_meta = new_extra;
491 av_freep(&new_extra);
492 avio_seek(pb, end, SEEK_SET);
495 typedef struct ID3v2EMFunc {
498 void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
499 void (*free)(void *obj);
502 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
503 { "GEO", "GEOB", read_geobtag, free_geobtag },
504 { "PIC", "APIC", read_apic, free_apic },
509 * Get the corresponding ID3v2EMFunc struct for a tag.
510 * @param isv34 Determines if v2.2 or v2.3/4 strings are used
511 * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
513 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
516 while (id3v2_extra_meta_funcs[i].tag3) {
518 (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
519 id3v2_extra_meta_funcs[i].tag3),
521 return &id3v2_extra_meta_funcs[i];
527 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
529 int isv34, tlen, unsync;
531 int64_t next, end = avio_tell(s->pb) + len;
533 const char *reason = NULL;
536 unsigned char *buffer = NULL;
538 const ID3v2EMFunc *extra_func;
543 reason = "compression";
561 unsync = flags & 0x80;
563 if (isv34 && flags & 0x40) /* Extended header present, just skip over it */
564 avio_skip(s->pb, get_size(s->pb, 4));
566 while (len >= taghdrlen) {
567 unsigned int tflags = 0;
571 avio_read(s->pb, tag, 4);
574 tlen = avio_rb32(s->pb);
576 tlen = get_size(s->pb, 4);
577 tflags = avio_rb16(s->pb);
578 tunsync = tflags & ID3v2_FLAG_UNSYNCH;
580 avio_read(s->pb, tag, 3);
582 tlen = avio_rb24(s->pb);
584 if (tlen < 0 || tlen > len - taghdrlen) {
585 av_log(s, AV_LOG_WARNING, "Invalid size in frame %s, skipping the rest of tag.\n", tag);
588 len -= taghdrlen + tlen;
589 next = avio_tell(s->pb) + tlen;
593 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
597 if (tflags & ID3v2_FLAG_DATALEN) {
602 if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
603 av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
604 avio_skip(s->pb, tlen);
605 /* check for text tag or supported special meta tag */
606 } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
607 if (unsync || tunsync) {
609 av_fast_malloc(&buffer, &buffer_size, tlen);
611 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
614 for (i = 0, j = 0; i < tlen; i++, j++) {
615 buffer[j] = avio_r8(s->pb);
616 if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
617 /* Unsynchronised byte, skip it */
621 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
623 pbx = &pb; // read from sync buffer
625 pbx = s->pb; // read straight from input
629 read_ttag(s, pbx, tlen, tag);
631 /* parse special meta tag */
632 extra_func->read(s, pbx, tlen, tag, extra_meta);
636 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
637 avio_skip(s->pb, tlen);
640 /* Skip to end of tag */
642 avio_seek(s->pb, next, SEEK_SET);
645 if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
650 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
651 avio_seek(s->pb, end, SEEK_SET);
656 void ff_id3v2_read(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
659 uint8_t buf[ID3v2_HEADER_SIZE];
664 /* save the current offset in case there's nothing to read/skip */
665 off = avio_tell(s->pb);
666 ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
667 if (ret != ID3v2_HEADER_SIZE)
669 found_header = ff_id3v2_match(buf, magic);
671 /* parse ID3v2 header */
672 len = ((buf[6] & 0x7f) << 21) |
673 ((buf[7] & 0x7f) << 14) |
674 ((buf[8] & 0x7f) << 7) |
676 ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
678 avio_seek(s->pb, off, SEEK_SET);
680 } while (found_header);
681 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
682 ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
683 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
684 merge_date(&s->metadata);
687 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
689 ID3v2ExtraMeta *current = *extra_meta, *next;
690 const ID3v2EMFunc *extra_func;
693 if ((extra_func = get_extra_meta_func(current->tag, 1)))
694 extra_func->free(current->data);
695 next = current->next;
701 int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
705 for (cur = *extra_meta; cur; cur = cur->next) {
706 ID3v2ExtraMetaAPIC *apic;
709 if (strcmp(cur->tag, "APIC"))
713 if (!(st = avformat_new_stream(s, NULL)))
714 return AVERROR(ENOMEM);
716 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
717 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
718 st->codec->codec_id = apic->id;
719 av_dict_set(&st->metadata, "title", apic->description, 0);
720 av_dict_set(&st->metadata, "comment", apic->type, 0);
722 av_init_packet(&st->attached_pic);
723 st->attached_pic.data = apic->data;
724 st->attached_pic.size = apic->len;
725 st->attached_pic.destruct = av_destruct_packet;
726 st->attached_pic.stream_index = st->index;