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