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.

481 lines
15KB

  1. /*
  2. * Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
  3. *
  4. * Permission is hereby granted, free of charge, to any person
  5. * obtaining a copy of this software and associated documentation
  6. * files (the "Software"), to deal in the Software without
  7. * restriction, including without limitation the rights to use, copy,
  8. * modify, merge, publish, distribute, sublicense, and/or sell copies
  9. * of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be
  13. * included in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  19. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  20. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  22. * DEALINGS IN THE SOFTWARE.
  23. */
  24. #include <stdlib.h>
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/base64.h"
  27. #include "libavutil/bswap.h"
  28. #include "libavutil/dict.h"
  29. #include "libavcodec/bytestream.h"
  30. #include "libavcodec/get_bits.h"
  31. #include "libavcodec/vorbis_parser.h"
  32. #include "avformat.h"
  33. #include "flac_picture.h"
  34. #include "internal.h"
  35. #include "oggdec.h"
  36. #include "vorbiscomment.h"
  37. #include "replaygain.h"
  38. static int ogm_chapter(AVFormatContext *as, uint8_t *key, uint8_t *val)
  39. {
  40. int i, cnum, h, m, s, ms, keylen = strlen(key);
  41. AVChapter *chapter = NULL;
  42. if (keylen < 9 || sscanf(key, "CHAPTER%03d", &cnum) != 1)
  43. return 0;
  44. if (keylen <= 10) {
  45. if (sscanf(val, "%02d:%02d:%02d.%03d", &h, &m, &s, &ms) < 4)
  46. return 0;
  47. avpriv_new_chapter(as, cnum, (AVRational) { 1, 1000 },
  48. ms + 1000 * (s + 60 * (m + 60 * h)),
  49. AV_NOPTS_VALUE, NULL);
  50. av_free(val);
  51. } else if (!strcmp(key + keylen - 4, "NAME")) {
  52. for (i = 0; i < as->nb_chapters; i++)
  53. if (as->chapters[i]->id == cnum) {
  54. chapter = as->chapters[i];
  55. break;
  56. }
  57. if (!chapter)
  58. return 0;
  59. av_dict_set(&chapter->metadata, "title", val, AV_DICT_DONT_STRDUP_VAL);
  60. } else
  61. return 0;
  62. av_free(key);
  63. return 1;
  64. }
  65. int ff_vorbis_comment(AVFormatContext *as, AVDictionary **m,
  66. const uint8_t *buf, int size,
  67. int parse_picture)
  68. {
  69. const uint8_t *p = buf;
  70. const uint8_t *end = buf + size;
  71. unsigned n, j;
  72. int s;
  73. /* must have vendor_length and user_comment_list_length */
  74. if (size < 8)
  75. return AVERROR_INVALIDDATA;
  76. s = bytestream_get_le32(&p);
  77. if (end - p - 4 < s || s < 0)
  78. return AVERROR_INVALIDDATA;
  79. p += s;
  80. n = bytestream_get_le32(&p);
  81. while (end - p >= 4 && n > 0) {
  82. const char *t, *v;
  83. int tl, vl;
  84. s = bytestream_get_le32(&p);
  85. if (end - p < s || s < 0)
  86. break;
  87. t = p;
  88. p += s;
  89. n--;
  90. v = memchr(t, '=', s);
  91. if (!v)
  92. continue;
  93. tl = v - t;
  94. vl = s - tl - 1;
  95. v++;
  96. if (tl && vl) {
  97. char *tt, *ct;
  98. tt = av_malloc(tl + 1);
  99. ct = av_malloc(vl + 1);
  100. if (!tt || !ct) {
  101. av_freep(&tt);
  102. av_freep(&ct);
  103. return AVERROR(ENOMEM);
  104. }
  105. for (j = 0; j < tl; j++)
  106. tt[j] = av_toupper(t[j]);
  107. tt[tl] = 0;
  108. memcpy(ct, v, vl);
  109. ct[vl] = 0;
  110. /* The format in which the pictures are stored is the FLAC format.
  111. * Xiph says: "The binary FLAC picture structure is base64 encoded
  112. * and placed within a VorbisComment with the tag name
  113. * 'METADATA_BLOCK_PICTURE'. This is the preferred and
  114. * recommended way of embedding cover art within VorbisComments."
  115. */
  116. if (!strcmp(tt, "METADATA_BLOCK_PICTURE") && parse_picture) {
  117. int ret;
  118. char *pict = av_malloc(vl);
  119. if (!pict) {
  120. av_log(as, AV_LOG_WARNING, "out-of-memory error. Skipping cover art block.\n");
  121. av_freep(&tt);
  122. av_freep(&ct);
  123. continue;
  124. }
  125. if ((ret = av_base64_decode(pict, ct, vl)) > 0)
  126. ret = ff_flac_parse_picture(as, pict, ret);
  127. av_freep(&tt);
  128. av_freep(&ct);
  129. av_freep(&pict);
  130. if (ret < 0) {
  131. av_log(as, AV_LOG_WARNING, "Failed to parse cover art block.\n");
  132. continue;
  133. }
  134. } else if (!ogm_chapter(as, tt, ct)) {
  135. if (av_dict_get(*m, tt, NULL, 0)) {
  136. av_dict_set(m, tt, ";", AV_DICT_APPEND);
  137. }
  138. av_dict_set(m, tt, ct,
  139. AV_DICT_DONT_STRDUP_KEY |
  140. AV_DICT_APPEND);
  141. av_freep(&ct);
  142. }
  143. }
  144. }
  145. if (p != end)
  146. av_log(as, AV_LOG_INFO,
  147. "%"PTRDIFF_SPECIFIER" bytes of comment header remain\n", end - p);
  148. if (n > 0)
  149. av_log(as, AV_LOG_INFO,
  150. "truncated comment header, %i comments not found\n", n);
  151. ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);
  152. return 0;
  153. }
  154. /*
  155. * Parse the vorbis header
  156. *
  157. * Vorbis Identification header from Vorbis_I_spec.html#vorbis-spec-codec
  158. * [vorbis_version] = read 32 bits as unsigned integer | Not used
  159. * [audio_channels] = read 8 bit integer as unsigned | Used
  160. * [audio_sample_rate] = read 32 bits as unsigned integer | Used
  161. * [bitrate_maximum] = read 32 bits as signed integer | Not used yet
  162. * [bitrate_nominal] = read 32 bits as signed integer | Not used yet
  163. * [bitrate_minimum] = read 32 bits as signed integer | Used as bitrate
  164. * [blocksize_0] = read 4 bits as unsigned integer | Not Used
  165. * [blocksize_1] = read 4 bits as unsigned integer | Not Used
  166. * [framing_flag] = read one bit | Not Used
  167. */
  168. struct oggvorbis_private {
  169. unsigned int len[3];
  170. unsigned char *packet[3];
  171. VorbisParseContext vp;
  172. int64_t final_pts;
  173. int final_duration;
  174. };
  175. static int fixup_vorbis_headers(AVFormatContext *as,
  176. struct oggvorbis_private *priv,
  177. uint8_t **buf)
  178. {
  179. int i, offset, len, err;
  180. int buf_len;
  181. unsigned char *ptr;
  182. len = priv->len[0] + priv->len[1] + priv->len[2];
  183. buf_len = len + len / 255 + 64;
  184. ptr = *buf = av_realloc(NULL, buf_len);
  185. if (!ptr)
  186. return AVERROR(ENOMEM);
  187. memset(*buf, '\0', buf_len);
  188. ptr[0] = 2;
  189. offset = 1;
  190. offset += av_xiphlacing(&ptr[offset], priv->len[0]);
  191. offset += av_xiphlacing(&ptr[offset], priv->len[1]);
  192. for (i = 0; i < 3; i++) {
  193. memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
  194. offset += priv->len[i];
  195. av_freep(&priv->packet[i]);
  196. }
  197. if ((err = av_reallocp(buf, offset + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
  198. return err;
  199. return offset;
  200. }
  201. static void vorbis_cleanup(AVFormatContext *s, int idx)
  202. {
  203. struct ogg *ogg = s->priv_data;
  204. struct ogg_stream *os = ogg->streams + idx;
  205. struct oggvorbis_private *priv = os->private;
  206. int i;
  207. if (os->private)
  208. for (i = 0; i < 3; i++)
  209. av_freep(&priv->packet[i]);
  210. }
  211. static int vorbis_update_metadata(AVFormatContext *s, int idx)
  212. {
  213. struct ogg *ogg = s->priv_data;
  214. struct ogg_stream *os = ogg->streams + idx;
  215. AVStream *st = s->streams[idx];
  216. int ret;
  217. if (os->psize <= 8)
  218. return 0;
  219. /* New metadata packet; release old data. */
  220. av_dict_free(&st->metadata);
  221. ret = ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7,
  222. os->psize - 8, 1);
  223. if (ret < 0)
  224. return ret;
  225. /* Update the metadata if possible. */
  226. av_freep(&os->new_metadata);
  227. if (st->metadata) {
  228. os->new_metadata = av_packet_pack_dictionary(st->metadata, &os->new_metadata_size);
  229. /* Send an empty dictionary to indicate that metadata has been cleared. */
  230. } else {
  231. os->new_metadata = av_malloc(1);
  232. os->new_metadata_size = 0;
  233. }
  234. return ret;
  235. }
  236. static int vorbis_header(AVFormatContext *s, int idx)
  237. {
  238. struct ogg *ogg = s->priv_data;
  239. AVStream *st = s->streams[idx];
  240. struct ogg_stream *os = ogg->streams + idx;
  241. struct oggvorbis_private *priv;
  242. int pkt_type = os->buf[os->pstart];
  243. if (!os->private) {
  244. os->private = av_mallocz(sizeof(struct oggvorbis_private));
  245. if (!os->private)
  246. return AVERROR(ENOMEM);
  247. }
  248. if (!(pkt_type & 1))
  249. return 0;
  250. if (os->psize < 1 || pkt_type > 5)
  251. return AVERROR_INVALIDDATA;
  252. priv = os->private;
  253. if (priv->packet[pkt_type >> 1])
  254. return AVERROR_INVALIDDATA;
  255. if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
  256. return AVERROR_INVALIDDATA;
  257. priv->len[pkt_type >> 1] = os->psize;
  258. priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
  259. if (!priv->packet[pkt_type >> 1])
  260. return AVERROR(ENOMEM);
  261. memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
  262. if (os->buf[os->pstart] == 1) {
  263. const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
  264. unsigned blocksize, bs0, bs1;
  265. int srate;
  266. int channels;
  267. if (os->psize != 30)
  268. return AVERROR_INVALIDDATA;
  269. if (bytestream_get_le32(&p) != 0) /* vorbis_version */
  270. return AVERROR_INVALIDDATA;
  271. channels = bytestream_get_byte(&p);
  272. if (st->codec->channels && channels != st->codec->channels) {
  273. av_log(s, AV_LOG_ERROR, "Channel change is not supported\n");
  274. return AVERROR_PATCHWELCOME;
  275. }
  276. st->codec->channels = channels;
  277. srate = bytestream_get_le32(&p);
  278. p += 4; // skip maximum bitrate
  279. st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
  280. p += 4; // skip minimum bitrate
  281. blocksize = bytestream_get_byte(&p);
  282. bs0 = blocksize & 15;
  283. bs1 = blocksize >> 4;
  284. if (bs0 > bs1)
  285. return AVERROR_INVALIDDATA;
  286. if (bs0 < 6 || bs1 > 13)
  287. return AVERROR_INVALIDDATA;
  288. if (bytestream_get_byte(&p) != 1) /* framing_flag */
  289. return AVERROR_INVALIDDATA;
  290. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  291. st->codec->codec_id = AV_CODEC_ID_VORBIS;
  292. if (srate > 0) {
  293. st->codec->sample_rate = srate;
  294. avpriv_set_pts_info(st, 64, 1, srate);
  295. }
  296. } else if (os->buf[os->pstart] == 3) {
  297. if (vorbis_update_metadata(s, idx) >= 0 && priv->len[1] > 10) {
  298. unsigned new_len;
  299. int ret = ff_replaygain_export(st, st->metadata);
  300. if (ret < 0)
  301. return ret;
  302. // drop all metadata we parsed and which is not required by libvorbis
  303. new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
  304. if (new_len >= 16 && new_len < os->psize) {
  305. AV_WL32(priv->packet[1] + new_len - 5, 0);
  306. priv->packet[1][new_len - 1] = 1;
  307. priv->len[1] = new_len;
  308. }
  309. }
  310. } else {
  311. int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);
  312. if (ret < 0) {
  313. st->codec->extradata_size = 0;
  314. return ret;
  315. }
  316. st->codec->extradata_size = ret;
  317. if ((ret = avpriv_vorbis_parse_extradata(st->codec, &priv->vp))) {
  318. av_freep(&st->codec->extradata);
  319. st->codec->extradata_size = 0;
  320. return ret;
  321. }
  322. }
  323. return 1;
  324. }
  325. static int vorbis_packet(AVFormatContext *s, int idx)
  326. {
  327. struct ogg *ogg = s->priv_data;
  328. struct ogg_stream *os = ogg->streams + idx;
  329. struct oggvorbis_private *priv = os->private;
  330. int duration, flags = 0;
  331. /* first packet handling
  332. * here we parse the duration of each packet in the first page and compare
  333. * the total duration to the page granule to find the encoder delay and
  334. * set the first timestamp */
  335. if ((!os->lastpts || os->lastpts == AV_NOPTS_VALUE) && !(os->flags & OGG_FLAG_EOS) && (int64_t)os->granule>=0) {
  336. int seg, d;
  337. uint8_t *last_pkt = os->buf + os->pstart;
  338. uint8_t *next_pkt = last_pkt;
  339. avpriv_vorbis_parse_reset(&priv->vp);
  340. duration = 0;
  341. seg = os->segp;
  342. d = avpriv_vorbis_parse_frame_flags(&priv->vp, last_pkt, 1, &flags);
  343. if (d < 0) {
  344. os->pflags |= AV_PKT_FLAG_CORRUPT;
  345. return 0;
  346. } else if (flags & VORBIS_FLAG_COMMENT) {
  347. vorbis_update_metadata(s, idx);
  348. flags = 0;
  349. }
  350. duration += d;
  351. last_pkt = next_pkt = next_pkt + os->psize;
  352. for (; seg < os->nsegs; seg++) {
  353. if (os->segments[seg] < 255) {
  354. int d = avpriv_vorbis_parse_frame_flags(&priv->vp, last_pkt, 1, &flags);
  355. if (d < 0) {
  356. duration = os->granule;
  357. break;
  358. } else if (flags & VORBIS_FLAG_COMMENT) {
  359. vorbis_update_metadata(s, idx);
  360. flags = 0;
  361. }
  362. duration += d;
  363. last_pkt = next_pkt + os->segments[seg];
  364. }
  365. next_pkt += os->segments[seg];
  366. }
  367. os->lastpts =
  368. os->lastdts = os->granule - duration;
  369. if (!os->granule && duration) //hack to deal with broken files (Ticket3710)
  370. os->lastpts = os->lastdts = AV_NOPTS_VALUE;
  371. if (s->streams[idx]->start_time == AV_NOPTS_VALUE) {
  372. s->streams[idx]->start_time = FFMAX(os->lastpts, 0);
  373. if (s->streams[idx]->duration != AV_NOPTS_VALUE)
  374. s->streams[idx]->duration -= s->streams[idx]->start_time;
  375. }
  376. priv->final_pts = AV_NOPTS_VALUE;
  377. avpriv_vorbis_parse_reset(&priv->vp);
  378. }
  379. /* parse packet duration */
  380. if (os->psize > 0) {
  381. duration = avpriv_vorbis_parse_frame_flags(&priv->vp, os->buf + os->pstart, 1, &flags);
  382. if (duration < 0) {
  383. os->pflags |= AV_PKT_FLAG_CORRUPT;
  384. return 0;
  385. } else if (flags & VORBIS_FLAG_COMMENT) {
  386. vorbis_update_metadata(s, idx);
  387. flags = 0;
  388. }
  389. os->pduration = duration;
  390. }
  391. /* final packet handling
  392. * here we save the pts of the first packet in the final page, sum up all
  393. * packet durations in the final page except for the last one, and compare
  394. * to the page granule to find the duration of the final packet */
  395. if (os->flags & OGG_FLAG_EOS) {
  396. if (os->lastpts != AV_NOPTS_VALUE) {
  397. priv->final_pts = os->lastpts;
  398. priv->final_duration = 0;
  399. }
  400. if (os->segp == os->nsegs)
  401. os->pduration = os->granule - priv->final_pts - priv->final_duration;
  402. priv->final_duration += os->pduration;
  403. }
  404. return 0;
  405. }
  406. const struct ogg_codec ff_vorbis_codec = {
  407. .magic = "\001vorbis",
  408. .magicsize = 7,
  409. .header = vorbis_header,
  410. .packet = vorbis_packet,
  411. .cleanup = vorbis_cleanup,
  412. .nb_header = 3,
  413. };