FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
id3v2.c
Go to the documentation of this file.
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 "libavutil/avstring.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/intreadwrite.h"
38 #include "avio_internal.h"
39 #include "internal.h"
40 #include "id3v1.h"
41 #include "id3v2.h"
42 
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 
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 
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 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 const char *ff_id3v2_picture_types[21] = {
103  "Other",
104  "32x32 pixels 'file icon'",
105  "Other file icon",
106  "Cover (front)",
107  "Cover (back)",
108  "Leaflet page",
109  "Media (e.g. label side of CD)",
110  "Lead artist/lead performer/soloist",
111  "Artist/performer",
112  "Conductor",
113  "Band/Orchestra",
114  "Composer",
115  "Lyricist/text writer",
116  "Recording Location",
117  "During recording",
118  "During performance",
119  "Movie/video screen capture",
120  "A bright coloured fish",
121  "Illustration",
122  "Band/artist logotype",
123  "Publisher/Studio logotype",
124 };
125 
127  { "image/gif", AV_CODEC_ID_GIF },
128  { "image/jpeg", AV_CODEC_ID_MJPEG },
129  { "image/jpg", AV_CODEC_ID_MJPEG },
130  { "image/png", AV_CODEC_ID_PNG },
131  { "image/tiff", AV_CODEC_ID_TIFF },
132  { "image/bmp", AV_CODEC_ID_BMP },
133  { "JPG", AV_CODEC_ID_MJPEG }, /* ID3v2.2 */
134  { "PNG", AV_CODEC_ID_PNG }, /* ID3v2.2 */
135  { "", AV_CODEC_ID_NONE },
136 };
137 
138 int ff_id3v2_match(const uint8_t *buf, const char *magic)
139 {
140  return buf[0] == magic[0] &&
141  buf[1] == magic[1] &&
142  buf[2] == magic[2] &&
143  buf[3] != 0xff &&
144  buf[4] != 0xff &&
145  (buf[6] & 0x80) == 0 &&
146  (buf[7] & 0x80) == 0 &&
147  (buf[8] & 0x80) == 0 &&
148  (buf[9] & 0x80) == 0;
149 }
150 
152 {
153  int len = ((buf[6] & 0x7f) << 21) +
154  ((buf[7] & 0x7f) << 14) +
155  ((buf[8] & 0x7f) << 7) +
156  (buf[9] & 0x7f) +
158  if (buf[5] & 0x10)
159  len += ID3v2_HEADER_SIZE;
160  return len;
161 }
162 
163 static unsigned int get_size(AVIOContext *s, int len)
164 {
165  int v = 0;
166  while (len--)
167  v = (v << 7) + (avio_r8(s) & 0x7F);
168  return v;
169 }
170 
171 /**
172  * Free GEOB type extra metadata.
173  */
174 static void free_geobtag(void *obj)
175 {
176  ID3v2ExtraMetaGEOB *geob = obj;
177  av_free(geob->mime_type);
178  av_free(geob->file_name);
179  av_free(geob->description);
180  av_free(geob->data);
181  av_free(geob);
182 }
183 
184 /**
185  * Decode characters to UTF-8 according to encoding type. The decoded buffer is
186  * always null terminated. Stop reading when either *maxread bytes are read from
187  * pb or U+0000 character is found.
188  *
189  * @param dst Pointer where the address of the buffer with the decoded bytes is
190  * stored. Buffer must be freed by caller.
191  * @param maxread Pointer to maximum number of characters to read from the
192  * AVIOContext. After execution the value is decremented by the number of bytes
193  * actually read.
194  * @returns 0 if no error occurred, dst is uninitialized on error
195  */
196 static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
197  uint8_t **dst, int *maxread)
198 {
199  int ret;
200  uint8_t tmp;
201  uint32_t ch = 1;
202  int left = *maxread;
203  unsigned int (*get)(AVIOContext*) = avio_rb16;
204  AVIOContext *dynbuf;
205 
206  if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
207  av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
208  return ret;
209  }
210 
211  switch (encoding) {
213  while (left && ch) {
214  ch = avio_r8(pb);
215  PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
216  left--;
217  }
218  break;
219 
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 
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,
274  AVDictionary **metadata, const char *key)
275 {
276  uint8_t *dst;
277  int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
278  unsigned genre;
279 
280  if (taglen < 1)
281  return;
282 
283  encoding = avio_r8(pb);
284  taglen--; /* account for encoding type byte */
285 
286  if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
287  av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
288  return;
289  }
290 
291  if (!(strcmp(key, "TCON") && strcmp(key, "TCO")) &&
292  (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1) &&
293  genre <= ID3v1_GENRE_MAX) {
294  av_freep(&dst);
295  dst = av_strdup(ff_id3v1_genre_str[genre]);
296  } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
297  /* dst now contains the key, need to get value */
298  key = dst;
299  if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
300  av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
301  av_freep(&key);
302  return;
303  }
304  dict_flags |= AV_DICT_DONT_STRDUP_KEY;
305  } else if (!*dst)
306  av_freep(&dst);
307 
308  if (dst)
309  av_dict_set(metadata, key, dst, dict_flags);
310 }
311 
312 /**
313  * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
314  */
315 static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen,
316  char *tag, ID3v2ExtraMeta **extra_meta, int isv34)
317 {
318  ID3v2ExtraMetaGEOB *geob_data = NULL;
319  ID3v2ExtraMeta *new_extra = NULL;
320  char encoding;
321  unsigned int len;
322 
323  if (taglen < 1)
324  return;
325 
326  geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
327  if (!geob_data) {
328  av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n",
329  sizeof(ID3v2ExtraMetaGEOB));
330  return;
331  }
332 
333  new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
334  if (!new_extra) {
335  av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n",
336  sizeof(ID3v2ExtraMeta));
337  goto fail;
338  }
339 
340  /* read encoding type byte */
341  encoding = avio_r8(pb);
342  taglen--;
343 
344  /* read MIME type (always ISO-8859) */
345  if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type,
346  &taglen) < 0 ||
347  taglen <= 0)
348  goto fail;
349 
350  /* read file name */
351  if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0 ||
352  taglen <= 0)
353  goto fail;
354 
355  /* read content description */
356  if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0 ||
357  taglen < 0)
358  goto fail;
359 
360  if (taglen) {
361  /* save encapsulated binary data */
362  geob_data->data = av_malloc(taglen);
363  if (!geob_data->data) {
364  av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
365  goto fail;
366  }
367  if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
369  "Error reading GEOB frame, data truncated.\n");
370  geob_data->datasize = len;
371  } else {
372  geob_data->data = NULL;
373  geob_data->datasize = 0;
374  }
375 
376  /* add data to the list */
377  new_extra->tag = "GEOB";
378  new_extra->data = geob_data;
379  new_extra->next = *extra_meta;
380  *extra_meta = new_extra;
381 
382  return;
383 
384 fail:
385  av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
386  free_geobtag(geob_data);
387  av_free(new_extra);
388  return;
389 }
390 
391 static int is_number(const char *str)
392 {
393  while (*str >= '0' && *str <= '9')
394  str++;
395  return !*str;
396 }
397 
399 {
401  if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
402  strlen(t->value) == 4 && is_number(t->value))
403  return t;
404  return NULL;
405 }
406 
407 static void merge_date(AVDictionary **m)
408 {
410  char date[17] = { 0 }; // YYYY-MM-DD hh:mm
411 
412  if (!(t = get_date_tag(*m, "TYER")) &&
413  !(t = get_date_tag(*m, "TYE")))
414  return;
415  av_strlcpy(date, t->value, 5);
416  av_dict_set(m, "TYER", NULL, 0);
417  av_dict_set(m, "TYE", NULL, 0);
418 
419  if (!(t = get_date_tag(*m, "TDAT")) &&
420  !(t = get_date_tag(*m, "TDA")))
421  goto finish;
422  snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
423  av_dict_set(m, "TDAT", NULL, 0);
424  av_dict_set(m, "TDA", NULL, 0);
425 
426  if (!(t = get_date_tag(*m, "TIME")) &&
427  !(t = get_date_tag(*m, "TIM")))
428  goto finish;
429  snprintf(date + 10, sizeof(date) - 10,
430  " %.2s:%.2s", t->value, t->value + 2);
431  av_dict_set(m, "TIME", NULL, 0);
432  av_dict_set(m, "TIM", NULL, 0);
433 
434 finish:
435  if (date[0])
436  av_dict_set(m, "date", date, 0);
437 }
438 
439 static void free_apic(void *obj)
440 {
441  ID3v2ExtraMetaAPIC *apic = obj;
442  av_buffer_unref(&apic->buf);
443  av_freep(&apic->description);
444  av_freep(&apic);
445 }
446 
447 static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen,
448  char *tag, ID3v2ExtraMeta **extra_meta, int isv34)
449 {
450  int enc, pic_type;
451  char mimetype[64];
452  const CodecMime *mime = ff_id3v2_mime_tags;
453  enum AVCodecID id = AV_CODEC_ID_NONE;
454  ID3v2ExtraMetaAPIC *apic = NULL;
455  ID3v2ExtraMeta *new_extra = NULL;
456  int64_t end = avio_tell(pb) + taglen;
457 
458  if (taglen <= 4)
459  goto fail;
460 
461  new_extra = av_mallocz(sizeof(*new_extra));
462  apic = av_mallocz(sizeof(*apic));
463  if (!new_extra || !apic)
464  goto fail;
465 
466  enc = avio_r8(pb);
467  taglen--;
468 
469  /* mimetype */
470  if (isv34) {
471  taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
472  } else {
473  avio_read(pb, mimetype, 3);
474  mimetype[3] = 0;
475  }
476  while (mime->id != AV_CODEC_ID_NONE) {
477  if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
478  id = mime->id;
479  break;
480  }
481  mime++;
482  }
483  if (id == AV_CODEC_ID_NONE) {
485  "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
486  goto fail;
487  }
488  apic->id = id;
489 
490  /* picture type */
491  pic_type = avio_r8(pb);
492  taglen--;
493  if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
494  av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
495  pic_type);
496  pic_type = 0;
497  }
498  apic->type = ff_id3v2_picture_types[pic_type];
499 
500  /* description and picture data */
501  if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
502  av_log(s, AV_LOG_ERROR,
503  "Error decoding attached picture description.\n");
504  goto fail;
505  }
506 
508  if (!apic->buf || !taglen || avio_read(pb, apic->buf->data, taglen) != taglen)
509  goto fail;
510  memset(apic->buf->data + taglen, 0, FF_INPUT_BUFFER_PADDING_SIZE);
511 
512  new_extra->tag = "APIC";
513  new_extra->data = apic;
514  new_extra->next = *extra_meta;
515  *extra_meta = new_extra;
516 
517  return;
518 
519 fail:
520  if (apic)
521  free_apic(apic);
522  av_freep(&new_extra);
523  avio_seek(pb, end, SEEK_SET);
524 }
525 
526 static void read_chapter(AVFormatContext *s, AVIOContext *pb, int len, char *ttag, ID3v2ExtraMeta **extra_meta, int isv34)
527 {
528  AVRational time_base = {1, 1000};
529  uint32_t start, end;
530  AVChapter *chapter;
531  uint8_t *dst = NULL;
532  int taglen;
533  char tag[5];
534 
535  if (!s) {
536  /* We should probably just put the chapter data to extra_meta here
537  * and do the AVFormatContext-needing part in a separate
538  * ff_id3v2_parse_apic()-like function. */
539  av_log(NULL, AV_LOG_DEBUG, "No AVFormatContext, skipped ID3 chapter data\n");
540  return;
541  }
542 
543  if (decode_str(s, pb, 0, &dst, &len) < 0)
544  return;
545  if (len < 16)
546  return;
547 
548  start = avio_rb32(pb);
549  end = avio_rb32(pb);
550  avio_skip(pb, 8);
551 
552  chapter = avpriv_new_chapter(s, s->nb_chapters + 1, time_base, start, end, dst);
553  if (!chapter) {
554  av_free(dst);
555  return;
556  }
557 
558  len -= 16;
559  while (len > 10) {
560  if (avio_read(pb, tag, 4) < 4)
561  goto end;
562  tag[4] = 0;
563  taglen = avio_rb32(pb);
564  avio_skip(pb, 2);
565  len -= 10;
566  if (taglen < 0 || taglen > len)
567  goto end;
568  if (tag[0] == 'T')
569  read_ttag(s, pb, taglen, &chapter->metadata, tag);
570  else
571  avio_skip(pb, taglen);
572  len -= taglen;
573  }
574 
575  ff_metadata_conv(&chapter->metadata, NULL, ff_id3v2_34_metadata_conv);
576  ff_metadata_conv(&chapter->metadata, NULL, ff_id3v2_4_metadata_conv);
577 end:
578  av_free(dst);
579 }
580 
581 static void free_priv(void *obj)
582 {
583  ID3v2ExtraMetaPRIV *priv = obj;
584  av_freep(&priv->owner);
585  av_freep(&priv->data);
586  av_freep(&priv);
587 }
588 
589 static void read_priv(AVFormatContext *s, AVIOContext *pb, int taglen,
590  char *tag, ID3v2ExtraMeta **extra_meta, int isv34)
591 {
592  ID3v2ExtraMeta *meta;
593  ID3v2ExtraMetaPRIV *priv;
594 
595  meta = av_mallocz(sizeof(*meta));
596  priv = av_mallocz(sizeof(*priv));
597 
598  if (!meta || !priv)
599  goto fail;
600 
601  if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &priv->owner, &taglen) < 0)
602  goto fail;
603 
604  priv->data = av_malloc(taglen);
605  if (!priv->data)
606  goto fail;
607 
608  priv->datasize = taglen;
609 
610  if (avio_read(pb, priv->data, priv->datasize) != priv->datasize)
611  goto fail;
612 
613  meta->tag = "PRIV";
614  meta->data = priv;
615  meta->next = *extra_meta;
616  *extra_meta = meta;
617 
618  return;
619 
620 fail:
621  if (priv)
622  free_priv(priv);
623  av_freep(&meta);
624 }
625 
626 typedef struct ID3v2EMFunc {
627  const char *tag3;
628  const char *tag4;
629  void (*read)(AVFormatContext *, AVIOContext *, int, char *,
630  ID3v2ExtraMeta **, int isv34);
631  void (*free)(void *obj);
632 } ID3v2EMFunc;
633 
635  { "GEO", "GEOB", read_geobtag, free_geobtag },
636  { "PIC", "APIC", read_apic, free_apic },
637  { "CHAP","CHAP", read_chapter, NULL },
638  { "PRIV","PRIV", read_priv, free_priv },
639  { NULL }
640 };
641 
642 /**
643  * Get the corresponding ID3v2EMFunc struct for a tag.
644  * @param isv34 Determines if v2.2 or v2.3/4 strings are used
645  * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
646  */
647 static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
648 {
649  int i = 0;
650  while (id3v2_extra_meta_funcs[i].tag3) {
651  if (tag && !memcmp(tag,
652  (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
653  id3v2_extra_meta_funcs[i].tag3),
654  (isv34 ? 4 : 3)))
655  return &id3v2_extra_meta_funcs[i];
656  i++;
657  }
658  return NULL;
659 }
660 
661 static void id3v2_parse(AVIOContext *pb, AVDictionary **metadata,
663  uint8_t flags, ID3v2ExtraMeta **extra_meta)
664 {
665  int isv34, unsync;
666  unsigned tlen;
667  char tag[5];
668  int64_t next, end = avio_tell(pb) + len;
669  int taghdrlen;
670  const char *reason = NULL;
671  AVIOContext pb_local;
672  AVIOContext *pbx;
673  unsigned char *buffer = NULL;
674  int buffer_size = 0;
675  const ID3v2EMFunc *extra_func = NULL;
676  unsigned char *uncompressed_buffer = NULL;
677  int uncompressed_buffer_size = 0;
678 
679  av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
680 
681  switch (version) {
682  case 2:
683  if (flags & 0x40) {
684  reason = "compression";
685  goto error;
686  }
687  isv34 = 0;
688  taghdrlen = 6;
689  break;
690 
691  case 3:
692  case 4:
693  isv34 = 1;
694  taghdrlen = 10;
695  break;
696 
697  default:
698  reason = "version";
699  goto error;
700  }
701 
702  unsync = flags & 0x80;
703 
704  if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
705  int extlen = get_size(pb, 4);
706  if (version == 4)
707  /* In v2.4 the length includes the length field we just read. */
708  extlen -= 4;
709 
710  if (extlen < 0) {
711  reason = "invalid extended header length";
712  goto error;
713  }
714  avio_skip(pb, extlen);
715  len -= extlen + 4;
716  if (len < 0) {
717  reason = "extended header too long.";
718  goto error;
719  }
720  }
721 
722  while (len >= taghdrlen) {
723  unsigned int tflags = 0;
724  int tunsync = 0;
725  int tcomp = 0;
726  int tencr = 0;
727  unsigned long dlen;
728 
729  if (isv34) {
730  if (avio_read(pb, tag, 4) < 4)
731  break;
732  tag[4] = 0;
733  if (version == 3) {
734  tlen = avio_rb32(pb);
735  } else
736  tlen = get_size(pb, 4);
737  tflags = avio_rb16(pb);
738  tunsync = tflags & ID3v2_FLAG_UNSYNCH;
739  } else {
740  if (avio_read(pb, tag, 3) < 3)
741  break;
742  tag[3] = 0;
743  tlen = avio_rb24(pb);
744  }
745  if (tlen > (1<<28))
746  break;
747  len -= taghdrlen + tlen;
748 
749  if (len < 0)
750  break;
751 
752  next = avio_tell(pb) + tlen;
753 
754  if (!tlen) {
755  if (tag[0])
756  av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
757  tag);
758  continue;
759  }
760 
761  if (tflags & ID3v2_FLAG_DATALEN) {
762  if (tlen < 4)
763  break;
764  dlen = avio_rb32(pb);
765  tlen -= 4;
766  } else
767  dlen = tlen;
768 
769  tcomp = tflags & ID3v2_FLAG_COMPRESSION;
770  tencr = tflags & ID3v2_FLAG_ENCRYPTION;
771 
772  /* skip encrypted tags and, if no zlib, compressed tags */
773  if (tencr || (!CONFIG_ZLIB && tcomp)) {
774  const char *type;
775  if (!tcomp)
776  type = "encrypted";
777  else if (!tencr)
778  type = "compressed";
779  else
780  type = "encrypted and compressed";
781 
782  av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
783  avio_skip(pb, tlen);
784  /* check for text tag or supported special meta tag */
785  } else if (tag[0] == 'T' ||
786  (extra_meta &&
787  (extra_func = get_extra_meta_func(tag, isv34)))) {
788  pbx = pb;
789 
790  if (unsync || tunsync || tcomp) {
791  av_fast_malloc(&buffer, &buffer_size, tlen);
792  if (!buffer) {
793  av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
794  goto seek;
795  }
796  }
797  if (unsync || tunsync) {
798  int64_t end = avio_tell(pb) + tlen;
799  uint8_t *b;
800 
801  b = buffer;
802  while (avio_tell(pb) < end && b - buffer < tlen && !pb->eof_reached) {
803  *b++ = avio_r8(pb);
804  if (*(b - 1) == 0xff && avio_tell(pb) < end - 1 &&
805  b - buffer < tlen &&
806  !pb->eof_reached ) {
807  uint8_t val = avio_r8(pb);
808  *b++ = val ? val : avio_r8(pb);
809  }
810  }
811  ffio_init_context(&pb_local, buffer, b - buffer, 0, NULL, NULL, NULL,
812  NULL);
813  tlen = b - buffer;
814  pbx = &pb_local; // read from sync buffer
815  }
816 
817 #if CONFIG_ZLIB
818  if (tcomp) {
819  int err;
820 
821  av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
822 
823  av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
824  if (!uncompressed_buffer) {
825  av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
826  goto seek;
827  }
828 
829  if (!(unsync || tunsync)) {
830  err = avio_read(pb, buffer, tlen);
831  if (err < 0) {
832  av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
833  goto seek;
834  }
835  tlen = err;
836  }
837 
838  err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
839  if (err != Z_OK) {
840  av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
841  goto seek;
842  }
843  ffio_init_context(&pb_local, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);
844  tlen = dlen;
845  pbx = &pb_local; // read from sync buffer
846  }
847 #endif
848  if (tag[0] == 'T')
849  /* parse text tag */
850  read_ttag(s, pbx, tlen, metadata, tag);
851  else
852  /* parse special meta tag */
853  extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);
854  } else if (!tag[0]) {
855  if (tag[1])
856  av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
857  avio_skip(pb, tlen);
858  break;
859  }
860  /* Skip to end of tag */
861 seek:
862  avio_seek(pb, next, SEEK_SET);
863  }
864 
865  /* Footer preset, always 10 bytes, skip over it */
866  if (version == 4 && flags & 0x10)
867  end += 10;
868 
869 error:
870  if (reason)
871  av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
872  version, reason);
873  avio_seek(pb, end, SEEK_SET);
874  av_free(buffer);
875  av_free(uncompressed_buffer);
876  return;
877 }
878 
879 static void id3v2_read_internal(AVIOContext *pb, AVDictionary **metadata,
880  AVFormatContext *s, const char *magic,
881  ID3v2ExtraMeta **extra_meta)
882 {
883  int len, ret;
885  int found_header;
886  int64_t off;
887 
888  do {
889  /* save the current offset in case there's nothing to read/skip */
890  off = avio_tell(pb);
891  ret = avio_read(pb, buf, ID3v2_HEADER_SIZE);
892  if (ret != ID3v2_HEADER_SIZE) {
893  avio_seek(pb, off, SEEK_SET);
894  break;
895  }
896  found_header = ff_id3v2_match(buf, magic);
897  if (found_header) {
898  /* parse ID3v2 header */
899  len = ((buf[6] & 0x7f) << 21) |
900  ((buf[7] & 0x7f) << 14) |
901  ((buf[8] & 0x7f) << 7) |
902  (buf[9] & 0x7f);
903  id3v2_parse(pb, metadata, s, len, buf[3], buf[5], extra_meta);
904  } else {
905  avio_seek(pb, off, SEEK_SET);
906  }
907  } while (found_header);
908  ff_metadata_conv(metadata, NULL, ff_id3v2_34_metadata_conv);
909  ff_metadata_conv(metadata, NULL, id3v2_2_metadata_conv);
910  ff_metadata_conv(metadata, NULL, ff_id3v2_4_metadata_conv);
911  merge_date(metadata);
912 }
913 
915  const char *magic, ID3v2ExtraMeta **extra_meta)
916 {
917  id3v2_read_internal(pb, metadata, NULL, magic, extra_meta);
918 }
919 
920 void ff_id3v2_read(AVFormatContext *s, const char *magic,
921  ID3v2ExtraMeta **extra_meta)
922 {
923  id3v2_read_internal(s->pb, &s->metadata, s, magic, extra_meta);
924 }
925 
927 {
928  ID3v2ExtraMeta *current = *extra_meta, *next;
929  const ID3v2EMFunc *extra_func;
930 
931  while (current) {
932  if ((extra_func = get_extra_meta_func(current->tag, 1)))
933  extra_func->free(current->data);
934  next = current->next;
935  av_freep(&current);
936  current = next;
937  }
938 }
939 
941 {
942  ID3v2ExtraMeta *cur;
943 
944  for (cur = *extra_meta; cur; cur = cur->next) {
945  ID3v2ExtraMetaAPIC *apic;
946  AVStream *st;
947 
948  if (strcmp(cur->tag, "APIC"))
949  continue;
950  apic = cur->data;
951 
952  if (!(st = avformat_new_stream(s, NULL)))
953  return AVERROR(ENOMEM);
954 
957  st->codec->codec_id = apic->id;
958  av_dict_set(&st->metadata, "title", apic->description, 0);
959  av_dict_set(&st->metadata, "comment", apic->type, 0);
960 
962  st->attached_pic.buf = apic->buf;
963  st->attached_pic.data = apic->buf->data;
965  st->attached_pic.stream_index = st->index;
967 
968  apic->buf = NULL;
969  }
970 
971  return 0;
972 }