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.

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