3 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
5 * This file is part of Libav.
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.
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.
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
24 #include "libavutil/crc.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/random_seed.h"
28 #include "libavcodec/xiph.h"
29 #include "libavcodec/bytestream.h"
30 #include "libavcodec/flac.h"
32 #include "avio_internal.h"
34 #include "vorbiscomment.h"
36 #define MAX_PAGE_SIZE 65025
38 typedef struct OGGPage {
39 int64_t start_granule;
43 uint8_t segments_count;
44 uint8_t segments[255];
45 uint8_t data[MAX_PAGE_SIZE];
49 typedef struct OGGStreamContext {
50 unsigned page_counter;
53 /** for theora granule */
58 unsigned page_count; ///< number of page buffered
59 OGGPage page; ///< current page
60 unsigned serial_num; ///< serial number
61 int64_t last_granule; ///< last packet granule
64 typedef struct OGGPageList {
66 struct OGGPageList *next;
69 typedef struct OGGContext {
71 OGGPageList *page_list;
72 int pref_size; ///< preferred page size (0 => fill all segments)
73 int64_t pref_duration; ///< preferred page duration (0 => fill all segments)
77 #define OFFSET(x) offsetof(OGGContext, x)
78 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
80 static const AVOption options[] = {
81 { "serial_offset", "serial number offset",
82 OFFSET(serial_offset), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, PARAM },
83 { "pagesize", "preferred page size in bytes (deprecated)",
84 OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
85 { "page_duration", "preferred page duration, in microseconds",
86 OFFSET(pref_duration), AV_OPT_TYPE_INT64, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
90 #define OGG_CLASS(flavor)\
91 static const AVClass flavor ## _muxer_class = {\
92 .class_name = #flavor " muxer",\
93 .item_name = av_default_item_name,\
95 .version = LIBAVUTIL_VERSION_INT,\
98 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
100 int64_t pos = avio_tell(pb);
101 uint32_t checksum = ffio_get_checksum(pb);
102 avio_seek(pb, crc_offset, SEEK_SET);
103 avio_wb32(pb, checksum);
104 avio_seek(pb, pos, SEEK_SET);
107 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
109 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
115 ret = avio_open_dyn_buf(&pb);
118 ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
119 ffio_wfourcc(pb, "OggS");
121 avio_w8(pb, page->flags | extra_flags);
122 avio_wl64(pb, page->granule);
123 avio_wl32(pb, oggstream->serial_num);
124 avio_wl32(pb, oggstream->page_counter++);
125 crc_offset = avio_tell(pb);
126 avio_wl32(pb, 0); // crc
127 avio_w8(pb, page->segments_count);
128 avio_write(pb, page->segments, page->segments_count);
129 avio_write(pb, page->data, page->size);
131 ogg_update_checksum(s, pb, crc_offset);
134 size = avio_close_dyn_buf(pb, &buf);
138 avio_write(s->pb, buf, size);
141 oggstream->page_count--;
145 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
147 if (oggstream->kfgshift)
148 return (granule>>oggstream->kfgshift) +
149 (granule & ((1<<oggstream->kfgshift)-1));
154 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
156 AVStream *st2 = s->streams[next->stream_index];
157 AVStream *st = s->streams[page->stream_index];
158 int64_t next_granule, cur_granule;
160 if (next->granule == -1 || page->granule == -1)
163 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
164 st2->time_base, AV_TIME_BASE_Q);
165 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
166 st ->time_base, AV_TIME_BASE_Q);
167 return next_granule > cur_granule;
170 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
172 oggstream->page.granule = -1;
173 oggstream->page.flags = 0;
174 oggstream->page.segments_count = 0;
175 oggstream->page.size = 0;
179 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
181 OGGContext *ogg = s->priv_data;
182 OGGPageList **p = &ogg->page_list;
183 OGGPageList *l = av_mallocz(sizeof(*l));
186 return AVERROR(ENOMEM);
187 l->page = oggstream->page;
189 oggstream->page.start_granule = oggstream->page.granule;
190 oggstream->page_count++;
191 ogg_reset_cur_page(oggstream);
194 if (ogg_compare_granule(s, &(*p)->page, &l->page))
204 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
205 uint8_t *data, unsigned size, int64_t granule,
208 OGGStreamContext *oggstream = st->priv_data;
209 OGGContext *ogg = s->priv_data;
210 int total_segments = size / 255 + 1;
212 int i, segments, len, flush = 0;
214 // Handles VFR by flushing page because this frame needs to have a timestamp
215 if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
216 ogg_granule_to_timestamp(oggstream, granule) >
217 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
218 if (oggstream->page.granule != -1)
219 ogg_buffer_page(s, oggstream);
223 // avoid a continued page
224 if (!header && oggstream->page.size > 0 &&
225 MAX_PAGE_SIZE - oggstream->page.size < size) {
226 ogg_buffer_page(s, oggstream);
229 for (i = 0; i < total_segments; ) {
230 OGGPage *page = &oggstream->page;
232 segments = FFMIN(total_segments - i, 255 - page->segments_count);
234 if (i && !page->segments_count)
235 page->flags |= 1; // continued packet
237 memset(page->segments+page->segments_count, 255, segments - 1);
238 page->segments_count += segments - 1;
240 len = FFMIN(size, segments*255);
241 page->segments[page->segments_count++] = len - (segments-1)*255;
242 memcpy(page->data+page->size, p, len);
248 if (i == total_segments)
249 page->granule = granule;
252 AVStream *st = s->streams[page->stream_index];
254 int64_t start = av_rescale_q(page->start_granule, st->time_base,
256 int64_t next = av_rescale_q(page->granule, st->time_base,
259 if (page->segments_count == 255 ||
260 (ogg->pref_size > 0 && page->size >= ogg->pref_size) ||
261 (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
262 ogg_buffer_page(s, oggstream);
267 if (flush && oggstream->page.granule != -1)
268 ogg_buffer_page(s, oggstream);
273 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
274 int *header_len, AVDictionary **m, int framing_bit)
276 const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
280 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
282 size = offset + ff_vorbiscomment_length(*m, vendor) + framing_bit;
283 p = av_mallocz(size);
289 ff_vorbiscomment_write(&p, m, vendor);
291 bytestream_put_byte(&p, 1);
297 static int ogg_build_flac_headers(AVCodecContext *avctx,
298 OGGStreamContext *oggstream, int bitexact,
303 if (avctx->extradata_size < FLAC_STREAMINFO_SIZE)
304 return AVERROR(EINVAL);
306 // first packet: STREAMINFO
307 oggstream->header_len[0] = 51;
308 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
309 p = oggstream->header[0];
311 return AVERROR(ENOMEM);
312 bytestream_put_byte(&p, 0x7F);
313 bytestream_put_buffer(&p, "FLAC", 4);
314 bytestream_put_byte(&p, 1); // major version
315 bytestream_put_byte(&p, 0); // minor version
316 bytestream_put_be16(&p, 1); // headers packets without this one
317 bytestream_put_buffer(&p, "fLaC", 4);
318 bytestream_put_byte(&p, 0x00); // streaminfo
319 bytestream_put_be24(&p, 34);
320 bytestream_put_buffer(&p, avctx->extradata, FLAC_STREAMINFO_SIZE);
322 // second packet: VorbisComment
323 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
325 return AVERROR(ENOMEM);
326 oggstream->header[1] = p;
327 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
328 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
333 #define SPEEX_HEADER_SIZE 80
335 static int ogg_build_speex_headers(AVCodecContext *avctx,
336 OGGStreamContext *oggstream, int bitexact,
341 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
344 // first packet: Speex header
345 p = av_mallocz(SPEEX_HEADER_SIZE);
347 return AVERROR(ENOMEM);
348 oggstream->header[0] = p;
349 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
350 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
351 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
353 // second packet: VorbisComment
354 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
356 return AVERROR(ENOMEM);
357 oggstream->header[1] = p;
362 #define OPUS_HEADER_SIZE 19
364 static int ogg_build_opus_headers(AVCodecContext *avctx,
365 OGGStreamContext *oggstream, int bitexact,
370 if (avctx->extradata_size < OPUS_HEADER_SIZE)
373 /* first packet: Opus header */
374 p = av_mallocz(avctx->extradata_size);
376 return AVERROR(ENOMEM);
377 oggstream->header[0] = p;
378 oggstream->header_len[0] = avctx->extradata_size;
379 bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
381 /* second packet: VorbisComment */
382 p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
384 return AVERROR(ENOMEM);
385 oggstream->header[1] = p;
386 bytestream_put_buffer(&p, "OpusTags", 8);
391 static void ogg_write_pages(AVFormatContext *s, int flush)
393 OGGContext *ogg = s->priv_data;
394 OGGPageList *next, *p;
399 for (p = ogg->page_list; p; ) {
400 OGGStreamContext *oggstream =
401 s->streams[p->page.stream_index]->priv_data;
402 if (oggstream->page_count < 2 && !flush)
404 ogg_write_page(s, &p->page,
405 flush == 1 && oggstream->page_count == 1 ? 4 : 0); // eos
413 static int ogg_write_header(AVFormatContext *s)
415 OGGContext *ogg = s->priv_data;
416 OGGStreamContext *oggstream;
420 av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
422 for (i = 0; i < s->nb_streams; i++) {
423 AVStream *st = s->streams[i];
424 unsigned serial_num = i + ogg->serial_offset;
426 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
427 if (st->codec->codec_id == AV_CODEC_ID_OPUS)
428 /* Opus requires a fixed 48kHz clock */
429 avpriv_set_pts_info(st, 64, 1, 48000);
431 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
433 if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
434 st->codec->codec_id != AV_CODEC_ID_THEORA &&
435 st->codec->codec_id != AV_CODEC_ID_SPEEX &&
436 st->codec->codec_id != AV_CODEC_ID_FLAC &&
437 st->codec->codec_id != AV_CODEC_ID_OPUS) {
438 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
442 if (!st->codec->extradata || !st->codec->extradata_size) {
443 av_log(s, AV_LOG_ERROR, "No extradata present\n");
446 oggstream = av_mallocz(sizeof(*oggstream));
448 return AVERROR(ENOMEM);
449 oggstream->page.stream_index = i;
451 if (!(s->flags & AVFMT_FLAG_BITEXACT))
453 serial_num = av_get_random_seed();
454 for (j = 0; j < i; j++) {
455 OGGStreamContext *sc = s->streams[j]->priv_data;
456 if (serial_num == sc->serial_num)
460 oggstream->serial_num = serial_num;
462 st->priv_data = oggstream;
463 if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
464 int err = ogg_build_flac_headers(st->codec, oggstream,
465 s->flags & AVFMT_FLAG_BITEXACT,
468 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
469 av_freep(&st->priv_data);
472 } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
473 int err = ogg_build_speex_headers(st->codec, oggstream,
474 s->flags & AVFMT_FLAG_BITEXACT,
477 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
478 av_freep(&st->priv_data);
481 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
482 int err = ogg_build_opus_headers(st->codec, oggstream,
483 s->flags & AVFMT_FLAG_BITEXACT,
486 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
487 av_freep(&st->priv_data);
492 const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
493 int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
494 int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
496 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
497 st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
498 oggstream->header, oggstream->header_len) < 0) {
499 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
500 av_freep(&st->priv_data);
504 p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
505 &oggstream->header_len[1], &s->metadata,
507 oggstream->header[1] = p;
509 return AVERROR(ENOMEM);
511 bytestream_put_byte(&p, header_type);
512 bytestream_put_buffer(&p, cstr, 6);
514 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
515 /** KFGSHIFT is the width of the less significant section of the granule position
516 The less significant section is the frame count since the last keyframe */
517 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
518 oggstream->vrev = oggstream->header[0][9];
519 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
520 oggstream->kfgshift, oggstream->vrev);
525 for (j = 0; j < s->nb_streams; j++) {
526 OGGStreamContext *oggstream = s->streams[j]->priv_data;
527 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
528 oggstream->header_len[0], 0, 1);
529 oggstream->page.flags |= 2; // bos
530 ogg_buffer_page(s, oggstream);
532 for (j = 0; j < s->nb_streams; j++) {
533 AVStream *st = s->streams[j];
534 OGGStreamContext *oggstream = st->priv_data;
535 for (i = 1; i < 3; i++) {
536 if (oggstream->header_len[i])
537 ogg_buffer_data(s, st, oggstream->header[i],
538 oggstream->header_len[i], 0, 1);
540 ogg_buffer_page(s, oggstream);
543 oggstream->page.start_granule = AV_NOPTS_VALUE;
545 ogg_write_pages(s, 2);
550 static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
552 AVStream *st = s->streams[pkt->stream_index];
553 OGGStreamContext *oggstream = st->priv_data;
557 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
558 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
560 if (pkt->flags & AV_PKT_FLAG_KEY)
561 oggstream->last_kf_pts = pts;
562 pframe_count = pts - oggstream->last_kf_pts;
563 // prevent frame count from overflow if key frame flag is not set
564 if (pframe_count >= (1<<oggstream->kfgshift)) {
565 oggstream->last_kf_pts += pframe_count;
568 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
569 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS)
570 granule = pkt->pts + pkt->duration +
571 av_rescale_q(st->codec->initial_padding,
572 (AVRational){ 1, st->codec->sample_rate },
575 granule = pkt->pts + pkt->duration;
577 if (oggstream->page.start_granule == AV_NOPTS_VALUE)
578 oggstream->page.start_granule = pkt->pts;
580 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
584 ogg_write_pages(s, 0);
586 oggstream->last_granule = granule;
591 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
596 return ogg_write_packet_internal(s, pkt);
598 for (i = 0; i < s->nb_streams; i++) {
599 OGGStreamContext *oggstream = s->streams[i]->priv_data;
600 if (oggstream->page.segments_count)
601 ogg_buffer_page(s, oggstream);
604 ogg_write_pages(s, 2);
608 static int ogg_write_trailer(AVFormatContext *s)
612 /* flush current page if needed */
613 for (i = 0; i < s->nb_streams; i++) {
614 OGGStreamContext *oggstream = s->streams[i]->priv_data;
616 if (oggstream->page.size > 0)
617 ogg_buffer_page(s, oggstream);
620 ogg_write_pages(s, 1);
622 for (i = 0; i < s->nb_streams; i++) {
623 AVStream *st = s->streams[i];
624 OGGStreamContext *oggstream = st->priv_data;
625 if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
626 st->codec->codec_id == AV_CODEC_ID_SPEEX ||
627 st->codec->codec_id == AV_CODEC_ID_OPUS) {
628 av_free(oggstream->header[0]);
630 av_freep(&oggstream->header[1]);
631 av_freep(&st->priv_data);
638 AVOutputFormat ff_ogg_muxer = {
640 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
641 .mime_type = "application/ogg",
642 .extensions = "ogg,ogv",
643 .priv_data_size = sizeof(OGGContext),
644 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
645 AV_CODEC_ID_VORBIS : AV_CODEC_ID_FLAC,
646 .video_codec = AV_CODEC_ID_THEORA,
647 .write_header = ogg_write_header,
648 .write_packet = ogg_write_packet,
649 .write_trailer = ogg_write_trailer,
650 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
651 .priv_class = &ogg_muxer_class,
657 AVOutputFormat ff_oga_muxer = {
659 .long_name = NULL_IF_CONFIG_SMALL("Ogg Audio"),
660 .mime_type = "audio/ogg",
662 .priv_data_size = sizeof(OGGContext),
663 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
664 AV_CODEC_ID_VORBIS : AV_CODEC_ID_FLAC,
665 .write_header = ogg_write_header,
666 .write_packet = ogg_write_packet,
667 .write_trailer = ogg_write_trailer,
668 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
669 .priv_class = &oga_muxer_class,
675 AVOutputFormat ff_spx_muxer = {
677 .long_name = NULL_IF_CONFIG_SMALL("Ogg Speex"),
678 .mime_type = "audio/ogg",
680 .priv_data_size = sizeof(OGGContext),
681 .audio_codec = AV_CODEC_ID_SPEEX,
682 .write_header = ogg_write_header,
683 .write_packet = ogg_write_packet,
684 .write_trailer = ogg_write_trailer,
685 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
686 .priv_class = &spx_muxer_class,
690 #if CONFIG_OPUS_MUXER
692 AVOutputFormat ff_opus_muxer = {
694 .long_name = NULL_IF_CONFIG_SMALL("Ogg Opus"),
695 .mime_type = "audio/ogg",
696 .extensions = "opus",
697 .priv_data_size = sizeof(OGGContext),
698 .audio_codec = AV_CODEC_ID_OPUS,
699 .write_header = ogg_write_header,
700 .write_packet = ogg_write_packet,
701 .write_trailer = ogg_write_trailer,
702 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
703 .priv_class = &opus_muxer_class,