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.

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