You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1046 lines
30KB

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