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
35 #include "libavutil/avstring.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/intreadwrite.h"
38 #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" },
57 { "TSSE", "encoder" },
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" },
83 const char ff_id3v2_tags[][4] = {
84 "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
85 "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
86 "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
87 "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
91 const char ff_id3v2_4_tags[][4] = {
92 "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
93 "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
97 const char ff_id3v2_3_tags[][4] = {
98 "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
102 const char *ff_id3v2_picture_types[21] = {
104 "32x32 pixels 'file icon'",
109 "Media (e.g. label side of CD)",
110 "Lead artist/lead performer/soloist",
115 "Lyricist/text writer",
116 "Recording Location",
118 "During performance",
119 "Movie/video screen capture",
120 "A bright coloured fish",
122 "Band/artist logotype",
123 "Publisher/Studio logotype",
126 const CodecMime ff_id3v2_mime_tags[] = {
127 { "image/gif", AV_CODEC_ID_GIF },
128 { "image/jpeg", AV_CODEC_ID_MJPEG },
129 { "image/jpg", AV_CODEC_ID_MJPEG },
130 { "image/png", AV_CODEC_ID_PNG },
131 { "image/tiff", AV_CODEC_ID_TIFF },
132 { "image/bmp", AV_CODEC_ID_BMP },
133 { "JPG", AV_CODEC_ID_MJPEG }, /* ID3v2.2 */
134 { "PNG", AV_CODEC_ID_PNG }, /* ID3v2.2 */
135 { "", AV_CODEC_ID_NONE },
138 int ff_id3v2_match(const uint8_t *buf, const char *magic)
140 return buf[0] == magic[0] &&
141 buf[1] == magic[1] &&
142 buf[2] == magic[2] &&
145 (buf[6] & 0x80) == 0 &&
146 (buf[7] & 0x80) == 0 &&
147 (buf[8] & 0x80) == 0 &&
148 (buf[9] & 0x80) == 0;
151 int ff_id3v2_tag_len(const uint8_t *buf)
153 int len = ((buf[6] & 0x7f) << 21) +
154 ((buf[7] & 0x7f) << 14) +
155 ((buf[8] & 0x7f) << 7) +
159 len += ID3v2_HEADER_SIZE;
163 static unsigned int get_size(AVIOContext *s, int len)
167 v = (v << 7) + (avio_r8(s) & 0x7F);
172 * Free GEOB type extra metadata.
174 static void free_geobtag(void *obj)
176 ID3v2ExtraMetaGEOB *geob = obj;
177 av_free(geob->mime_type);
178 av_free(geob->file_name);
179 av_free(geob->description);
185 * Decode characters to UTF-8 according to encoding type. The decoded buffer is
186 * always null terminated. Stop reading when either *maxread bytes are read from
187 * pb or U+0000 character is found.
189 * @param dst Pointer where the address of the buffer with the decoded bytes is
190 * stored. Buffer must be freed by caller.
191 * @param maxread Pointer to maximum number of characters to read from the
192 * AVIOContext. After execution the value is decremented by the number of bytes
194 * @returns 0 if no error occurred, dst is uninitialized on error
196 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
197 uint8_t **dst, int *maxread)
203 unsigned int (*get)(AVIOContext*) = avio_rb16;
206 if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
207 av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
212 case ID3v2_ENCODING_ISO8859:
215 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
220 case ID3v2_ENCODING_UTF16BOM:
221 if ((left -= 2) < 0) {
222 av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
223 avio_close_dyn_buf(dynbuf, dst);
225 return AVERROR_INVALIDDATA;
227 switch (avio_rb16(pb)) {
233 av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
234 avio_close_dyn_buf(dynbuf, dst);
237 return AVERROR_INVALIDDATA;
241 case ID3v2_ENCODING_UTF16BE:
242 while ((left > 1) && ch) {
243 GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
244 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
247 left += 2; /* did not read last char from pb */
250 case ID3v2_ENCODING_UTF8:
258 av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
264 avio_close_dyn_buf(dynbuf, dst);
273 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen,
277 int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
283 encoding = avio_r8(pb);
284 taglen--; /* account for encoding type byte */
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 if (!(strcmp(key, "TCON") && strcmp(key, "TCO")) &&
292 (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1) &&
293 genre <= ID3v1_GENRE_MAX) {
295 dst = av_strdup(ff_id3v1_genre_str[genre]);
296 } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
297 /* dst now contains the key, need to get value */
299 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
300 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
304 dict_flags |= AV_DICT_DONT_STRDUP_KEY;
309 av_dict_set(&s->metadata, key, dst, dict_flags);
313 * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
315 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen,
316 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",
329 sizeof(ID3v2ExtraMetaGEOB));
333 new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
335 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n",
336 sizeof(ID3v2ExtraMeta));
340 /* read encoding type byte */
341 encoding = avio_r8(pb);
344 /* read MIME type (always ISO-8859) */
345 if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type,
351 if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0 ||
355 /* read content description */
356 if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0 ||
361 /* save encapsulated binary data */
362 geob_data->data = av_malloc(taglen);
363 if (!geob_data->data) {
364 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
367 if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
368 av_log(s, AV_LOG_WARNING,
369 "Error reading GEOB frame, data truncated.\n");
370 geob_data->datasize = len;
372 geob_data->data = NULL;
373 geob_data->datasize = 0;
376 /* add data to the list */
377 new_extra->tag = "GEOB";
378 new_extra->data = geob_data;
379 new_extra->next = *extra_meta;
380 *extra_meta = new_extra;
385 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
386 free_geobtag(geob_data);
391 static int is_number(const char *str)
393 while (*str >= '0' && *str <= '9')
398 static AVDictionaryEntry *get_date_tag(AVDictionary *m, const char *tag)
400 AVDictionaryEntry *t;
401 if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
402 strlen(t->value) == 4 && is_number(t->value))
407 static void merge_date(AVDictionary **m)
409 AVDictionaryEntry *t;
410 char date[17] = { 0 }; // YYYY-MM-DD hh:mm
412 if (!(t = get_date_tag(*m, "TYER")) &&
413 !(t = get_date_tag(*m, "TYE")))
415 av_strlcpy(date, t->value, 5);
416 av_dict_set(m, "TYER", NULL, 0);
417 av_dict_set(m, "TYE", NULL, 0);
419 if (!(t = get_date_tag(*m, "TDAT")) &&
420 !(t = get_date_tag(*m, "TDA")))
422 snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
423 av_dict_set(m, "TDAT", NULL, 0);
424 av_dict_set(m, "TDA", NULL, 0);
426 if (!(t = get_date_tag(*m, "TIME")) &&
427 !(t = get_date_tag(*m, "TIM")))
429 snprintf(date + 10, sizeof(date) - 10,
430 " %.2s:%.2s", t->value, t->value + 2);
431 av_dict_set(m, "TIME", NULL, 0);
432 av_dict_set(m, "TIM", NULL, 0);
436 av_dict_set(m, "date", date, 0);
439 static void free_apic(void *obj)
441 ID3v2ExtraMetaAPIC *apic = obj;
442 av_buffer_unref(&apic->buf);
443 av_freep(&apic->description);
447 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen,
448 char *tag, ID3v2ExtraMeta **extra_meta)
452 const CodecMime *mime = ff_id3v2_mime_tags;
453 enum AVCodecID id = AV_CODEC_ID_NONE;
454 ID3v2ExtraMetaAPIC *apic = NULL;
455 ID3v2ExtraMeta *new_extra = NULL;
456 int64_t end = avio_tell(pb) + taglen;
461 new_extra = av_mallocz(sizeof(*new_extra));
462 apic = av_mallocz(sizeof(*apic));
463 if (!new_extra || !apic)
470 taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
471 while (mime->id != AV_CODEC_ID_NONE) {
472 if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
478 if (id == AV_CODEC_ID_NONE) {
479 av_log(s, AV_LOG_WARNING,
480 "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
486 pic_type = avio_r8(pb);
488 if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
489 av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
493 apic->type = ff_id3v2_picture_types[pic_type];
495 /* description and picture data */
496 if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
497 av_log(s, AV_LOG_ERROR,
498 "Error decoding attached picture description.\n");
502 apic->buf = av_buffer_alloc(taglen + FF_INPUT_BUFFER_PADDING_SIZE);
503 if (!apic->buf || !taglen || avio_read(pb, apic->buf->data, taglen) != taglen)
505 memset(apic->buf->data + taglen, 0, FF_INPUT_BUFFER_PADDING_SIZE);
507 new_extra->tag = "APIC";
508 new_extra->data = apic;
509 new_extra->next = *extra_meta;
510 *extra_meta = new_extra;
517 av_freep(&new_extra);
518 avio_seek(pb, end, SEEK_SET);
521 static void read_chapter(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
523 AVRational time_base = {1, 1000};
528 decode_str(s, pb, 0, &dst, &taglen);
532 start = avio_rb32(pb);
539 avio_read(pb, tag, 4);
540 if (!memcmp(tag, "TIT2", 4)) {
541 taglen = FFMIN(taglen, avio_rb32(pb));
547 encoding = avio_r8(pb);
549 decode_str(s, pb, encoding, &dst, &taglen);
553 avpriv_new_chapter(s, s->nb_chapters + 1, time_base, start, end, dst);
557 typedef struct ID3v2EMFunc {
560 void (*read)(AVFormatContext *, AVIOContext *, int, char *,
562 void (*free)(void *obj);
565 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
566 { "GEO", "GEOB", read_geobtag, free_geobtag },
567 { "PIC", "APIC", read_apic, free_apic },
568 { "CHAP","CHAP", read_chapter, NULL },
573 * Get the corresponding ID3v2EMFunc struct for a tag.
574 * @param isv34 Determines if v2.2 or v2.3/4 strings are used
575 * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
577 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
580 while (id3v2_extra_meta_funcs[i].tag3) {
581 if (tag && !memcmp(tag,
582 (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
583 id3v2_extra_meta_funcs[i].tag3),
585 return &id3v2_extra_meta_funcs[i];
591 static void id3v2_parse(AVFormatContext *s, int len, uint8_t version,
592 uint8_t flags, ID3v2ExtraMeta **extra_meta)
597 int64_t next, end = avio_tell(s->pb) + len;
599 const char *reason = NULL;
602 unsigned char *buffer = NULL;
604 const ID3v2EMFunc *extra_func = NULL;
605 unsigned char *uncompressed_buffer = NULL;
606 int uncompressed_buffer_size = 0;
608 av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
613 reason = "compression";
631 unsync = flags & 0x80;
633 if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
634 int extlen = get_size(s->pb, 4);
636 /* In v2.4 the length includes the length field we just read. */
640 reason = "invalid extended header length";
643 avio_skip(s->pb, extlen);
646 reason = "extended header too long.";
651 while (len >= taghdrlen) {
652 unsigned int tflags = 0;
659 avio_read(s->pb, tag, 4);
662 tlen = avio_rb32(s->pb);
664 tlen = get_size(s->pb, 4);
665 tflags = avio_rb16(s->pb);
666 tunsync = tflags & ID3v2_FLAG_UNSYNCH;
668 avio_read(s->pb, tag, 3);
670 tlen = avio_rb24(s->pb);
674 len -= taghdrlen + tlen;
679 next = avio_tell(s->pb) + tlen;
683 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
688 if (tflags & ID3v2_FLAG_DATALEN) {
691 dlen = avio_rb32(s->pb);
696 tcomp = tflags & ID3v2_FLAG_COMPRESSION;
697 tencr = tflags & ID3v2_FLAG_ENCRYPTION;
699 /* skip encrypted tags and, if no zlib, compressed tags */
700 if (tencr || (!CONFIG_ZLIB && tcomp)) {
707 type = "encrypted and compressed";
709 av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
710 avio_skip(s->pb, tlen);
711 /* check for text tag or supported special meta tag */
712 } else if (tag[0] == 'T' ||
714 (extra_func = get_extra_meta_func(tag, isv34)))) {
717 if (unsync || tunsync || tcomp) {
718 av_fast_malloc(&buffer, &buffer_size, tlen);
720 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
724 if (unsync || tunsync) {
725 int64_t end = avio_tell(s->pb) + tlen;
729 while (avio_tell(s->pb) < end && b - buffer < tlen && !s->pb->eof_reached) {
730 *b++ = avio_r8(s->pb);
731 if (*(b - 1) == 0xff && avio_tell(s->pb) < end - 1 &&
733 !s->pb->eof_reached ) {
734 uint8_t val = avio_r8(s->pb);
735 *b++ = val ? val : avio_r8(s->pb);
738 ffio_init_context(&pb, buffer, b - buffer, 0, NULL, NULL, NULL,
741 pbx = &pb; // read from sync buffer
748 av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
750 av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
751 if (!uncompressed_buffer) {
752 av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
756 if (!(unsync || tunsync)) {
757 err = avio_read(s->pb, buffer, tlen);
759 av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
765 err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
767 av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
770 ffio_init_context(&pb, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);
772 pbx = &pb; // read from sync buffer
777 read_ttag(s, pbx, tlen, tag);
779 /* parse special meta tag */
780 extra_func->read(s, pbx, tlen, tag, extra_meta);
781 } else if (!tag[0]) {
783 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
784 avio_skip(s->pb, tlen);
787 /* Skip to end of tag */
789 avio_seek(s->pb, next, SEEK_SET);
792 /* Footer preset, always 10 bytes, skip over it */
793 if (version == 4 && flags & 0x10)
798 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
800 avio_seek(s->pb, end, SEEK_SET);
802 av_free(uncompressed_buffer);
806 void ff_id3v2_read(AVFormatContext *s, const char *magic,
807 ID3v2ExtraMeta **extra_meta)
810 uint8_t buf[ID3v2_HEADER_SIZE];
815 /* save the current offset in case there's nothing to read/skip */
816 off = avio_tell(s->pb);
817 ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
818 if (ret != ID3v2_HEADER_SIZE) {
819 avio_seek(s->pb, off, SEEK_SET);
822 found_header = ff_id3v2_match(buf, magic);
824 /* parse ID3v2 header */
825 len = ((buf[6] & 0x7f) << 21) |
826 ((buf[7] & 0x7f) << 14) |
827 ((buf[8] & 0x7f) << 7) |
829 id3v2_parse(s, len, buf[3], buf[5], extra_meta);
831 avio_seek(s->pb, off, SEEK_SET);
833 } while (found_header);
834 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
835 ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
836 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
837 merge_date(&s->metadata);
840 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
842 ID3v2ExtraMeta *current = *extra_meta, *next;
843 const ID3v2EMFunc *extra_func;
846 if ((extra_func = get_extra_meta_func(current->tag, 1)))
847 extra_func->free(current->data);
848 next = current->next;
854 int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
858 for (cur = *extra_meta; cur; cur = cur->next) {
859 ID3v2ExtraMetaAPIC *apic;
862 if (strcmp(cur->tag, "APIC"))
866 if (!(st = avformat_new_stream(s, NULL)))
867 return AVERROR(ENOMEM);
869 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
870 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
871 st->codec->codec_id = apic->id;
872 av_dict_set(&st->metadata, "title", apic->description, 0);
873 av_dict_set(&st->metadata, "comment", apic->type, 0);
875 av_init_packet(&st->attached_pic);
876 st->attached_pic.buf = apic->buf;
877 st->attached_pic.data = apic->buf->data;
878 st->attached_pic.size = apic->buf->size - FF_INPUT_BUFFER_PADDING_SIZE;
879 st->attached_pic.stream_index = st->index;
880 st->attached_pic.flags |= AV_PKT_FLAG_KEY;