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.

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