2 * Copyright (c) 2003 Fabrice Bellard
4 * This file is part of FFmpeg.
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.
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.
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
25 * Specifications available at:
26 * http://id3.org/Developer_Information
37 #include "libavutil/avstring.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/dict.h"
40 #include "avio_internal.h"
43 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
45 { "TCOM", "composer"},
47 { "TCOP", "copyright"},
48 { "TENC", "encoded_by"},
50 { "TLAN", "language"},
52 { "TPE2", "album_artist"},
53 { "TPE3", "performer"},
55 { "TPUB", "publisher"},
61 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
64 { "TDEN", "creation_time"},
65 { "TSOA", "album-sort"},
66 { "TSOP", "artist-sort"},
67 { "TSOT", "title-sort"},
71 static const AVMetadataConv id3v2_2_metadata_conv[] = {
75 { "TEN", "encoded_by"},
77 { "TP2", "album_artist"},
78 { "TP3", "performer"},
84 const char ff_id3v2_tags[][4] = {
85 "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
86 "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
87 "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
88 "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
92 const char ff_id3v2_4_tags[][4] = {
93 "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
94 "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
98 const char ff_id3v2_3_tags[][4] = {
99 "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
103 const char *ff_id3v2_picture_types[21] = {
105 "32x32 pixels 'file icon'",
110 "Media (e.g. label side of CD)",
111 "Lead artist/lead performer/soloist",
116 "Lyricist/text writer",
117 "Recording Location",
119 "During performance",
120 "Movie/video screen capture",
121 "A bright coloured fish",
123 "Band/artist logotype",
124 "Publisher/Studio logotype",
127 const CodecMime ff_id3v2_mime_tags[] = {
128 {"image/gif" , AV_CODEC_ID_GIF},
129 {"image/jpeg", AV_CODEC_ID_MJPEG},
130 {"image/jpg", AV_CODEC_ID_MJPEG},
131 {"image/png" , AV_CODEC_ID_PNG},
132 {"image/tiff", AV_CODEC_ID_TIFF},
133 {"image/bmp", AV_CODEC_ID_BMP},
134 {"JPG", AV_CODEC_ID_MJPEG}, /* ID3v2.2 */
135 {"PNG" , AV_CODEC_ID_PNG}, /* ID3v2.2 */
136 {"", AV_CODEC_ID_NONE},
139 int ff_id3v2_match(const uint8_t *buf, const char * magic)
141 return buf[0] == magic[0] &&
142 buf[1] == magic[1] &&
143 buf[2] == magic[2] &&
146 (buf[6] & 0x80) == 0 &&
147 (buf[7] & 0x80) == 0 &&
148 (buf[8] & 0x80) == 0 &&
149 (buf[9] & 0x80) == 0;
152 int ff_id3v2_tag_len(const uint8_t * buf)
154 int len = ((buf[6] & 0x7f) << 21) +
155 ((buf[7] & 0x7f) << 14) +
156 ((buf[8] & 0x7f) << 7) +
160 len += ID3v2_HEADER_SIZE;
164 static unsigned int get_size(AVIOContext *s, int len)
168 v = (v << 7) + (avio_r8(s) & 0x7F);
173 * Free GEOB type extra metadata.
175 static void free_geobtag(void *obj)
177 ID3v2ExtraMetaGEOB *geob = obj;
178 av_free(geob->mime_type);
179 av_free(geob->file_name);
180 av_free(geob->description);
186 * Decode characters to UTF-8 according to encoding type. The decoded buffer is
187 * always null terminated. Stop reading when either *maxread bytes are read from
188 * pb or U+0000 character is found.
190 * @param dst Pointer where the address of the buffer with the decoded bytes is
191 * stored. Buffer must be freed by caller.
192 * @param maxread Pointer to maximum number of characters to read from the
193 * AVIOContext. After execution the value is decremented by the number of bytes
195 * @returns 0 if no error occurred, dst is uninitialized on error
197 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
198 uint8_t **dst, int *maxread)
204 unsigned int (*get)(AVIOContext*) = avio_rb16;
207 if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
208 av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
214 case ID3v2_ENCODING_ISO8859:
217 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
222 case ID3v2_ENCODING_UTF16BOM:
223 if ((left -= 2) < 0) {
224 av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
225 avio_close_dyn_buf(dynbuf, dst);
227 return AVERROR_INVALIDDATA;
229 switch (avio_rb16(pb)) {
235 av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
236 avio_close_dyn_buf(dynbuf, dst);
239 return AVERROR_INVALIDDATA;
243 case ID3v2_ENCODING_UTF16BE:
244 while ((left > 1) && ch) {
245 GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
246 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
249 left += 2; /* did not read last char from pb */
252 case ID3v2_ENCODING_UTF8:
260 av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
266 avio_close_dyn_buf(dynbuf, dst);
275 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
278 int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
284 encoding = avio_r8(pb);
285 taglen--; /* account for encoding type byte */
287 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
288 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
292 if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
293 && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
294 && genre <= ID3v1_GENRE_MAX) {
296 dst = av_strdup(ff_id3v1_genre_str[genre]);
297 } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
298 /* dst now contains the key, need to get value */
300 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
301 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
305 dict_flags |= AV_DICT_DONT_STRDUP_KEY;
310 av_dict_set(&s->metadata, key, dst, dict_flags);
314 * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
316 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
318 ID3v2ExtraMetaGEOB *geob_data = NULL;
319 ID3v2ExtraMeta *new_extra = NULL;
326 geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
328 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
332 new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
334 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
338 /* read encoding type byte */
339 encoding = avio_r8(pb);
342 /* read MIME type (always ISO-8859) */
343 if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
348 if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
352 /* read content description */
353 if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
358 /* save encapsulated binary data */
359 geob_data->data = av_malloc(taglen);
360 if (!geob_data->data) {
361 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
364 if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
365 av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
366 geob_data->datasize = len;
368 geob_data->data = NULL;
369 geob_data->datasize = 0;
372 /* add data to the list */
373 new_extra->tag = "GEOB";
374 new_extra->data = geob_data;
375 new_extra->next = *extra_meta;
376 *extra_meta = new_extra;
381 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
382 free_geobtag(geob_data);
387 static int is_number(const char *str)
389 while (*str >= '0' && *str <= '9') str++;
393 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
395 AVDictionaryEntry *t;
396 if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
397 strlen(t->value) == 4 && is_number(t->value))
402 static void merge_date(AVDictionary **m)
404 AVDictionaryEntry *t;
405 char date[17] = {0}; // YYYY-MM-DD hh:mm
407 if (!(t = get_date_tag(*m, "TYER")) &&
408 !(t = get_date_tag(*m, "TYE")))
410 av_strlcpy(date, t->value, 5);
411 av_dict_set(m, "TYER", NULL, 0);
412 av_dict_set(m, "TYE", NULL, 0);
414 if (!(t = get_date_tag(*m, "TDAT")) &&
415 !(t = get_date_tag(*m, "TDA")))
417 snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
418 av_dict_set(m, "TDAT", NULL, 0);
419 av_dict_set(m, "TDA", NULL, 0);
421 if (!(t = get_date_tag(*m, "TIME")) &&
422 !(t = get_date_tag(*m, "TIM")))
424 snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
425 av_dict_set(m, "TIME", NULL, 0);
426 av_dict_set(m, "TIM", NULL, 0);
430 av_dict_set(m, "date", date, 0);
433 static void free_apic(void *obj)
435 ID3v2ExtraMetaAPIC *apic = obj;
436 av_freep(&apic->data);
437 av_freep(&apic->description);
441 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
445 const CodecMime *mime = ff_id3v2_mime_tags;
446 enum AVCodecID id = AV_CODEC_ID_NONE;
447 ID3v2ExtraMetaAPIC *apic = NULL;
448 ID3v2ExtraMeta *new_extra = NULL;
449 int64_t end = avio_tell(pb) + taglen;
454 new_extra = av_mallocz(sizeof(*new_extra));
455 apic = av_mallocz(sizeof(*apic));
456 if (!new_extra || !apic)
463 taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
464 while (mime->id != AV_CODEC_ID_NONE) {
465 if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
471 if (id == AV_CODEC_ID_NONE) {
472 av_log(s, AV_LOG_WARNING, "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
478 pic_type = avio_r8(pb);
480 if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
481 av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n", pic_type);
484 apic->type = ff_id3v2_picture_types[pic_type];
486 /* description and picture data */
487 if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
488 av_log(s, AV_LOG_ERROR, "Error decoding attached picture description.\n");
493 apic->data = av_malloc(taglen);
494 if (!apic->data || !apic->len || avio_read(pb, apic->data, taglen) != taglen)
497 new_extra->tag = "APIC";
498 new_extra->data = apic;
499 new_extra->next = *extra_meta;
500 *extra_meta = new_extra;
507 av_freep(&new_extra);
508 avio_seek(pb, end, SEEK_SET);
511 typedef struct ID3v2EMFunc {
514 void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
515 void (*free)(void *obj);
518 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
519 { "GEO", "GEOB", read_geobtag, free_geobtag },
520 { "PIC", "APIC", read_apic, free_apic },
525 * Get the corresponding ID3v2EMFunc struct for a tag.
526 * @param isv34 Determines if v2.2 or v2.3/4 strings are used
527 * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
529 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
532 while (id3v2_extra_meta_funcs[i].tag3) {
533 if (tag && !memcmp(tag,
534 (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
535 id3v2_extra_meta_funcs[i].tag3),
537 return &id3v2_extra_meta_funcs[i];
543 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
548 int64_t next, end = avio_tell(s->pb) + len;
550 const char *reason = NULL;
553 unsigned char *buffer = NULL;
555 const ID3v2EMFunc *extra_func = NULL;
556 unsigned char *compressed_buffer = NULL;
557 int compressed_buffer_size = 0;
562 reason = "compression";
580 unsync = flags & 0x80;
582 if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
583 int extlen = get_size(s->pb, 4);
585 extlen -= 4; // in v2.4 the length includes the length field we just read
588 reason = "invalid extended header length";
591 avio_skip(s->pb, extlen);
594 reason = "extended header too long.";
599 while (len >= taghdrlen) {
600 unsigned int tflags = 0;
607 avio_read(s->pb, tag, 4);
610 tlen = avio_rb32(s->pb);
612 tlen = get_size(s->pb, 4);
613 tflags = avio_rb16(s->pb);
614 tunsync = tflags & ID3v2_FLAG_UNSYNCH;
616 avio_read(s->pb, tag, 3);
618 tlen = avio_rb24(s->pb);
622 len -= taghdrlen + tlen;
627 next = avio_tell(s->pb) + tlen;
631 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
635 if (tflags & ID3v2_FLAG_DATALEN) {
638 dlen = avio_rb32(s->pb);
643 tcomp = tflags & ID3v2_FLAG_COMPRESSION;
644 tencr = tflags & ID3v2_FLAG_ENCRYPTION;
646 /* skip encrypted tags and, if no zlib, compressed tags */
647 if (tencr || (!CONFIG_ZLIB && tcomp)) {
654 type = "encrypted and compressed";
656 av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
657 avio_skip(s->pb, tlen);
658 /* check for text tag or supported special meta tag */
659 } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
660 if (unsync || tunsync || tcomp) {
663 av_fast_malloc(&buffer, &buffer_size, dlen);
665 av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
672 av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
674 av_fast_malloc(&compressed_buffer, &compressed_buffer_size, tlen);
675 if (!compressed_buffer) {
676 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
680 n = avio_read(s->pb, compressed_buffer, tlen);
682 av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
686 err = uncompress(buffer, &dlen, compressed_buffer, n);
688 av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
694 for (i = 0, j = 0; i < dlen; i++, j++) {
696 buffer[j] = avio_r8(s->pb);
697 if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
698 /* Unsynchronised byte, skip it */
702 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
704 pbx = &pb; // read from sync buffer
706 pbx = s->pb; // read straight from input
710 read_ttag(s, pbx, tlen, tag);
712 /* parse special meta tag */
713 extra_func->read(s, pbx, tlen, tag, extra_meta);
717 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
718 avio_skip(s->pb, tlen);
721 /* Skip to end of tag */
723 avio_seek(s->pb, next, SEEK_SET);
726 if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
731 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
732 avio_seek(s->pb, end, SEEK_SET);
734 av_free(compressed_buffer);
738 void ff_id3v2_read(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
741 uint8_t buf[ID3v2_HEADER_SIZE];
746 /* save the current offset in case there's nothing to read/skip */
747 off = avio_tell(s->pb);
748 ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
749 if (ret != ID3v2_HEADER_SIZE)
751 found_header = ff_id3v2_match(buf, magic);
753 /* parse ID3v2 header */
754 len = ((buf[6] & 0x7f) << 21) |
755 ((buf[7] & 0x7f) << 14) |
756 ((buf[8] & 0x7f) << 7) |
758 ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
760 avio_seek(s->pb, off, SEEK_SET);
762 } while (found_header);
763 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
764 ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
765 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
766 merge_date(&s->metadata);
769 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
771 ID3v2ExtraMeta *current = *extra_meta, *next;
772 const ID3v2EMFunc *extra_func;
775 if ((extra_func = get_extra_meta_func(current->tag, 1)))
776 extra_func->free(current->data);
777 next = current->next;
783 int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
787 for (cur = *extra_meta; cur; cur = cur->next) {
788 ID3v2ExtraMetaAPIC *apic;
791 if (strcmp(cur->tag, "APIC"))
795 if (!(st = avformat_new_stream(s, NULL)))
796 return AVERROR(ENOMEM);
798 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
799 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
800 st->codec->codec_id = apic->id;
801 av_dict_set(&st->metadata, "title", apic->description, 0);
802 av_dict_set(&st->metadata, "comment", apic->type, 0);
804 av_init_packet(&st->attached_pic);
805 st->attached_pic.data = apic->data;
806 st->attached_pic.size = apic->len;
807 st->attached_pic.destruct = av_destruct_packet;
808 st->attached_pic.stream_index = st->index;
809 st->attached_pic.flags |= AV_PKT_FLAG_KEY;