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.

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