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
39 int64_t start_granule;
43 uint8_t segments_count;
44 uint8_t segments[255];
45 uint8_t data[MAX_PAGE_SIZE];
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;
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)
76 #define OFFSET(x) offsetof(OGGContext, x)
77 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
79 static const AVOption options[] = {
80 { "pagesize", "preferred page size in bytes (deprecated)",
81 OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
82 { "page_duration", "preferred page duration, in microseconds",
83 OFFSET(pref_duration), AV_OPT_TYPE_INT64, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
87 #define OGG_CLASS(flavor)\
88 static const AVClass flavor ## _muxer_class = {\
89 .class_name = #flavor " muxer",\
90 .item_name = av_default_item_name,\
92 .version = LIBAVUTIL_VERSION_INT,\
95 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
97 int64_t pos = avio_tell(pb);
98 uint32_t checksum = ffio_get_checksum(pb);
99 avio_seek(pb, crc_offset, SEEK_SET);
100 avio_wb32(pb, checksum);
101 avio_seek(pb, pos, SEEK_SET);
104 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
106 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
112 ret = avio_open_dyn_buf(&pb);
115 ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
116 ffio_wfourcc(pb, "OggS");
118 avio_w8(pb, page->flags | extra_flags);
119 avio_wl64(pb, page->granule);
120 avio_wl32(pb, oggstream->serial_num);
121 avio_wl32(pb, oggstream->page_counter++);
122 crc_offset = avio_tell(pb);
123 avio_wl32(pb, 0); // crc
124 avio_w8(pb, page->segments_count);
125 avio_write(pb, page->segments, page->segments_count);
126 avio_write(pb, page->data, page->size);
128 ogg_update_checksum(s, pb, crc_offset);
131 size = avio_close_dyn_buf(pb, &buf);
135 avio_write(s->pb, buf, size);
138 oggstream->page_count--;
142 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
144 if (oggstream->kfgshift)
145 return (granule>>oggstream->kfgshift) +
146 (granule & ((1<<oggstream->kfgshift)-1));
151 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
153 AVStream *st2 = s->streams[next->stream_index];
154 AVStream *st = s->streams[page->stream_index];
155 int64_t next_granule, cur_granule;
157 if (next->granule == -1 || page->granule == -1)
160 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
161 st2->time_base, AV_TIME_BASE_Q);
162 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
163 st ->time_base, AV_TIME_BASE_Q);
164 return next_granule > cur_granule;
167 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
169 oggstream->page.granule = -1;
170 oggstream->page.flags = 0;
171 oggstream->page.segments_count = 0;
172 oggstream->page.size = 0;
176 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
178 OGGContext *ogg = s->priv_data;
179 OGGPageList **p = &ogg->page_list;
180 OGGPageList *l = av_mallocz(sizeof(*l));
183 return AVERROR(ENOMEM);
184 l->page = oggstream->page;
186 oggstream->page.start_granule = oggstream->page.granule;
187 oggstream->page_count++;
188 ogg_reset_cur_page(oggstream);
191 if (ogg_compare_granule(s, &(*p)->page, &l->page))
201 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
202 uint8_t *data, unsigned size, int64_t granule,
205 OGGStreamContext *oggstream = st->priv_data;
206 OGGContext *ogg = s->priv_data;
207 int total_segments = size / 255 + 1;
209 int i, segments, len, flush = 0;
211 // Handles VFR by flushing page because this frame needs to have a timestamp
212 if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
213 ogg_granule_to_timestamp(oggstream, granule) >
214 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
215 if (oggstream->page.granule != -1)
216 ogg_buffer_page(s, oggstream);
220 // avoid a continued page
221 if (!header && oggstream->page.size > 0 &&
222 MAX_PAGE_SIZE - oggstream->page.size < size) {
223 ogg_buffer_page(s, oggstream);
226 for (i = 0; i < total_segments; ) {
227 OGGPage *page = &oggstream->page;
229 segments = FFMIN(total_segments - i, 255 - page->segments_count);
231 if (i && !page->segments_count)
232 page->flags |= 1; // continued packet
234 memset(page->segments+page->segments_count, 255, segments - 1);
235 page->segments_count += segments - 1;
237 len = FFMIN(size, segments*255);
238 page->segments[page->segments_count++] = len - (segments-1)*255;
239 memcpy(page->data+page->size, p, len);
245 if (i == total_segments)
246 page->granule = granule;
249 AVStream *st = s->streams[page->stream_index];
251 int64_t start = av_rescale_q(page->start_granule, st->time_base,
253 int64_t next = av_rescale_q(page->granule, st->time_base,
256 if (page->segments_count == 255 ||
257 (ogg->pref_size > 0 && page->size >= ogg->pref_size) ||
258 (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
259 ogg_buffer_page(s, oggstream);
264 if (flush && oggstream->page.granule != -1)
265 ogg_buffer_page(s, oggstream);
270 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
271 int *header_len, AVDictionary **m, int framing_bit)
273 const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
277 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
279 size = offset + ff_vorbiscomment_length(*m, vendor) + framing_bit;
280 p = av_mallocz(size);
286 ff_vorbiscomment_write(&p, m, vendor);
288 bytestream_put_byte(&p, 1);
294 static int ogg_build_flac_headers(AVCodecContext *avctx,
295 OGGStreamContext *oggstream, int bitexact,
300 if (avctx->extradata_size < FLAC_STREAMINFO_SIZE)
301 return AVERROR(EINVAL);
303 // first packet: STREAMINFO
304 oggstream->header_len[0] = 51;
305 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
306 p = oggstream->header[0];
308 return AVERROR(ENOMEM);
309 bytestream_put_byte(&p, 0x7F);
310 bytestream_put_buffer(&p, "FLAC", 4);
311 bytestream_put_byte(&p, 1); // major version
312 bytestream_put_byte(&p, 0); // minor version
313 bytestream_put_be16(&p, 1); // headers packets without this one
314 bytestream_put_buffer(&p, "fLaC", 4);
315 bytestream_put_byte(&p, 0x00); // streaminfo
316 bytestream_put_be24(&p, 34);
317 bytestream_put_buffer(&p, avctx->extradata, FLAC_STREAMINFO_SIZE);
319 // second packet: VorbisComment
320 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
322 return AVERROR(ENOMEM);
323 oggstream->header[1] = p;
324 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
325 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
330 #define SPEEX_HEADER_SIZE 80
332 static int ogg_build_speex_headers(AVCodecContext *avctx,
333 OGGStreamContext *oggstream, int bitexact,
338 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
341 // first packet: Speex header
342 p = av_mallocz(SPEEX_HEADER_SIZE);
344 return AVERROR(ENOMEM);
345 oggstream->header[0] = p;
346 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
347 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
348 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
350 // second packet: VorbisComment
351 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
353 return AVERROR(ENOMEM);
354 oggstream->header[1] = p;
359 #define OPUS_HEADER_SIZE 19
361 static int ogg_build_opus_headers(AVCodecContext *avctx,
362 OGGStreamContext *oggstream, int bitexact,
367 if (avctx->extradata_size < OPUS_HEADER_SIZE)
370 /* first packet: Opus header */
371 p = av_mallocz(avctx->extradata_size);
373 return AVERROR(ENOMEM);
374 oggstream->header[0] = p;
375 oggstream->header_len[0] = avctx->extradata_size;
376 bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
378 /* second packet: VorbisComment */
379 p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
381 return AVERROR(ENOMEM);
382 oggstream->header[1] = p;
383 bytestream_put_buffer(&p, "OpusTags", 8);
388 static void ogg_write_pages(AVFormatContext *s, int flush)
390 OGGContext *ogg = s->priv_data;
391 OGGPageList *next, *p;
396 for (p = ogg->page_list; p; ) {
397 OGGStreamContext *oggstream =
398 s->streams[p->page.stream_index]->priv_data;
399 if (oggstream->page_count < 2 && !flush)
401 ogg_write_page(s, &p->page,
402 flush == 1 && oggstream->page_count == 1 ? 4 : 0); // eos
410 static int ogg_write_header(AVFormatContext *s)
412 OGGContext *ogg = s->priv_data;
413 OGGStreamContext *oggstream;
417 av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
419 for (i = 0; i < s->nb_streams; i++) {
420 AVStream *st = s->streams[i];
421 unsigned serial_num = i;
423 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
424 if (st->codec->codec_id == AV_CODEC_ID_OPUS)
425 /* Opus requires a fixed 48kHz clock */
426 avpriv_set_pts_info(st, 64, 1, 48000);
428 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
430 if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
431 st->codec->codec_id != AV_CODEC_ID_THEORA &&
432 st->codec->codec_id != AV_CODEC_ID_SPEEX &&
433 st->codec->codec_id != AV_CODEC_ID_FLAC &&
434 st->codec->codec_id != AV_CODEC_ID_OPUS) {
435 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
439 if (!st->codec->extradata || !st->codec->extradata_size) {
440 av_log(s, AV_LOG_ERROR, "No extradata present\n");
443 oggstream = av_mallocz(sizeof(*oggstream));
444 oggstream->page.stream_index = i;
446 if (!(s->flags & AVFMT_FLAG_BITEXACT))
448 serial_num = av_get_random_seed();
449 for (j = 0; j < i; j++) {
450 OGGStreamContext *sc = s->streams[j]->priv_data;
451 if (serial_num == sc->serial_num)
455 oggstream->serial_num = serial_num;
457 st->priv_data = oggstream;
458 if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
459 int err = ogg_build_flac_headers(st->codec, oggstream,
460 s->flags & AVFMT_FLAG_BITEXACT,
463 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
464 av_freep(&st->priv_data);
467 } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
468 int err = ogg_build_speex_headers(st->codec, oggstream,
469 s->flags & AVFMT_FLAG_BITEXACT,
472 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
473 av_freep(&st->priv_data);
476 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
477 int err = ogg_build_opus_headers(st->codec, oggstream,
478 s->flags & AVFMT_FLAG_BITEXACT,
481 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
482 av_freep(&st->priv_data);
487 const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
488 int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
489 int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
491 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
492 st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
493 oggstream->header, oggstream->header_len) < 0) {
494 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
495 av_freep(&st->priv_data);
499 p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
500 &oggstream->header_len[1], &s->metadata,
502 oggstream->header[1] = p;
504 return AVERROR(ENOMEM);
506 bytestream_put_byte(&p, header_type);
507 bytestream_put_buffer(&p, cstr, 6);
509 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
510 /** KFGSHIFT is the width of the less significant section of the granule position
511 The less significant section is the frame count since the last keyframe */
512 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
513 oggstream->vrev = oggstream->header[0][9];
514 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
515 oggstream->kfgshift, oggstream->vrev);
520 for (j = 0; j < s->nb_streams; j++) {
521 OGGStreamContext *oggstream = s->streams[j]->priv_data;
522 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
523 oggstream->header_len[0], 0, 1);
524 oggstream->page.flags |= 2; // bos
525 ogg_buffer_page(s, oggstream);
527 for (j = 0; j < s->nb_streams; j++) {
528 AVStream *st = s->streams[j];
529 OGGStreamContext *oggstream = st->priv_data;
530 for (i = 1; i < 3; i++) {
531 if (oggstream->header_len[i])
532 ogg_buffer_data(s, st, oggstream->header[i],
533 oggstream->header_len[i], 0, 1);
535 ogg_buffer_page(s, oggstream);
538 oggstream->page.start_granule = AV_NOPTS_VALUE;
540 ogg_write_pages(s, 2);
545 static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
547 AVStream *st = s->streams[pkt->stream_index];
548 OGGStreamContext *oggstream = st->priv_data;
552 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
553 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
555 if (pkt->flags & AV_PKT_FLAG_KEY)
556 oggstream->last_kf_pts = pts;
557 pframe_count = pts - oggstream->last_kf_pts;
558 // prevent frame count from overflow if key frame flag is not set
559 if (pframe_count >= (1<<oggstream->kfgshift)) {
560 oggstream->last_kf_pts += pframe_count;
563 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
564 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS)
565 granule = pkt->pts + pkt->duration +
566 av_rescale_q(st->codec->initial_padding,
567 (AVRational){ 1, st->codec->sample_rate },
570 granule = pkt->pts + pkt->duration;
572 if (oggstream->page.start_granule == AV_NOPTS_VALUE)
573 oggstream->page.start_granule = pkt->pts;
575 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
579 ogg_write_pages(s, 0);
581 oggstream->last_granule = granule;
586 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
591 return ogg_write_packet_internal(s, pkt);
593 for (i = 0; i < s->nb_streams; i++) {
594 OGGStreamContext *oggstream = s->streams[i]->priv_data;
595 if (oggstream->page.segments_count)
596 ogg_buffer_page(s, oggstream);
599 ogg_write_pages(s, 2);
603 static int ogg_write_trailer(AVFormatContext *s)
607 /* flush current page if needed */
608 for (i = 0; i < s->nb_streams; i++) {
609 OGGStreamContext *oggstream = s->streams[i]->priv_data;
611 if (oggstream->page.size > 0)
612 ogg_buffer_page(s, oggstream);
615 ogg_write_pages(s, 1);
617 for (i = 0; i < s->nb_streams; i++) {
618 AVStream *st = s->streams[i];
619 OGGStreamContext *oggstream = st->priv_data;
620 if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
621 st->codec->codec_id == AV_CODEC_ID_SPEEX ||
622 st->codec->codec_id == AV_CODEC_ID_OPUS) {
623 av_free(oggstream->header[0]);
625 av_freep(&oggstream->header[1]);
626 av_freep(&st->priv_data);
633 AVOutputFormat ff_ogg_muxer = {
635 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
636 .mime_type = "application/ogg",
637 .extensions = "ogg,ogv",
638 .priv_data_size = sizeof(OGGContext),
639 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
640 AV_CODEC_ID_VORBIS : AV_CODEC_ID_FLAC,
641 .video_codec = AV_CODEC_ID_THEORA,
642 .write_header = ogg_write_header,
643 .write_packet = ogg_write_packet,
644 .write_trailer = ogg_write_trailer,
645 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
646 .priv_class = &ogg_muxer_class,
652 AVOutputFormat ff_oga_muxer = {
654 .long_name = NULL_IF_CONFIG_SMALL("Ogg Audio"),
655 .mime_type = "audio/ogg",
657 .priv_data_size = sizeof(OGGContext),
658 .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
659 AV_CODEC_ID_VORBIS : AV_CODEC_ID_FLAC,
660 .write_header = ogg_write_header,
661 .write_packet = ogg_write_packet,
662 .write_trailer = ogg_write_trailer,
663 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
664 .priv_class = &oga_muxer_class,
670 AVOutputFormat ff_spx_muxer = {
672 .long_name = NULL_IF_CONFIG_SMALL("Ogg Speex"),
673 .mime_type = "audio/ogg",
675 .priv_data_size = sizeof(OGGContext),
676 .audio_codec = AV_CODEC_ID_SPEEX,
677 .write_header = ogg_write_header,
678 .write_packet = ogg_write_packet,
679 .write_trailer = ogg_write_trailer,
680 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
681 .priv_class = &spx_muxer_class,
685 #if CONFIG_OPUS_MUXER
687 AVOutputFormat ff_opus_muxer = {
689 .long_name = NULL_IF_CONFIG_SMALL("Ogg Opus"),
690 .mime_type = "audio/ogg",
691 .extensions = "opus",
692 .priv_data_size = sizeof(OGGContext),
693 .audio_codec = AV_CODEC_ID_OPUS,
694 .write_header = ogg_write_header,
695 .write_packet = ogg_write_packet,
696 .write_trailer = ogg_write_trailer,
697 .flags = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
698 .priv_class = &opus_muxer_class,