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"
29 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
31 { "TCOM", "composer"},
33 { "TCOP", "copyright"},
34 { "TENC", "encoded_by"},
36 { "TLAN", "language"},
38 { "TPE2", "album_artist"},
39 { "TPE3", "performer"},
41 { "TPUB", "publisher"},
47 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
50 { "TDEN", "creation_time"},
51 { "TSOA", "album-sort"},
52 { "TSOP", "artist-sort"},
53 { "TSOT", "title-sort"},
57 static const AVMetadataConv id3v2_2_metadata_conv[] = {
61 { "TEN", "encoded_by"},
63 { "TP2", "album_artist"},
64 { "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 int ff_id3v2_match(const uint8_t *buf, const char * magic)
91 return buf[0] == magic[0] &&
96 (buf[6] & 0x80) == 0 &&
97 (buf[7] & 0x80) == 0 &&
98 (buf[8] & 0x80) == 0 &&
102 int ff_id3v2_tag_len(const uint8_t * buf)
104 int len = ((buf[6] & 0x7f) << 21) +
105 ((buf[7] & 0x7f) << 14) +
106 ((buf[8] & 0x7f) << 7) +
110 len += ID3v2_HEADER_SIZE;
114 static unsigned int get_size(AVIOContext *s, int len)
118 v = (v << 7) + (avio_r8(s) & 0x7F);
123 * Free GEOB type extra metadata.
125 static void free_geobtag(void *obj)
127 ID3v2ExtraMetaGEOB *geob = obj;
128 av_free(geob->mime_type);
129 av_free(geob->file_name);
130 av_free(geob->description);
136 * Decode characters to UTF-8 according to encoding type. The decoded buffer is
137 * always null terminated. Stop reading when either *maxread bytes are read from
138 * pb or U+0000 character is found.
140 * @param dst Pointer where the address of the buffer with the decoded bytes is
141 * stored. Buffer must be freed by caller.
142 * @param maxread Pointer to maximum number of characters to read from the
143 * AVIOContext. After execution the value is decremented by the number of bytes
145 * @returns 0 if no error occurred, dst is uninitialized on error
147 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
148 uint8_t **dst, int *maxread)
154 unsigned int (*get)(AVIOContext*) = avio_rb16;
157 if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
158 av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
164 case ID3v2_ENCODING_ISO8859:
167 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
172 case ID3v2_ENCODING_UTF16BOM:
173 if ((left -= 2) < 0) {
174 av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
175 avio_close_dyn_buf(dynbuf, dst);
177 return AVERROR_INVALIDDATA;
179 switch (avio_rb16(pb)) {
185 av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
186 avio_close_dyn_buf(dynbuf, dst);
189 return AVERROR_INVALIDDATA;
193 case ID3v2_ENCODING_UTF16BE:
194 while ((left > 1) && ch) {
195 GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
196 PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
199 left += 2; /* did not read last char from pb */
202 case ID3v2_ENCODING_UTF8:
210 av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
216 avio_close_dyn_buf(dynbuf, dst);
225 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
228 int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
234 encoding = avio_r8(pb);
235 taglen--; /* account for encoding type byte */
237 if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
238 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
242 if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
243 && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
244 && genre <= ID3v1_GENRE_MAX) {
246 dst = ff_id3v1_genre_str[genre];
247 } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
248 /* dst now contains the key, need to get value */
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 dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
258 dict_flags |= AV_DICT_DONT_STRDUP_VAL;
261 av_dict_set(&s->metadata, key, dst, dict_flags);
265 * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
267 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
269 ID3v2ExtraMetaGEOB *geob_data = NULL;
270 ID3v2ExtraMeta *new_extra = NULL;
277 geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
279 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
283 new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
285 av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
289 /* read encoding type byte */
290 encoding = avio_r8(pb);
293 /* read MIME type (always ISO-8859) */
294 if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
299 if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
303 /* read content description */
304 if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
309 /* save encapsulated binary data */
310 geob_data->data = av_malloc(taglen);
311 if (!geob_data->data) {
312 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
315 if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
316 av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
317 geob_data->datasize = len;
319 geob_data->data = NULL;
320 geob_data->datasize = 0;
323 /* add data to the list */
324 new_extra->tag = "GEOB";
325 new_extra->data = geob_data;
326 new_extra->next = *extra_meta;
327 *extra_meta = new_extra;
332 av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
333 free_geobtag(geob_data);
338 static int is_number(const char *str)
340 while (*str >= '0' && *str <= '9') str++;
344 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
346 AVDictionaryEntry *t;
347 if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
348 strlen(t->value) == 4 && is_number(t->value))
353 static void merge_date(AVDictionary **m)
355 AVDictionaryEntry *t;
356 char date[17] = {0}; // YYYY-MM-DD hh:mm
358 if (!(t = get_date_tag(*m, "TYER")) &&
359 !(t = get_date_tag(*m, "TYE")))
361 av_strlcpy(date, t->value, 5);
362 av_dict_set(m, "TYER", NULL, 0);
363 av_dict_set(m, "TYE", NULL, 0);
365 if (!(t = get_date_tag(*m, "TDAT")) &&
366 !(t = get_date_tag(*m, "TDA")))
368 snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
369 av_dict_set(m, "TDAT", NULL, 0);
370 av_dict_set(m, "TDA", NULL, 0);
372 if (!(t = get_date_tag(*m, "TIME")) &&
373 !(t = get_date_tag(*m, "TIM")))
375 snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
376 av_dict_set(m, "TIME", NULL, 0);
377 av_dict_set(m, "TIM", NULL, 0);
381 av_dict_set(m, "date", date, 0);
384 typedef struct ID3v2EMFunc {
387 void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
388 void (*free)(void *obj);
391 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
392 { "GEO", "GEOB", read_geobtag, free_geobtag },
397 * Get the corresponding ID3v2EMFunc struct for a tag.
398 * @param isv34 Determines if v2.2 or v2.3/4 strings are used
399 * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
401 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
404 while (id3v2_extra_meta_funcs[i].tag3) {
406 (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
407 id3v2_extra_meta_funcs[i].tag3),
409 return &id3v2_extra_meta_funcs[i];
415 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
417 int isv34, tlen, unsync;
419 int64_t next, end = avio_tell(s->pb) + len;
421 const char *reason = NULL;
424 unsigned char *buffer = NULL;
426 const ID3v2EMFunc *extra_func;
431 reason = "compression";
449 unsync = flags & 0x80;
451 if (isv34 && flags & 0x40) /* Extended header present, just skip over it */
452 avio_skip(s->pb, get_size(s->pb, 4));
454 while (len >= taghdrlen) {
455 unsigned int tflags = 0;
459 avio_read(s->pb, tag, 4);
462 tlen = avio_rb32(s->pb);
464 tlen = get_size(s->pb, 4);
465 tflags = avio_rb16(s->pb);
466 tunsync = tflags & ID3v2_FLAG_UNSYNCH;
468 avio_read(s->pb, tag, 3);
470 tlen = avio_rb24(s->pb);
472 if (tlen < 0 || tlen > len - taghdrlen) {
473 av_log(s, AV_LOG_WARNING, "Invalid size in frame %s, skipping the rest of tag.\n", tag);
476 len -= taghdrlen + tlen;
477 next = avio_tell(s->pb) + tlen;
481 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
485 if (tflags & ID3v2_FLAG_DATALEN) {
490 if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
491 av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
492 avio_skip(s->pb, tlen);
493 /* check for text tag or supported special meta tag */
494 } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
495 if (unsync || tunsync) {
497 av_fast_malloc(&buffer, &buffer_size, tlen);
499 av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
502 for (i = 0, j = 0; i < tlen; i++, j++) {
503 buffer[j] = avio_r8(s->pb);
504 if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
505 /* Unsynchronised byte, skip it */
509 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
511 pbx = &pb; // read from sync buffer
513 pbx = s->pb; // read straight from input
517 read_ttag(s, pbx, tlen, tag);
519 /* parse special meta tag */
520 extra_func->read(s, pbx, tlen, tag, extra_meta);
524 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
525 avio_skip(s->pb, tlen);
528 /* Skip to end of tag */
530 avio_seek(s->pb, next, SEEK_SET);
533 if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
538 av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
539 avio_seek(s->pb, end, SEEK_SET);
544 void ff_id3v2_read_all(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
547 uint8_t buf[ID3v2_HEADER_SIZE];
552 /* save the current offset in case there's nothing to read/skip */
553 off = avio_tell(s->pb);
554 ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
555 if (ret != ID3v2_HEADER_SIZE)
557 found_header = ff_id3v2_match(buf, magic);
559 /* parse ID3v2 header */
560 len = ((buf[6] & 0x7f) << 21) |
561 ((buf[7] & 0x7f) << 14) |
562 ((buf[8] & 0x7f) << 7) |
564 ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
566 avio_seek(s->pb, off, SEEK_SET);
568 } while (found_header);
569 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
570 ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
571 ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
572 merge_date(&s->metadata);
575 void ff_id3v2_read(AVFormatContext *s, const char *magic)
577 ff_id3v2_read_all(s, magic, NULL);
580 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
582 ID3v2ExtraMeta *current = *extra_meta, *next;
583 const ID3v2EMFunc *extra_func;
586 if ((extra_func = get_extra_meta_func(current->tag, 1)))
587 extra_func->free(current->data);
588 next = current->next;