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.

1273 lines
36KB

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