]> 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 "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 #include "internal.h"
42
43 const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
44     { "TALB", "album"},
45     { "TCOM", "composer"},
46     { "TCON", "genre"},
47     { "TCOP", "copyright"},
48     { "TENC", "encoded_by"},
49     { "TIT2", "title"},
50     { "TLAN", "language"},
51     { "TPE1", "artist"},
52     { "TPE2", "album_artist"},
53     { "TPE3", "performer"},
54     { "TPOS", "disc"},
55     { "TPUB", "publisher"},
56     { "TRCK", "track"},
57     { "TSSE", "encoder"},
58     { 0 }
59 };
60
61 const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
62     { "TDRL", "date"},
63     { "TDRC", "date"},
64     { "TDEN", "creation_time"},
65     { "TSOA", "album-sort"},
66     { "TSOP", "artist-sort"},
67     { "TSOT", "title-sort"},
68     { 0 }
69 };
70
71 static const AVMetadataConv id3v2_2_metadata_conv[] = {
72     { "TAL",  "album"},
73     { "TCO",  "genre"},
74     { "TT2",  "title"},
75     { "TEN",  "encoded_by"},
76     { "TP1",  "artist"},
77     { "TP2",  "album_artist"},
78     { "TP3",  "performer"},
79     { "TRK",  "track"},
80     { 0 }
81 };
82
83
84 const char ff_id3v2_tags[][4] = {
85    "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
86    "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
87    "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
88    "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
89    { 0 },
90 };
91
92 const char ff_id3v2_4_tags[][4] = {
93    "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
94    "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
95    { 0 },
96 };
97
98 const char ff_id3v2_3_tags[][4] = {
99    "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
100    { 0 },
101 };
102
103 const char *ff_id3v2_picture_types[21] = {
104     "Other",
105     "32x32 pixels 'file icon'",
106     "Other file icon",
107     "Cover (front)",
108     "Cover (back)",
109     "Leaflet page",
110     "Media (e.g. label side of CD)",
111     "Lead artist/lead performer/soloist",
112     "Artist/performer",
113     "Conductor",
114     "Band/Orchestra",
115     "Composer",
116     "Lyricist/text writer",
117     "Recording Location",
118     "During recording",
119     "During performance",
120     "Movie/video screen capture",
121     "A bright coloured fish",
122     "Illustration",
123     "Band/artist logotype",
124     "Publisher/Studio logotype",
125 };
126
127 const CodecMime ff_id3v2_mime_tags[] = {
128     {"image/gif" , CODEC_ID_GIF},
129     {"image/jpeg", CODEC_ID_MJPEG},
130     {"image/jpg",  CODEC_ID_MJPEG},
131     {"image/png" , CODEC_ID_PNG},
132     {"image/tiff", CODEC_ID_TIFF},
133     {"",           CODEC_ID_NONE},
134 };
135
136 int ff_id3v2_match(const uint8_t *buf, const char * magic)
137 {
138     return  buf[0]         == magic[0] &&
139             buf[1]         == magic[1] &&
140             buf[2]         == magic[2] &&
141             buf[3]         != 0xff &&
142             buf[4]         != 0xff &&
143            (buf[6] & 0x80) ==    0 &&
144            (buf[7] & 0x80) ==    0 &&
145            (buf[8] & 0x80) ==    0 &&
146            (buf[9] & 0x80) ==    0;
147 }
148
149 int ff_id3v2_tag_len(const uint8_t * buf)
150 {
151     int len = ((buf[6] & 0x7f) << 21) +
152               ((buf[7] & 0x7f) << 14) +
153               ((buf[8] & 0x7f) << 7) +
154                (buf[9] & 0x7f) +
155               ID3v2_HEADER_SIZE;
156     if (buf[5] & 0x10)
157         len += ID3v2_HEADER_SIZE;
158     return len;
159 }
160
161 static unsigned int get_size(AVIOContext *s, int len)
162 {
163     int v = 0;
164     while (len--)
165         v = (v << 7) + (avio_r8(s) & 0x7F);
166     return v;
167 }
168
169 /**
170  * Free GEOB type extra metadata.
171  */
172 static void free_geobtag(void *obj)
173 {
174     ID3v2ExtraMetaGEOB *geob = obj;
175     av_free(geob->mime_type);
176     av_free(geob->file_name);
177     av_free(geob->description);
178     av_free(geob->data);
179     av_free(geob);
180 }
181
182 /**
183  * Decode characters to UTF-8 according to encoding type. The decoded buffer is
184  * always null terminated. Stop reading when either *maxread bytes are read from
185  * pb or U+0000 character is found.
186  *
187  * @param dst Pointer where the address of the buffer with the decoded bytes is
188  * stored. Buffer must be freed by caller.
189  * @param maxread Pointer to maximum number of characters to read from the
190  * AVIOContext. After execution the value is decremented by the number of bytes
191  * actually read.
192  * @returns 0 if no error occurred, dst is uninitialized on error
193  */
194 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
195                       uint8_t **dst, int *maxread)
196 {
197     int ret;
198     uint8_t tmp;
199     uint32_t ch = 1;
200     int left = *maxread;
201     unsigned int (*get)(AVIOContext*) = avio_rb16;
202     AVIOContext *dynbuf;
203
204     if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
205         av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
206         return ret;
207     }
208
209     switch (encoding) {
210
211     case ID3v2_ENCODING_ISO8859:
212         while (left && ch) {
213             ch = avio_r8(pb);
214             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
215             left--;
216         }
217         break;
218
219     case ID3v2_ENCODING_UTF16BOM:
220         if ((left -= 2) < 0) {
221             av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
222             avio_close_dyn_buf(dynbuf, dst);
223             av_freep(dst);
224             return AVERROR_INVALIDDATA;
225         }
226         switch (avio_rb16(pb)) {
227         case 0xfffe:
228             get = avio_rl16;
229         case 0xfeff:
230             break;
231         default:
232             av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
233             avio_close_dyn_buf(dynbuf, dst);
234             av_freep(dst);
235             *maxread = left;
236             return AVERROR_INVALIDDATA;
237         }
238         // fall-through
239
240     case ID3v2_ENCODING_UTF16BE:
241         while ((left > 1) && ch) {
242             GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
243             PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
244         }
245         if (left < 0)
246             left += 2; /* did not read last char from pb */
247         break;
248
249     case ID3v2_ENCODING_UTF8:
250         while (left && ch) {
251             ch = avio_r8(pb);
252             avio_w8(dynbuf, ch);
253             left--;
254         }
255         break;
256     default:
257         av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
258     }
259
260     if (ch)
261         avio_w8(dynbuf, 0);
262
263     avio_close_dyn_buf(dynbuf, dst);
264     *maxread = left;
265
266     return 0;
267 }
268
269 /**
270  * Parse a text tag.
271  */
272 static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
273 {
274     uint8_t *dst;
275     int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
276     unsigned genre;
277
278     if (taglen < 1)
279         return;
280
281     encoding = avio_r8(pb);
282     taglen--; /* account for encoding type byte */
283
284     if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
285         av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
286         return;
287     }
288
289     if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
290         && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
291         && genre <= ID3v1_GENRE_MAX) {
292         av_freep(&dst);
293         dst = av_strdup(ff_id3v1_genre_str[genre]);
294     } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
295         /* dst now contains the key, need to get value */
296         key = dst;
297         if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
298             av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
299             av_freep(&key);
300             return;
301         }
302         dict_flags |= AV_DICT_DONT_STRDUP_KEY;
303     } else if (!*dst)
304         av_freep(&dst);
305
306     if (dst)
307         av_dict_set(&s->metadata, key, dst, dict_flags);
308 }
309
310 /**
311  * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
312  */
313 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
314 {
315     ID3v2ExtraMetaGEOB *geob_data = NULL;
316     ID3v2ExtraMeta *new_extra = NULL;
317     char encoding;
318     unsigned int len;
319
320     if (taglen < 1)
321         return;
322
323     geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
324     if (!geob_data) {
325         av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
326         return;
327     }
328
329     new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
330     if (!new_extra) {
331         av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
332         goto fail;
333     }
334
335     /* read encoding type byte */
336     encoding = avio_r8(pb);
337     taglen--;
338
339     /* read MIME type (always ISO-8859) */
340     if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
341         || taglen <= 0)
342         goto fail;
343
344     /* read file name */
345     if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
346         || taglen <= 0)
347         goto fail;
348
349     /* read content description */
350     if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
351         || taglen < 0)
352         goto fail;
353
354     if (taglen) {
355         /* save encapsulated binary data */
356         geob_data->data = av_malloc(taglen);
357         if (!geob_data->data) {
358             av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
359             goto fail;
360         }
361         if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
362             av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
363         geob_data->datasize = len;
364     } else {
365         geob_data->data = NULL;
366         geob_data->datasize = 0;
367     }
368
369     /* add data to the list */
370     new_extra->tag = "GEOB";
371     new_extra->data = geob_data;
372     new_extra->next = *extra_meta;
373     *extra_meta = new_extra;
374
375     return;
376
377 fail:
378     av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
379     free_geobtag(geob_data);
380     av_free(new_extra);
381     return;
382 }
383
384 static int is_number(const char *str)
385 {
386     while (*str >= '0' && *str <= '9') str++;
387     return !*str;
388 }
389
390 static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
391 {
392     AVDictionaryEntry *t;
393     if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
394         strlen(t->value) == 4 && is_number(t->value))
395         return t;
396     return NULL;
397 }
398
399 static void merge_date(AVDictionary **m)
400 {
401     AVDictionaryEntry *t;
402     char date[17] = {0};      // YYYY-MM-DD hh:mm
403
404     if (!(t = get_date_tag(*m, "TYER")) &&
405         !(t = get_date_tag(*m, "TYE")))
406         return;
407     av_strlcpy(date, t->value, 5);
408     av_dict_set(m, "TYER", NULL, 0);
409     av_dict_set(m, "TYE",  NULL, 0);
410
411     if (!(t = get_date_tag(*m, "TDAT")) &&
412         !(t = get_date_tag(*m, "TDA")))
413         goto finish;
414     snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
415     av_dict_set(m, "TDAT", NULL, 0);
416     av_dict_set(m, "TDA",  NULL, 0);
417
418     if (!(t = get_date_tag(*m, "TIME")) &&
419         !(t = get_date_tag(*m, "TIM")))
420         goto finish;
421     snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
422     av_dict_set(m, "TIME", NULL, 0);
423     av_dict_set(m, "TIM",  NULL, 0);
424
425 finish:
426     if (date[0])
427         av_dict_set(m, "date", date, 0);
428 }
429
430 static void free_apic(void *obj)
431 {
432     ID3v2ExtraMetaAPIC *apic = obj;
433     av_freep(&apic->data);
434     av_freep(&apic->description);
435     av_freep(&apic);
436 }
437
438 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
439 {
440     int enc, pic_type;
441     char             mimetype[64];
442     const CodecMime     *mime = ff_id3v2_mime_tags;
443     enum CodecID           id = CODEC_ID_NONE;
444     ID3v2ExtraMetaAPIC  *apic = NULL;
445     ID3v2ExtraMeta *new_extra = NULL;
446     int64_t               end = avio_tell(pb) + taglen;
447
448     if (taglen <= 4)
449         goto fail;
450
451     new_extra = av_mallocz(sizeof(*new_extra));
452     apic      = av_mallocz(sizeof(*apic));
453     if (!new_extra || !apic)
454         goto fail;
455
456     enc = avio_r8(pb);
457     taglen--;
458
459     /* mimetype */
460     taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
461     while (mime->id != CODEC_ID_NONE) {
462         if (!strncmp(mime->str, mimetype, sizeof(mimetype))) {
463             id = mime->id;
464             break;
465         }
466         mime++;
467     }
468     if (id == CODEC_ID_NONE) {
469         av_log(s, AV_LOG_WARNING, "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
470         goto fail;
471     }
472     apic->id = id;
473
474     /* picture type */
475     pic_type = avio_r8(pb);
476     taglen--;
477     if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
478         av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n", pic_type);
479         pic_type = 0;
480     }
481     apic->type = ff_id3v2_picture_types[pic_type];
482
483     /* description and picture data */
484     if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
485         av_log(s, AV_LOG_ERROR, "Error decoding attached picture description.\n");
486         goto fail;
487     }
488
489     apic->len   = taglen;
490     apic->data  = av_malloc(taglen);
491     if (!apic->data || !apic->len || avio_read(pb, apic->data, taglen) != taglen)
492         goto fail;
493
494     new_extra->tag    = "APIC";
495     new_extra->data   = apic;
496     new_extra->next   = *extra_meta;
497     *extra_meta       = new_extra;
498
499     return;
500
501 fail:
502     if (apic)
503         free_apic(apic);
504     av_freep(&new_extra);
505     avio_seek(pb, end, SEEK_SET);
506 }
507
508 typedef struct ID3v2EMFunc {
509     const char *tag3;
510     const char *tag4;
511     void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
512     void (*free)(void *obj);
513 } ID3v2EMFunc;
514
515 static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
516     { "GEO", "GEOB", read_geobtag, free_geobtag },
517     { "PIC", "APIC", read_apic,    free_apic },
518     { NULL }
519 };
520
521 /**
522  * Get the corresponding ID3v2EMFunc struct for a tag.
523  * @param isv34 Determines if v2.2 or v2.3/4 strings are used
524  * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
525  */
526 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
527 {
528     int i = 0;
529     while (id3v2_extra_meta_funcs[i].tag3) {
530         if (tag && !memcmp(tag,
531                     (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
532                              id3v2_extra_meta_funcs[i].tag3),
533                     (isv34 ? 4 : 3)))
534             return &id3v2_extra_meta_funcs[i];
535         i++;
536     }
537     return NULL;
538 }
539
540 static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
541 {
542     int isv34, unsync;
543     unsigned tlen;
544     char tag[5];
545     int64_t next, end = avio_tell(s->pb) + len;
546     int taghdrlen;
547     const char *reason = NULL;
548     AVIOContext pb;
549     AVIOContext *pbx;
550     unsigned char *buffer = NULL;
551     int buffer_size = 0;
552     const ID3v2EMFunc *extra_func = NULL;
553     unsigned char *compressed_buffer = NULL;
554     int compressed_buffer_size = 0;
555
556     switch (version) {
557     case 2:
558         if (flags & 0x40) {
559             reason = "compression";
560             goto error;
561         }
562         isv34 = 0;
563         taghdrlen = 6;
564         break;
565
566     case 3:
567     case 4:
568         isv34 = 1;
569         taghdrlen = 10;
570         break;
571
572     default:
573         reason = "version";
574         goto error;
575     }
576
577     unsync = flags & 0x80;
578
579     if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
580         int extlen = get_size(s->pb, 4);
581         if (version == 4)
582             extlen -= 4;     // in v2.4 the length includes the length field we just read
583
584         if (extlen < 0) {
585             reason = "invalid extended header length";
586             goto error;
587         }
588         avio_skip(s->pb, extlen);
589         len -= extlen + 4;
590         if (len < 0) {
591             reason = "extended header too long.";
592             goto error;
593         }
594     }
595
596     while (len >= taghdrlen) {
597         unsigned int tflags = 0;
598         int tunsync = 0;
599         int tcomp = 0;
600         int tencr = 0;
601         unsigned long dlen;
602
603         if (isv34) {
604             avio_read(s->pb, tag, 4);
605             tag[4] = 0;
606             if(version==3){
607                 tlen = avio_rb32(s->pb);
608             }else
609                 tlen = get_size(s->pb, 4);
610             tflags = avio_rb16(s->pb);
611             tunsync = tflags & ID3v2_FLAG_UNSYNCH;
612         } else {
613             avio_read(s->pb, tag, 3);
614             tag[3] = 0;
615             tlen = avio_rb24(s->pb);
616         }
617         if (tlen > (1<<28))
618             break;
619         len -= taghdrlen + tlen;
620
621         if (len < 0)
622             break;
623
624         next = avio_tell(s->pb) + tlen;
625
626         if (!tlen) {
627             if (tag[0])
628                 av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
629             continue;
630         }
631
632         if (tflags & ID3v2_FLAG_DATALEN) {
633             if (tlen < 4)
634                 break;
635             dlen = avio_rb32(s->pb);
636             tlen -= 4;
637         } else
638             dlen = tlen;
639
640         tcomp = tflags & ID3v2_FLAG_COMPRESSION;
641         tencr = tflags & ID3v2_FLAG_ENCRYPTION;
642
643         /* skip encrypted tags and, if no zlib, compressed tags */
644         if (tencr || (!CONFIG_ZLIB && tcomp)) {
645             const char *type;
646             if (!tcomp)
647                 type = "encrypted";
648             else if (!tencr)
649                 type = "compressed";
650             else
651                 type = "encrypted and compressed";
652
653             av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
654             avio_skip(s->pb, tlen);
655         /* check for text tag or supported special meta tag */
656         } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
657             if (unsync || tunsync || tcomp) {
658                 int i, j;
659
660                 av_fast_malloc(&buffer, &buffer_size, dlen);
661                 if (!buffer) {
662                     av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
663                     goto seek;
664                 }
665 #if CONFIG_ZLIB
666                 if (tcomp) {
667                     int n, err;
668
669                     av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
670
671                     av_fast_malloc(&compressed_buffer, &compressed_buffer_size, tlen);
672                     if (!compressed_buffer) {
673                         av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
674                         goto seek;
675                     }
676
677                     n = avio_read(s->pb, compressed_buffer, tlen);
678                     if (n < 0) {
679                         av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
680                         goto seek;
681                     }
682
683                     err = uncompress(buffer, &dlen, compressed_buffer, n);
684                     if (err != Z_OK) {
685                         av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
686                         goto seek;
687                     }
688                 }
689 #endif
690
691                 for (i = 0, j = 0; i < dlen; i++, j++) {
692                     if (!tcomp)
693                         buffer[j] = avio_r8(s->pb);
694                     if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
695                         /* Unsynchronised byte, skip it */
696                         j--;
697                     }
698                 }
699                 ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
700                 tlen = j;
701                 pbx = &pb; // read from sync buffer
702             } else {
703                 pbx = s->pb; // read straight from input
704             }
705             if (tag[0] == 'T')
706                 /* parse text tag */
707                 read_ttag(s, pbx, tlen, tag);
708             else
709                 /* parse special meta tag */
710                 extra_func->read(s, pbx, tlen, tag, extra_meta);
711         }
712         else if (!tag[0]) {
713             if (tag[1])
714                 av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
715             avio_skip(s->pb, tlen);
716             break;
717         }
718         /* Skip to end of tag */
719 seek:
720         avio_seek(s->pb, next, SEEK_SET);
721     }
722
723     if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
724         end += 10;
725
726   error:
727     if (reason)
728         av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
729     avio_seek(s->pb, end, SEEK_SET);
730     av_free(buffer);
731     av_free(compressed_buffer);
732     return;
733 }
734
735 void ff_id3v2_read(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
736 {
737     int len, ret;
738     uint8_t buf[ID3v2_HEADER_SIZE];
739     int     found_header;
740     int64_t off;
741
742     do {
743         /* save the current offset in case there's nothing to read/skip */
744         off = avio_tell(s->pb);
745         ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
746         if (ret != ID3v2_HEADER_SIZE)
747             break;
748             found_header = ff_id3v2_match(buf, magic);
749             if (found_header) {
750             /* parse ID3v2 header */
751             len = ((buf[6] & 0x7f) << 21) |
752                   ((buf[7] & 0x7f) << 14) |
753                   ((buf[8] & 0x7f) << 7) |
754                    (buf[9] & 0x7f);
755             ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
756         } else {
757             avio_seek(s->pb, off, SEEK_SET);
758         }
759     } while (found_header);
760     ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
761     ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
762     ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
763     merge_date(&s->metadata);
764 }
765
766 void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
767 {
768     ID3v2ExtraMeta *current = *extra_meta, *next;
769     const ID3v2EMFunc *extra_func;
770
771     while (current) {
772         if ((extra_func = get_extra_meta_func(current->tag, 1)))
773             extra_func->free(current->data);
774         next = current->next;
775         av_freep(&current);
776         current = next;
777     }
778 }
779
780 int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
781 {
782     ID3v2ExtraMeta *cur;
783
784     for (cur = *extra_meta; cur; cur = cur->next) {
785         ID3v2ExtraMetaAPIC *apic;
786         AVStream *st;
787
788         if (strcmp(cur->tag, "APIC"))
789             continue;
790         apic = cur->data;
791
792         if (!(st = avformat_new_stream(s, NULL)))
793             return AVERROR(ENOMEM);
794
795         st->disposition      |= AV_DISPOSITION_ATTACHED_PIC;
796         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
797         st->codec->codec_id   = apic->id;
798         av_dict_set(&st->metadata, "title",   apic->description, 0);
799         av_dict_set(&st->metadata, "comment", apic->type, 0);
800
801         av_init_packet(&st->attached_pic);
802         st->attached_pic.data         = apic->data;
803         st->attached_pic.size         = apic->len;
804         st->attached_pic.destruct     = av_destruct_packet;
805         st->attached_pic.stream_index = st->index;
806         st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
807
808         apic->data = NULL;
809         apic->len  = 0;
810     }
811
812     return 0;
813 }