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.

593 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(void *obj)
  114. {
  115. ID3v2ExtraMetaGEOB *geob = obj;
  116. av_free(geob->mime_type);
  117. av_free(geob->file_name);
  118. av_free(geob->description);
  119. av_free(geob->data);
  120. av_free(geob);
  121. }
  122. /**
  123. * Decode characters to UTF-8 according to encoding type. The decoded buffer is
  124. * always null terminated. Stop reading when either *maxread bytes are read from
  125. * pb or U+0000 character is found.
  126. *
  127. * @param dst Pointer where the address of the buffer with the decoded bytes is
  128. * stored. Buffer must be freed by caller.
  129. * @param maxread Pointer to maximum number of characters to read from the
  130. * AVIOContext. After execution the value is decremented by the number of bytes
  131. * actually read.
  132. * @returns 0 if no error occurred, dst is uninitialized on error
  133. */
  134. static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
  135. uint8_t **dst, int *maxread)
  136. {
  137. int ret;
  138. uint8_t tmp;
  139. uint32_t ch = 1;
  140. int left = *maxread;
  141. unsigned int (*get)(AVIOContext*) = avio_rb16;
  142. AVIOContext *dynbuf;
  143. if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
  144. av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
  145. return ret;
  146. }
  147. switch (encoding) {
  148. case ID3v2_ENCODING_ISO8859:
  149. while (left && ch) {
  150. ch = avio_r8(pb);
  151. PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
  152. left--;
  153. }
  154. break;
  155. case ID3v2_ENCODING_UTF16BOM:
  156. if ((left -= 2) < 0) {
  157. av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
  158. avio_close_dyn_buf(dynbuf, dst);
  159. av_freep(dst);
  160. return AVERROR_INVALIDDATA;
  161. }
  162. switch (avio_rb16(pb)) {
  163. case 0xfffe:
  164. get = avio_rl16;
  165. case 0xfeff:
  166. break;
  167. default:
  168. av_log(s, AV_LOG_ERROR, "Incorrect BOM value\n");
  169. avio_close_dyn_buf(dynbuf, dst);
  170. av_freep(dst);
  171. *maxread = left;
  172. return AVERROR_INVALIDDATA;
  173. }
  174. // fall-through
  175. case ID3v2_ENCODING_UTF16BE:
  176. while ((left > 1) && ch) {
  177. GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
  178. PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
  179. }
  180. if (left < 0)
  181. left += 2; /* did not read last char from pb */
  182. break;
  183. case ID3v2_ENCODING_UTF8:
  184. while (left && ch) {
  185. ch = avio_r8(pb);
  186. avio_w8(dynbuf, ch);
  187. left--;
  188. }
  189. break;
  190. default:
  191. av_log(s, AV_LOG_WARNING, "Unknown encoding\n");
  192. }
  193. if (ch)
  194. avio_w8(dynbuf, 0);
  195. avio_close_dyn_buf(dynbuf, dst);
  196. *maxread = left;
  197. return 0;
  198. }
  199. /**
  200. * Parse a text tag.
  201. */
  202. static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen, const char *key)
  203. {
  204. uint8_t *dst;
  205. int encoding, dict_flags = AV_DICT_DONT_OVERWRITE;
  206. unsigned genre;
  207. if (taglen < 1)
  208. return;
  209. encoding = avio_r8(pb);
  210. taglen--; /* account for encoding type byte */
  211. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  212. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
  213. return;
  214. }
  215. if (!(strcmp(key, "TCON") && strcmp(key, "TCO"))
  216. && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)
  217. && genre <= ID3v1_GENRE_MAX) {
  218. av_freep(&dst);
  219. dst = ff_id3v1_genre_str[genre];
  220. } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
  221. /* dst now contains the key, need to get value */
  222. key = dst;
  223. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  224. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
  225. av_freep(&key);
  226. return;
  227. }
  228. dict_flags |= AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_STRDUP_KEY;
  229. }
  230. else if (*dst)
  231. dict_flags |= AV_DICT_DONT_STRDUP_VAL;
  232. if (dst)
  233. av_dict_set(&s->metadata, key, dst, dict_flags);
  234. }
  235. /**
  236. * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
  237. */
  238. static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen, char *tag, ID3v2ExtraMeta **extra_meta)
  239. {
  240. ID3v2ExtraMetaGEOB *geob_data = NULL;
  241. ID3v2ExtraMeta *new_extra = NULL;
  242. char encoding;
  243. unsigned int len;
  244. if (taglen < 1)
  245. return;
  246. geob_data = av_mallocz(sizeof(ID3v2ExtraMetaGEOB));
  247. if (!geob_data) {
  248. av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMetaGEOB));
  249. return;
  250. }
  251. new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
  252. if (!new_extra) {
  253. av_log(s, AV_LOG_ERROR, "Failed to alloc %zu bytes\n", sizeof(ID3v2ExtraMeta));
  254. goto fail;
  255. }
  256. /* read encoding type byte */
  257. encoding = avio_r8(pb);
  258. taglen--;
  259. /* read MIME type (always ISO-8859) */
  260. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type, &taglen) < 0
  261. || taglen <= 0)
  262. goto fail;
  263. /* read file name */
  264. if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0
  265. || taglen <= 0)
  266. goto fail;
  267. /* read content description */
  268. if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0
  269. || taglen < 0)
  270. goto fail;
  271. if (taglen) {
  272. /* save encapsulated binary data */
  273. geob_data->data = av_malloc(taglen);
  274. if (!geob_data->data) {
  275. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
  276. goto fail;
  277. }
  278. if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
  279. av_log(s, AV_LOG_WARNING, "Error reading GEOB frame, data truncated.\n");
  280. geob_data->datasize = len;
  281. } else {
  282. geob_data->data = NULL;
  283. geob_data->datasize = 0;
  284. }
  285. /* add data to the list */
  286. new_extra->tag = "GEOB";
  287. new_extra->data = geob_data;
  288. new_extra->next = *extra_meta;
  289. *extra_meta = new_extra;
  290. return;
  291. fail:
  292. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
  293. free_geobtag(geob_data);
  294. av_free(new_extra);
  295. return;
  296. }
  297. static int is_number(const char *str)
  298. {
  299. while (*str >= '0' && *str <= '9') str++;
  300. return !*str;
  301. }
  302. static AVDictionaryEntry* get_date_tag(AVDictionary *m, const char *tag)
  303. {
  304. AVDictionaryEntry *t;
  305. if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
  306. strlen(t->value) == 4 && is_number(t->value))
  307. return t;
  308. return NULL;
  309. }
  310. static void merge_date(AVDictionary **m)
  311. {
  312. AVDictionaryEntry *t;
  313. char date[17] = {0}; // YYYY-MM-DD hh:mm
  314. if (!(t = get_date_tag(*m, "TYER")) &&
  315. !(t = get_date_tag(*m, "TYE")))
  316. return;
  317. av_strlcpy(date, t->value, 5);
  318. av_dict_set(m, "TYER", NULL, 0);
  319. av_dict_set(m, "TYE", NULL, 0);
  320. if (!(t = get_date_tag(*m, "TDAT")) &&
  321. !(t = get_date_tag(*m, "TDA")))
  322. goto finish;
  323. snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
  324. av_dict_set(m, "TDAT", NULL, 0);
  325. av_dict_set(m, "TDA", NULL, 0);
  326. if (!(t = get_date_tag(*m, "TIME")) &&
  327. !(t = get_date_tag(*m, "TIM")))
  328. goto finish;
  329. snprintf(date + 10, sizeof(date) - 10, " %.2s:%.2s", t->value, t->value + 2);
  330. av_dict_set(m, "TIME", NULL, 0);
  331. av_dict_set(m, "TIM", NULL, 0);
  332. finish:
  333. if (date[0])
  334. av_dict_set(m, "date", date, 0);
  335. }
  336. typedef struct ID3v2EMFunc {
  337. const char *tag3;
  338. const char *tag4;
  339. void (*read)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta **);
  340. void (*free)(void *obj);
  341. } ID3v2EMFunc;
  342. static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
  343. { "GEO", "GEOB", read_geobtag, free_geobtag },
  344. { NULL }
  345. };
  346. /**
  347. * Get the corresponding ID3v2EMFunc struct for a tag.
  348. * @param isv34 Determines if v2.2 or v2.3/4 strings are used
  349. * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
  350. */
  351. static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
  352. {
  353. int i = 0;
  354. while (id3v2_extra_meta_funcs[i].tag3) {
  355. if (!memcmp(tag,
  356. (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
  357. id3v2_extra_meta_funcs[i].tag3),
  358. (isv34 ? 4 : 3)))
  359. return &id3v2_extra_meta_funcs[i];
  360. i++;
  361. }
  362. return NULL;
  363. }
  364. static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)
  365. {
  366. int isv34, tlen, unsync;
  367. char tag[5];
  368. int64_t next, end = avio_tell(s->pb) + len;
  369. int taghdrlen;
  370. const char *reason = NULL;
  371. AVIOContext pb;
  372. AVIOContext *pbx;
  373. unsigned char *buffer = NULL;
  374. int buffer_size = 0;
  375. const ID3v2EMFunc *extra_func;
  376. switch (version) {
  377. case 2:
  378. if (flags & 0x40) {
  379. reason = "compression";
  380. goto error;
  381. }
  382. isv34 = 0;
  383. taghdrlen = 6;
  384. break;
  385. case 3:
  386. case 4:
  387. isv34 = 1;
  388. taghdrlen = 10;
  389. break;
  390. default:
  391. reason = "version";
  392. goto error;
  393. }
  394. unsync = flags & 0x80;
  395. if (isv34 && flags & 0x40) /* Extended header present, just skip over it */
  396. avio_skip(s->pb, get_size(s->pb, 4));
  397. while (len >= taghdrlen) {
  398. unsigned int tflags = 0;
  399. int tunsync = 0;
  400. if (isv34) {
  401. avio_read(s->pb, tag, 4);
  402. tag[4] = 0;
  403. if(version==3){
  404. tlen = avio_rb32(s->pb);
  405. }else
  406. tlen = get_size(s->pb, 4);
  407. tflags = avio_rb16(s->pb);
  408. tunsync = tflags & ID3v2_FLAG_UNSYNCH;
  409. } else {
  410. avio_read(s->pb, tag, 3);
  411. tag[3] = 0;
  412. tlen = avio_rb24(s->pb);
  413. }
  414. if (tlen < 0 || tlen > len - taghdrlen) {
  415. av_log(s, AV_LOG_WARNING, "Invalid size in frame %s, skipping the rest of tag.\n", tag);
  416. break;
  417. }
  418. len -= taghdrlen + tlen;
  419. next = avio_tell(s->pb) + tlen;
  420. if (!tlen) {
  421. if (tag[0])
  422. av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n", tag);
  423. continue;
  424. }
  425. if (tflags & ID3v2_FLAG_DATALEN) {
  426. avio_rb32(s->pb);
  427. tlen -= 4;
  428. }
  429. if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {
  430. av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);
  431. avio_skip(s->pb, tlen);
  432. /* check for text tag or supported special meta tag */
  433. } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)))) {
  434. if (unsync || tunsync) {
  435. int i, j;
  436. av_fast_malloc(&buffer, &buffer_size, tlen);
  437. if (!buffer) {
  438. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
  439. goto seek;
  440. }
  441. for (i = 0, j = 0; i < tlen; i++, j++) {
  442. buffer[j] = avio_r8(s->pb);
  443. if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {
  444. /* Unsynchronised byte, skip it */
  445. j--;
  446. }
  447. }
  448. ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);
  449. tlen = j;
  450. pbx = &pb; // read from sync buffer
  451. } else {
  452. pbx = s->pb; // read straight from input
  453. }
  454. if (tag[0] == 'T')
  455. /* parse text tag */
  456. read_ttag(s, pbx, tlen, tag);
  457. else
  458. /* parse special meta tag */
  459. extra_func->read(s, pbx, tlen, tag, extra_meta);
  460. }
  461. else if (!tag[0]) {
  462. if (tag[1])
  463. av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");
  464. avio_skip(s->pb, tlen);
  465. break;
  466. }
  467. /* Skip to end of tag */
  468. seek:
  469. avio_seek(s->pb, next, SEEK_SET);
  470. }
  471. if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
  472. end += 10;
  473. error:
  474. if (reason)
  475. av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
  476. avio_seek(s->pb, end, SEEK_SET);
  477. av_free(buffer);
  478. return;
  479. }
  480. void ff_id3v2_read_all(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta)
  481. {
  482. int len, ret;
  483. uint8_t buf[ID3v2_HEADER_SIZE];
  484. int found_header;
  485. int64_t off;
  486. do {
  487. /* save the current offset in case there's nothing to read/skip */
  488. off = avio_tell(s->pb);
  489. ret = avio_read(s->pb, buf, ID3v2_HEADER_SIZE);
  490. if (ret != ID3v2_HEADER_SIZE)
  491. break;
  492. found_header = ff_id3v2_match(buf, magic);
  493. if (found_header) {
  494. /* parse ID3v2 header */
  495. len = ((buf[6] & 0x7f) << 21) |
  496. ((buf[7] & 0x7f) << 14) |
  497. ((buf[8] & 0x7f) << 7) |
  498. (buf[9] & 0x7f);
  499. ff_id3v2_parse(s, len, buf[3], buf[5], extra_meta);
  500. } else {
  501. avio_seek(s->pb, off, SEEK_SET);
  502. }
  503. } while (found_header);
  504. ff_metadata_conv(&s->metadata, NULL, ff_id3v2_34_metadata_conv);
  505. ff_metadata_conv(&s->metadata, NULL, id3v2_2_metadata_conv);
  506. ff_metadata_conv(&s->metadata, NULL, ff_id3v2_4_metadata_conv);
  507. merge_date(&s->metadata);
  508. }
  509. void ff_id3v2_read(AVFormatContext *s, const char *magic)
  510. {
  511. ff_id3v2_read_all(s, magic, NULL);
  512. }
  513. void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
  514. {
  515. ID3v2ExtraMeta *current = *extra_meta, *next;
  516. const ID3v2EMFunc *extra_func;
  517. while (current) {
  518. if ((extra_func = get_extra_meta_func(current->tag, 1)))
  519. extra_func->free(current->data);
  520. next = current->next;
  521. av_freep(&current);
  522. current = next;
  523. }
  524. }