oggenc.c 16 KB

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