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.

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