]> git.sesse.net Git - ffmpeg/blob - libavformat/id3v2.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / id3v2.c
1 /*
2  * Copyright (c) 2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
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.
10  *
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.
15  *
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
19  */
20
21 /**
22  * @file
23  * ID3v2 header parser
24  *
25  * Specifications available at:
26  * http://id3.org/Developer_Information
27  */
28
29 #include "id3v2.h"
30 #include "id3v1.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/dict.h"
34 #include "avio_internal.h"
35
36 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
37     { "TALB", "album"},
38     { "TCOM", "composer"},
39     { "TCON", "genre"},
40     { "TCOP", "copyright"},
41     { "TENC", "encoded_by"},
42     { "TIT2", "title"},
43     { "TLAN", "language"},
44     { "TPE1", "artist"},
45     { "TPE2", "album_artist"},
46     { "TPE3", "performer"},
47     { "TPOS", "disc"},
48     { "TPUB", "publisher"},
49     { "TRCK", "track"},
50     { "TSSE", "encoder"},
51     { 0 }
52 };
53
54 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
55     { "TDRL", "date"},
56     { "TDRC", "date"},
57     { "TDEN", "creation_time"},
58     { "TSOA", "album-sort"},
59     { "TSOP", "artist-sort"},
60     { "TSOT", "title-sort"},
61     { 0 }
62 };
63
64 static const AVMetadataConv id3v2_2_metadata_conv[] = {
65     { "TAL",  "album"},
66     { "TCO",  "genre"},
67     { "TT2",  "title"},
68     { "TEN",  "encoded_by"},
69     { "TP1",  "artist"},
70     { "TP2",  "album_artist"},
71     { "TP3",  "performer"},
72     { "TRK",  "track"},
73     { 0 }
74 };
75
76
77 const char ff_id3v2_tags[][4] = {
78    "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
79    "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
80    "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
81    "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
82    { 0 },
83 };
84
85 const char ff_id3v2_4_tags[][4] = {
86    "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
87    "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
88    { 0 },
89 };
90
91 const char ff_id3v2_3_tags[][4] = {
92    "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
93    { 0 },
94 };
95
96 int ff_id3v2_match(const uint8_t *buf, const char * magic)
97 {
98     return  buf[0]         == magic[0] &&
99             buf[1]         == magic[1] &&
100             buf[2]         == magic[2] &&
101             buf[3]         != 0xff &&
102             buf[4]         != 0xff &&
103            (buf[6] & 0x80) ==    0 &&
104            (buf[7] & 0x80) ==    0 &&
105            (buf[8] & 0x80) ==    0 &&
106            (buf[9] & 0x80) ==    0;
107 }
108
109 int ff_id3v2_tag_len(const uint8_t * buf)
110 {
111     int len = ((buf[6] & 0x7f) << 21) +
112               ((buf[7] & 0x7f) << 14) +
113               ((buf[8] & 0x7f) << 7) +
114                (buf[9] & 0x7f) +
115               ID3v2_HEADER_SIZE;
116     if (buf[5] & 0x10)
117         len += ID3v2_HEADER_SIZE;
118     return len;
119 }
120
121 static unsigned int get_size(AVIOContext *s, int len)
122 {
123     int v = 0;
124     while (len--)
125         v = (v << 7) + (avio_r8(s) & 0x7F);
126     return v;
127 }
128
129 /**
130  * Free GEOB type extra metadata.
131  */
132 static void free_geobtag(void *obj)
133 {
134     ID3v2ExtraMetaGEOB *geob = obj;
135     av_free(geob->mime_type);
136     av_free(geob->file_name);
137     av_free(geob->description);
138     av_free(geob->data);
139     av_free(geob);
140 }
141
142 /**
143  * Decode characters to UTF-8 according to encoding type. The decoded buffer is
144  * always null terminated. Stop reading when either *maxread bytes are read from
145  * pb or U+0000 character is found.
146  *
147  * @param dst Pointer where the address of the buffer with the decoded bytes is
148  * stored. Buffer must be freed by caller.
149  * @param maxread Pointer to maximum number of characters to read from the
150  * AVIOContext. After execution the value is decremented by the number of bytes
151  * actually read.
152  * @returns 0 if no error occured, dst is uninitialized on error
153  */
154 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
155                       uint8_t **dst, int *maxread)
156 {
157     int ret;
158     uint8_t tmp;
159     uint32_t ch = 1;
160     int left = *maxread;
161     unsigned int (*get)(AVIOContext*) = avio_rb16;
162     AVIOContext *dynbuf;
163
164     if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
165         av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
166         return ret;
167     }
168
169     switch (encoding) {
170
171     case ID3v2_ENCODING_ISO8859:
172         while (left && ch) {
173             ch = avio_r8(pb);
174             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
175             left--;
176         }
177         break;
178
179     case ID3v2_ENCODING_UTF16BOM:
180         if ((left -= 2) < 0) {
181             av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
182             avio_close_dyn_buf(dynbuf, dst);
183             av_freep(dst);
184             return AVERROR_INVALIDDATA;
185         }
186         switch (avio_rb16(pb)) {
187         case 0xfffe:
188             get = avio_rl16;
189         case 0xfeff:
190             break;
191         default:
192             av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
193             avio_close_dyn_buf(dynbuf, dst);
194             av_freep(dst);
195             *maxread = left;
196             return AVERROR_INVALIDDATA;
197         }
198         // fall-through
199
200     case ID3v2_ENCODING_UTF16BE:
201         while ((left > 1) && ch) {
202             GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
203             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
204         }
205         if (left < 0)
206             left += 2; /* did not read last char from pb */
207         break;
208
209     case ID3v2_ENCODING_UTF8:
210         while (left && ch) {
211             ch = avio_r8(pb);
212             avio_w8(dynbuf, ch);
213             left--;
214         }
215         break;
216     default:
217         av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
218     }
219
220     if (ch)
221         avio_w8(dynbuf, 0);
222
223     avio_close_dyn_buf(dynbuf, dst);
224     *maxread = left;
225
226     return 0;
227 }
228
229 /**
230  * Parse a text tag.
231  */
232 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
233 {
234     uint8_t *dst;
235     int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
236     unsigned genre;
237
238     if (taglen < 1)
239         return;
240
241     encoding = avio_r8(pb);
242     taglen--; /* account for encoding type byte */
243
244     if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
245         av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
246         return;
247     }
248
249     if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
250         && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
251         && genre <= ID3v1_GENRE_MAX) {
252         av_freep(&dst);
253         dst = ff_id3v1_genre_str[genre];
254     } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
255         /* dst now contains the key, need to get value */
256         key = dst;
257         if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
258             av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
259             av_freep(&key);
260             return;
261         }
262         dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
263     }
264     else if (*dst)
265         dict_flags |= AV_DICT_DONT_STRDUP_VAL;
266
267     if (dst)
268         av_dict_set(&s->metadata, key, dst, dict_flags);
269 }
270
271 /**
272  * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
273  */
274 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
275 {
276     ID3v2ExtraMetaGEOB *geob_data = NULL;
277     ID3v2ExtraMeta *new_extra = NULL;
278     char encoding;
279     unsigned int len;
280
281     if (taglen < 1)
282         return;
283
284     geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
285     if (!geob_data) {
286         av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
287         return;
288     }
289
290     new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
291     if (!new_extra) {
292         av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
293         goto fail;
294     }
295
296     /* read encoding type byte */
297     encoding = avio_r8(pb);
298     taglen--;
299
300     /* read MIME type (always ISO-8859) */
301     if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
302         || taglen <= 0)
303         goto fail;
304
305     /* read file name */
306     if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
307         || taglen <= 0)
308         goto fail;
309
310     /* read content description */
311     if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
312         || taglen < 0)
313         goto fail;
314
315     if (taglen) {
316         /* save encapsulated binary data */
317         geob_data->data = av_malloc(taglen);
318         if (!geob_data->data) {
319             av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
320             goto fail;
321         }
322         if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
323             av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
324         geob_data->datasize = len;
325     } else {
326         geob_data->data = NULL;
327         geob_data->datasize = 0;
328     }
329
330     /* add data to the list */
331     new_extra->tag = "GEOB";
332     new_extra->data = geob_data;
333     new_extra->next = *extra_meta;
334     *extra_meta = new_extra;
335
336     return;
337
338 fail:
339     av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
340     free_geobtag(geob_data);
341     av_free(new_extra);
342     return;
343 }
344
345 static int is_number(const char *str)
346 {
347     while (*str >= '0' && *str <= '9') str++;
348     return !*str;
349 }
350
351 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
352 {
353     AVDictionaryEntry *t;
354     if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
355         strlen(t->value) == 4 && is_number(t->value))
356         return t;
357     return NULL;
358 }
359
360 static void merge_date(AVDictionary **m)
361 {
362     AVDictionaryEntry *t;
363     char date[17] = {0};      // YYYY-MM-DD hh:mm
364
365     if (!(t = get_date_tag(*m, "TYER")) &&
366         !(t = get_date_tag(*m, "TYE")))
367         return;
368     av_strlcpy(date, t->value, 5);
369     av_dict_set(m, "TYER", NULL, 0);
370     av_dict_set(m, "TYE",  NULL, 0);
371
372     if (!(t = get_date_tag(*m, "TDAT")) &&
373         !(t = get_date_tag(*m, "TDA")))
374         goto finish;
375     snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
376     av_dict_set(m, "TDAT", NULL, 0);
377     av_dict_set(m, "TDA",  NULL, 0);
378
379     if (!(t = get_date_tag(*m, "TIME")) &&
380         !(t = get_date_tag(*m, "TIM")))
381         goto finish;
382     snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
383     av_dict_set(m, "TIME", NULL, 0);
384     av_dict_set(m, "TIM",  NULL, 0);
385
386 finish:
387     if (date[0])
388         av_dict_set(m, "date", date, 0);
389 }
390
391 typedef struct ID3v2EMFunc {
392     const char *tag3;
393     const char *tag4;
394     void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
395     void (*free)(void *obj);
396 } ID3v2EMFunc;
397
398 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
399     { "GEO", "GEOB", read_geobtag, free_geobtag },
400     { NULL }
401 };
402
403 /**
404  * Get the corresponding ID3v2EMFunc struct for a tag.
405  * @param isv34 Determines if v2.2 or v2.3/4 strings are used
406  * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
407  */
408 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
409 {
410     int i = 0;
411     while (id3v2_extra_meta_funcs[i].tag3) {
412         if (!memcmp(tag,
413                     (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
414                              id3v2_extra_meta_funcs[i].tag3),
415                     (isv34 ? 4 : 3)))
416             return &id3v2_extra_meta_funcs[i];
417         i++;
418     }
419     return &id3v2_extra_meta_funcs[i];
420 }
421
422 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
423 {
424     int isv34, unsync;
425     unsigned tlen;
426     char tag[5];
427     int64_t next, end = avio_tell(s->pb) + len;
428     int taghdrlen;
429     const char *reason = NULL;
430     AVIOContext pb;
431     AVIOContext *pbx;
432     unsigned char *buffer = NULL;
433     int buffer_size = 0;
434     const ID3v2EMFunc *extra_func;
435
436     switch (version) {
437     case 2:
438         if (flags & 0x40) {
439             reason = "compression";
440             goto error;
441         }
442         isv34 = 0;
443         taghdrlen = 6;
444         break;
445
446     case 3:
447     case 4:
448         isv34 = 1;
449         taghdrlen = 10;
450         break;
451
452     default:
453         reason = "version";
454         goto error;
455     }
456
457     unsync = flags & 0x80;
458
459     if (isv34 && flags & 0x40) /* Extended header present, just skip over it */
460         avio_skip(s->pb, get_size(s->pb, 4));
461
462     while (len >= taghdrlen) {
463         unsigned int tflags = 0;
464         int tunsync = 0;
465
466         if (isv34) {
467             avio_read(s->pb, tag, 4);
468             tag[4] = 0;
469             if(version==3){
470                 tlen = avio_rb32(s->pb);
471             }else
472                 tlen = get_size(s->pb, 4);
473             tflags = avio_rb16(s->pb);
474             tunsync = tflags & ID3v2_FLAG_UNSYNCH;
475         } else {
476             avio_read(s->pb, tag, 3);
477             tag[3] = 0;
478             tlen = avio_rb24(s->pb);
479         }
480         if (tlen > (1<<28))
481             break;
482         len -= taghdrlen + tlen;
483
484         if (len < 0)
485             break;
486
487         next = avio_tell(s->pb) + tlen;
488
489         if (!tlen) {
490             if (tag[0])
491                 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
492             continue;
493         }
494
495         if (tflags & ID3v2_FLAG_DATALEN) {
496             if (tlen < 4)
497                 break;
498             avio_rb32(s->pb);
499             tlen -= 4;
500         }
501
502         if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
503             av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
504             avio_skip(s->pb, tlen);
505         /* check for text tag or supported special meta tag */
506         } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
507             if (unsync || tunsync) {
508                 int i, j;
509                 av_fast_malloc(&buffer, &buffer_size, tlen);
510                 if (!buffer) {
511                     av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
512                     goto seek;
513                 }
514                 for (i = 0, j = 0; i < tlen; i++, j++) {
515                     buffer[j] = avio_r8(s->pb);
516                     if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
517                         /* Unsynchronised byte, skip it */
518                         j--;
519                     }
520                 }
521                 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
522                 tlen = j;
523                 pbx = &pb; // read from sync buffer
524             } else {
525                 pbx = s->pb; // read straight from input
526             }
527             if (tag[0] == 'T')
528                 /* parse text tag */
529                 read_ttag(s, pbx, tlen, tag);
530             else
531                 /* parse special meta tag */
532                 extra_func->read(s, pbx, tlen, tag, extra_meta);
533         }
534         else if (!tag[0]) {
535             if (tag[1])
536                 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
537             avio_skip(s->pb, tlen);
538             break;
539         }
540         /* Skip to end of tag */
541 seek:
542         avio_seek(s->pb, next, SEEK_SET);
543     }
544
545     if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
546         end += 10;
547
548   error:
549     if (reason)
550         av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
551     avio_seek(s->pb, end, SEEK_SET);
552     av_free(buffer);
553     return;
554 }
555
556 void ff_id3v2_read_all(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
557 {
558     int len, ret;
559     uint8_t buf[ID3v2_HEADER_SIZE];
560     int     found_header;
561     int64_t off;
562
563     do {
564         /* save the current offset in case there's nothing to read/skip */
565         off = avio_tell(s->pb);
566         ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
567         if (ret != ID3v2_HEADER_SIZE)
568             break;
569             found_header = ff_id3v2_match(buf, magic);
570             if (found_header) {
571             /* parse ID3v2 header */
572             len = ((buf[6] & 0x7f) << 21) |
573                   ((buf[7] & 0x7f) << 14) |
574                   ((buf[8] & 0x7f) << 7) |
575                    (buf[9] & 0x7f);
576             ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
577         } else {
578             avio_seek(s->pb, off, SEEK_SET);
579         }
580     } while (found_header);
581     ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
582     ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
583     ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
584     merge_date(&s->metadata);
585 }
586
587 void ff_id3v2_read(AVFormatContext *s, const char *magic)
588 {
589     ff_id3v2_read_all(s, magic, NULL);
590 }
591
592 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
593 {
594     ID3v2ExtraMeta *current = *extra_meta, *next;
595     const ID3v2EMFunc *extra_func;
596
597     while (current) {
598         if ((extra_func = get_extra_meta_func(current->tag, 1)))
599             extra_func->free(current->data);
600         next = current->next;
601         av_freep(&current);
602         current = next;
603     }
604 }