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.

519 lines
16KB

  1. /*
  2. * Ogg muxer
  3. * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/crc.h"
  22. #include "libavutil/mathematics.h"
  23. #include "libavutil/random_seed.h"
  24. #include "libavcodec/xiph.h"
  25. #include "libavcodec/bytestream.h"
  26. #include "libavcodec/flac.h"
  27. #include "avformat.h"
  28. #include "avio_internal.h"
  29. #include "internal.h"
  30. #include "vorbiscomment.h"
  31. #define MAX_PAGE_SIZE 65025
  32. typedef struct {
  33. int64_t granule;
  34. int stream_index;
  35. uint8_t flags;
  36. uint8_t segments_count;
  37. uint8_t segments[255];
  38. uint8_t data[MAX_PAGE_SIZE];
  39. uint16_t size;
  40. } OGGPage;
  41. typedef struct {
  42. unsigned page_counter;
  43. uint8_t *header[3];
  44. int header_len[3];
  45. /** for theora granule */
  46. int kfgshift;
  47. int64_t last_kf_pts;
  48. int vrev;
  49. int eos;
  50. unsigned page_count; ///< number of page buffered
  51. OGGPage page; ///< current page
  52. unsigned serial_num; ///< serial number
  53. int64_t last_granule; ///< last packet granule
  54. } OGGStreamContext;
  55. typedef struct OGGPageList {
  56. OGGPage page;
  57. struct OGGPageList *next;
  58. } OGGPageList;
  59. typedef struct {
  60. OGGPageList *page_list;
  61. } OGGContext;
  62. static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
  63. {
  64. int64_t pos = avio_tell(pb);
  65. uint32_t checksum = ffio_get_checksum(pb);
  66. avio_seek(pb, crc_offset, SEEK_SET);
  67. avio_wb32(pb, checksum);
  68. avio_seek(pb, pos, SEEK_SET);
  69. }
  70. static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
  71. {
  72. OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
  73. AVIOContext *pb;
  74. int64_t crc_offset;
  75. int ret, size;
  76. uint8_t *buf;
  77. ret = avio_open_dyn_buf(&pb);
  78. if (ret < 0)
  79. return ret;
  80. ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
  81. ffio_wfourcc(pb, "OggS");
  82. avio_w8(pb, 0);
  83. avio_w8(pb, page->flags | extra_flags);
  84. avio_wl64(pb, page->granule);
  85. avio_wl32(pb, oggstream->serial_num);
  86. avio_wl32(pb, oggstream->page_counter++);
  87. crc_offset = avio_tell(pb);
  88. avio_wl32(pb, 0); // crc
  89. avio_w8(pb, page->segments_count);
  90. avio_write(pb, page->segments, page->segments_count);
  91. avio_write(pb, page->data, page->size);
  92. ogg_update_checksum(s, pb, crc_offset);
  93. avio_flush(pb);
  94. size = avio_close_dyn_buf(pb, &buf);
  95. if (size < 0)
  96. return size;
  97. avio_write(s->pb, buf, size);
  98. avio_flush(s->pb);
  99. av_free(buf);
  100. oggstream->page_count--;
  101. return 0;
  102. }
  103. static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
  104. {
  105. if (oggstream->kfgshift)
  106. return (granule>>oggstream->kfgshift) +
  107. (granule & ((1<<oggstream->kfgshift)-1));
  108. else
  109. return granule;
  110. }
  111. static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
  112. {
  113. AVStream *st2 = s->streams[next->stream_index];
  114. AVStream *st = s->streams[page->stream_index];
  115. int64_t next_granule, cur_granule;
  116. if (next->granule == -1 || page->granule == -1)
  117. return 0;
  118. next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
  119. st2->time_base, AV_TIME_BASE_Q);
  120. cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
  121. st ->time_base, AV_TIME_BASE_Q);
  122. return next_granule > cur_granule;
  123. }
  124. static int ogg_reset_cur_page(OGGStreamContext *oggstream)
  125. {
  126. oggstream->page.granule = -1;
  127. oggstream->page.flags = 0;
  128. oggstream->page.segments_count = 0;
  129. oggstream->page.size = 0;
  130. return 0;
  131. }
  132. static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
  133. {
  134. OGGContext *ogg = s->priv_data;
  135. OGGPageList **p = &ogg->page_list;
  136. OGGPageList *l = av_mallocz(sizeof(*l));
  137. if (!l)
  138. return AVERROR(ENOMEM);
  139. l->page = oggstream->page;
  140. oggstream->page_count++;
  141. ogg_reset_cur_page(oggstream);
  142. while (*p) {
  143. if (ogg_compare_granule(s, &(*p)->page, &l->page))
  144. break;
  145. p = &(*p)->next;
  146. }
  147. l->next = *p;
  148. *p = l;
  149. return 0;
  150. }
  151. static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
  152. uint8_t *data, unsigned size, int64_t granule)
  153. {
  154. OGGStreamContext *oggstream = st->priv_data;
  155. int total_segments = size / 255 + 1;
  156. uint8_t *p = data;
  157. int i, segments, len, flush = 0;
  158. // Handles VFR by flushing page because this frame needs to have a timestamp
  159. if (st->codec->codec_id == CODEC_ID_THEORA &&
  160. ogg_granule_to_timestamp(oggstream, granule) >
  161. ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
  162. if (oggstream->page.granule != -1)
  163. ogg_buffer_page(s, oggstream);
  164. flush = 1;
  165. }
  166. for (i = 0; i < total_segments; ) {
  167. OGGPage *page = &oggstream->page;
  168. segments = FFMIN(total_segments - i, 255 - page->segments_count);
  169. if (i && !page->segments_count)
  170. page->flags |= 1; // continued packet
  171. memset(page->segments+page->segments_count, 255, segments - 1);
  172. page->segments_count += segments - 1;
  173. len = FFMIN(size, segments*255);
  174. page->segments[page->segments_count++] = len - (segments-1)*255;
  175. memcpy(page->data+page->size, p, len);
  176. p += len;
  177. size -= len;
  178. i += segments;
  179. page->size += len;
  180. if (i == total_segments)
  181. page->granule = granule;
  182. if (page->segments_count == 255) {
  183. ogg_buffer_page(s, oggstream);
  184. }
  185. }
  186. if (flush && oggstream->page.granule != -1)
  187. ogg_buffer_page(s, oggstream);
  188. return 0;
  189. }
  190. static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
  191. int *header_len, AVDictionary **m, int framing_bit)
  192. {
  193. const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
  194. int size;
  195. uint8_t *p, *p0;
  196. unsigned int count;
  197. ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
  198. size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
  199. p = av_mallocz(size);
  200. if (!p)
  201. return NULL;
  202. p0 = p;
  203. p += offset;
  204. ff_vorbiscomment_write(&p, m, vendor, count);
  205. if (framing_bit)
  206. bytestream_put_byte(&p, 1);
  207. *header_len = size;
  208. return p0;
  209. }
  210. static int ogg_build_flac_headers(AVCodecContext *avctx,
  211. OGGStreamContext *oggstream, int bitexact,
  212. AVDictionary **m)
  213. {
  214. enum FLACExtradataFormat format;
  215. uint8_t *streaminfo;
  216. uint8_t *p;
  217. if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
  218. return -1;
  219. // first packet: STREAMINFO
  220. oggstream->header_len[0] = 51;
  221. oggstream->header[0] = av_mallocz(51); // per ogg flac specs
  222. p = oggstream->header[0];
  223. if (!p)
  224. return AVERROR(ENOMEM);
  225. bytestream_put_byte(&p, 0x7F);
  226. bytestream_put_buffer(&p, "FLAC", 4);
  227. bytestream_put_byte(&p, 1); // major version
  228. bytestream_put_byte(&p, 0); // minor version
  229. bytestream_put_be16(&p, 1); // headers packets without this one
  230. bytestream_put_buffer(&p, "fLaC", 4);
  231. bytestream_put_byte(&p, 0x00); // streaminfo
  232. bytestream_put_be24(&p, 34);
  233. bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
  234. // second packet: VorbisComment
  235. p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
  236. if (!p)
  237. return AVERROR(ENOMEM);
  238. oggstream->header[1] = p;
  239. bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
  240. bytestream_put_be24(&p, oggstream->header_len[1] - 4);
  241. return 0;
  242. }
  243. #define SPEEX_HEADER_SIZE 80
  244. static int ogg_build_speex_headers(AVCodecContext *avctx,
  245. OGGStreamContext *oggstream, int bitexact,
  246. AVDictionary **m)
  247. {
  248. uint8_t *p;
  249. if (avctx->extradata_size < SPEEX_HEADER_SIZE)
  250. return -1;
  251. // first packet: Speex header
  252. p = av_mallocz(SPEEX_HEADER_SIZE);
  253. if (!p)
  254. return AVERROR(ENOMEM);
  255. oggstream->header[0] = p;
  256. oggstream->header_len[0] = SPEEX_HEADER_SIZE;
  257. bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
  258. AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
  259. // second packet: VorbisComment
  260. p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
  261. if (!p)
  262. return AVERROR(ENOMEM);
  263. oggstream->header[1] = p;
  264. return 0;
  265. }
  266. static int ogg_write_header(AVFormatContext *s)
  267. {
  268. OGGStreamContext *oggstream;
  269. int i, j;
  270. for (i = 0; i < s->nb_streams; i++) {
  271. AVStream *st = s->streams[i];
  272. unsigned serial_num = i;
  273. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  274. av_set_pts_info(st, 64, 1, st->codec->sample_rate);
  275. else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  276. av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
  277. if (st->codec->codec_id != CODEC_ID_VORBIS &&
  278. st->codec->codec_id != CODEC_ID_THEORA &&
  279. st->codec->codec_id != CODEC_ID_SPEEX &&
  280. st->codec->codec_id != CODEC_ID_FLAC) {
  281. av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
  282. return -1;
  283. }
  284. if (!st->codec->extradata || !st->codec->extradata_size) {
  285. av_log(s, AV_LOG_ERROR, "No extradata present\n");
  286. return -1;
  287. }
  288. oggstream = av_mallocz(sizeof(*oggstream));
  289. oggstream->page.stream_index = i;
  290. if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
  291. do {
  292. serial_num = av_get_random_seed();
  293. for (j = 0; j < i; j++) {
  294. OGGStreamContext *sc = s->streams[j]->priv_data;
  295. if (serial_num == sc->serial_num)
  296. break;
  297. }
  298. } while (j < i);
  299. oggstream->serial_num = serial_num;
  300. st->priv_data = oggstream;
  301. if (st->codec->codec_id == CODEC_ID_FLAC) {
  302. int err = ogg_build_flac_headers(st->codec, oggstream,
  303. st->codec->flags & CODEC_FLAG_BITEXACT,
  304. &s->metadata);
  305. if (err) {
  306. av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
  307. av_freep(&st->priv_data);
  308. return err;
  309. }
  310. } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
  311. int err = ogg_build_speex_headers(st->codec, oggstream,
  312. st->codec->flags & CODEC_FLAG_BITEXACT,
  313. &s->metadata);
  314. if (err) {
  315. av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
  316. av_freep(&st->priv_data);
  317. return err;
  318. }
  319. } else {
  320. uint8_t *p;
  321. const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
  322. int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
  323. int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
  324. if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
  325. st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
  326. oggstream->header, oggstream->header_len) < 0) {
  327. av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
  328. av_freep(&st->priv_data);
  329. return -1;
  330. }
  331. p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
  332. &oggstream->header_len[1], &s->metadata,
  333. framing_bit);
  334. if (!p)
  335. return AVERROR(ENOMEM);
  336. oggstream->header[1] = p;
  337. bytestream_put_byte(&p, header_type);
  338. bytestream_put_buffer(&p, cstr, 6);
  339. if (st->codec->codec_id == CODEC_ID_THEORA) {
  340. /** KFGSHIFT is the width of the less significant section of the granule position
  341. The less significant section is the frame count since the last keyframe */
  342. oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
  343. oggstream->vrev = oggstream->header[0][9];
  344. av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
  345. oggstream->kfgshift, oggstream->vrev);
  346. }
  347. }
  348. }
  349. for (j = 0; j < s->nb_streams; j++) {
  350. OGGStreamContext *oggstream = s->streams[j]->priv_data;
  351. ogg_buffer_data(s, s->streams[j], oggstream->header[0],
  352. oggstream->header_len[0], 0);
  353. oggstream->page.flags |= 2; // bos
  354. ogg_buffer_page(s, oggstream);
  355. }
  356. for (j = 0; j < s->nb_streams; j++) {
  357. AVStream *st = s->streams[j];
  358. OGGStreamContext *oggstream = st->priv_data;
  359. for (i = 1; i < 3; i++) {
  360. if (oggstream && oggstream->header_len[i])
  361. ogg_buffer_data(s, st, oggstream->header[i],
  362. oggstream->header_len[i], 0);
  363. }
  364. ogg_buffer_page(s, oggstream);
  365. }
  366. return 0;
  367. }
  368. static void ogg_write_pages(AVFormatContext *s, int flush)
  369. {
  370. OGGContext *ogg = s->priv_data;
  371. OGGPageList *next, *p;
  372. if (!ogg->page_list)
  373. return;
  374. for (p = ogg->page_list; p; ) {
  375. OGGStreamContext *oggstream =
  376. s->streams[p->page.stream_index]->priv_data;
  377. if (oggstream->page_count < 2 && !flush)
  378. break;
  379. ogg_write_page(s, &p->page,
  380. flush && oggstream->page_count == 1 ? 4 : 0); // eos
  381. next = p->next;
  382. av_freep(&p);
  383. p = next;
  384. }
  385. ogg->page_list = p;
  386. }
  387. static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
  388. {
  389. AVStream *st = s->streams[pkt->stream_index];
  390. OGGStreamContext *oggstream = st->priv_data;
  391. int ret;
  392. int64_t granule;
  393. if (st->codec->codec_id == CODEC_ID_THEORA) {
  394. int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
  395. int pframe_count;
  396. if (pkt->flags & AV_PKT_FLAG_KEY)
  397. oggstream->last_kf_pts = pts;
  398. pframe_count = pts - oggstream->last_kf_pts;
  399. // prevent frame count from overflow if key frame flag is not set
  400. if (pframe_count >= (1<<oggstream->kfgshift)) {
  401. oggstream->last_kf_pts += pframe_count;
  402. pframe_count = 0;
  403. }
  404. granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
  405. } else
  406. granule = pkt->pts + pkt->duration;
  407. ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
  408. if (ret < 0)
  409. return ret;
  410. ogg_write_pages(s, 0);
  411. oggstream->last_granule = granule;
  412. return 0;
  413. }
  414. static int ogg_write_trailer(AVFormatContext *s)
  415. {
  416. int i;
  417. /* flush current page */
  418. for (i = 0; i < s->nb_streams; i++)
  419. ogg_buffer_page(s, s->streams[i]->priv_data);
  420. ogg_write_pages(s, 1);
  421. for (i = 0; i < s->nb_streams; i++) {
  422. AVStream *st = s->streams[i];
  423. OGGStreamContext *oggstream = st->priv_data;
  424. if (st->codec->codec_id == CODEC_ID_FLAC ||
  425. st->codec->codec_id == CODEC_ID_SPEEX) {
  426. av_free(oggstream->header[0]);
  427. av_free(oggstream->header[1]);
  428. }
  429. av_freep(&st->priv_data);
  430. }
  431. return 0;
  432. }
  433. AVOutputFormat ff_ogg_muxer = {
  434. .name = "ogg",
  435. .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
  436. .mime_type = "application/ogg",
  437. .extensions = "ogg,ogv,spx",
  438. .priv_data_size = sizeof(OGGContext),
  439. .audio_codec = CODEC_ID_FLAC,
  440. .video_codec = CODEC_ID_THEORA,
  441. .write_header = ogg_write_header,
  442. .write_packet = ogg_write_packet,
  443. .write_trailer = ogg_write_trailer,
  444. };