3 * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
5 * This file is part of FFmpeg.
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.
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.
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
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 { "oggpagesize", "Set preferred Ogg page size.",
81 offsetof(OGGContext, pref_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, MAX_PAGE_SIZE, AV_OPT_FLAG_ENCODING_PARAM},
82 { "pagesize", "preferred page size in bytes (deprecated)",
83 OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
84 { "page_duration", "preferred page duration, in microseconds",
85 OFFSET(pref_duration), AV_OPT_TYPE_INT64, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
89 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
91 int64_t pos = avio_tell(pb);
92 uint32_t checksum = ffio_get_checksum(pb);
93 avio_seek(pb, crc_offset, SEEK_SET);
94 avio_wb32(pb, checksum);
95 avio_seek(pb, pos, SEEK_SET);
98 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
100 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
106 ret = avio_open_dyn_buf(&pb);
109 ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
110 ffio_wfourcc(pb, "OggS");
112 avio_w8(pb, page->flags | extra_flags);
113 avio_wl64(pb, page->granule);
114 avio_wl32(pb, oggstream->serial_num);
115 avio_wl32(pb, oggstream->page_counter++);
116 crc_offset = avio_tell(pb);
117 avio_wl32(pb, 0); // crc
118 avio_w8(pb, page->segments_count);
119 avio_write(pb, page->segments, page->segments_count);
120 avio_write(pb, page->data, page->size);
122 ogg_update_checksum(s, pb, crc_offset);
125 size = avio_close_dyn_buf(pb, &buf);
129 avio_write(s->pb, buf, size);
132 oggstream->page_count--;
136 static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
138 return oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1));
141 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
143 if (oggstream->kfgshift)
144 return (granule>>oggstream->kfgshift) +
145 (granule & ((1<<oggstream->kfgshift)-1));
150 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
152 AVStream *st2 = s->streams[next->stream_index];
153 AVStream *st = s->streams[page->stream_index];
154 int64_t next_granule, cur_granule;
156 if (next->granule == -1 || page->granule == -1)
159 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
160 st2->time_base, AV_TIME_BASE_Q);
161 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
162 st ->time_base, AV_TIME_BASE_Q);
163 return next_granule > cur_granule;
166 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
168 oggstream->page.granule = -1;
169 oggstream->page.flags = 0;
170 oggstream->page.segments_count = 0;
171 oggstream->page.size = 0;
175 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
177 OGGContext *ogg = s->priv_data;
178 OGGPageList **p = &ogg->page_list;
179 OGGPageList *l = av_mallocz(sizeof(*l));
182 return AVERROR(ENOMEM);
183 l->page = oggstream->page;
185 oggstream->page.start_granule = oggstream->page.granule;
186 oggstream->page_count++;
187 ogg_reset_cur_page(oggstream);
190 if (ogg_compare_granule(s, &(*p)->page, &l->page))
200 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
201 uint8_t *data, unsigned size, int64_t granule,
204 OGGStreamContext *oggstream = st->priv_data;
205 OGGContext *ogg = s->priv_data;
206 int total_segments = size / 255 + 1;
208 int i, segments, len, flush = 0;
210 // Handles VFR by flushing page because this frame needs to have a timestamp
211 // For theora, keyframes also need to have a timestamp to correctly mark
212 // them as such, otherwise seeking will not work correctly at the very
213 // least with old libogg versions.
214 // Do not try to flush header packets though, that will create broken files.
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 ogg_key_granule(oggstream, granule))) {
219 if (oggstream->page.granule != -1)
220 ogg_buffer_page(s, oggstream);
224 // avoid a continued page
225 if (!header && oggstream->page.size > 0 &&
226 MAX_PAGE_SIZE - oggstream->page.size < size) {
227 ogg_buffer_page(s, oggstream);
230 for (i = 0; i < total_segments; ) {
231 OGGPage *page = &oggstream->page;
233 segments = FFMIN(total_segments - i, 255 - page->segments_count);
235 if (i && !page->segments_count)
236 page->flags |= 1; // continued packet
238 memset(page->segments+page->segments_count, 255, segments - 1);
239 page->segments_count += segments - 1;
241 len = FFMIN(size, segments*255);
242 page->segments[page->segments_count++] = len - (segments-1)*255;
243 memcpy(page->data+page->size, p, len);
249 if (i == total_segments)
250 page->granule = granule;
253 AVStream *st = s->streams[page->stream_index];
255 int64_t start = av_rescale_q(page->start_granule, st->time_base,
257 int64_t next = av_rescale_q(page->granule, st->time_base,
260 if (page->segments_count == 255 ||
261 (ogg->pref_size > 0 && page->size >= ogg->pref_size) ||
262 (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
263 ogg_buffer_page(s, oggstream);
268 if (flush && oggstream->page.granule != -1)
269 ogg_buffer_page(s, oggstream);
274 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
275 int *header_len, AVDictionary **m, int framing_bit)
277 const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
282 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
284 size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
285 p = av_mallocz(size);
291 ff_vorbiscomment_write(&p, m, vendor, count);
293 bytestream_put_byte(&p, 1);
299 static int ogg_build_flac_headers(AVCodecContext *avctx,
300 OGGStreamContext *oggstream, int bitexact,
303 enum FLACExtradataFormat format;
307 if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
310 // first packet: STREAMINFO
311 oggstream->header_len[0] = 51;
312 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
313 p = oggstream->header[0];
315 return AVERROR(ENOMEM);
316 bytestream_put_byte(&p, 0x7F);
317 bytestream_put_buffer(&p, "FLAC", 4);
318 bytestream_put_byte(&p, 1); // major version
319 bytestream_put_byte(&p, 0); // minor version
320 bytestream_put_be16(&p, 1); // headers packets without this one
321 bytestream_put_buffer(&p, "fLaC", 4);
322 bytestream_put_byte(&p, 0x00); // streaminfo
323 bytestream_put_be24(&p, 34);
324 bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
326 // second packet: VorbisComment
327 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
329 return AVERROR(ENOMEM);
330 oggstream->header[1] = p;
331 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
332 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
337 #define SPEEX_HEADER_SIZE 80
339 static int ogg_build_speex_headers(AVCodecContext *avctx,
340 OGGStreamContext *oggstream, int bitexact,
345 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
348 // first packet: Speex header
349 p = av_mallocz(SPEEX_HEADER_SIZE);
351 return AVERROR(ENOMEM);
352 oggstream->header[0] = p;
353 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
354 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
355 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
357 // second packet: VorbisComment
358 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
360 return AVERROR(ENOMEM);
361 oggstream->header[1] = p;
366 #define OPUS_HEADER_SIZE 19
368 static int ogg_build_opus_headers(AVCodecContext *avctx,
369 OGGStreamContext *oggstream, int bitexact,
374 if (avctx->extradata_size < OPUS_HEADER_SIZE)
377 /* first packet: Opus header */
378 p = av_mallocz(avctx->extradata_size);
380 return AVERROR(ENOMEM);
381 oggstream->header[0] = p;
382 oggstream->header_len[0] = avctx->extradata_size;
383 bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
385 /* second packet: VorbisComment */
386 p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
388 return AVERROR(ENOMEM);
389 oggstream->header[1] = p;
390 bytestream_put_buffer(&p, "OpusTags", 8);
395 static int ogg_write_header(AVFormatContext *s)
397 OGGContext *ogg = s->priv_data;
398 OGGStreamContext *oggstream = NULL;
402 av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
404 for (i = 0; i < s->nb_streams; i++) {
405 AVStream *st = s->streams[i];
406 unsigned serial_num = i;
408 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
409 if (st->codec->codec_id == AV_CODEC_ID_OPUS)
410 /* Opus requires a fixed 48kHz clock */
411 avpriv_set_pts_info(st, 64, 1, 48000);
413 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
414 } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
415 avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
416 if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
417 st->codec->codec_id != AV_CODEC_ID_THEORA &&
418 st->codec->codec_id != AV_CODEC_ID_SPEEX &&
419 st->codec->codec_id != AV_CODEC_ID_FLAC &&
420 st->codec->codec_id != AV_CODEC_ID_OPUS) {
421 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
425 if (!st->codec->extradata || !st->codec->extradata_size) {
426 av_log(s, AV_LOG_ERROR, "No extradata present\n");
429 oggstream = av_mallocz(sizeof(*oggstream));
430 oggstream->page.stream_index = i;
432 if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
434 serial_num = av_get_random_seed();
435 for (j = 0; j < i; j++) {
436 OGGStreamContext *sc = s->streams[j]->priv_data;
437 if (serial_num == sc->serial_num)
441 oggstream->serial_num = serial_num;
443 av_dict_copy(&st->metadata, s->metadata, AV_DICT_DONT_OVERWRITE);
445 st->priv_data = oggstream;
446 if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
447 int err = ogg_build_flac_headers(st->codec, oggstream,
448 st->codec->flags & CODEC_FLAG_BITEXACT,
451 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
452 av_freep(&st->priv_data);
455 } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
456 int err = ogg_build_speex_headers(st->codec, oggstream,
457 st->codec->flags & CODEC_FLAG_BITEXACT,
460 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
461 av_freep(&st->priv_data);
464 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
465 int err = ogg_build_opus_headers(st->codec, oggstream,
466 st->codec->flags & CODEC_FLAG_BITEXACT,
469 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
470 av_freep(&st->priv_data);
475 const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
476 int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
477 int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
479 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
480 st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
481 oggstream->header, oggstream->header_len) < 0) {
482 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
483 av_freep(&st->priv_data);
487 p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
488 &oggstream->header_len[1], &st->metadata,
490 oggstream->header[1] = p;
492 return AVERROR(ENOMEM);
494 bytestream_put_byte(&p, header_type);
495 bytestream_put_buffer(&p, cstr, 6);
497 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
498 /** KFGSHIFT is the width of the less significant section of the granule position
499 The less significant section is the frame count since the last keyframe */
500 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
501 oggstream->vrev = oggstream->header[0][9];
502 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
503 oggstream->kfgshift, oggstream->vrev);
508 for (j = 0; j < s->nb_streams; j++) {
509 OGGStreamContext *oggstream = s->streams[j]->priv_data;
510 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
511 oggstream->header_len[0], 0, 1);
512 oggstream->page.flags |= 2; // bos
513 ogg_buffer_page(s, oggstream);
515 for (j = 0; j < s->nb_streams; j++) {
516 AVStream *st = s->streams[j];
517 OGGStreamContext *oggstream = st->priv_data;
518 for (i = 1; i < 3; i++) {
519 if (oggstream->header_len[i])
520 ogg_buffer_data(s, st, oggstream->header[i],
521 oggstream->header_len[i], 0, 1);
523 ogg_buffer_page(s, oggstream);
526 oggstream->page.start_granule = AV_NOPTS_VALUE;
531 static void ogg_write_pages(AVFormatContext *s, int flush)
533 OGGContext *ogg = s->priv_data;
534 OGGPageList *next, *p;
539 for (p = ogg->page_list; p; ) {
540 OGGStreamContext *oggstream =
541 s->streams[p->page.stream_index]->priv_data;
542 if (oggstream->page_count < 2 && !flush)
544 ogg_write_page(s, &p->page,
545 flush && oggstream->page_count == 1 ? 4 : 0); // eos
553 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
555 AVStream *st = s->streams[pkt->stream_index];
556 OGGStreamContext *oggstream = st->priv_data;
560 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
561 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
563 if (pkt->flags & AV_PKT_FLAG_KEY)
564 oggstream->last_kf_pts = pts;
565 pframe_count = pts - oggstream->last_kf_pts;
566 // prevent frame count from overflow if key frame flag is not set
567 if (pframe_count >= (1<<oggstream->kfgshift)) {
568 oggstream->last_kf_pts += pframe_count;
571 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
572 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS)
573 granule = pkt->pts + pkt->duration + av_rescale_q(st->codec->delay, (AVRational){ 1, st->codec->sample_rate }, st->time_base);
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_trailer(AVFormatContext *s)
595 /* flush current page if needed */
596 for (i = 0; i < s->nb_streams; i++) {
597 OGGStreamContext *oggstream = s->streams[i]->priv_data;
599 if (oggstream->page.size > 0)
600 ogg_buffer_page(s, oggstream);
603 ogg_write_pages(s, 1);
605 for (i = 0; i < s->nb_streams; i++) {
606 AVStream *st = s->streams[i];
607 OGGStreamContext *oggstream = st->priv_data;
608 if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
609 st->codec->codec_id == AV_CODEC_ID_SPEEX ||
610 st->codec->codec_id == AV_CODEC_ID_OPUS) {
611 av_freep(&oggstream->header[0]);
613 av_freep(&oggstream->header[1]);
614 av_freep(&st->priv_data);
620 static const AVClass ogg_muxer_class = {
621 .class_name = "Ogg muxer",
622 .item_name = av_default_item_name,
624 .version = LIBAVUTIL_VERSION_INT,
627 AVOutputFormat ff_ogg_muxer = {
629 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
630 .mime_type = "application/ogg",
631 .extensions = "ogg,ogv"
632 #if !CONFIG_SPEEX_MUXER
635 #if !CONFIG_OPUS_MUXER
639 .priv_data_size = sizeof(OGGContext),
640 .audio_codec = 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,
646 .priv_class = &ogg_muxer_class,
650 #if CONFIG_SPEEX_MUXER
651 static const AVClass speex_muxer_class = {
652 .class_name = "Speex muxer",
653 .item_name = av_default_item_name,
655 .version = LIBAVUTIL_VERSION_INT,
658 AVOutputFormat ff_speex_muxer = {
660 .long_name = NULL_IF_CONFIG_SMALL("Speex"),
661 .mime_type = "audio/ogg",
663 .priv_data_size = sizeof(OGGContext),
664 .audio_codec = AV_CODEC_ID_SPEEX,
665 .video_codec = AV_CODEC_ID_NONE,
666 .write_header = ogg_write_header,
667 .write_packet = ogg_write_packet,
668 .write_trailer = ogg_write_trailer,
669 .flags = AVFMT_TS_NEGATIVE,
670 .priv_class = &speex_muxer_class,
674 #if CONFIG_OPUS_MUXER
675 static const AVClass opus_muxer_class = {
676 .class_name = "Opus muxer",
677 .item_name = av_default_item_name,
679 .version = LIBAVUTIL_VERSION_INT,
682 AVOutputFormat ff_opus_muxer = {
684 .long_name = NULL_IF_CONFIG_SMALL("Opus"),
685 .mime_type = "audio/ogg",
686 .extensions = "opus",
687 .priv_data_size = sizeof(OGGContext),
688 .audio_codec = AV_CODEC_ID_OPUS,
689 .video_codec = AV_CODEC_ID_NONE,
690 .write_header = ogg_write_header,
691 .write_packet = ogg_write_packet,
692 .write_trailer = ogg_write_trailer,
693 .flags = AVFMT_TS_NEGATIVE,
694 .priv_class = &opus_muxer_class,