Update ffmpeg to n0.10.2 (f139838d6473c7b5152178f602cb953a824c2ff9)
[vuplus_xbmc] / lib / 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 "config.h"
30
31 #if CONFIG_ZLIB
32 #include <zlib.h>
33 #endif
34
35 #include "id3v2.h"
36 #include "id3v1.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/dict.h"
40 #include "avio_internal.h"
41
42 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
43     { "TALB", "album"},
44     { "TCOM", "composer"},
45     { "TCON", "genre"},
46     { "TCOP", "copyright"},
47     { "TENC", "encoded_by"},
48     { "TIT2", "title"},
49     { "TLAN", "language"},
50     { "TPE1", "artist"},
51     { "TPE2", "album_artist"},
52     { "TPE3", "performer"},
53     { "TPOS", "disc"},
54     { "TPUB", "publisher"},
55     { "TRCK", "track"},
56     { "TSSE", "encoder"},
57     { 0 }
58 };
59
60 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
61     { "TDRL", "date"},
62     { "TDRC", "date"},
63     { "TDEN", "creation_time"},
64     { "TSOA", "album-sort"},
65     { "TSOP", "artist-sort"},
66     { "TSOT", "title-sort"},
67     { 0 }
68 };
69
70 static const AVMetadataConv id3v2_2_metadata_conv[] = {
71     { "TAL",  "album"},
72     { "TCO",  "genre"},
73     { "TT2",  "title"},
74     { "TEN",  "encoded_by"},
75     { "TP1",  "artist"},
76     { "TP2",  "album_artist"},
77     { "TP3",  "performer"},
78     { "TRK",  "track"},
79     { 0 }
80 };
81
82
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",
88    { 0 },
89 };
90
91 const char ff_id3v2_4_tags[][4] = {
92    "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
93    "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
94    { 0 },
95 };
96
97 const char ff_id3v2_3_tags[][4] = {
98    "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
99    { 0 },
100 };
101
102 int ff_id3v2_match(const uint8_t *buf, const char * magic)
103 {
104     return  buf[0]         == magic[0] &&
105             buf[1]         == magic[1] &&
106             buf[2]         == magic[2] &&
107             buf[3]         != 0xff &&
108             buf[4]         != 0xff &&
109            (buf[6] & 0x80) ==    0 &&
110            (buf[7] & 0x80) ==    0 &&
111            (buf[8] & 0x80) ==    0 &&
112            (buf[9] & 0x80) ==    0;
113 }
114
115 int ff_id3v2_tag_len(const uint8_t * buf)
116 {
117     int len = ((buf[6] & 0x7f) << 21) +
118               ((buf[7] & 0x7f) << 14) +
119               ((buf[8] & 0x7f) << 7) +
120                (buf[9] & 0x7f) +
121               ID3v2_HEADER_SIZE;
122     if (buf[5] & 0x10)
123         len += ID3v2_HEADER_SIZE;
124     return len;
125 }
126
127 static unsigned int get_size(AVIOContext *s, int len)
128 {
129     int v = 0;
130     while (len--)
131         v = (v << 7) + (avio_r8(s) & 0x7F);
132     return v;
133 }
134
135 /**
136  * Free GEOB type extra metadata.
137  */
138 static void free_geobtag(void *obj)
139 {
140     ID3v2ExtraMetaGEOB *geob = obj;
141     av_free(geob->mime_type);
142     av_free(geob->file_name);
143     av_free(geob->description);
144     av_free(geob->data);
145     av_free(geob);
146 }
147
148 /**
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.
152  *
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
157  * actually read.
158  * @returns 0 if no error occurred, dst is uninitialized on error
159  */
160 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
161                       uint8_t **dst, int *maxread)
162 {
163     int ret;
164     uint8_t tmp;
165     uint32_t ch = 1;
166     int left = *maxread;
167     unsigned int (*get)(AVIOContext*) = avio_rb16;
168     AVIOContext *dynbuf;
169
170     if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
171         av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
172         return ret;
173     }
174
175     switch (encoding) {
176
177     case ID3v2_ENCODING_ISO8859:
178         while (left && ch) {
179             ch = avio_r8(pb);
180             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
181             left--;
182         }
183         break;
184
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);
189             av_freep(dst);
190             return AVERROR_INVALIDDATA;
191         }
192         switch (avio_rb16(pb)) {
193         case 0xfffe:
194             get = avio_rl16;
195         case 0xfeff:
196             break;
197         default:
198             av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
199             avio_close_dyn_buf(dynbuf, dst);
200             av_freep(dst);
201             *maxread = left;
202             return AVERROR_INVALIDDATA;
203         }
204         // fall-through
205
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);)
210         }
211         if (left < 0)
212             left += 2; /* did not read last char from pb */
213         break;
214
215     case ID3v2_ENCODING_UTF8:
216         while (left && ch) {
217             ch = avio_r8(pb);
218             avio_w8(dynbuf, ch);
219             left--;
220         }
221         break;
222     default:
223         av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
224     }
225
226     if (ch)
227         avio_w8(dynbuf, 0);
228
229     avio_close_dyn_buf(dynbuf, dst);
230     *maxread = left;
231
232     return 0;
233 }
234
235 /**
236  * Parse a text tag.
237  */
238 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
239 {
240     uint8_t *dst;
241     int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
242     unsigned genre;
243
244     if (taglen < 1)
245         return;
246
247     encoding = avio_r8(pb);
248     taglen--; /* account for encoding type byte */
249
250     if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
251         av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
252         return;
253     }
254
255     if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
256         && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
257         && genre <= ID3v1_GENRE_MAX) {
258         av_freep(&dst);
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 */
262         key = dst;
263         if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
264             av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
265             av_freep(&key);
266             return;
267         }
268         dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
269     }
270     else if (*dst)
271         dict_flags |= AV_DICT_DONT_STRDUP_VAL;
272
273     if (dst)
274         av_dict_set(&s->metadata, key, dst, dict_flags);
275 }
276
277 /**
278  * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
279  */
280 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
281 {
282     ID3v2ExtraMetaGEOB *geob_data = NULL;
283     ID3v2ExtraMeta *new_extra = NULL;
284     char encoding;
285     unsigned int len;
286
287     if (taglen < 1)
288         return;
289
290     geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
291     if (!geob_data) {
292         av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
293         return;
294     }
295
296     new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
297     if (!new_extra) {
298         av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
299         goto fail;
300     }
301
302     /* read encoding type byte */
303     encoding = avio_r8(pb);
304     taglen--;
305
306     /* read MIME type (always ISO-8859) */
307     if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
308         || taglen <= 0)
309         goto fail;
310
311     /* read file name */
312     if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
313         || taglen <= 0)
314         goto fail;
315
316     /* read content description */
317     if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
318         || taglen < 0)
319         goto fail;
320
321     if (taglen) {
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);
326             goto fail;
327         }
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;
331     } else {
332         geob_data->data = NULL;
333         geob_data->datasize = 0;
334     }
335
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;
341
342     return;
343
344 fail:
345     av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
346     free_geobtag(geob_data);
347     av_free(new_extra);
348     return;
349 }
350
351 static int is_number(const char *str)
352 {
353     while (*str >= '0' && *str <= '9') str++;
354     return !*str;
355 }
356
357 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
358 {
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))
362         return t;
363     return NULL;
364 }
365
366 static void merge_date(AVDictionary **m)
367 {
368     AVDictionaryEntry *t;
369     char date[17] = {0};      // YYYY-MM-DD hh:mm
370
371     if (!(t = get_date_tag(*m, "TYER")) &&
372         !(t = get_date_tag(*m, "TYE")))
373         return;
374     av_strlcpy(date, t->value, 5);
375     av_dict_set(m, "TYER", NULL, 0);
376     av_dict_set(m, "TYE",  NULL, 0);
377
378     if (!(t = get_date_tag(*m, "TDAT")) &&
379         !(t = get_date_tag(*m, "TDA")))
380         goto finish;
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);
384
385     if (!(t = get_date_tag(*m, "TIME")) &&
386         !(t = get_date_tag(*m, "TIM")))
387         goto finish;
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);
391
392 finish:
393     if (date[0])
394         av_dict_set(m, "date", date, 0);
395 }
396
397 typedef struct ID3v2EMFunc {
398     const char *tag3;
399     const char *tag4;
400     void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
401     void (*free)(void *obj);
402 } ID3v2EMFunc;
403
404 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
405     { "GEO", "GEOB", read_geobtag, free_geobtag },
406     { NULL }
407 };
408
409 /**
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.
413  */
414 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
415 {
416     int i = 0;
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),
421                     (isv34 ? 4 : 3)))
422             return &id3v2_extra_meta_funcs[i];
423         i++;
424     }
425     return NULL;
426 }
427
428 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
429 {
430     int isv34, unsync;
431     unsigned tlen;
432     char tag[5];
433     int64_t next, end = avio_tell(s->pb) + len;
434     int taghdrlen;
435     const char *reason = NULL;
436     AVIOContext pb;
437     AVIOContext *pbx;
438     unsigned char *buffer = NULL;
439     int buffer_size = 0;
440     const ID3v2EMFunc *extra_func = NULL;
441     unsigned char *compressed_buffer = NULL;
442     int compressed_buffer_size = 0;
443
444     switch (version) {
445     case 2:
446         if (flags & 0x40) {
447             reason = "compression";
448             goto error;
449         }
450         isv34 = 0;
451         taghdrlen = 6;
452         break;
453
454     case 3:
455     case 4:
456         isv34 = 1;
457         taghdrlen = 10;
458         break;
459
460     default:
461         reason = "version";
462         goto error;
463     }
464
465     unsync = flags & 0x80;
466
467     /* Extended header present, just skip over it */
468     if (isv34 && flags & 0x40) {
469         int size = get_size(s->pb, 4);
470         if (size < 6) {
471             reason = "extended header too short.";
472             goto error;
473         }
474         len -= size;
475         if (len < 0) {
476             reason = "extended header too long.";
477             goto error;
478         }
479         /* already seeked past size, skip the reset */
480         size -= 4;
481         avio_skip(s->pb, size);
482     }
483
484     while (len >= taghdrlen) {
485         unsigned int tflags = 0;
486         int tunsync = 0;
487         int tcomp = 0;
488         int tencr = 0;
489         unsigned long dlen;
490
491         if (isv34) {
492             avio_read(s->pb, tag, 4);
493             tag[4] = 0;
494             if(version==3){
495                 tlen = avio_rb32(s->pb);
496             }else
497                 tlen = get_size(s->pb, 4);
498             tflags = avio_rb16(s->pb);
499             tunsync = tflags & ID3v2_FLAG_UNSYNCH;
500         } else {
501             avio_read(s->pb, tag, 3);
502             tag[3] = 0;
503             tlen = avio_rb24(s->pb);
504         }
505         if (tlen > (1<<28))
506             break;
507         len -= taghdrlen + tlen;
508
509         if (len < 0)
510             break;
511
512         next = avio_tell(s->pb) + tlen;
513
514         if (!tlen) {
515             if (tag[0])
516                 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
517             continue;
518         }
519
520         if (tflags & ID3v2_FLAG_DATALEN) {
521             if (tlen < 4)
522                 break;
523             dlen = avio_rb32(s->pb);
524             tlen -= 4;
525         } else
526             dlen = tlen;
527
528         tcomp = tflags & ID3v2_FLAG_COMPRESSION;
529         tencr = tflags & ID3v2_FLAG_ENCRYPTION;
530
531         /* skip encrypted tags and, if no zlib, compressed tags */
532         if (tencr || (!CONFIG_ZLIB && tcomp)) {
533             const char *type;
534             if (!tcomp)
535                 type = "encrypted";
536             else if (!tencr)
537                 type = "compressed";
538             else
539                 type = "encrypted and compressed";
540
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) {
546                 int i, j;
547
548                 av_fast_malloc(&buffer, &buffer_size, dlen);
549                 if (!buffer) {
550                     av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
551                     goto seek;
552                 }
553 #if CONFIG_ZLIB
554                 if (tcomp) {
555                     int n, err;
556
557                     av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
558
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);
562                         goto seek;
563                     }
564
565                     n = avio_read(s->pb, compressed_buffer, tlen);
566                     if (n < 0) {
567                         av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
568                         goto seek;
569                     }
570
571                     err = uncompress(buffer, &dlen, compressed_buffer, n);
572                     if (err != Z_OK) {
573                         av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
574                         goto seek;
575                     }
576                 }
577 #endif
578
579                 for (i = 0, j = 0; i < dlen; i++, j++) {
580                     if (!tcomp)
581                         buffer[j] = avio_r8(s->pb);
582                     if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
583                         /* Unsynchronised byte, skip it */
584                         j--;
585                     }
586                 }
587                 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
588                 tlen = j;
589                 pbx = &pb; // read from sync buffer
590             } else {
591                 pbx = s->pb; // read straight from input
592             }
593             if (tag[0] == 'T')
594                 /* parse text tag */
595                 read_ttag(s, pbx, tlen, tag);
596             else
597                 /* parse special meta tag */
598                 extra_func->read(s, pbx, tlen, tag, extra_meta);
599         }
600         else if (!tag[0]) {
601             if (tag[1])
602                 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
603             avio_skip(s->pb, tlen);
604             break;
605         }
606         /* Skip to end of tag */
607 seek:
608         avio_seek(s->pb, next, SEEK_SET);
609     }
610
611     if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
612         end += 10;
613
614   error:
615     if (reason)
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);
618     av_free(buffer);
619     av_free(compressed_buffer);
620     return;
621 }
622
623 void ff_id3v2_read_all(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
624 {
625     int len, ret;
626     uint8_t buf[ID3v2_HEADER_SIZE];
627     int     found_header;
628     int64_t off;
629
630     do {
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)
635             break;
636             found_header = ff_id3v2_match(buf, magic);
637             if (found_header) {
638             /* parse ID3v2 header */
639             len = ((buf[6] & 0x7f) << 21) |
640                   ((buf[7] & 0x7f) << 14) |
641                   ((buf[8] & 0x7f) << 7) |
642                    (buf[9] & 0x7f);
643             ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
644         } else {
645             avio_seek(s->pb, off, SEEK_SET);
646         }
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);
652 }
653
654 void ff_id3v2_read(AVFormatContext *s, const char *magic)
655 {
656     ff_id3v2_read_all(s, magic, NULL);
657 }
658
659 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
660 {
661     ID3v2ExtraMeta *current = *extra_meta, *next;
662     const ID3v2EMFunc *extra_func;
663
664     while (current) {
665         if ((extra_func = get_extra_meta_func(current->tag, 1)))
666             extra_func->free(current->data);
667         next = current->next;
668         av_freep(&current);
669         current = next;
670     }
671 }