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.

592 lines
17KB

  1. /*
  2. * ID3v2 header parser
  3. * Copyright (c) 2003 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "id3v2.h"
  22. #include "id3v1.h"
  23. #include "libavutil/avstring.h"
  24. #include "libavutil/intreadwrite.h"
  25. #include "libavutil/dict.h"
  26. #include "avio_internal.h"
  27. const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
  28. { "TALB", "album"},
  29. { "TCOM", "composer"},
  30. { "TCON", "genre"},
  31. { "TCOP", "copyright"},
  32. { "TENC", "encoded_by"},
  33. { "TIT2", "title"},
  34. { "TLAN", "language"},
  35. { "TPE1", "artist"},
  36. { "TPE2", "album_artist"},
  37. { "TPE3", "performer"},
  38. { "TPOS", "disc"},
  39. { "TPUB", "publisher"},
  40. { "TRCK", "track"},
  41. { "TSSE", "encoder"},
  42. { 0 }
  43. };
  44. const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
  45. { "TDRL", "date"},
  46. { "TDRC", "date"},
  47. { "TDEN", "creation_time"},
  48. { "TSOA", "album-sort"},
  49. { "TSOP", "artist-sort"},
  50. { "TSOT", "title-sort"},
  51. { 0 }
  52. };
  53. static const AVMetadataConv id3v2_2_metadata_conv[] = {
  54. { "TAL", "album"},
  55. { "TCO", "genre"},
  56. { "TT2", "title"},
  57. { "TEN", "encoded_by"},
  58. { "TP1", "artist"},
  59. { "TP2", "album_artist"},
  60. { "TP3", "performer"},
  61. { "TRK", "track"},
  62. { 0 }
  63. };
  64. const char ff_id3v2_tags[][4] = {
  65. "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
  66. "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
  67. "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
  68. "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
  69. { 0 },
  70. };
  71. const char ff_id3v2_4_tags[][4] = {
  72. "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
  73. "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
  74. { 0 },
  75. };
  76. const char ff_id3v2_3_tags[][4] = {
  77. "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
  78. { 0 },
  79. };
  80. int ff_id3v2_match(const uint8_t *buf, const char * magic)
  81. {
  82. return buf[0] == magic[0] &&
  83. buf[1] == magic[1] &&
  84. buf[2] == magic[2] &&
  85. buf[3] != 0xff &&
  86. buf[4] != 0xff &&
  87. (buf[6] & 0x80) == 0 &&
  88. (buf[7] & 0x80) == 0 &&
  89. (buf[8] & 0x80) == 0 &&
  90. (buf[9] & 0x80) == 0;
  91. }
  92. int ff_id3v2_tag_len(const uint8_t * buf)
  93. {
  94. int len = ((buf[6] & 0x7f) << 21) +
  95. ((buf[7] & 0x7f) << 14) +
  96. ((buf[8] & 0x7f) << 7) +
  97. (buf[9] & 0x7f) +
  98. ID3v2_HEADER_SIZE;
  99. if (buf[5] & 0x10)
  100. len += ID3v2_HEADER_SIZE;
  101. return len;
  102. }
  103. static unsigned int get_size(AVIOContext *s, int len)
  104. {
  105. int v = 0;
  106. while (len--)
  107. v = (v << 7) + (avio_r8(s) & 0x7F);
  108. return v;
  109. }
  110. /**
  111. * Free GEOB type extra metadata.
  112. */
  113. static void free_geobtag(ID3v2ExtraMetaGEOB *geob)
  114. {
  115. av_free(geob->mime_type);
  116. av_free(geob->file_name);
  117. av_free(geob->description);
  118. av_free(geob->data);
  119. av_free(geob);
  120. }
  121. /**
  122. * Decode characters to UTF-8 according to encoding type. The decoded buffer is
  123. * always null terminated. Stop reading when either *maxread bytes are read from
  124. * pb or U+0000 character is found.
  125. *
  126. * @param dst Pointer where the address of the buffer with the decoded bytes is
  127. * stored. Buffer must be freed by caller.
  128. * @param maxread Pointer to maximum number of characters to read from the
  129. * AVIOContext. After execution the value is decremented by the number of bytes
  130. * actually read.
  131. * @returns 0 if no error occured, dst is uninitialized on error
  132. */
  133. static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
  134. uint8_t **dst, int *maxread)
  135. {
  136. int ret;
  137. uint8_t tmp;
  138. uint32_t ch = 1;
  139. int left = *maxread;
  140. unsigned int (*get)(AVIOContext*) = avio_rb16;
  141. AVIOContext *dynbuf;
  142. if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
  143. av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
  144. return ret;
  145. }
  146. switch (encoding) {
  147. case ID3v2_ENCODING_ISO8859:
  148. while (left && ch) {
  149. ch = avio_r8(pb);
  150. PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
  151. left--;
  152. }
  153. break;
  154. case ID3v2_ENCODING_UTF16BOM:
  155. if ((left -= 2) < 0) {
  156. av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
  157. avio_close_dyn_buf(dynbuf, dst);
  158. av_freep(dst);
  159. return AVERROR_INVALIDDATA;
  160. }
  161. switch (avio_rb16(pb)) {
  162. case 0xfffe:
  163. get = avio_rl16;
  164. case 0xfeff:
  165. break;
  166. default:
  167. av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
  168. avio_close_dyn_buf(dynbuf, dst);
  169. av_freep(dst);
  170. *maxread = left;
  171. return AVERROR_INVALIDDATA;
  172. }
  173. // fall-through
  174. case ID3v2_ENCODING_UTF16BE:
  175. while ((left > 1) && ch) {
  176. GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
  177. PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
  178. }
  179. if (left < 0)
  180. left += 2; /* did not read last char from pb */
  181. break;
  182. case ID3v2_ENCODING_UTF8:
  183. while (left && ch) {
  184. ch = avio_r8(pb);
  185. avio_w8(dynbuf, ch);
  186. left--;
  187. }
  188. break;
  189. default:
  190. av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
  191. }
  192. if (ch)
  193. avio_w8(dynbuf, 0);
  194. avio_close_dyn_buf(dynbuf, dst);
  195. *maxread = left;
  196. return 0;
  197. }
  198. /**
  199. * Parse a text tag.
  200. */
  201. static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
  202. {
  203. uint8_t *dst;
  204. int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
  205. unsigned genre;
  206. if (taglen < 1)
  207. return;
  208. encoding = avio_r8(pb);
  209. taglen--; /* account for encoding type byte */
  210. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  211. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
  212. return;
  213. }
  214. if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
  215. && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
  216. && genre <= ID3v1_GENRE_MAX) {
  217. av_freep(&dst);
  218. dst = ff_id3v1_genre_str[genre];
  219. } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
  220. /* dst now contains the key, need to get value */
  221. key = dst;
  222. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  223. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
  224. av_freep(&key);
  225. return;
  226. }
  227. dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
  228. }
  229. else if (*dst)
  230. dict_flags |= AV_DICT_DONT_STRDUP_VAL;
  231. if (dst)
  232. av_dict_set(&s->metadata, key, dst, dict_flags);
  233. }
  234. /**
  235. * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
  236. */
  237. static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
  238. {
  239. ID3v2ExtraMetaGEOB *geob_data = NULL;
  240. ID3v2ExtraMeta *new_extra = NULL;
  241. char encoding;
  242. unsigned int len;
  243. if (taglen < 1)
  244. return;
  245. geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
  246. if (!geob_data) {
  247. av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
  248. return;
  249. }
  250. new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
  251. if (!new_extra) {
  252. av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
  253. goto fail;
  254. }
  255. /* read encoding type byte */
  256. encoding = avio_r8(pb);
  257. taglen--;
  258. /* read MIME type (always ISO-8859) */
  259. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
  260. || taglen <= 0)
  261. goto fail;
  262. /* read file name */
  263. if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
  264. || taglen <= 0)
  265. goto fail;
  266. /* read content description */
  267. if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
  268. || taglen < 0)
  269. goto fail;
  270. if (taglen) {
  271. /* save encapsulated binary data */
  272. geob_data->data = av_malloc(taglen);
  273. if (!geob_data->data) {
  274. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
  275. goto fail;
  276. }
  277. if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
  278. av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
  279. geob_data->datasize = len;
  280. } else {
  281. geob_data->data = NULL;
  282. geob_data->datasize = 0;
  283. }
  284. /* add data to the list */
  285. new_extra->tag = "GEOB";
  286. new_extra->data = geob_data;
  287. new_extra->next = *extra_meta;
  288. *extra_meta = new_extra;
  289. return;
  290. fail:
  291. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
  292. free_geobtag(geob_data);
  293. av_free(new_extra);
  294. return;
  295. }
  296. static int is_number(const char *str)
  297. {
  298. while (*str >= '0' && *str <= '9') str++;
  299. return !*str;
  300. }
  301. static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
  302. {
  303. AVDictionaryEntry *t;
  304. if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
  305. strlen(t->value) == 4 && is_number(t->value))
  306. return t;
  307. return NULL;
  308. }
  309. static void merge_date(AVDictionary **m)
  310. {
  311. AVDictionaryEntry *t;
  312. char date[17] = {0}; // YYYY-MM-DD hh:mm
  313. if (!(t = get_date_tag(*m, "TYER")) &&
  314. !(t = get_date_tag(*m, "TYE")))
  315. return;
  316. av_strlcpy(date, t->value, 5);
  317. av_dict_set(m, "TYER", NULL, 0);
  318. av_dict_set(m, "TYE", NULL, 0);
  319. if (!(t = get_date_tag(*m, "TDAT")) &&
  320. !(t = get_date_tag(*m, "TDA")))
  321. goto finish;
  322. snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
  323. av_dict_set(m, "TDAT", NULL, 0);
  324. av_dict_set(m, "TDA", NULL, 0);
  325. if (!(t = get_date_tag(*m, "TIME")) &&
  326. !(t = get_date_tag(*m, "TIM")))
  327. goto finish;
  328. snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
  329. av_dict_set(m, "TIME", NULL, 0);
  330. av_dict_set(m, "TIM", NULL, 0);
  331. finish:
  332. if (date[0])
  333. av_dict_set(m, "date", date, 0);
  334. }
  335. typedef struct ID3v2EMFunc {
  336. const char *tag3;
  337. const char *tag4;
  338. void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
  339. void (*free)();
  340. } ID3v2EMFunc;
  341. static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
  342. { "GEO", "GEOB", read_geobtag, free_geobtag },
  343. { NULL }
  344. };
  345. /**
  346. * Get the corresponding ID3v2EMFunc struct for a tag.
  347. * @param isv34 Determines if v2.2 or v2.3/4 strings are used
  348. * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
  349. */
  350. static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
  351. {
  352. int i = 0;
  353. while (id3v2_extra_meta_funcs[i].tag3) {
  354. if (!memcmp(tag,
  355. (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
  356. id3v2_extra_meta_funcs[i].tag3),
  357. (isv34 ? 4 : 3)))
  358. return &id3v2_extra_meta_funcs[i];
  359. i++;
  360. }
  361. return NULL;
  362. }
  363. static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
  364. {
  365. int isv34, tlen, unsync;
  366. char tag[5];
  367. int64_t next, end = avio_tell(s->pb) + len;
  368. int taghdrlen;
  369. const char *reason = NULL;
  370. AVIOContext pb;
  371. AVIOContext *pbx;
  372. unsigned char *buffer = NULL;
  373. int buffer_size = 0;
  374. const ID3v2EMFunc *extra_func;
  375. switch (version) {
  376. case 2:
  377. if (flags & 0x40) {
  378. reason = "compression";
  379. goto error;
  380. }
  381. isv34 = 0;
  382. taghdrlen = 6;
  383. break;
  384. case 3:
  385. case 4:
  386. isv34 = 1;
  387. taghdrlen = 10;
  388. break;
  389. default:
  390. reason = "version";
  391. goto error;
  392. }
  393. unsync = flags & 0x80;
  394. if (isv34 && flags & 0x40) /* Extended header present, just skip over it */
  395. avio_skip(s->pb, get_size(s->pb, 4));
  396. while (len >= taghdrlen) {
  397. unsigned int tflags = 0;
  398. int tunsync = 0;
  399. if (isv34) {
  400. avio_read(s->pb, tag, 4);
  401. tag[4] = 0;
  402. if(version==3){
  403. tlen = avio_rb32(s->pb);
  404. }else
  405. tlen = get_size(s->pb, 4);
  406. tflags = avio_rb16(s->pb);
  407. tunsync = tflags & ID3v2_FLAG_UNSYNCH;
  408. } else {
  409. avio_read(s->pb, tag, 3);
  410. tag[3] = 0;
  411. tlen = avio_rb24(s->pb);
  412. }
  413. if (tlen < 0 || tlen > len - taghdrlen) {
  414. av_log(s, AV_LOG_WARNING, "Invalid size in frame %s, skipping the rest of tag.\n", tag);
  415. break;
  416. }
  417. len -= taghdrlen + tlen;
  418. next = avio_tell(s->pb) + tlen;
  419. if (!tlen) {
  420. if (tag[0])
  421. av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
  422. continue;
  423. }
  424. if (tflags & ID3v2_FLAG_DATALEN) {
  425. avio_rb32(s->pb);
  426. tlen -= 4;
  427. }
  428. if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
  429. av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
  430. avio_skip(s->pb, tlen);
  431. /* check for text tag or supported special meta tag */
  432. } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
  433. if (unsync || tunsync) {
  434. int i, j;
  435. av_fast_malloc(&buffer, &buffer_size, tlen);
  436. if (!buffer) {
  437. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
  438. goto seek;
  439. }
  440. for (i = 0, j = 0; i < tlen; i++, j++) {
  441. buffer[j] = avio_r8(s->pb);
  442. if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
  443. /* Unsynchronised byte, skip it */
  444. j--;
  445. }
  446. }
  447. ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
  448. tlen = j;
  449. pbx = &pb; // read from sync buffer
  450. } else {
  451. pbx = s->pb; // read straight from input
  452. }
  453. if (tag[0] == 'T')
  454. /* parse text tag */
  455. read_ttag(s, pbx, tlen, tag);
  456. else
  457. /* parse special meta tag */
  458. extra_func->read(s, pbx, tlen, tag, extra_meta);
  459. }
  460. else if (!tag[0]) {
  461. if (tag[1])
  462. av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
  463. avio_skip(s->pb, tlen);
  464. break;
  465. }
  466. /* Skip to end of tag */
  467. seek:
  468. avio_seek(s->pb, next, SEEK_SET);
  469. }
  470. if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
  471. end += 10;
  472. error:
  473. if (reason)
  474. av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
  475. avio_seek(s->pb, end, SEEK_SET);
  476. av_free(buffer);
  477. return;
  478. }
  479. void ff_id3v2_read_all(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
  480. {
  481. int len, ret;
  482. uint8_t buf[ID3v2_HEADER_SIZE];
  483. int found_header;
  484. int64_t off;
  485. do {
  486. /* save the current offset in case there's nothing to read/skip */
  487. off = avio_tell(s->pb);
  488. ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
  489. if (ret != ID3v2_HEADER_SIZE)
  490. break;
  491. found_header = ff_id3v2_match(buf, magic);
  492. if (found_header) {
  493. /* parse ID3v2 header */
  494. len = ((buf[6] & 0x7f) << 21) |
  495. ((buf[7] & 0x7f) << 14) |
  496. ((buf[8] & 0x7f) << 7) |
  497. (buf[9] & 0x7f);
  498. ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
  499. } else {
  500. avio_seek(s->pb, off, SEEK_SET);
  501. }
  502. } while (found_header);
  503. ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
  504. ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
  505. ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
  506. merge_date(&s->metadata);
  507. }
  508. void ff_id3v2_read(AVFormatContext *s, const char *magic)
  509. {
  510. ff_id3v2_read_all(s, magic, NULL);
  511. }
  512. void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
  513. {
  514. ID3v2ExtraMeta *current = *extra_meta, *next;
  515. const ID3v2EMFunc *extra_func;
  516. while (current) {
  517. if ((extra_func = get_extra_meta_func(current->tag, 1)))
  518. extra_func->free(current->data);
  519. next = current->next;
  520. av_freep(&current);
  521. current = next;
  522. }
  523. }