oggenc.c 17 KB

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