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.

619 lines
17KB

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