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.

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