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.

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