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.

1167 lines
33KB

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