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.

1100 lines
31KB

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