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.

427 lines
14KB

  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. static int ogm_chapter(AVFormatContext *as, uint8_t *key, uint8_t *val)
  38. {
  39. int i, cnum, h, m, s, ms, keylen = strlen(key);
  40. AVChapter *chapter = NULL;
  41. if (keylen < 9 || sscanf(key, "CHAPTER%03d", &cnum) != 1)
  42. return 0;
  43. if (keylen <= 10) {
  44. if (sscanf(val, "%02d:%02d:%02d.%03d", &h, &m, &s, &ms) < 4)
  45. return 0;
  46. avpriv_new_chapter(as, cnum, (AVRational) { 1, 1000 },
  47. ms + 1000 * (s + 60 * (m + 60 * h)),
  48. AV_NOPTS_VALUE, NULL);
  49. av_free(val);
  50. } else if (!strcmp(key + keylen - 4, "NAME")) {
  51. for (i = 0; i < as->nb_chapters; i++)
  52. if (as->chapters[i]->id == cnum) {
  53. chapter = as->chapters[i];
  54. break;
  55. }
  56. if (!chapter)
  57. return 0;
  58. av_dict_set(&chapter->metadata, "title", val, AV_DICT_DONT_STRDUP_VAL);
  59. } else
  60. return 0;
  61. av_free(key);
  62. return 1;
  63. }
  64. int ff_vorbis_comment(AVFormatContext *as, AVDictionary **m,
  65. const uint8_t *buf, int size)
  66. {
  67. const uint8_t *p = buf;
  68. const uint8_t *end = buf + size;
  69. unsigned n, j;
  70. int s;
  71. /* must have vendor_length and user_comment_list_length */
  72. if (size < 8)
  73. return AVERROR_INVALIDDATA;
  74. s = bytestream_get_le32(&p);
  75. if (end - p - 4 < s || s < 0)
  76. return AVERROR_INVALIDDATA;
  77. p += s;
  78. n = bytestream_get_le32(&p);
  79. while (end - p >= 4 && n > 0) {
  80. const char *t, *v;
  81. int tl, vl;
  82. s = bytestream_get_le32(&p);
  83. if (end - p < s || s < 0)
  84. break;
  85. t = p;
  86. p += s;
  87. n--;
  88. v = memchr(t, '=', s);
  89. if (!v)
  90. continue;
  91. tl = v - t;
  92. vl = s - tl - 1;
  93. v++;
  94. if (tl && vl) {
  95. char *tt, *ct;
  96. tt = av_malloc(tl + 1);
  97. ct = av_malloc(vl + 1);
  98. if (!tt || !ct) {
  99. av_freep(&tt);
  100. av_freep(&ct);
  101. return AVERROR(ENOMEM);
  102. }
  103. for (j = 0; j < tl; j++)
  104. tt[j] = av_toupper(t[j]);
  105. tt[tl] = 0;
  106. memcpy(ct, v, vl);
  107. ct[vl] = 0;
  108. /* The format in which the pictures are stored is the FLAC format.
  109. * Xiph says: "The binary FLAC picture structure is base64 encoded
  110. * and placed within a VorbisComment with the tag name
  111. * 'METADATA_BLOCK_PICTURE'. This is the preferred and
  112. * recommended way of embedding cover art within VorbisComments."
  113. */
  114. if (!strcmp(tt, "METADATA_BLOCK_PICTURE")) {
  115. int ret;
  116. char *pict = av_malloc(vl);
  117. if (!pict) {
  118. av_log(as, AV_LOG_WARNING, "out-of-memory error. Skipping cover art block.\n");
  119. av_freep(&tt);
  120. av_freep(&ct);
  121. continue;
  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. int buf_len;
  174. unsigned char *ptr;
  175. len = priv->len[0] + priv->len[1] + priv->len[2];
  176. buf_len = len + len / 255 + 64;
  177. ptr = *buf = av_realloc(NULL, buf_len);
  178. if (!ptr)
  179. return AVERROR(ENOMEM);
  180. memset(*buf, '\0', buf_len);
  181. ptr[0] = 2;
  182. offset = 1;
  183. offset += av_xiphlacing(&ptr[offset], priv->len[0]);
  184. offset += av_xiphlacing(&ptr[offset], priv->len[1]);
  185. for (i = 0; i < 3; i++) {
  186. memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
  187. offset += priv->len[i];
  188. av_freep(&priv->packet[i]);
  189. }
  190. if ((err = av_reallocp(buf, offset + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
  191. return err;
  192. return offset;
  193. }
  194. static void vorbis_cleanup(AVFormatContext *s, int idx)
  195. {
  196. struct ogg *ogg = s->priv_data;
  197. struct ogg_stream *os = ogg->streams + idx;
  198. struct oggvorbis_private *priv = os->private;
  199. int i;
  200. if (os->private)
  201. for (i = 0; i < 3; i++)
  202. av_freep(&priv->packet[i]);
  203. }
  204. static int vorbis_header(AVFormatContext *s, int idx)
  205. {
  206. struct ogg *ogg = s->priv_data;
  207. AVStream *st = s->streams[idx];
  208. struct ogg_stream *os = ogg->streams + idx;
  209. struct oggvorbis_private *priv;
  210. int pkt_type = os->buf[os->pstart];
  211. if (!os->private) {
  212. os->private = av_mallocz(sizeof(struct oggvorbis_private));
  213. if (!os->private)
  214. return AVERROR(ENOMEM);
  215. }
  216. if (!(pkt_type & 1))
  217. return 0;
  218. if (os->psize < 1 || pkt_type > 5)
  219. return AVERROR_INVALIDDATA;
  220. priv = os->private;
  221. if (priv->packet[pkt_type >> 1])
  222. return AVERROR_INVALIDDATA;
  223. if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
  224. return AVERROR_INVALIDDATA;
  225. priv->len[pkt_type >> 1] = os->psize;
  226. priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
  227. if (!priv->packet[pkt_type >> 1])
  228. return AVERROR(ENOMEM);
  229. memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
  230. if (os->buf[os->pstart] == 1) {
  231. const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
  232. unsigned blocksize, bs0, bs1;
  233. int srate;
  234. int channels;
  235. if (os->psize != 30)
  236. return AVERROR_INVALIDDATA;
  237. if (bytestream_get_le32(&p) != 0) /* vorbis_version */
  238. return AVERROR_INVALIDDATA;
  239. channels = bytestream_get_byte(&p);
  240. if (st->codec->channels && channels != st->codec->channels) {
  241. av_log(s, AV_LOG_ERROR, "Channel change is not supported\n");
  242. return AVERROR_PATCHWELCOME;
  243. }
  244. st->codec->channels = channels;
  245. srate = bytestream_get_le32(&p);
  246. p += 4; // skip maximum bitrate
  247. st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
  248. p += 4; // skip minimum bitrate
  249. blocksize = bytestream_get_byte(&p);
  250. bs0 = blocksize & 15;
  251. bs1 = blocksize >> 4;
  252. if (bs0 > bs1)
  253. return AVERROR_INVALIDDATA;
  254. if (bs0 < 6 || bs1 > 13)
  255. return AVERROR_INVALIDDATA;
  256. if (bytestream_get_byte(&p) != 1) /* framing_flag */
  257. return AVERROR_INVALIDDATA;
  258. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  259. st->codec->codec_id = AV_CODEC_ID_VORBIS;
  260. if (srate > 0) {
  261. st->codec->sample_rate = srate;
  262. avpriv_set_pts_info(st, 64, 1, srate);
  263. }
  264. } else if (os->buf[os->pstart] == 3) {
  265. if (os->psize > 8 &&
  266. ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7,
  267. os->psize - 8) >= 0) {
  268. // drop all metadata we parsed and which is not required by libvorbis
  269. unsigned new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
  270. if (new_len >= 16 && new_len < os->psize) {
  271. AV_WL32(priv->packet[1] + new_len - 5, 0);
  272. priv->packet[1][new_len - 1] = 1;
  273. priv->len[1] = new_len;
  274. }
  275. }
  276. } else {
  277. int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);
  278. if (ret < 0) {
  279. st->codec->extradata_size = 0;
  280. return ret;
  281. }
  282. st->codec->extradata_size = ret;
  283. if ((ret = avpriv_vorbis_parse_extradata(st->codec, &priv->vp))) {
  284. av_freep(&st->codec->extradata);
  285. st->codec->extradata_size = 0;
  286. return ret;
  287. }
  288. }
  289. return 1;
  290. }
  291. static int vorbis_packet(AVFormatContext *s, int idx)
  292. {
  293. struct ogg *ogg = s->priv_data;
  294. struct ogg_stream *os = ogg->streams + idx;
  295. struct oggvorbis_private *priv = os->private;
  296. int duration;
  297. /* first packet handling
  298. * here we parse the duration of each packet in the first page and compare
  299. * the total duration to the page granule to find the encoder delay and
  300. * set the first timestamp */
  301. if ((!os->lastpts || os->lastpts == AV_NOPTS_VALUE) && !(os->flags & OGG_FLAG_EOS)) {
  302. int seg, d;
  303. uint8_t *last_pkt = os->buf + os->pstart;
  304. uint8_t *next_pkt = last_pkt;
  305. avpriv_vorbis_parse_reset(&priv->vp);
  306. duration = 0;
  307. seg = os->segp;
  308. d = avpriv_vorbis_parse_frame(&priv->vp, last_pkt, 1);
  309. if (d < 0) {
  310. os->pflags |= AV_PKT_FLAG_CORRUPT;
  311. return 0;
  312. }
  313. duration += d;
  314. last_pkt = next_pkt = next_pkt + os->psize;
  315. for (; seg < os->nsegs; seg++) {
  316. if (os->segments[seg] < 255) {
  317. int d = avpriv_vorbis_parse_frame(&priv->vp, last_pkt, 1);
  318. if (d < 0) {
  319. duration = os->granule;
  320. break;
  321. }
  322. duration += d;
  323. last_pkt = next_pkt + os->segments[seg];
  324. }
  325. next_pkt += os->segments[seg];
  326. }
  327. os->lastpts =
  328. os->lastdts = os->granule - duration;
  329. if (s->streams[idx]->start_time == AV_NOPTS_VALUE) {
  330. s->streams[idx]->start_time = FFMAX(os->lastpts, 0);
  331. if (s->streams[idx]->duration)
  332. s->streams[idx]->duration -= s->streams[idx]->start_time;
  333. }
  334. priv->final_pts = AV_NOPTS_VALUE;
  335. avpriv_vorbis_parse_reset(&priv->vp);
  336. }
  337. /* parse packet duration */
  338. if (os->psize > 0) {
  339. duration = avpriv_vorbis_parse_frame(&priv->vp, os->buf + os->pstart, 1);
  340. if (duration < 0) {
  341. os->pflags |= AV_PKT_FLAG_CORRUPT;
  342. return 0;
  343. }
  344. os->pduration = duration;
  345. }
  346. /* final packet handling
  347. * here we save the pts of the first packet in the final page, sum up all
  348. * packet durations in the final page except for the last one, and compare
  349. * to the page granule to find the duration of the final packet */
  350. if (os->flags & OGG_FLAG_EOS) {
  351. if (os->lastpts != AV_NOPTS_VALUE) {
  352. priv->final_pts = os->lastpts;
  353. priv->final_duration = 0;
  354. }
  355. if (os->segp == os->nsegs)
  356. os->pduration = os->granule - priv->final_pts - priv->final_duration;
  357. priv->final_duration += os->pduration;
  358. }
  359. return 0;
  360. }
  361. const struct ogg_codec ff_vorbis_codec = {
  362. .magic = "\001vorbis",
  363. .magicsize = 7,
  364. .header = vorbis_header,
  365. .packet = vorbis_packet,
  366. .cleanup = vorbis_cleanup,
  367. .nb_header = 3,
  368. };