/libavformat/id3v2.c

http://github.com/FFmpeg/FFmpeg · C · 1278 lines · 1005 code · 186 blank · 87 comment · 233 complexity · 13cfc49dde12b6fcbaf840b806648c92 MD5 · raw file

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