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.

1270 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. taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
  527. } else {
  528. if (avio_read(pb, mimetype, 3) < 0)
  529. goto fail;
  530. mimetype[3] = 0;
  531. taglen -= 3;
  532. }
  533. while (mime->id != AV_CODEC_ID_NONE) {
  534. if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
  535. id = mime->id;
  536. break;
  537. }
  538. mime++;
  539. }
  540. if (id == AV_CODEC_ID_NONE) {
  541. av_log(s, AV_LOG_WARNING,
  542. "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
  543. goto fail;
  544. }
  545. apic->id = id;
  546. /* picture type */
  547. pic_type = avio_r8(pb);
  548. taglen--;
  549. if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
  550. av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
  551. pic_type);
  552. pic_type = 0;
  553. }
  554. apic->type = ff_id3v2_picture_types[pic_type];
  555. /* description and picture data */
  556. if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
  557. av_log(s, AV_LOG_ERROR,
  558. "Error decoding attached picture description.\n");
  559. goto fail;
  560. }
  561. apic->buf = av_buffer_alloc(taglen + AV_INPUT_BUFFER_PADDING_SIZE);
  562. if (!apic->buf || !taglen || avio_read(pb, apic->buf->data, taglen) != taglen)
  563. goto fail;
  564. memset(apic->buf->data + taglen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  565. new_extra->tag = "APIC";
  566. new_extra->next = *extra_meta;
  567. *extra_meta = new_extra;
  568. // The description must be unique, and some ID3v2 tag writers add spaces
  569. // to write several APIC entries with the same description.
  570. rstrip_spaces(apic->description);
  571. return;
  572. fail:
  573. if (apic)
  574. free_apic(apic);
  575. av_freep(&new_extra);
  576. avio_seek(pb, end, SEEK_SET);
  577. }
  578. static void free_chapter(void *obj)
  579. {
  580. ID3v2ExtraMetaCHAP *chap = obj;
  581. av_freep(&chap->element_id);
  582. av_dict_free(&chap->meta);
  583. }
  584. static void read_chapter(AVFormatContext *s, AVIOContext *pb, int len, const char *ttag, ID3v2ExtraMeta **extra_meta, int isv34)
  585. {
  586. int taglen;
  587. char tag[5];
  588. ID3v2ExtraMeta *new_extra = NULL;
  589. ID3v2ExtraMetaCHAP *chap = NULL;
  590. new_extra = av_mallocz(sizeof(*new_extra));
  591. if (!new_extra)
  592. return;
  593. chap = &new_extra->data.chap;
  594. if (decode_str(s, pb, 0, &chap->element_id, &len) < 0)
  595. goto fail;
  596. if (len < 16)
  597. goto fail;
  598. chap->start = avio_rb32(pb);
  599. chap->end = avio_rb32(pb);
  600. avio_skip(pb, 8);
  601. len -= 16;
  602. while (len > 10) {
  603. if (avio_read(pb, tag, 4) < 4)
  604. goto fail;
  605. tag[4] = 0;
  606. taglen = avio_rb32(pb);
  607. avio_skip(pb, 2);
  608. len -= 10;
  609. if (taglen < 0 || taglen > len)
  610. goto fail;
  611. if (tag[0] == 'T')
  612. read_ttag(s, pb, taglen, &chap->meta, tag);
  613. else
  614. avio_skip(pb, taglen);
  615. len -= taglen;
  616. }
  617. ff_metadata_conv(&chap->meta, NULL, ff_id3v2_34_metadata_conv);
  618. ff_metadata_conv(&chap->meta, NULL, ff_id3v2_4_metadata_conv);
  619. new_extra->tag = "CHAP";
  620. new_extra->next = *extra_meta;
  621. *extra_meta = new_extra;
  622. return;
  623. fail:
  624. free_chapter(chap);
  625. av_freep(&new_extra);
  626. }
  627. static void free_priv(void *obj)
  628. {
  629. ID3v2ExtraMetaPRIV *priv = obj;
  630. av_freep(&priv->owner);
  631. av_freep(&priv->data);
  632. }
  633. static void read_priv(AVFormatContext *s, AVIOContext *pb, int taglen,
  634. const char *tag, ID3v2ExtraMeta **extra_meta, int isv34)
  635. {
  636. ID3v2ExtraMeta *meta;
  637. ID3v2ExtraMetaPRIV *priv;
  638. meta = av_mallocz(sizeof(*meta));
  639. if (!meta)
  640. return;
  641. priv = &meta->data.priv;
  642. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &priv->owner, &taglen) < 0)
  643. goto fail;
  644. priv->data = av_malloc(taglen);
  645. if (!priv->data)
  646. goto fail;
  647. priv->datasize = taglen;
  648. if (avio_read(pb, priv->data, priv->datasize) != priv->datasize)
  649. goto fail;
  650. meta->tag = "PRIV";
  651. meta->next = *extra_meta;
  652. *extra_meta = meta;
  653. return;
  654. fail:
  655. free_priv(priv);
  656. av_freep(&meta);
  657. }
  658. typedef struct ID3v2EMFunc {
  659. const char *tag3;
  660. const char *tag4;
  661. void (*read)(AVFormatContext *s, AVIOContext *pb, int taglen,
  662. const char *tag, ID3v2ExtraMeta **extra_meta,
  663. int isv34);
  664. void (*free)(void *obj);
  665. } ID3v2EMFunc;
  666. static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
  667. { "GEO", "GEOB", read_geobtag, free_geobtag },
  668. { "PIC", "APIC", read_apic, free_apic },
  669. { "CHAP","CHAP", read_chapter, free_chapter },
  670. { "PRIV","PRIV", read_priv, free_priv },
  671. { NULL }
  672. };
  673. /**
  674. * Get the corresponding ID3v2EMFunc struct for a tag.
  675. * @param isv34 Determines if v2.2 or v2.3/4 strings are used
  676. * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
  677. */
  678. static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
  679. {
  680. int i = 0;
  681. while (id3v2_extra_meta_funcs[i].tag3) {
  682. if (tag && !memcmp(tag,
  683. (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
  684. id3v2_extra_meta_funcs[i].tag3),
  685. (isv34 ? 4 : 3)))
  686. return &id3v2_extra_meta_funcs[i];
  687. i++;
  688. }
  689. return NULL;
  690. }
  691. static void id3v2_parse(AVIOContext *pb, AVDictionary **metadata,
  692. AVFormatContext *s, int len, uint8_t version,
  693. uint8_t flags, ID3v2ExtraMeta **extra_meta)
  694. {
  695. int isv34, unsync;
  696. unsigned tlen;
  697. char tag[5];
  698. int64_t next, end = avio_tell(pb) + len;
  699. int taghdrlen;
  700. const char *reason = NULL;
  701. AVIOContext pb_local;
  702. AVIOContext *pbx;
  703. unsigned char *buffer = NULL;
  704. int buffer_size = 0;
  705. const ID3v2EMFunc *extra_func = NULL;
  706. unsigned char *uncompressed_buffer = NULL;
  707. av_unused int uncompressed_buffer_size = 0;
  708. const char *comm_frame;
  709. av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
  710. switch (version) {
  711. case 2:
  712. if (flags & 0x40) {
  713. reason = "compression";
  714. goto error;
  715. }
  716. isv34 = 0;
  717. taghdrlen = 6;
  718. comm_frame = "COM";
  719. break;
  720. case 3:
  721. case 4:
  722. isv34 = 1;
  723. taghdrlen = 10;
  724. comm_frame = "COMM";
  725. break;
  726. default:
  727. reason = "version";
  728. goto error;
  729. }
  730. unsync = flags & 0x80;
  731. if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
  732. int extlen = get_size(pb, 4);
  733. if (version == 4)
  734. /* In v2.4 the length includes the length field we just read. */
  735. extlen -= 4;
  736. if (extlen < 0) {
  737. reason = "invalid extended header length";
  738. goto error;
  739. }
  740. avio_skip(pb, extlen);
  741. len -= extlen + 4;
  742. if (len < 0) {
  743. reason = "extended header too long.";
  744. goto error;
  745. }
  746. }
  747. while (len >= taghdrlen) {
  748. unsigned int tflags = 0;
  749. int tunsync = 0;
  750. int tcomp = 0;
  751. int tencr = 0;
  752. unsigned long av_unused dlen;
  753. if (isv34) {
  754. if (avio_read(pb, tag, 4) < 4)
  755. break;
  756. tag[4] = 0;
  757. if (version == 3) {
  758. tlen = avio_rb32(pb);
  759. } else {
  760. /* some encoders incorrectly uses v3 sizes instead of syncsafe ones
  761. * so check the next tag to see which one to use */
  762. tlen = avio_rb32(pb);
  763. if (tlen > 0x7f) {
  764. if (tlen < len) {
  765. int64_t cur = avio_tell(pb);
  766. if (ffio_ensure_seekback(pb, 2 /* tflags */ + tlen + 4 /* next tag */))
  767. break;
  768. if (check_tag(pb, cur + 2 + size_to_syncsafe(tlen), 4) == 1)
  769. tlen = size_to_syncsafe(tlen);
  770. else if (check_tag(pb, cur + 2 + tlen, 4) != 1)
  771. break;
  772. avio_seek(pb, cur, SEEK_SET);
  773. } else
  774. tlen = size_to_syncsafe(tlen);
  775. }
  776. }
  777. tflags = avio_rb16(pb);
  778. tunsync = tflags & ID3v2_FLAG_UNSYNCH;
  779. } else {
  780. if (avio_read(pb, tag, 3) < 3)
  781. break;
  782. tag[3] = 0;
  783. tlen = avio_rb24(pb);
  784. }
  785. if (tlen > (1<<28))
  786. break;
  787. len -= taghdrlen + tlen;
  788. if (len < 0)
  789. break;
  790. next = avio_tell(pb) + tlen;
  791. if (!tlen) {
  792. if (tag[0])
  793. av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
  794. tag);
  795. continue;
  796. }
  797. if (tflags & ID3v2_FLAG_DATALEN) {
  798. if (tlen < 4)
  799. break;
  800. dlen = avio_rb32(pb);
  801. tlen -= 4;
  802. } else
  803. dlen = tlen;
  804. tcomp = tflags & ID3v2_FLAG_COMPRESSION;
  805. tencr = tflags & ID3v2_FLAG_ENCRYPTION;
  806. /* skip encrypted tags and, if no zlib, compressed tags */
  807. if (tencr || (!CONFIG_ZLIB && tcomp)) {
  808. const char *type;
  809. if (!tcomp)
  810. type = "encrypted";
  811. else if (!tencr)
  812. type = "compressed";
  813. else
  814. type = "encrypted and compressed";
  815. av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
  816. avio_skip(pb, tlen);
  817. /* check for text tag or supported special meta tag */
  818. } else if (tag[0] == 'T' ||
  819. !memcmp(tag, "USLT", 4) ||
  820. !strcmp(tag, comm_frame) ||
  821. (extra_meta &&
  822. (extra_func = get_extra_meta_func(tag, isv34)))) {
  823. pbx = pb;
  824. if (unsync || tunsync || tcomp) {
  825. av_fast_malloc(&buffer, &buffer_size, tlen);
  826. if (!buffer) {
  827. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
  828. goto seek;
  829. }
  830. }
  831. if (unsync || tunsync) {
  832. uint8_t *b = buffer;
  833. uint8_t *t = buffer;
  834. uint8_t *end = t + tlen;
  835. if (avio_read(pb, buffer, tlen) != tlen) {
  836. av_log(s, AV_LOG_ERROR, "Failed to read tag data\n");
  837. goto seek;
  838. }
  839. while (t != end) {
  840. *b++ = *t++;
  841. if (t != end && t[-1] == 0xff && !t[0])
  842. t++;
  843. }
  844. ffio_init_context(&pb_local, buffer, b - buffer, 0, NULL, NULL, NULL,
  845. NULL);
  846. tlen = b - buffer;
  847. pbx = &pb_local; // read from sync buffer
  848. }
  849. #if CONFIG_ZLIB
  850. if (tcomp) {
  851. int err;
  852. av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
  853. if (tlen <= 0)
  854. goto seek;
  855. if (dlen / 32768 > tlen)
  856. goto seek;
  857. av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
  858. if (!uncompressed_buffer) {
  859. av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
  860. goto seek;
  861. }
  862. if (!(unsync || tunsync)) {
  863. err = avio_read(pb, buffer, tlen);
  864. if (err < 0) {
  865. av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
  866. goto seek;
  867. }
  868. tlen = err;
  869. }
  870. err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
  871. if (err != Z_OK) {
  872. av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
  873. goto seek;
  874. }
  875. ffio_init_context(&pb_local, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);
  876. tlen = dlen;
  877. pbx = &pb_local; // read from sync buffer
  878. }
  879. #endif
  880. if (tag[0] == 'T')
  881. /* parse text tag */
  882. read_ttag(s, pbx, tlen, metadata, tag);
  883. else if (!memcmp(tag, "USLT", 4))
  884. read_uslt(s, pbx, tlen, metadata);
  885. else if (!strcmp(tag, comm_frame))
  886. read_comment(s, pbx, tlen, metadata);
  887. else
  888. /* parse special meta tag */
  889. extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);
  890. } else if (!tag[0]) {
  891. if (tag[1])
  892. av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
  893. avio_skip(pb, tlen);
  894. break;
  895. }
  896. /* Skip to end of tag */
  897. seek:
  898. avio_seek(pb, next, SEEK_SET);
  899. }
  900. /* Footer preset, always 10 bytes, skip over it */
  901. if (version == 4 && flags & 0x10)
  902. end += 10;
  903. error:
  904. if (reason)
  905. av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
  906. version, reason);
  907. avio_seek(pb, end, SEEK_SET);
  908. av_free(buffer);
  909. av_free(uncompressed_buffer);
  910. return;
  911. }
  912. static void id3v2_read_internal(AVIOContext *pb, AVDictionary **metadata,
  913. AVFormatContext *s, const char *magic,
  914. ID3v2ExtraMeta **extra_meta, int64_t max_search_size)
  915. {
  916. int len, ret;
  917. uint8_t buf[ID3v2_HEADER_SIZE];
  918. int found_header;
  919. int64_t start, off;
  920. if (max_search_size && max_search_size < ID3v2_HEADER_SIZE)
  921. return;
  922. start = avio_tell(pb);
  923. do {
  924. /* save the current offset in case there's nothing to read/skip */
  925. off = avio_tell(pb);
  926. if (max_search_size && off - start >= max_search_size - ID3v2_HEADER_SIZE) {
  927. avio_seek(pb, off, SEEK_SET);
  928. break;
  929. }
  930. ret = ffio_ensure_seekback(pb, ID3v2_HEADER_SIZE);
  931. if (ret >= 0)
  932. ret = avio_read(pb, buf, ID3v2_HEADER_SIZE);
  933. if (ret != ID3v2_HEADER_SIZE) {
  934. avio_seek(pb, off, SEEK_SET);
  935. break;
  936. }
  937. found_header = ff_id3v2_match(buf, magic);
  938. if (found_header) {
  939. /* parse ID3v2 header */
  940. len = ((buf[6] & 0x7f) << 21) |
  941. ((buf[7] & 0x7f) << 14) |
  942. ((buf[8] & 0x7f) << 7) |
  943. (buf[9] & 0x7f);
  944. id3v2_parse(pb, metadata, s, len, buf[3], buf[5], extra_meta);
  945. } else {
  946. avio_seek(pb, off, SEEK_SET);
  947. }
  948. } while (found_header);
  949. ff_metadata_conv(metadata, NULL, ff_id3v2_34_metadata_conv);
  950. ff_metadata_conv(metadata, NULL, id3v2_2_metadata_conv);
  951. ff_metadata_conv(metadata, NULL, ff_id3v2_4_metadata_conv);
  952. merge_date(metadata);
  953. }
  954. void ff_id3v2_read_dict(AVIOContext *pb, AVDictionary **metadata,
  955. const char *magic, ID3v2ExtraMeta **extra_meta)
  956. {
  957. id3v2_read_internal(pb, metadata, NULL, magic, extra_meta, 0);
  958. }
  959. void ff_id3v2_read(AVFormatContext *s, const char *magic,
  960. ID3v2ExtraMeta **extra_meta, unsigned int max_search_size)
  961. {
  962. id3v2_read_internal(s->pb, &s->metadata, s, magic, extra_meta, max_search_size);
  963. }
  964. void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
  965. {
  966. ID3v2ExtraMeta *current = *extra_meta, *next;
  967. const ID3v2EMFunc *extra_func;
  968. while (current) {
  969. if ((extra_func = get_extra_meta_func(current->tag, 1)))
  970. extra_func->free(&current->data);
  971. next = current->next;
  972. av_freep(&current);
  973. current = next;
  974. }
  975. *extra_meta = NULL;
  976. }
  977. int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
  978. {
  979. ID3v2ExtraMeta *cur;
  980. for (cur = extra_meta; cur; cur = cur->next) {
  981. ID3v2ExtraMetaAPIC *apic;
  982. AVStream *st;
  983. if (strcmp(cur->tag, "APIC"))
  984. continue;
  985. apic = &cur->data.apic;
  986. if (!(st = avformat_new_stream(s, NULL)))
  987. return AVERROR(ENOMEM);
  988. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  989. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  990. st->codecpar->codec_id = apic->id;
  991. if (AV_RB64(apic->buf->data) == PNGSIG)
  992. st->codecpar->codec_id = AV_CODEC_ID_PNG;
  993. if (apic->description[0])
  994. av_dict_set(&st->metadata, "title", apic->description, 0);
  995. av_dict_set(&st->metadata, "comment", apic->type, 0);
  996. av_init_packet(&st->attached_pic);
  997. st->attached_pic.buf = apic->buf;
  998. st->attached_pic.data = apic->buf->data;
  999. st->attached_pic.size = apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE;
  1000. st->attached_pic.stream_index = st->index;
  1001. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  1002. apic->buf = NULL;
  1003. }
  1004. return 0;
  1005. }
  1006. int ff_id3v2_parse_chapters(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
  1007. {
  1008. int ret = 0;
  1009. ID3v2ExtraMeta *cur;
  1010. AVRational time_base = {1, 1000};
  1011. ID3v2ExtraMetaCHAP **chapters = NULL;
  1012. int num_chapters = 0;
  1013. int i;
  1014. // since extra_meta is a linked list where elements are prepended,
  1015. // we need to reverse the order of chapters
  1016. for (cur = extra_meta; cur; cur = cur->next) {
  1017. ID3v2ExtraMetaCHAP *chap;
  1018. if (strcmp(cur->tag, "CHAP"))
  1019. continue;
  1020. chap = &cur->data.chap;
  1021. if ((ret = av_dynarray_add_nofree(&chapters, &num_chapters, chap)) < 0)
  1022. goto end;
  1023. }
  1024. for (i = 0; i < (num_chapters / 2); i++) {
  1025. ID3v2ExtraMetaCHAP *right;
  1026. int right_index;
  1027. right_index = (num_chapters - 1) - i;
  1028. right = chapters[right_index];
  1029. chapters[right_index] = chapters[i];
  1030. chapters[i] = right;
  1031. }
  1032. for (i = 0; i < num_chapters; i++) {
  1033. ID3v2ExtraMetaCHAP *chap;
  1034. AVChapter *chapter;
  1035. chap = chapters[i];
  1036. chapter = avpriv_new_chapter(s, i, time_base, chap->start, chap->end, chap->element_id);
  1037. if (!chapter)
  1038. continue;
  1039. if ((ret = av_dict_copy(&chapter->metadata, chap->meta, 0)) < 0)
  1040. goto end;
  1041. }
  1042. end:
  1043. av_freep(&chapters);
  1044. return ret;
  1045. }
  1046. int ff_id3v2_parse_priv_dict(AVDictionary **metadata, ID3v2ExtraMeta *extra_meta)
  1047. {
  1048. ID3v2ExtraMeta *cur;
  1049. int dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL;
  1050. for (cur = extra_meta; cur; cur = cur->next) {
  1051. if (!strcmp(cur->tag, "PRIV")) {
  1052. ID3v2ExtraMetaPRIV *priv = &cur->data.priv;
  1053. AVBPrint bprint;
  1054. char *escaped, *key;
  1055. int i, ret;
  1056. if ((key = av_asprintf(ID3v2_PRIV_METADATA_PREFIX "%s", priv->owner)) == NULL) {
  1057. return AVERROR(ENOMEM);
  1058. }
  1059. av_bprint_init(&bprint, priv->datasize + 1, AV_BPRINT_SIZE_UNLIMITED);
  1060. for (i = 0; i < priv->datasize; i++) {
  1061. if (priv->data[i] < 32 || priv->data[i] > 126 || priv->data[i] == '\\') {
  1062. av_bprintf(&bprint, "\\x%02x", priv->data[i]);
  1063. } else {
  1064. av_bprint_chars(&bprint, priv->data[i], 1);
  1065. }
  1066. }
  1067. if ((ret = av_bprint_finalize(&bprint, &escaped)) < 0) {
  1068. av_free(key);
  1069. return ret;
  1070. }
  1071. if ((ret = av_dict_set(metadata, key, escaped, dict_flags)) < 0) {
  1072. return ret;
  1073. }
  1074. }
  1075. }
  1076. return 0;
  1077. }
  1078. int ff_id3v2_parse_priv(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
  1079. {
  1080. return ff_id3v2_parse_priv_dict(&s->metadata, extra_meta);
  1081. }