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.

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