id3v2.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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 "config.h"
  28. #if CONFIG_ZLIB
  29. #include <zlib.h>
  30. #endif
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/bprint.h"
  33. #include "libavutil/dict.h"
  34. #include "libavutil/intreadwrite.h"
  35. #include "libavutil/mem.h"
  36. #include "libavcodec/png.h"
  37. #include "avio_internal.h"
  38. #include "demux.h"
  39. #include "id3v1.h"
  40. #include "id3v2.h"
  41. const AVMetadataConv ff_id3v2_34_metadata_conv[] = {
  42. { "TALB", "album" },
  43. { "TCOM", "composer" },
  44. { "TCON", "genre" },
  45. { "TCOP", "copyright" },
  46. { "TENC", "encoded_by" },
  47. { "TIT2", "title" },
  48. { "TLAN", "language" },
  49. { "TPE1", "artist" },
  50. { "TPE2", "album_artist" },
  51. { "TPE3", "performer" },
  52. { "TPOS", "disc" },
  53. { "TPUB", "publisher" },
  54. { "TRCK", "track" },
  55. { "TSSE", "encoder" },
  56. { "USLT", "lyrics" },
  57. { 0 }
  58. };
  59. const AVMetadataConv ff_id3v2_4_metadata_conv[] = {
  60. { "TCMP", "compilation" },
  61. { "TDRC", "date" },
  62. { "TDRL", "date" },
  63. { "TDEN", "creation_time" },
  64. { "TSOA", "album-sort" },
  65. { "TSOP", "artist-sort" },
  66. { "TSOT", "title-sort" },
  67. { "TIT1", "grouping" },
  68. { 0 }
  69. };
  70. static const AVMetadataConv id3v2_2_metadata_conv[] = {
  71. { "TAL", "album" },
  72. { "TCO", "genre" },
  73. { "TCP", "compilation" },
  74. { "TT2", "title" },
  75. { "TEN", "encoded_by" },
  76. { "TP1", "artist" },
  77. { "TP2", "album_artist" },
  78. { "TP3", "performer" },
  79. { "TRK", "track" },
  80. { 0 }
  81. };
  82. const char ff_id3v2_tags[][4] = {
  83. "TALB", "TBPM", "TCOM", "TCON", "TCOP", "TDLY", "TENC", "TEXT",
  84. "TFLT", "TIT1", "TIT2", "TIT3", "TKEY", "TLAN", "TLEN", "TMED",
  85. "TOAL", "TOFN", "TOLY", "TOPE", "TOWN", "TPE1", "TPE2", "TPE3",
  86. "TPE4", "TPOS", "TPUB", "TRCK", "TRSN", "TRSO", "TSRC", "TSSE",
  87. { 0 },
  88. };
  89. const char ff_id3v2_4_tags[][4] = {
  90. "TDEN", "TDOR", "TDRC", "TDRL", "TDTG", "TIPL", "TMCL", "TMOO",
  91. "TPRO", "TSOA", "TSOP", "TSOT", "TSST",
  92. { 0 },
  93. };
  94. const char ff_id3v2_3_tags[][4] = {
  95. "TDAT", "TIME", "TORY", "TRDA", "TSIZ", "TYER",
  96. { 0 },
  97. };
  98. const char * const ff_id3v2_picture_types[21] = {
  99. "Other",
  100. "32x32 pixels 'file icon'",
  101. "Other file icon",
  102. "Cover (front)",
  103. "Cover (back)",
  104. "Leaflet page",
  105. "Media (e.g. label side of CD)",
  106. "Lead artist/lead performer/soloist",
  107. "Artist/performer",
  108. "Conductor",
  109. "Band/Orchestra",
  110. "Composer",
  111. "Lyricist/text writer",
  112. "Recording Location",
  113. "During recording",
  114. "During performance",
  115. "Movie/video screen capture",
  116. "A bright coloured fish",
  117. "Illustration",
  118. "Band/artist logotype",
  119. "Publisher/Studio logotype",
  120. };
  121. const CodecMime ff_id3v2_mime_tags[] = {
  122. { "image/gif", AV_CODEC_ID_GIF },
  123. { "image/jpeg", AV_CODEC_ID_MJPEG },
  124. { "image/jpg", AV_CODEC_ID_MJPEG },
  125. { "image/png", AV_CODEC_ID_PNG },
  126. { "image/tiff", AV_CODEC_ID_TIFF },
  127. { "image/bmp", AV_CODEC_ID_BMP },
  128. { "image/webp", AV_CODEC_ID_WEBP },
  129. { "JPG", AV_CODEC_ID_MJPEG }, /* ID3v2.2 */
  130. { "PNG", AV_CODEC_ID_PNG }, /* ID3v2.2 */
  131. { "", AV_CODEC_ID_NONE },
  132. };
  133. int ff_id3v2_match(const uint8_t *buf, const char *magic)
  134. {
  135. return buf[0] == magic[0] &&
  136. buf[1] == magic[1] &&
  137. buf[2] == magic[2] &&
  138. buf[3] != 0xff &&
  139. buf[4] != 0xff &&
  140. (buf[6] & 0x80) == 0 &&
  141. (buf[7] & 0x80) == 0 &&
  142. (buf[8] & 0x80) == 0 &&
  143. (buf[9] & 0x80) == 0;
  144. }
  145. int ff_id3v2_tag_len(const uint8_t *buf)
  146. {
  147. int len = ((buf[6] & 0x7f) << 21) +
  148. ((buf[7] & 0x7f) << 14) +
  149. ((buf[8] & 0x7f) << 7) +
  150. (buf[9] & 0x7f) +
  151. ID3v2_HEADER_SIZE;
  152. if (buf[5] & 0x10)
  153. len += ID3v2_HEADER_SIZE;
  154. return len;
  155. }
  156. static unsigned int get_size(AVIOContext *s, int len)
  157. {
  158. int v = 0;
  159. while (len--)
  160. v = (v << 7) + (avio_r8(s) & 0x7F);
  161. return v;
  162. }
  163. static unsigned int size_to_syncsafe(unsigned int size)
  164. {
  165. return (((size) & (0x7f << 0)) >> 0) +
  166. (((size) & (0x7f << 8)) >> 1) +
  167. (((size) & (0x7f << 16)) >> 2) +
  168. (((size) & (0x7f << 24)) >> 3);
  169. }
  170. /* No real verification, only check that the tag consists of
  171. * a combination of capital alpha-numerical characters */
  172. static int is_tag(const char *buf, unsigned int len)
  173. {
  174. if (!len)
  175. return 0;
  176. while (len--)
  177. if ((buf[len] < 'A' ||
  178. buf[len] > 'Z') &&
  179. (buf[len] < '0' ||
  180. buf[len] > '9'))
  181. return 0;
  182. return 1;
  183. }
  184. /**
  185. * Return 1 if the tag of length len at the given offset is valid, 0 if not, -1 on error
  186. */
  187. static int check_tag(AVIOContext *s, int offset, unsigned int len)
  188. {
  189. char tag[4];
  190. if (len > 4 ||
  191. avio_seek(s, offset, SEEK_SET) < 0 ||
  192. avio_read(s, tag, len) < (int)len)
  193. return -1;
  194. else if (!AV_RB32(tag) || is_tag(tag, len))
  195. return 1;
  196. return 0;
  197. }
  198. /**
  199. * Free GEOB type extra metadata.
  200. */
  201. static void free_geobtag(void *obj)
  202. {
  203. ID3v2ExtraMetaGEOB *geob = obj;
  204. av_freep(&geob->mime_type);
  205. av_freep(&geob->file_name);
  206. av_freep(&geob->description);
  207. av_freep(&geob->data);
  208. }
  209. /**
  210. * Decode characters to UTF-8 according to encoding type. The decoded buffer is
  211. * always null terminated. Stop reading when either *maxread bytes are read from
  212. * pb or U+0000 character is found.
  213. *
  214. * @param dst Pointer where the address of the buffer with the decoded bytes is
  215. * stored. Buffer must be freed by caller.
  216. * @param maxread Pointer to maximum number of characters to read from the
  217. * AVIOContext. After execution the value is decremented by the number of bytes
  218. * actually read.
  219. * @returns 0 if no error occurred, dst is uninitialized on error
  220. */
  221. static int decode_str(AVFormatContext *s, AVIOContext *pb, int encoding,
  222. uint8_t **dst, int *maxread)
  223. {
  224. int ret;
  225. uint8_t tmp;
  226. uint32_t ch = 1;
  227. int left = *maxread, dynsize;
  228. unsigned int (*get)(AVIOContext*) = avio_rb16;
  229. AVIOContext *dynbuf;
  230. if ((ret = avio_open_dyn_buf(&dynbuf)) < 0) {
  231. av_log(s, AV_LOG_ERROR, "Error opening memory stream\n");
  232. return ret;
  233. }
  234. switch (encoding) {
  235. case ID3v2_ENCODING_ISO8859:
  236. while (left && ch) {
  237. ch = avio_r8(pb);
  238. PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
  239. left--;
  240. }
  241. break;
  242. case ID3v2_ENCODING_UTF16BOM:
  243. if ((left -= 2) < 0) {
  244. av_log(s, AV_LOG_ERROR, "Cannot read BOM value, input too short\n");
  245. ffio_free_dyn_buf(&dynbuf);
  246. *dst = NULL;
  247. return AVERROR_INVALIDDATA;
  248. }
  249. uint16_t bom = avio_rb16(pb);
  250. switch (bom) {
  251. case 0xfffe:
  252. get = avio_rl16;
  253. case 0xfeff:
  254. break;
  255. default:
  256. av_log(s, AV_LOG_ERROR, "Incorrect BOM value: 0x%x\n", bom);
  257. ffio_free_dyn_buf(&dynbuf);
  258. *dst = NULL;
  259. *maxread = left;
  260. return AVERROR_INVALIDDATA;
  261. }
  262. // fall-through
  263. case ID3v2_ENCODING_UTF16BE:
  264. while ((left > 1) && ch) {
  265. GET_UTF16(ch, ((left -= 2) >= 0 ? get(pb) : 0), break;)
  266. PUT_UTF8(ch, tmp, avio_w8(dynbuf, tmp);)
  267. }
  268. if (left < 0)
  269. left += 2; /* did not read last char from pb */
  270. break;
  271. case ID3v2_ENCODING_UTF8:
  272. while (left && ch) {
  273. ch = avio_r8(pb);
  274. avio_w8(dynbuf, ch);
  275. left--;
  276. }
  277. break;
  278. default:
  279. av_log(s, AV_LOG_WARNING, "Unknown encoding %d\n", encoding);
  280. }
  281. if (ch)
  282. avio_w8(dynbuf, 0);
  283. dynsize = avio_close_dyn_buf(dynbuf, dst);
  284. if (dynsize <= 0) {
  285. av_freep(dst);
  286. return AVERROR(ENOMEM);
  287. }
  288. *maxread = left;
  289. return 0;
  290. }
  291. /**
  292. * Parse a text tag.
  293. */
  294. static void read_ttag(AVFormatContext *s, AVIOContext *pb, int taglen,
  295. AVDictionary **metadata, const char *key)
  296. {
  297. uint8_t *dst;
  298. int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
  299. unsigned genre;
  300. if (taglen < 1)
  301. return;
  302. encoding = avio_r8(pb);
  303. taglen--; /* account for encoding type byte */
  304. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  305. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
  306. return;
  307. }
  308. if (!(strcmp(key, "TCON") && strcmp(key, "TCO")) &&
  309. (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1) &&
  310. genre <= ID3v1_GENRE_MAX) {
  311. av_freep(&dst);
  312. dst = av_strdup(ff_id3v1_genre_str[genre]);
  313. } else if (!(strcmp(key, "TXXX") && strcmp(key, "TXX"))) {
  314. /* dst now contains the key, need to get value */
  315. key = dst;
  316. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  317. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", key);
  318. av_freep(&key);
  319. return;
  320. }
  321. dict_flags |= AV_DICT_DONT_STRDUP_KEY;
  322. } else if (!*dst)
  323. av_freep(&dst);
  324. if (dst)
  325. av_dict_set(metadata, key, dst, dict_flags);
  326. }
  327. static void read_uslt(AVFormatContext *s, AVIOContext *pb, int taglen,
  328. AVDictionary **metadata)
  329. {
  330. uint8_t lang[4];
  331. uint8_t *descriptor = NULL; // 'Content descriptor'
  332. uint8_t *text;
  333. char *key;
  334. int encoding;
  335. int ok = 0;
  336. if (taglen < 4)
  337. goto error;
  338. encoding = avio_r8(pb);
  339. taglen--;
  340. if (avio_read(pb, lang, 3) < 3)
  341. goto error;
  342. lang[3] = '\0';
  343. taglen -= 3;
  344. if (decode_str(s, pb, encoding, &descriptor, &taglen) < 0 || taglen < 0)
  345. goto error;
  346. if (decode_str(s, pb, encoding, &text, &taglen) < 0 || taglen < 0)
  347. goto error;
  348. // FFmpeg does not support hierarchical metadata, so concatenate the keys.
  349. key = av_asprintf("lyrics-%s%s%s", descriptor[0] ? (char *)descriptor : "",
  350. descriptor[0] ? "-" : "",
  351. lang);
  352. if (!key) {
  353. av_free(text);
  354. goto error;
  355. }
  356. av_dict_set(metadata, key, text,
  357. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  358. ok = 1;
  359. error:
  360. if (!ok)
  361. av_log(s, AV_LOG_ERROR, "Error reading lyrics, skipped\n");
  362. av_free(descriptor);
  363. }
  364. /**
  365. * Parse a comment tag.
  366. */
  367. static void read_comment(AVFormatContext *s, AVIOContext *pb, int taglen,
  368. AVDictionary **metadata)
  369. {
  370. const char *key = "comment";
  371. uint8_t *dst;
  372. int encoding, dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_VAL;
  373. av_unused int language;
  374. if (taglen < 4)
  375. return;
  376. encoding = avio_r8(pb);
  377. language = avio_rl24(pb);
  378. taglen -= 4;
  379. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  380. av_log(s, AV_LOG_ERROR, "Error reading comment frame, skipped\n");
  381. return;
  382. }
  383. if (dst && !*dst)
  384. av_freep(&dst);
  385. if (dst) {
  386. key = (const char *) dst;
  387. dict_flags |= AV_DICT_DONT_STRDUP_KEY;
  388. }
  389. if (decode_str(s, pb, encoding, &dst, &taglen) < 0) {
  390. av_log(s, AV_LOG_ERROR, "Error reading comment frame, skipped\n");
  391. if (dict_flags & AV_DICT_DONT_STRDUP_KEY)
  392. av_freep((void*)&key);
  393. return;
  394. }
  395. if (dst)
  396. av_dict_set(metadata, key, (const char *) dst, dict_flags);
  397. }
  398. typedef struct ExtraMetaList {
  399. ID3v2ExtraMeta *head, *tail;
  400. } ExtraMetaList;
  401. static void list_append(ID3v2ExtraMeta *new_elem, ExtraMetaList *list)
  402. {
  403. if (list->tail)
  404. list->tail->next = new_elem;
  405. else
  406. list->head = new_elem;
  407. list->tail = new_elem;
  408. }
  409. /**
  410. * Parse GEOB tag into a ID3v2ExtraMetaGEOB struct.
  411. */
  412. static void read_geobtag(AVFormatContext *s, AVIOContext *pb, int taglen,
  413. const char *tag, ExtraMetaList *extra_meta, int isv34)
  414. {
  415. ID3v2ExtraMetaGEOB *geob_data = NULL;
  416. ID3v2ExtraMeta *new_extra = NULL;
  417. char encoding;
  418. unsigned int len;
  419. if (taglen < 1)
  420. return;
  421. new_extra = av_mallocz(sizeof(ID3v2ExtraMeta));
  422. if (!new_extra) {
  423. av_log(s, AV_LOG_ERROR, "Failed to alloc %"SIZE_SPECIFIER" bytes\n",
  424. sizeof(ID3v2ExtraMeta));
  425. return;
  426. }
  427. geob_data = &new_extra->data.geob;
  428. /* read encoding type byte */
  429. encoding = avio_r8(pb);
  430. taglen--;
  431. /* read MIME type (always ISO-8859) */
  432. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &geob_data->mime_type,
  433. &taglen) < 0 ||
  434. taglen <= 0)
  435. goto fail;
  436. /* read file name */
  437. if (decode_str(s, pb, encoding, &geob_data->file_name, &taglen) < 0 ||
  438. taglen <= 0)
  439. goto fail;
  440. /* read content description */
  441. if (decode_str(s, pb, encoding, &geob_data->description, &taglen) < 0 ||
  442. taglen < 0)
  443. goto fail;
  444. if (taglen) {
  445. /* save encapsulated binary data */
  446. geob_data->data = av_malloc(taglen);
  447. if (!geob_data->data) {
  448. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", taglen);
  449. goto fail;
  450. }
  451. if ((len = avio_read(pb, geob_data->data, taglen)) < taglen)
  452. av_log(s, AV_LOG_WARNING,
  453. "Error reading GEOB frame, data truncated.\n");
  454. geob_data->datasize = len;
  455. } else {
  456. geob_data->data = NULL;
  457. geob_data->datasize = 0;
  458. }
  459. /* add data to the list */
  460. new_extra->tag = "GEOB";
  461. list_append(new_extra, extra_meta);
  462. return;
  463. fail:
  464. av_log(s, AV_LOG_ERROR, "Error reading frame %s, skipped\n", tag);
  465. free_geobtag(geob_data);
  466. av_free(new_extra);
  467. return;
  468. }
  469. static int is_number(const char *str)
  470. {
  471. while (*str >= '0' && *str <= '9')
  472. str++;
  473. return !*str;
  474. }
  475. static AVDictionaryEntry *get_date_tag(AVDictionary *m, const char *tag)
  476. {
  477. AVDictionaryEntry *t;
  478. if ((t = av_dict_get(m, tag, NULL, AV_DICT_MATCH_CASE)) &&
  479. strlen(t->value) == 4 && is_number(t->value))
  480. return t;
  481. return NULL;
  482. }
  483. static void merge_date(AVDictionary **m)
  484. {
  485. AVDictionaryEntry *t;
  486. char date[17] = { 0 }; // YYYY-MM-DD hh:mm
  487. if (!(t = get_date_tag(*m, "TYER")) &&
  488. !(t = get_date_tag(*m, "TYE")))
  489. return;
  490. av_strlcpy(date, t->value, 5);
  491. av_dict_set(m, "TYER", NULL, 0);
  492. av_dict_set(m, "TYE", NULL, 0);
  493. if (!(t = get_date_tag(*m, "TDAT")) &&
  494. !(t = get_date_tag(*m, "TDA")))
  495. goto finish;
  496. snprintf(date + 4, sizeof(date) - 4, "-%.2s-%.2s", t->value + 2, t->value);
  497. av_dict_set(m, "TDAT", NULL, 0);
  498. av_dict_set(m, "TDA", NULL, 0);
  499. if (!(t = get_date_tag(*m, "TIME")) &&
  500. !(t = get_date_tag(*m, "TIM")))
  501. goto finish;
  502. snprintf(date + 10, sizeof(date) - 10,
  503. " %.2s:%.2s", t->value, t->value + 2);
  504. av_dict_set(m, "TIME", NULL, 0);
  505. av_dict_set(m, "TIM", NULL, 0);
  506. finish:
  507. if (date[0])
  508. av_dict_set(m, "date", date, 0);
  509. }
  510. static void free_apic(void *obj)
  511. {
  512. ID3v2ExtraMetaAPIC *apic = obj;
  513. av_buffer_unref(&apic->buf);
  514. av_freep(&apic->description);
  515. }
  516. static void rstrip_spaces(char *buf)
  517. {
  518. size_t len = strlen(buf);
  519. while (len > 0 && buf[len - 1] == ' ')
  520. buf[--len] = 0;
  521. }
  522. static void read_apic(AVFormatContext *s, AVIOContext *pb, int taglen,
  523. const char *tag, ExtraMetaList *extra_meta, int isv34)
  524. {
  525. int enc, pic_type;
  526. char mimetype[64] = {0};
  527. const CodecMime *mime = ff_id3v2_mime_tags;
  528. enum AVCodecID id = AV_CODEC_ID_NONE;
  529. ID3v2ExtraMetaAPIC *apic = NULL;
  530. ID3v2ExtraMeta *new_extra = NULL;
  531. int64_t end = avio_tell(pb) + taglen;
  532. if (taglen <= 4 || (!isv34 && taglen <= 6))
  533. goto fail;
  534. new_extra = av_mallocz(sizeof(*new_extra));
  535. if (!new_extra)
  536. goto fail;
  537. apic = &new_extra->data.apic;
  538. enc = avio_r8(pb);
  539. taglen--;
  540. /* mimetype */
  541. if (isv34) {
  542. int ret = avio_get_str(pb, taglen, mimetype, sizeof(mimetype));
  543. if (ret < 0 || ret >= taglen)
  544. goto fail;
  545. taglen -= ret;
  546. } else {
  547. if (avio_read(pb, mimetype, 3) < 0)
  548. goto fail;
  549. mimetype[3] = 0;
  550. taglen -= 3;
  551. }
  552. while (mime->id != AV_CODEC_ID_NONE) {
  553. if (!av_strncasecmp(mime->str, mimetype, sizeof(mimetype))) {
  554. id = mime->id;
  555. break;
  556. }
  557. mime++;
  558. }
  559. if (id == AV_CODEC_ID_NONE) {
  560. av_log(s, AV_LOG_WARNING,
  561. "Unknown attached picture mimetype: %s, skipping.\n", mimetype);
  562. goto fail;
  563. }
  564. apic->id = id;
  565. /* picture type */
  566. pic_type = avio_r8(pb);
  567. taglen--;
  568. if (pic_type < 0 || pic_type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types)) {
  569. av_log(s, AV_LOG_WARNING, "Unknown attached picture type %d.\n",
  570. pic_type);
  571. pic_type = 0;
  572. }
  573. apic->type = ff_id3v2_picture_types[pic_type];
  574. /* description and picture data */
  575. if (decode_str(s, pb, enc, &apic->description, &taglen) < 0) {
  576. av_log(s, AV_LOG_ERROR,
  577. "Error decoding attached picture description.\n");
  578. goto fail;
  579. }
  580. apic->buf = av_buffer_alloc(taglen + AV_INPUT_BUFFER_PADDING_SIZE);
  581. if (!apic->buf || !taglen || avio_read(pb, apic->buf->data, taglen) != taglen)
  582. goto fail;
  583. memset(apic->buf->data + taglen, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  584. new_extra->tag = "APIC";
  585. // The description must be unique, and some ID3v2 tag writers add spaces
  586. // to write several APIC entries with the same description.
  587. rstrip_spaces(apic->description);
  588. list_append(new_extra, extra_meta);
  589. return;
  590. fail:
  591. if (apic)
  592. free_apic(apic);
  593. av_freep(&new_extra);
  594. avio_seek(pb, end, SEEK_SET);
  595. }
  596. static void free_chapter(void *obj)
  597. {
  598. ID3v2ExtraMetaCHAP *chap = obj;
  599. av_freep(&chap->element_id);
  600. av_dict_free(&chap->meta);
  601. }
  602. static void read_chapter(AVFormatContext *s, AVIOContext *pb, int len,
  603. const char *ttag, ExtraMetaList *extra_meta, int isv34)
  604. {
  605. int taglen;
  606. char tag[5];
  607. ID3v2ExtraMeta *new_extra = NULL;
  608. ID3v2ExtraMetaCHAP *chap = NULL;
  609. new_extra = av_mallocz(sizeof(*new_extra));
  610. if (!new_extra)
  611. return;
  612. chap = &new_extra->data.chap;
  613. if (decode_str(s, pb, 0, &chap->element_id, &len) < 0)
  614. goto fail;
  615. if (len < 16)
  616. goto fail;
  617. chap->start = avio_rb32(pb);
  618. chap->end = avio_rb32(pb);
  619. avio_skip(pb, 8);
  620. len -= 16;
  621. while (len > 10) {
  622. if (avio_read(pb, tag, 4) < 4)
  623. goto fail;
  624. tag[4] = 0;
  625. taglen = avio_rb32(pb);
  626. avio_skip(pb, 2);
  627. len -= 10;
  628. if (taglen < 0 || taglen > len)
  629. goto fail;
  630. if (tag[0] == 'T')
  631. read_ttag(s, pb, taglen, &chap->meta, tag);
  632. else
  633. avio_skip(pb, taglen);
  634. len -= taglen;
  635. }
  636. ff_metadata_conv(&chap->meta, NULL, ff_id3v2_34_metadata_conv);
  637. ff_metadata_conv(&chap->meta, NULL, ff_id3v2_4_metadata_conv);
  638. new_extra->tag = "CHAP";
  639. list_append(new_extra, extra_meta);
  640. return;
  641. fail:
  642. free_chapter(chap);
  643. av_freep(&new_extra);
  644. }
  645. static void free_priv(void *obj)
  646. {
  647. ID3v2ExtraMetaPRIV *priv = obj;
  648. av_freep(&priv->owner);
  649. av_freep(&priv->data);
  650. }
  651. static void read_priv(AVFormatContext *s, AVIOContext *pb, int taglen,
  652. const char *tag, ExtraMetaList *extra_meta, int isv34)
  653. {
  654. ID3v2ExtraMeta *meta;
  655. ID3v2ExtraMetaPRIV *priv;
  656. meta = av_mallocz(sizeof(*meta));
  657. if (!meta)
  658. return;
  659. priv = &meta->data.priv;
  660. if (decode_str(s, pb, ID3v2_ENCODING_ISO8859, &priv->owner, &taglen) < 0)
  661. goto fail;
  662. priv->data = av_malloc(taglen);
  663. if (!priv->data)
  664. goto fail;
  665. priv->datasize = taglen;
  666. if (avio_read(pb, priv->data, priv->datasize) != priv->datasize)
  667. goto fail;
  668. meta->tag = "PRIV";
  669. list_append(meta, extra_meta);
  670. return;
  671. fail:
  672. free_priv(priv);
  673. av_freep(&meta);
  674. }
  675. typedef struct ID3v2EMFunc {
  676. const char *tag3;
  677. const char *tag4;
  678. void (*read)(AVFormatContext *s, AVIOContext *pb, int taglen,
  679. const char *tag, ExtraMetaList *extra_meta,
  680. int isv34);
  681. void (*free)(void *obj);
  682. } ID3v2EMFunc;
  683. static const ID3v2EMFunc id3v2_extra_meta_funcs[] = {
  684. { "GEO", "GEOB", read_geobtag, free_geobtag },
  685. { "PIC", "APIC", read_apic, free_apic },
  686. { "CHAP","CHAP", read_chapter, free_chapter },
  687. { "PRIV","PRIV", read_priv, free_priv },
  688. { NULL }
  689. };
  690. /**
  691. * Get the corresponding ID3v2EMFunc struct for a tag.
  692. * @param isv34 Determines if v2.2 or v2.3/4 strings are used
  693. * @return A pointer to the ID3v2EMFunc struct if found, NULL otherwise.
  694. */
  695. static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)
  696. {
  697. int i = 0;
  698. while (id3v2_extra_meta_funcs[i].tag3) {
  699. if (tag && !memcmp(tag,
  700. (isv34 ? id3v2_extra_meta_funcs[i].tag4 :
  701. id3v2_extra_meta_funcs[i].tag3),
  702. (isv34 ? 4 : 3)))
  703. return &id3v2_extra_meta_funcs[i];
  704. i++;
  705. }
  706. return NULL;
  707. }
  708. static void id3v2_parse(AVIOContext *pb, AVDictionary **metadata,
  709. AVFormatContext *s, int len, uint8_t version,
  710. uint8_t flags, ExtraMetaList *extra_meta)
  711. {
  712. int isv34, unsync;
  713. unsigned tlen;
  714. char tag[5];
  715. int64_t next, end = avio_tell(pb);
  716. int taghdrlen;
  717. const char *reason = NULL;
  718. FFIOContext pb_local;
  719. AVIOContext *pbx;
  720. unsigned char *buffer = NULL;
  721. int buffer_size = 0;
  722. const ID3v2EMFunc *extra_func = NULL;
  723. unsigned char *uncompressed_buffer = NULL;
  724. av_unused int uncompressed_buffer_size = 0;
  725. const char *comm_frame;
  726. if (end > INT64_MAX - len - 10)
  727. return;
  728. end += len;
  729. av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);
  730. switch (version) {
  731. case 2:
  732. if (flags & 0x40) {
  733. reason = "compression";
  734. goto error;
  735. }
  736. isv34 = 0;
  737. taghdrlen = 6;
  738. comm_frame = "COM";
  739. break;
  740. case 3:
  741. case 4:
  742. isv34 = 1;
  743. taghdrlen = 10;
  744. comm_frame = "COMM";
  745. break;
  746. default:
  747. reason = "version";
  748. goto error;
  749. }
  750. unsync = flags & 0x80;
  751. if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */
  752. int extlen = get_size(pb, 4);
  753. if (version == 4)
  754. /* In v2.4 the length includes the length field we just read. */
  755. extlen -= 4;
  756. if (extlen < 0) {
  757. reason = "invalid extended header length";
  758. goto error;
  759. }
  760. avio_skip(pb, extlen);
  761. len -= extlen + 4;
  762. if (len < 0) {
  763. reason = "extended header too long.";
  764. goto error;
  765. }
  766. }
  767. while (len >= taghdrlen) {
  768. unsigned int tflags = 0;
  769. int tunsync = 0;
  770. int tcomp = 0;
  771. int tencr = 0;
  772. av_unused unsigned long dlen;
  773. if (isv34) {
  774. if (avio_read(pb, tag, 4) < 4)
  775. break;
  776. tag[4] = 0;
  777. if (version == 3) {
  778. tlen = avio_rb32(pb);
  779. } else {
  780. /* some encoders incorrectly uses v3 sizes instead of syncsafe ones
  781. * so check the next tag to see which one to use */
  782. tlen = avio_rb32(pb);
  783. if (tlen > 0x7f) {
  784. if (tlen < len) {
  785. int64_t cur = avio_tell(pb);
  786. if (ffio_ensure_seekback(pb, 2 /* tflags */ + tlen + 4 /* next tag */))
  787. break;
  788. if (check_tag(pb, cur + 2 + size_to_syncsafe(tlen), 4) == 1)
  789. tlen = size_to_syncsafe(tlen);
  790. else if (check_tag(pb, cur + 2 + tlen, 4) != 1)
  791. break;
  792. avio_seek(pb, cur, SEEK_SET);
  793. } else
  794. tlen = size_to_syncsafe(tlen);
  795. }
  796. }
  797. tflags = avio_rb16(pb);
  798. tunsync = tflags & ID3v2_FLAG_UNSYNCH;
  799. } else {
  800. if (avio_read(pb, tag, 3) < 3)
  801. break;
  802. tag[3] = 0;
  803. tlen = avio_rb24(pb);
  804. }
  805. if (tlen > (1<<28))
  806. break;
  807. len -= taghdrlen + tlen;
  808. if (len < 0)
  809. break;
  810. next = avio_tell(pb) + tlen;
  811. if (!tlen) {
  812. if (tag[0])
  813. av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",
  814. tag);
  815. continue;
  816. }
  817. if (tflags & ID3v2_FLAG_DATALEN) {
  818. if (tlen < 4)
  819. break;
  820. dlen = avio_rb32(pb);
  821. tlen -= 4;
  822. } else
  823. dlen = tlen;
  824. tcomp = tflags & ID3v2_FLAG_COMPRESSION;
  825. tencr = tflags & ID3v2_FLAG_ENCRYPTION;
  826. /* skip encrypted tags and, if no zlib, compressed tags */
  827. if (tencr || (!CONFIG_ZLIB && tcomp)) {
  828. const char *type;
  829. if (!tcomp)
  830. type = "encrypted";
  831. else if (!tencr)
  832. type = "compressed";
  833. else
  834. type = "encrypted and compressed";
  835. av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);
  836. avio_skip(pb, tlen);
  837. /* check for text tag or supported special meta tag */
  838. } else if (tag[0] == 'T' ||
  839. !memcmp(tag, "USLT", 4) ||
  840. !strcmp(tag, comm_frame) ||
  841. (extra_meta &&
  842. (extra_func = get_extra_meta_func(tag, isv34)))) {
  843. pbx = pb;
  844. if (unsync || tunsync || tcomp) {
  845. av_fast_malloc(&buffer, &buffer_size, tlen);
  846. if (!buffer) {
  847. av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);
  848. goto seek;
  849. }
  850. }
  851. if (unsync || tunsync) {
  852. uint8_t *b = buffer;
  853. uint8_t *t = buffer;
  854. uint8_t *end = t + tlen;
  855. if (avio_read(pb, buffer, tlen) != tlen) {
  856. av_log(s, AV_LOG_ERROR, "Failed to read tag data\n");
  857. goto seek;
  858. }
  859. while (t != end) {
  860. *b++ = *t++;
  861. if (t != end && t[-1] == 0xff && !t[0])
  862. t++;
  863. }
  864. ffio_init_read_context(&pb_local, buffer, b - buffer);
  865. tlen = b - buffer;
  866. pbx = &pb_local.pub; // read from sync buffer
  867. }
  868. #if CONFIG_ZLIB
  869. if (tcomp) {
  870. int err;
  871. av_log(s, AV_LOG_DEBUG, "Compressed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);
  872. if (tlen <= 0)
  873. goto seek;
  874. if (dlen / 32768 > tlen)
  875. goto seek;
  876. av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);
  877. if (!uncompressed_buffer) {
  878. av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);
  879. goto seek;
  880. }
  881. if (!(unsync || tunsync)) {
  882. err = avio_read(pb, buffer, tlen);
  883. if (err < 0) {
  884. av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");
  885. goto seek;
  886. }
  887. tlen = err;
  888. }
  889. err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);
  890. if (err != Z_OK) {
  891. av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);
  892. goto seek;
  893. }
  894. ffio_init_read_context(&pb_local, uncompressed_buffer, dlen);
  895. tlen = dlen;
  896. pbx = &pb_local.pub; // read from sync buffer
  897. }
  898. #endif
  899. if (tag[0] == 'T')
  900. /* parse text tag */
  901. read_ttag(s, pbx, tlen, metadata, tag);
  902. else if (!memcmp(tag, "USLT", 4))
  903. read_uslt(s, pbx, tlen, metadata);
  904. else if (!strcmp(tag, comm_frame))
  905. read_comment(s, pbx, tlen, metadata);
  906. else
  907. /* parse special meta tag */
  908. extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);
  909. } else if (!tag[0]) {
  910. if (tag[1])
  911. av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");
  912. avio_skip(pb, tlen);
  913. break;
  914. }
  915. /* Skip to end of tag */
  916. seek:
  917. avio_seek(pb, next, SEEK_SET);
  918. }
  919. /* Footer preset, always 10 bytes, skip over it */
  920. if (version == 4 && flags & 0x10)
  921. end += 10;
  922. error:
  923. if (reason)
  924. av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",
  925. version, reason);
  926. avio_seek(pb, end, SEEK_SET);
  927. av_free(buffer);
  928. av_free(uncompressed_buffer);
  929. return;
  930. }
  931. static void id3v2_read_internal(AVIOContext *pb, AVDictionary **metadata,
  932. AVFormatContext *s, const char *magic,
  933. ID3v2ExtraMeta **extra_metap, int64_t max_search_size)
  934. {
  935. int len, ret;
  936. uint8_t buf[ID3v2_HEADER_SIZE];
  937. ExtraMetaList extra_meta = { NULL };
  938. int found_header;
  939. int64_t start, off;
  940. if (extra_metap)
  941. *extra_metap = NULL;
  942. if (max_search_size && max_search_size < ID3v2_HEADER_SIZE)
  943. return;
  944. start = avio_tell(pb);
  945. do {
  946. /* save the current offset in case there's nothing to read/skip */
  947. off = avio_tell(pb);
  948. if (max_search_size && off - start >= max_search_size - ID3v2_HEADER_SIZE) {
  949. avio_seek(pb, off, SEEK_SET);
  950. break;
  951. }
  952. ret = ffio_ensure_seekback(pb, ID3v2_HEADER_SIZE);
  953. if (ret >= 0)
  954. ret = avio_read(pb, buf, ID3v2_HEADER_SIZE);
  955. if (ret != ID3v2_HEADER_SIZE) {
  956. avio_seek(pb, off, SEEK_SET);
  957. break;
  958. }
  959. found_header = ff_id3v2_match(buf, magic);
  960. if (found_header) {
  961. /* parse ID3v2 header */
  962. len = ((buf[6] & 0x7f) << 21) |
  963. ((buf[7] & 0x7f) << 14) |
  964. ((buf[8] & 0x7f) << 7) |
  965. (buf[9] & 0x7f);
  966. id3v2_parse(pb, metadata, s, len, buf[3], buf[5],
  967. extra_metap ? &extra_meta : NULL);
  968. } else {
  969. avio_seek(pb, off, SEEK_SET);
  970. }
  971. } while (found_header);
  972. ff_metadata_conv(metadata, NULL, ff_id3v2_34_metadata_conv);
  973. ff_metadata_conv(metadata, NULL, id3v2_2_metadata_conv);
  974. ff_metadata_conv(metadata, NULL, ff_id3v2_4_metadata_conv);
  975. merge_date(metadata);
  976. if (extra_metap)
  977. *extra_metap = extra_meta.head;
  978. }
  979. void ff_id3v2_read_dict(AVIOContext *pb, AVDictionary **metadata,
  980. const char *magic, ID3v2ExtraMeta **extra_meta)
  981. {
  982. id3v2_read_internal(pb, metadata, NULL, magic, extra_meta, 0);
  983. }
  984. void ff_id3v2_read(AVFormatContext *s, const char *magic,
  985. ID3v2ExtraMeta **extra_meta, unsigned int max_search_size)
  986. {
  987. id3v2_read_internal(s->pb, &s->metadata, s, magic, extra_meta, max_search_size);
  988. }
  989. void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
  990. {
  991. ID3v2ExtraMeta *current = *extra_meta, *next;
  992. const ID3v2EMFunc *extra_func;
  993. while (current) {
  994. if ((extra_func = get_extra_meta_func(current->tag, 1)))
  995. extra_func->free(&current->data);
  996. next = current->next;
  997. av_freep(&current);
  998. current = next;
  999. }
  1000. *extra_meta = NULL;
  1001. }
  1002. int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
  1003. {
  1004. ID3v2ExtraMeta *cur;
  1005. for (cur = extra_meta; cur; cur = cur->next) {
  1006. ID3v2ExtraMetaAPIC *apic;
  1007. AVStream *st;
  1008. int ret;
  1009. if (strcmp(cur->tag, "APIC"))
  1010. continue;
  1011. apic = &cur->data.apic;
  1012. ret = ff_add_attached_pic(s, NULL, NULL, &apic->buf, 0);
  1013. if (ret < 0)
  1014. return ret;
  1015. st = s->streams[s->nb_streams - 1];
  1016. st->codecpar->codec_id = apic->id;
  1017. if (AV_RB64(st->attached_pic.data) == PNGSIG)
  1018. st->codecpar->codec_id = AV_CODEC_ID_PNG;
  1019. if (apic->description[0])
  1020. av_dict_set(&st->metadata, "title", apic->description, 0);
  1021. av_dict_set(&st->metadata, "comment", apic->type, 0);
  1022. }
  1023. return 0;
  1024. }
  1025. int ff_id3v2_parse_chapters(AVFormatContext *s, ID3v2ExtraMeta *cur)
  1026. {
  1027. AVRational time_base = {1, 1000};
  1028. int ret;
  1029. for (unsigned i = 0; cur; cur = cur->next) {
  1030. ID3v2ExtraMetaCHAP *chap;
  1031. AVChapter *chapter;
  1032. if (strcmp(cur->tag, "CHAP"))
  1033. continue;
  1034. chap = &cur->data.chap;
  1035. chapter = avpriv_new_chapter(s, i++, time_base, chap->start,
  1036. chap->end, chap->element_id);
  1037. if (!chapter)
  1038. continue;
  1039. if ((ret = av_dict_copy(&chapter->metadata, chap->meta, 0)) < 0)
  1040. return ret;
  1041. }
  1042. return 0;
  1043. }
  1044. int ff_id3v2_parse_priv_dict(AVDictionary **metadata, ID3v2ExtraMeta *extra_meta)
  1045. {
  1046. ID3v2ExtraMeta *cur;
  1047. int dict_flags = AV_DICT_DONT_OVERWRITE | AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL;
  1048. for (cur = extra_meta; cur; cur = cur->next) {
  1049. if (!strcmp(cur->tag, "PRIV")) {
  1050. ID3v2ExtraMetaPRIV *priv = &cur->data.priv;
  1051. AVBPrint bprint;
  1052. char *escaped, *key;
  1053. int i, ret;
  1054. if ((key = av_asprintf(ID3v2_PRIV_METADATA_PREFIX "%s", priv->owner)) == NULL) {
  1055. return AVERROR(ENOMEM);
  1056. }
  1057. av_bprint_init(&bprint, priv->datasize + 1, AV_BPRINT_SIZE_UNLIMITED);
  1058. for (i = 0; i < priv->datasize; i++) {
  1059. if (priv->data[i] < 32 || priv->data[i] > 126 || priv->data[i] == '\\') {
  1060. av_bprintf(&bprint, "\\x%02x", priv->data[i]);
  1061. } else {
  1062. av_bprint_chars(&bprint, priv->data[i], 1);
  1063. }
  1064. }
  1065. if ((ret = av_bprint_finalize(&bprint, &escaped)) < 0) {
  1066. av_free(key);
  1067. return ret;
  1068. }
  1069. if ((ret = av_dict_set(metadata, key, escaped, dict_flags)) < 0) {
  1070. return ret;
  1071. }
  1072. }
  1073. }
  1074. return 0;
  1075. }
  1076. int ff_id3v2_parse_priv(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
  1077. {
  1078. return ff_id3v2_parse_priv_dict(&s->metadata, extra_meta);
  1079. }