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"
42 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
44 { "TCOM", "composer"},
46 { "TCOP", "copyright"},
47 { "TENC", "encoded_by"},
49 { "TLAN", "language"},
51 { "TPE2", "album_artist"},
52 { "TPE3", "performer"},
54 { "TPUB", "publisher"},
60 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
63 { "TDEN", "creation_time"},
64 { "TSOA", "album-sort"},
65 { "TSOP", "artist-sort"},
66 { "TSOT", "title-sort"},
70 static const AVMetadataConv id3v2_2_metadata_conv[] = {
74 { "TEN", "encoded_by"},
76 { "TP2", "album_artist"},
77 { "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 int ff_id3v2_match(const uint8_t *buf, const char * magic)
104 return buf[0] == magic[0] &&
105 buf[1] == magic[1] &&
106 buf[2] == magic[2] &&
109 (buf[6] & 0x80) == 0 &&
110 (buf[7] & 0x80) == 0 &&
111 (buf[8] & 0x80) == 0 &&
112 (buf[9] & 0x80) == 0;
115 int ff_id3v2_tag_len(const uint8_t * buf)
117 int len = ((buf[6] & 0x7f) << 21) +
118 ((buf[7] & 0x7f) << 14) +
119 ((buf[8] & 0x7f) << 7) +
123 len += ID3v2_HEADER_SIZE;
127 static unsigned int get_size(AVIOContext *s, int len)
131 v = (v << 7) + (avio_r8(s) & 0x7F);
136 * Free GEOB type extra metadata.
138 static void free_geobtag(void *obj)
140 ID3v2ExtraMetaGEOB *geob = obj;
141 av_free(geob->mime_type);
142 av_free(geob->file_name);
143 av_free(geob->description);
149 * Decode characters to UTF-8 according to encoding type. The decoded buffer is
150 * always null terminated. Stop reading when either *maxread bytes are read from
151 * pb or U+0000 character is found.
153 * @param dst Pointer where the address of the buffer with the decoded bytes is
154 * stored. Buffer must be freed by caller.
155 * @param maxread Pointer to maximum number of characters to read from the
156 * AVIOContext. After execution the value is decremented by the number of bytes
158 * @returns 0 if no error occurred, dst is uninitialized on error
160 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
161 uint8_t **dst, int *maxread)
167 unsigned int (*get)(AVIOContext*) = avio_rb16;
170 if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
171 av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
177 case ID3v2_ENCODING_ISO8859:
180 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
185 case ID3v2_ENCODING_UTF16BOM:
186 if ((left -= 2) < 0) {
187 av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
188 avio_close_dyn_buf(dynbuf, dst);
190 return AVERROR_INVALIDDATA;
192 switch (avio_rb16(pb)) {
198 av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
199 avio_close_dyn_buf(dynbuf, dst);
202 return AVERROR_INVALIDDATA;
206 case ID3v2_ENCODING_UTF16BE:
207 while ((left > 1) && ch) {
208 GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
209 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
212 left += 2; /* did not read last char from pb */
215 case ID3v2_ENCODING_UTF8:
223 av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
229 avio_close_dyn_buf(dynbuf, dst);
238 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
241 int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
247 encoding = avio_r8(pb);
248 taglen--; /* account for encoding type byte */
250 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
251 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
255 if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
256 && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
257 && genre <= ID3v1_GENRE_MAX) {
259 dst = ff_id3v1_genre_str[genre];
260 } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
261 /* dst now contains the key, need to get value */
263 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
264 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
268 dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
271 dict_flags |= AV_DICT_DONT_STRDUP_VAL;
274 av_dict_set(&s->metadata, key, dst, dict_flags);
278 * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
280 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
282 ID3v2ExtraMetaGEOB *geob_data = NULL;
283 ID3v2ExtraMeta *new_extra = NULL;
290 geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
292 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
296 new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
298 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
302 /* read encoding type byte */
303 encoding = avio_r8(pb);
306 /* read MIME type (always ISO-8859) */
307 if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
312 if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
316 /* read content description */
317 if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
322 /* save encapsulated binary data */
323 geob_data->data = av_malloc(taglen);
324 if (!geob_data->data) {
325 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
328 if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
329 av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
330 geob_data->datasize = len;
332 geob_data->data = NULL;
333 geob_data->datasize = 0;
336 /* add data to the list */
337 new_extra->tag = "GEOB";
338 new_extra->data = geob_data;
339 new_extra->next = *extra_meta;
340 *extra_meta = new_extra;
345 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
346 free_geobtag(geob_data);
351 static int is_number(const char *str)
353 while (*str >= '0' && *str <= '9') str++;
357 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
359 AVDictionaryEntry *t;
360 if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
361 strlen(t->value) == 4 && is_number(t->value))
366 static void merge_date(AVDictionary **m)
368 AVDictionaryEntry *t;
369 char date[17] = {0}; // YYYY-MM-DD hh:mm
371 if (!(t = get_date_tag(*m, "TYER")) &&
372 !(t = get_date_tag(*m, "TYE")))
374 av_strlcpy(date, t->value, 5);
375 av_dict_set(m, "TYER", NULL, 0);
376 av_dict_set(m, "TYE", NULL, 0);
378 if (!(t = get_date_tag(*m, "TDAT")) &&
379 !(t = get_date_tag(*m, "TDA")))
381 snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
382 av_dict_set(m, "TDAT", NULL, 0);
383 av_dict_set(m, "TDA", NULL, 0);
385 if (!(t = get_date_tag(*m, "TIME")) &&
386 !(t = get_date_tag(*m, "TIM")))
388 snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
389 av_dict_set(m, "TIME", NULL, 0);
390 av_dict_set(m, "TIM", NULL, 0);
394 av_dict_set(m, "date", date, 0);
397 typedef struct ID3v2EMFunc {
400 void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
401 void (*free)(void *obj);
404 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
405 { "GEO", "GEOB", read_geobtag, free_geobtag },
410 * Get the corresponding ID3v2EMFunc struct for a tag.
411 * @param isv34 Determines if v2.2 or v2.3/4 strings are used
412 * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
414 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
417 while (id3v2_extra_meta_funcs[i].tag3) {
418 if (tag && !memcmp(tag,
419 (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
420 id3v2_extra_meta_funcs[i].tag3),
422 return &id3v2_extra_meta_funcs[i];
428 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
433 int64_t next, end = avio_tell(s->pb) + len;
435 const char *reason = NULL;
438 unsigned char *buffer = NULL;
440 const ID3v2EMFunc *extra_func = NULL;
441 unsigned char *compressed_buffer = NULL;
442 int compressed_buffer_size = 0;
447 reason = "compression";
465 unsync = flags & 0x80;
467 /* Extended header present, just skip over it */
468 if (isv34 && flags & 0x40) {
469 int size = get_size(s->pb, 4);
471 reason = "extended header too short.";
476 reason = "extended header too long.";
479 /* already seeked past size, skip the reset */
481 avio_skip(s->pb, size);
484 while (len >= taghdrlen) {
485 unsigned int tflags = 0;
492 avio_read(s->pb, tag, 4);
495 tlen = avio_rb32(s->pb);
497 tlen = get_size(s->pb, 4);
498 tflags = avio_rb16(s->pb);
499 tunsync = tflags & ID3v2_FLAG_UNSYNCH;
501 avio_read(s->pb, tag, 3);
503 tlen = avio_rb24(s->pb);
507 len -= taghdrlen + tlen;
512 next = avio_tell(s->pb) + tlen;
516 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
520 if (tflags & ID3v2_FLAG_DATALEN) {
523 dlen = avio_rb32(s->pb);
528 tcomp = tflags & ID3v2_FLAG_COMPRESSION;
529 tencr = tflags & ID3v2_FLAG_ENCRYPTION;
531 /* skip encrypted tags and, if no zlib, compressed tags */
532 if (tencr || (!CONFIG_ZLIB && tcomp)) {
539 type = "encrypted and compressed";
541 av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
542 avio_skip(s->pb, tlen);
543 /* check for text tag or supported special meta tag */
544 } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
545 if (unsync || tunsync || tcomp) {
548 av_fast_malloc(&buffer, &buffer_size, dlen);
550 av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
557 av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
559 av_fast_malloc(&compressed_buffer, &compressed_buffer_size, tlen);
560 if (!compressed_buffer) {
561 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
565 n = avio_read(s->pb, compressed_buffer, tlen);
567 av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
571 err = uncompress(buffer, &dlen, compressed_buffer, n);
573 av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
579 for (i = 0, j = 0; i < dlen; i++, j++) {
581 buffer[j] = avio_r8(s->pb);
582 if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
583 /* Unsynchronised byte, skip it */
587 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
589 pbx = &pb; // read from sync buffer
591 pbx = s->pb; // read straight from input
595 read_ttag(s, pbx, tlen, tag);
597 /* parse special meta tag */
598 extra_func->read(s, pbx, tlen, tag, extra_meta);
602 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
603 avio_skip(s->pb, tlen);
606 /* Skip to end of tag */
608 avio_seek(s->pb, next, SEEK_SET);
611 if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
616 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
617 avio_seek(s->pb, end, SEEK_SET);
619 av_free(compressed_buffer);
623 void ff_id3v2_read_all(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
626 uint8_t buf[ID3v2_HEADER_SIZE];
631 /* save the current offset in case there's nothing to read/skip */
632 off = avio_tell(s->pb);
633 ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
634 if (ret != ID3v2_HEADER_SIZE)
636 found_header = ff_id3v2_match(buf, magic);
638 /* parse ID3v2 header */
639 len = ((buf[6] & 0x7f) << 21) |
640 ((buf[7] & 0x7f) << 14) |
641 ((buf[8] & 0x7f) << 7) |
643 ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
645 avio_seek(s->pb, off, SEEK_SET);
647 } while (found_header);
648 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
649 ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
650 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
651 merge_date(&s->metadata);
654 void ff_id3v2_read(AVFormatContext *s, const char *magic)
656 ff_id3v2_read_all(s, magic, NULL);
659 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
661 ID3v2ExtraMeta *current = *extra_meta, *next;
662 const ID3v2EMFunc *extra_func;
665 if ((extra_func = get_extra_meta_func(current->tag, 1)))
666 extra_func->free(current->data);
667 next = current->next;