id3v2.c 17 KB

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