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.

419 lines
13KB

  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_freep(&tt);
  121. av_freep(&ct);
  122. return AVERROR(ENOMEM);
  123. }
  124. if ((ret = av_base64_decode(pict, ct, vl)) > 0)
  125. ret = ff_flac_parse_picture(as, pict, ret);
  126. av_freep(&tt);
  127. av_freep(&ct);
  128. av_freep(&pict);
  129. if (ret < 0) {
  130. av_log(as, AV_LOG_WARNING, "Failed to parse cover art block.\n");
  131. continue;
  132. }
  133. } else if (!ogm_chapter(as, tt, ct))
  134. av_dict_set(m, tt, ct,
  135. AV_DICT_DONT_STRDUP_KEY |
  136. AV_DICT_DONT_STRDUP_VAL);
  137. }
  138. }
  139. if (p != end)
  140. av_log(as, AV_LOG_INFO,
  141. "%ti bytes of comment header remain\n", end - p);
  142. if (n > 0)
  143. av_log(as, AV_LOG_INFO,
  144. "truncated comment header, %i comments not found\n", n);
  145. ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);
  146. return 0;
  147. }
  148. /*
  149. * Parse the vorbis header
  150. *
  151. * Vorbis Identification header from Vorbis_I_spec.html#vorbis-spec-codec
  152. * [vorbis_version] = read 32 bits as unsigned integer | Not used
  153. * [audio_channels] = read 8 bit integer as unsigned | Used
  154. * [audio_sample_rate] = read 32 bits as unsigned integer | Used
  155. * [bitrate_maximum] = read 32 bits as signed integer | Not used yet
  156. * [bitrate_nominal] = read 32 bits as signed integer | Not used yet
  157. * [bitrate_minimum] = read 32 bits as signed integer | Used as bitrate
  158. * [blocksize_0] = read 4 bits as unsigned integer | Not Used
  159. * [blocksize_1] = read 4 bits as unsigned integer | Not Used
  160. * [framing_flag] = read one bit | Not Used
  161. */
  162. struct oggvorbis_private {
  163. unsigned int len[3];
  164. unsigned char *packet[3];
  165. VorbisParseContext vp;
  166. int64_t final_pts;
  167. int final_duration;
  168. };
  169. static int fixup_vorbis_headers(AVFormatContext *as,
  170. struct oggvorbis_private *priv,
  171. uint8_t **buf)
  172. {
  173. int i, offset, len, err;
  174. unsigned char *ptr;
  175. len = priv->len[0] + priv->len[1] + priv->len[2];
  176. ptr = *buf = av_mallocz(len + len / 255 + 64);
  177. if (!ptr)
  178. return AVERROR(ENOMEM);
  179. ptr[0] = 2;
  180. offset = 1;
  181. offset += av_xiphlacing(&ptr[offset], priv->len[0]);
  182. offset += av_xiphlacing(&ptr[offset], priv->len[1]);
  183. for (i = 0; i < 3; i++) {
  184. memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
  185. offset += priv->len[i];
  186. av_freep(&priv->packet[i]);
  187. }
  188. if ((err = av_reallocp(buf, offset + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
  189. return err;
  190. return offset;
  191. }
  192. static void vorbis_cleanup(AVFormatContext *s, int idx)
  193. {
  194. struct ogg *ogg = s->priv_data;
  195. struct ogg_stream *os = ogg->streams + idx;
  196. struct oggvorbis_private *priv = os->private;
  197. int i;
  198. if (os->private)
  199. for (i = 0; i < 3; i++)
  200. av_freep(&priv->packet[i]);
  201. }
  202. static int vorbis_header(AVFormatContext *s, int idx)
  203. {
  204. struct ogg *ogg = s->priv_data;
  205. AVStream *st = s->streams[idx];
  206. struct ogg_stream *os = ogg->streams + idx;
  207. struct oggvorbis_private *priv;
  208. int pkt_type = os->buf[os->pstart];
  209. if (!os->private) {
  210. os->private = av_mallocz(sizeof(struct oggvorbis_private));
  211. if (!os->private)
  212. return AVERROR(ENOMEM);
  213. }
  214. if (!(pkt_type & 1))
  215. return 0;
  216. if (os->psize < 1 || pkt_type > 5)
  217. return AVERROR_INVALIDDATA;
  218. priv = os->private;
  219. if (priv->packet[pkt_type >> 1])
  220. return AVERROR_INVALIDDATA;
  221. if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
  222. return AVERROR_INVALIDDATA;
  223. priv->len[pkt_type >> 1] = os->psize;
  224. priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
  225. if (!priv->packet[pkt_type >> 1])
  226. return AVERROR(ENOMEM);
  227. memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
  228. if (os->buf[os->pstart] == 1) {
  229. const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
  230. unsigned blocksize, bs0, bs1;
  231. int srate;
  232. if (os->psize != 30)
  233. return AVERROR_INVALIDDATA;
  234. if (bytestream_get_le32(&p) != 0) /* vorbis_version */
  235. return AVERROR_INVALIDDATA;
  236. st->codec->channels = bytestream_get_byte(&p);
  237. srate = bytestream_get_le32(&p);
  238. p += 4; // skip maximum bitrate
  239. st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
  240. p += 4; // skip minimum bitrate
  241. blocksize = bytestream_get_byte(&p);
  242. bs0 = blocksize & 15;
  243. bs1 = blocksize >> 4;
  244. if (bs0 > bs1)
  245. return AVERROR_INVALIDDATA;
  246. if (bs0 < 6 || bs1 > 13)
  247. return AVERROR_INVALIDDATA;
  248. if (bytestream_get_byte(&p) != 1) /* framing_flag */
  249. return AVERROR_INVALIDDATA;
  250. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  251. st->codec->codec_id = AV_CODEC_ID_VORBIS;
  252. if (srate > 0) {
  253. st->codec->sample_rate = srate;
  254. avpriv_set_pts_info(st, 64, 1, srate);
  255. }
  256. } else if (os->buf[os->pstart] == 3) {
  257. if (os->psize > 8 &&
  258. ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7,
  259. os->psize - 8, 1) >= 0) {
  260. unsigned new_len;
  261. int ret = ff_replaygain_export(st, st->metadata);
  262. if (ret < 0)
  263. return ret;
  264. // drop all metadata we parsed and which is not required by libvorbis
  265. new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
  266. if (new_len >= 16 && new_len < os->psize) {
  267. AV_WL32(priv->packet[1] + new_len - 5, 0);
  268. priv->packet[1][new_len - 1] = 1;
  269. priv->len[1] = new_len;
  270. }
  271. }
  272. } else {
  273. int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);
  274. if (ret < 0) {
  275. st->codec->extradata_size = 0;
  276. return ret;
  277. }
  278. st->codec->extradata_size = ret;
  279. if ((ret = avpriv_vorbis_parse_extradata(st->codec, &priv->vp))) {
  280. av_freep(&st->codec->extradata);
  281. st->codec->extradata_size = 0;
  282. return ret;
  283. }
  284. }
  285. return 1;
  286. }
  287. static int vorbis_packet(AVFormatContext *s, int idx)
  288. {
  289. struct ogg *ogg = s->priv_data;
  290. struct ogg_stream *os = ogg->streams + idx;
  291. struct oggvorbis_private *priv = os->private;
  292. int duration;
  293. /* first packet handling
  294. * here we parse the duration of each packet in the first page and compare
  295. * the total duration to the page granule to find the encoder delay and
  296. * set the first timestamp */
  297. if (!os->lastpts) {
  298. int seg;
  299. uint8_t *last_pkt = os->buf + os->pstart;
  300. uint8_t *next_pkt = last_pkt;
  301. int first_duration = 0;
  302. avpriv_vorbis_parse_reset(&priv->vp);
  303. duration = 0;
  304. for (seg = 0; seg < os->nsegs; seg++) {
  305. if (os->segments[seg] < 255) {
  306. int d = avpriv_vorbis_parse_frame(&priv->vp, last_pkt, 1);
  307. if (d < 0) {
  308. duration = os->granule;
  309. break;
  310. }
  311. if (!duration)
  312. first_duration = d;
  313. duration += d;
  314. last_pkt = next_pkt + os->segments[seg];
  315. }
  316. next_pkt += os->segments[seg];
  317. }
  318. os->lastpts =
  319. os->lastdts = os->granule - duration;
  320. s->streams[idx]->start_time = os->lastpts + first_duration;
  321. if (s->streams[idx]->duration)
  322. s->streams[idx]->duration -= s->streams[idx]->start_time;
  323. s->streams[idx]->cur_dts = AV_NOPTS_VALUE;
  324. priv->final_pts = AV_NOPTS_VALUE;
  325. avpriv_vorbis_parse_reset(&priv->vp);
  326. }
  327. /* parse packet duration */
  328. if (os->psize > 0) {
  329. duration = avpriv_vorbis_parse_frame(&priv->vp, os->buf + os->pstart, 1);
  330. if (duration <= 0) {
  331. os->pflags |= AV_PKT_FLAG_CORRUPT;
  332. return 0;
  333. }
  334. os->pduration = duration;
  335. }
  336. /* final packet handling
  337. * here we save the pts of the first packet in the final page, sum up all
  338. * packet durations in the final page except for the last one, and compare
  339. * to the page granule to find the duration of the final packet */
  340. if (os->flags & OGG_FLAG_EOS) {
  341. if (os->lastpts != AV_NOPTS_VALUE) {
  342. priv->final_pts = os->lastpts;
  343. priv->final_duration = 0;
  344. }
  345. if (os->segp == os->nsegs)
  346. os->pduration = os->granule - priv->final_pts - priv->final_duration;
  347. priv->final_duration += os->pduration;
  348. }
  349. return 0;
  350. }
  351. const struct ogg_codec ff_vorbis_codec = {
  352. .magic = "\001vorbis",
  353. .magicsize = 7,
  354. .header = vorbis_header,
  355. .packet = vorbis_packet,
  356. .cleanup = vorbis_cleanup,
  357. .nb_header = 3,
  358. };