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.

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