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.

1117 lines
32KB

  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 *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 GEOB tag into a ID3v2ExtraMetaGEOB struct.
  356. */
  357. static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen,
  358. const char *tag, ID3v2ExtraMeta **extra_meta,
  359. int isv34)
  360. {
  361. ID3v2ExtraMetaGEOB *geob_data = NULL;
  362. ID3v2ExtraMeta *new_extra = NULL;
  363. char encoding;
  364. unsigned int len;
  365. if (taglen < 1)
  366. return;
  367. geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
  368. if (!geob_data) {
  369. av_log(s, AV_LOG_ERROR, "Failed to alloc %"SIZE_SPECIFIER" bytes\n",
  370. sizeof(ID3v2ExtraMetaGEOB));
  371. return;
  372. }
  373. new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
  374. if (!new_extra) {
  375. av_log(s, AV_LOG_ERROR, "Failed to alloc %"SIZE_SPECIFIER" bytes\n",
  376. sizeof(ID3v2ExtraMeta));
  377. goto fail;
  378. }
  379. /* read encoding type byte */
  380. encoding = avio_r8(pb);
  381. taglen--;
  382. /* read MIME type (always ISO-8859) */
  383. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type,
  384. &taglen) < 0 ||
  385. taglen <= 0)
  386. goto fail;
  387. /* read file name */
  388. if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0 ||
  389. taglen <= 0)
  390. goto fail;
  391. /* read content description */
  392. if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0 ||
  393. taglen < 0)
  394. goto fail;
  395. if (taglen) {
  396. /* save encapsulated binary data */
  397. geob_data->data = av_malloc(taglen);
  398. if (!geob_data->data) {
  399. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
  400. goto fail;
  401. }
  402. if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
  403. av_log(s, AV_LOG_WARNING,
  404. "Error reading GEOB frame, data truncated.\n");
  405. geob_data->datasize = len;
  406. } else {
  407. geob_data->data = NULL;
  408. geob_data->datasize = 0;
  409. }
  410. /* add data to the list */
  411. new_extra->tag = "GEOB";
  412. new_extra->data = geob_data;
  413. new_extra->next = *extra_meta;
  414. *extra_meta = new_extra;
  415. return;
  416. fail:
  417. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
  418. free_geobtag(geob_data);
  419. av_free(new_extra);
  420. return;
  421. }
  422. static int is_number(const char *str)
  423. {
  424. while (*str >= '0' && *str <= '9')
  425. str++;
  426. return !*str;
  427. }
  428. static AVDictionaryEntry *get_date_tag(AVDictionary *m, const char *tag)
  429. {
  430. AVDictionaryEntry *t;
  431. if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
  432. strlen(t->value) == 4 && is_number(t->value))
  433. return t;
  434. return NULL;
  435. }
  436. static void merge_date(AVDictionary **m)
  437. {
  438. AVDictionaryEntry *t;
  439. char date[17] = { 0 }; // YYYY-MM-DD hh:mm
  440. if (!(t = get_date_tag(*m, "TYER")) &&
  441. !(t = get_date_tag(*m, "TYE")))
  442. return;
  443. av_strlcpy(date, t->value, 5);
  444. av_dict_set(m, "TYER", NULL, 0);
  445. av_dict_set(m, "TYE", NULL, 0);
  446. if (!(t = get_date_tag(*m, "TDAT")) &&
  447. !(t = get_date_tag(*m, "TDA")))
  448. goto finish;
  449. snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
  450. av_dict_set(m, "TDAT", NULL, 0);
  451. av_dict_set(m, "TDA", NULL, 0);
  452. if (!(t = get_date_tag(*m, "TIME")) &&
  453. !(t = get_date_tag(*m, "TIM")))
  454. goto finish;
  455. snprintf(date + 10, sizeof(date) - 10,
  456. " %.2s:%.2s", t->value, t->value + 2);
  457. av_dict_set(m, "TIME", NULL, 0);
  458. av_dict_set(m, "TIM", NULL, 0);
  459. finish:
  460. if (date[0])
  461. av_dict_set(m, "date", date, 0);
  462. }
  463. static void free_apic(void *obj)
  464. {
  465. ID3v2ExtraMetaAPIC *apic = obj;
  466. av_buffer_unref(&apic->buf);
  467. av_freep(&apic->description);
  468. av_freep(&apic);
  469. }
  470. static void rstrip_spaces(char *buf)
  471. {
  472. size_t len = strlen(buf);
  473. while (len > 0 && buf[len - 1] == ' ')
  474. buf[--len] = 0;
  475. }
  476. static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen,
  477. const char *tag, ID3v2ExtraMeta **extra_meta,
  478. int isv34)
  479. {
  480. int enc, pic_type;
  481. char mimetype[64];
  482. const CodecMime *mime = ff_id3v2_mime_tags;
  483. enum AVCodecID id = AV_CODEC_ID_NONE;
  484. ID3v2ExtraMetaAPIC *apic = NULL;
  485. ID3v2ExtraMeta *new_extra = NULL;
  486. int64_t end = avio_tell(pb) + taglen;
  487. if (taglen <= 4 || (!isv34 && taglen <= 6))
  488. goto fail;
  489. new_extra = av_mallocz(sizeof(*new_extra));
  490. apic = av_mallocz(sizeof(*apic));
  491. if (!new_extra || !apic)
  492. goto fail;
  493. enc = avio_r8(pb);
  494. taglen--;
  495. /* mimetype */
  496. if (isv34) {
  497. taglen -= avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
  498. } else {
  499. avio_read(pb, mimetype, 3);
  500. mimetype[3] = 0;
  501. taglen -= 3;
  502. }
  503. while (mime->id != AV_CODEC_ID_NONE) {
  504. if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
  505. id = mime->id;
  506. break;
  507. }
  508. mime++;
  509. }
  510. if (id == AV_CODEC_ID_NONE) {
  511. av_log(s, AV_LOG_WARNING,
  512. "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
  513. goto fail;
  514. }
  515. apic->id = id;
  516. /* picture type */
  517. pic_type = avio_r8(pb);
  518. taglen--;
  519. if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
  520. av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
  521. pic_type);
  522. pic_type = 0;
  523. }
  524. apic->type = ff_id3v2_picture_types[pic_type];
  525. /* description and picture data */
  526. if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
  527. av_log(s, AV_LOG_ERROR,
  528. "Error decoding attached picture description.\n");
  529. goto fail;
  530. }
  531. apic->buf = av_buffer_alloc(taglen + FF_INPUT_BUFFER_PADDING_SIZE);
  532. if (!apic->buf || !taglen || avio_read(pb, apic->buf->data, taglen) != taglen)
  533. goto fail;
  534. memset(apic->buf->data + taglen, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  535. new_extra->tag = "APIC";
  536. new_extra->data = apic;
  537. new_extra->next = *extra_meta;
  538. *extra_meta = new_extra;
  539. // The description must be unique, and some ID3v2 tag writers add spaces
  540. // to write several APIC entries with the same description.
  541. rstrip_spaces(apic->description);
  542. return;
  543. fail:
  544. if (apic)
  545. free_apic(apic);
  546. av_freep(&new_extra);
  547. avio_seek(pb, end, SEEK_SET);
  548. }
  549. static void read_chapter(AVFormatContext *s, AVIOContext *pb, int len, const char *ttag, ID3v2ExtraMeta **extra_meta, int isv34)
  550. {
  551. AVRational time_base = {1, 1000};
  552. uint32_t start, end;
  553. AVChapter *chapter;
  554. uint8_t *dst = NULL;
  555. int taglen;
  556. char tag[5];
  557. if (!s) {
  558. /* We should probably just put the chapter data to extra_meta here
  559. * and do the AVFormatContext-needing part in a separate
  560. * ff_id3v2_parse_apic()-like function. */
  561. av_log(NULL, AV_LOG_DEBUG, "No AVFormatContext, skipped ID3 chapter data\n");
  562. return;
  563. }
  564. if (decode_str(s, pb, 0, &dst, &len) < 0)
  565. return;
  566. if (len < 16)
  567. return;
  568. start = avio_rb32(pb);
  569. end = avio_rb32(pb);
  570. avio_skip(pb, 8);
  571. chapter = avpriv_new_chapter(s, s->nb_chapters + 1, time_base, start, end, dst);
  572. if (!chapter) {
  573. av_free(dst);
  574. return;
  575. }
  576. len -= 16;
  577. while (len > 10) {
  578. if (avio_read(pb, tag, 4) < 4)
  579. goto end;
  580. tag[4] = 0;
  581. taglen = avio_rb32(pb);
  582. avio_skip(pb, 2);
  583. len -= 10;
  584. if (taglen < 0 || taglen > len)
  585. goto end;
  586. if (tag[0] == 'T')
  587. read_ttag(s, pb, taglen, &chapter->metadata, tag);
  588. else
  589. avio_skip(pb, taglen);
  590. len -= taglen;
  591. }
  592. ff_metadata_conv(&chapter->metadata, NULL, ff_id3v2_34_metadata_conv);
  593. ff_metadata_conv(&chapter->metadata, NULL, ff_id3v2_4_metadata_conv);
  594. end:
  595. av_free(dst);
  596. }
  597. static void free_priv(void *obj)
  598. {
  599. ID3v2ExtraMetaPRIV *priv = obj;
  600. av_freep(&priv->owner);
  601. av_freep(&priv->data);
  602. av_freep(&priv);
  603. }
  604. static void read_priv(AVFormatContext *s, AVIOContext *pb, int taglen,
  605. const char *tag, ID3v2ExtraMeta **extra_meta, int isv34)
  606. {
  607. ID3v2ExtraMeta *meta;
  608. ID3v2ExtraMetaPRIV *priv;
  609. meta = av_mallocz(sizeof(*meta));
  610. priv = av_mallocz(sizeof(*priv));
  611. if (!meta || !priv)
  612. goto fail;
  613. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &priv->owner, &taglen) < 0)
  614. goto fail;
  615. priv->data = av_malloc(taglen);
  616. if (!priv->data)
  617. goto fail;
  618. priv->datasize = taglen;
  619. if (avio_read(pb, priv->data, priv->datasize) != priv->datasize)
  620. goto fail;
  621. meta->tag = "PRIV";
  622. meta->data = priv;
  623. meta->next = *extra_meta;
  624. *extra_meta = meta;
  625. return;
  626. fail:
  627. if (priv)
  628. free_priv(priv);
  629. av_freep(&meta);
  630. }
  631. typedef struct ID3v2EMFunc {
  632. const char *tag3;
  633. const char *tag4;
  634. void (*read)(AVFormatContext *s, AVIOContext *pb, int taglen,
  635. const char *tag, ID3v2ExtraMeta **extra_meta,
  636. int isv34);
  637. void (*free)(void *obj);
  638. } ID3v2EMFunc;
  639. static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
  640. { "GEO", "GEOB", read_geobtag, free_geobtag },
  641. { "PIC", "APIC", read_apic, free_apic },
  642. { "CHAP","CHAP", read_chapter, NULL },
  643. { "PRIV","PRIV", read_priv, free_priv },
  644. { NULL }
  645. };
  646. /**
  647. * Get the corresponding ID3v2EMFunc struct for a tag.
  648. * @param isv34 Determines if v2.2 or v2.3/4 strings are used
  649. * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
  650. */
  651. static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
  652. {
  653. int i = 0;
  654. while (id3v2_extra_meta_funcs[i].tag3) {
  655. if (tag && !memcmp(tag,
  656. (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
  657. id3v2_extra_meta_funcs[i].tag3),
  658. (isv34 ? 4 : 3)))
  659. return &id3v2_extra_meta_funcs[i];
  660. i++;
  661. }
  662. return NULL;
  663. }
  664. static void id3v2_parse(AVIOContext *pb, AVDictionary **metadata,
  665. AVFormatContext *s, int len, uint8_t version,
  666. uint8_t flags, ID3v2ExtraMeta **extra_meta)
  667. {
  668. int isv34, unsync;
  669. unsigned tlen;
  670. char tag[5];
  671. int64_t next, end = avio_tell(pb) + len;
  672. int taghdrlen;
  673. const char *reason = NULL;
  674. AVIOContext pb_local;
  675. AVIOContext *pbx;
  676. unsigned char *buffer = NULL;
  677. int buffer_size = 0;
  678. const ID3v2EMFunc *extra_func = NULL;
  679. unsigned char *uncompressed_buffer = NULL;
  680. av_unused int uncompressed_buffer_size = 0;
  681. av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
  682. switch (version) {
  683. case 2:
  684. if (flags & 0x40) {
  685. reason = "compression";
  686. goto error;
  687. }
  688. isv34 = 0;
  689. taghdrlen = 6;
  690. break;
  691. case 3:
  692. case 4:
  693. isv34 = 1;
  694. taghdrlen = 10;
  695. break;
  696. default:
  697. reason = "version";
  698. goto error;
  699. }
  700. unsync = flags & 0x80;
  701. if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
  702. int extlen = get_size(pb, 4);
  703. if (version == 4)
  704. /* In v2.4 the length includes the length field we just read. */
  705. extlen -= 4;
  706. if (extlen < 0) {
  707. reason = "invalid extended header length";
  708. goto error;
  709. }
  710. avio_skip(pb, extlen);
  711. len -= extlen + 4;
  712. if (len < 0) {
  713. reason = "extended header too long.";
  714. goto error;
  715. }
  716. }
  717. while (len >= taghdrlen) {
  718. unsigned int tflags = 0;
  719. int tunsync = 0;
  720. int tcomp = 0;
  721. int tencr = 0;
  722. unsigned long av_unused dlen;
  723. if (isv34) {
  724. if (avio_read(pb, tag, 4) < 4)
  725. break;
  726. tag[4] = 0;
  727. if (version == 3) {
  728. tlen = avio_rb32(pb);
  729. } else {
  730. /* some encoders incorrectly uses v3 sizes instead of syncsafe ones
  731. * so check the next tag to see which one to use */
  732. tlen = avio_rb32(pb);
  733. if (tlen > 0x7f) {
  734. if (tlen < len) {
  735. int64_t cur = avio_tell(pb);
  736. if (ffio_ensure_seekback(pb, 2 /* tflags */ + tlen + 4 /* next tag */))
  737. break;
  738. if (check_tag(pb, cur + 2 + size_to_syncsafe(tlen), 4) == 1)
  739. tlen = size_to_syncsafe(tlen);
  740. else if (check_tag(pb, cur + 2 + tlen, 4) != 1)
  741. break;
  742. avio_seek(pb, cur, SEEK_SET);
  743. } else
  744. tlen = size_to_syncsafe(tlen);
  745. }
  746. }
  747. tflags = avio_rb16(pb);
  748. tunsync = tflags & ID3v2_FLAG_UNSYNCH;
  749. } else {
  750. if (avio_read(pb, tag, 3) < 3)
  751. break;
  752. tag[3] = 0;
  753. tlen = avio_rb24(pb);
  754. }
  755. if (tlen > (1<<28))
  756. break;
  757. len -= taghdrlen + tlen;
  758. if (len < 0)
  759. break;
  760. next = avio_tell(pb) + tlen;
  761. if (!tlen) {
  762. if (tag[0])
  763. av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
  764. tag);
  765. continue;
  766. }
  767. if (tflags & ID3v2_FLAG_DATALEN) {
  768. if (tlen < 4)
  769. break;
  770. dlen = avio_rb32(pb);
  771. tlen -= 4;
  772. } else
  773. dlen = tlen;
  774. tcomp = tflags & ID3v2_FLAG_COMPRESSION;
  775. tencr = tflags & ID3v2_FLAG_ENCRYPTION;
  776. /* skip encrypted tags and, if no zlib, compressed tags */
  777. if (tencr || (!CONFIG_ZLIB && tcomp)) {
  778. const char *type;
  779. if (!tcomp)
  780. type = "encrypted";
  781. else if (!tencr)
  782. type = "compressed";
  783. else
  784. type = "encrypted and compressed";
  785. av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
  786. avio_skip(pb, tlen);
  787. /* check for text tag or supported special meta tag */
  788. } else if (tag[0] == 'T' ||
  789. !memcmp(tag, "USLT", 4) ||
  790. (extra_meta &&
  791. (extra_func = get_extra_meta_func(tag, isv34)))) {
  792. pbx = pb;
  793. if (unsync || tunsync || tcomp) {
  794. av_fast_malloc(&buffer, &buffer_size, tlen);
  795. if (!buffer) {
  796. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
  797. goto seek;
  798. }
  799. }
  800. if (unsync || tunsync) {
  801. int64_t end = avio_tell(pb) + tlen;
  802. uint8_t *b;
  803. b = buffer;
  804. while (avio_tell(pb) < end && b - buffer < tlen && !pb->eof_reached) {
  805. *b++ = avio_r8(pb);
  806. if (*(b - 1) == 0xff && avio_tell(pb) < end - 1 &&
  807. b - buffer < tlen &&
  808. !pb->eof_reached ) {
  809. uint8_t val = avio_r8(pb);
  810. *b++ = val ? val : avio_r8(pb);
  811. }
  812. }
  813. ffio_init_context(&pb_local, buffer, b - buffer, 0, NULL, NULL, NULL,
  814. NULL);
  815. tlen = b - buffer;
  816. pbx = &pb_local; // read from sync buffer
  817. }
  818. #if CONFIG_ZLIB
  819. if (tcomp) {
  820. int err;
  821. av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
  822. av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
  823. if (!uncompressed_buffer) {
  824. av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
  825. goto seek;
  826. }
  827. if (!(unsync || tunsync)) {
  828. err = avio_read(pb, buffer, tlen);
  829. if (err < 0) {
  830. av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
  831. goto seek;
  832. }
  833. tlen = err;
  834. }
  835. err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
  836. if (err != Z_OK) {
  837. av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
  838. goto seek;
  839. }
  840. ffio_init_context(&pb_local, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);
  841. tlen = dlen;
  842. pbx = &pb_local; // read from sync buffer
  843. }
  844. #endif
  845. if (tag[0] == 'T')
  846. /* parse text tag */
  847. read_ttag(s, pbx, tlen, metadata, tag);
  848. else if (!memcmp(tag, "USLT", 4))
  849. read_uslt(s, pbx, tlen, metadata);
  850. else
  851. /* parse special meta tag */
  852. extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);
  853. } else if (!tag[0]) {
  854. if (tag[1])
  855. av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
  856. avio_skip(pb, tlen);
  857. break;
  858. }
  859. /* Skip to end of tag */
  860. seek:
  861. avio_seek(pb, next, SEEK_SET);
  862. }
  863. /* Footer preset, always 10 bytes, skip over it */
  864. if (version == 4 && flags & 0x10)
  865. end += 10;
  866. error:
  867. if (reason)
  868. av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
  869. version, reason);
  870. avio_seek(pb, end, SEEK_SET);
  871. av_free(buffer);
  872. av_free(uncompressed_buffer);
  873. return;
  874. }
  875. static void id3v2_read_internal(AVIOContext *pb, AVDictionary **metadata,
  876. AVFormatContext *s, const char *magic,
  877. ID3v2ExtraMeta **extra_meta, int64_t max_search_size)
  878. {
  879. int len, ret;
  880. uint8_t buf[ID3v2_HEADER_SIZE];
  881. int found_header;
  882. int64_t start, off;
  883. if (max_search_size && max_search_size < ID3v2_HEADER_SIZE)
  884. return;
  885. start = avio_tell(pb);
  886. do {
  887. /* save the current offset in case there's nothing to read/skip */
  888. off = avio_tell(pb);
  889. if (max_search_size && off - start >= max_search_size - ID3v2_HEADER_SIZE) {
  890. avio_seek(pb, off, SEEK_SET);
  891. break;
  892. }
  893. ret = avio_read(pb, buf, ID3v2_HEADER_SIZE);
  894. if (ret != ID3v2_HEADER_SIZE) {
  895. avio_seek(pb, off, SEEK_SET);
  896. break;
  897. }
  898. found_header = ff_id3v2_match(buf, magic);
  899. if (found_header) {
  900. /* parse ID3v2 header */
  901. len = ((buf[6] & 0x7f) << 21) |
  902. ((buf[7] & 0x7f) << 14) |
  903. ((buf[8] & 0x7f) << 7) |
  904. (buf[9] & 0x7f);
  905. id3v2_parse(pb, metadata, s, len, buf[3], buf[5], extra_meta);
  906. } else {
  907. avio_seek(pb, off, SEEK_SET);
  908. }
  909. } while (found_header);
  910. ff_metadata_conv(metadata, NULL, ff_id3v2_34_metadata_conv);
  911. ff_metadata_conv(metadata, NULL, id3v2_2_metadata_conv);
  912. ff_metadata_conv(metadata, NULL, ff_id3v2_4_metadata_conv);
  913. merge_date(metadata);
  914. }
  915. void ff_id3v2_read_dict(AVIOContext *pb, AVDictionary **metadata,
  916. const char *magic, ID3v2ExtraMeta **extra_meta)
  917. {
  918. id3v2_read_internal(pb, metadata, NULL, magic, extra_meta, 0);
  919. }
  920. void ff_id3v2_read(AVFormatContext *s, const char *magic,
  921. ID3v2ExtraMeta **extra_meta, unsigned int max_search_size)
  922. {
  923. id3v2_read_internal(s->pb, &s->metadata, s, magic, extra_meta, max_search_size);
  924. }
  925. void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
  926. {
  927. ID3v2ExtraMeta *current = *extra_meta, *next;
  928. const ID3v2EMFunc *extra_func;
  929. while (current) {
  930. if ((extra_func = get_extra_meta_func(current->tag, 1)))
  931. extra_func->free(current->data);
  932. next = current->next;
  933. av_freep(&current);
  934. current = next;
  935. }
  936. *extra_meta = NULL;
  937. }
  938. int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
  939. {
  940. ID3v2ExtraMeta *cur;
  941. for (cur = *extra_meta; cur; cur = cur->next) {
  942. ID3v2ExtraMetaAPIC *apic;
  943. AVStream *st;
  944. if (strcmp(cur->tag, "APIC"))
  945. continue;
  946. apic = cur->data;
  947. if (!(st = avformat_new_stream(s, NULL)))
  948. return AVERROR(ENOMEM);
  949. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  950. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  951. st->codec->codec_id = apic->id;
  952. if (AV_RB64(apic->buf->data) == 0x89504e470d0a1a0a)
  953. st->codec->codec_id = AV_CODEC_ID_PNG;
  954. if (apic->description[0])
  955. av_dict_set(&st->metadata, "title", apic->description, 0);
  956. av_dict_set(&st->metadata, "comment", apic->type, 0);
  957. av_init_packet(&st->attached_pic);
  958. st->attached_pic.buf = apic->buf;
  959. st->attached_pic.data = apic->buf->data;
  960. st->attached_pic.size = apic->buf->size - FF_INPUT_BUFFER_PADDING_SIZE;
  961. st->attached_pic.stream_index = st->index;
  962. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  963. apic->buf = NULL;
  964. }
  965. return 0;
  966. }