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
22 #include "libavutil/crc.h"
23 #include "libavutil/mathematics.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/random_seed.h"
26 #include "libavcodec/xiph.h"
27 #include "libavcodec/bytestream.h"
28 #include "libavcodec/flac.h"
30 #include "avio_internal.h"
32 #include "vorbiscomment.h"
34 #define MAX_PAGE_SIZE 65025
40 uint8_t segments_count;
41 uint8_t segments[255];
42 uint8_t data[MAX_PAGE_SIZE];
47 unsigned page_counter;
50 /** for theora granule */
55 unsigned page_count; ///< number of page buffered
56 OGGPage page; ///< current page
57 unsigned serial_num; ///< serial number
58 int64_t last_granule; ///< last packet granule
61 typedef struct OGGPageList {
63 struct OGGPageList *next;
68 OGGPageList *page_list;
69 int pref_size; ///< preferred page size (0 => fill all segments)
72 #define OFFSET(x) offsetof(OGGContext, x)
73 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
75 static const AVOption options[] = {
76 { "pagesize", "preferred page size in bytes",
77 OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
81 static const AVClass ogg_muxer_class = {
82 .class_name = "Ogg muxer",
83 .item_name = av_default_item_name,
85 .version = LIBAVUTIL_VERSION_INT,
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 int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
138 if (oggstream->kfgshift)
139 return (granule>>oggstream->kfgshift) +
140 (granule & ((1<<oggstream->kfgshift)-1));
145 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
147 AVStream *st2 = s->streams[next->stream_index];
148 AVStream *st = s->streams[page->stream_index];
149 int64_t next_granule, cur_granule;
151 if (next->granule == -1 || page->granule == -1)
154 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
155 st2->time_base, AV_TIME_BASE_Q);
156 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
157 st ->time_base, AV_TIME_BASE_Q);
158 return next_granule > cur_granule;
161 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
163 oggstream->page.granule = -1;
164 oggstream->page.flags = 0;
165 oggstream->page.segments_count = 0;
166 oggstream->page.size = 0;
170 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
172 OGGContext *ogg = s->priv_data;
173 OGGPageList **p = &ogg->page_list;
174 OGGPageList *l = av_mallocz(sizeof(*l));
177 return AVERROR(ENOMEM);
178 l->page = oggstream->page;
180 oggstream->page_count++;
181 ogg_reset_cur_page(oggstream);
184 if (ogg_compare_granule(s, &(*p)->page, &l->page))
194 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
195 uint8_t *data, unsigned size, int64_t granule,
198 OGGStreamContext *oggstream = st->priv_data;
199 OGGContext *ogg = s->priv_data;
200 int total_segments = size / 255 + 1;
202 int i, segments, len, flush = 0;
204 // Handles VFR by flushing page because this frame needs to have a timestamp
205 if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
206 ogg_granule_to_timestamp(oggstream, granule) >
207 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
208 if (oggstream->page.granule != -1)
209 ogg_buffer_page(s, oggstream);
213 for (i = 0; i < total_segments; ) {
214 OGGPage *page = &oggstream->page;
216 segments = FFMIN(total_segments - i, 255 - page->segments_count);
218 if (i && !page->segments_count)
219 page->flags |= 1; // continued packet
221 memset(page->segments+page->segments_count, 255, segments - 1);
222 page->segments_count += segments - 1;
224 len = FFMIN(size, segments*255);
225 page->segments[page->segments_count++] = len - (segments-1)*255;
226 memcpy(page->data+page->size, p, len);
232 if (i == total_segments)
233 page->granule = granule;
235 if (!header && (page->segments_count == 255 ||
236 (ogg->pref_size > 0 && page->size >= ogg->pref_size))) {
237 ogg_buffer_page(s, oggstream);
241 if (flush && oggstream->page.granule != -1)
242 ogg_buffer_page(s, oggstream);
247 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
248 int *header_len, AVDictionary **m, int framing_bit)
250 const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
255 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
257 size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
258 p = av_mallocz(size);
264 ff_vorbiscomment_write(&p, m, vendor, count);
266 bytestream_put_byte(&p, 1);
272 static int ogg_build_flac_headers(AVCodecContext *avctx,
273 OGGStreamContext *oggstream, int bitexact,
276 enum FLACExtradataFormat format;
280 if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
283 // first packet: STREAMINFO
284 oggstream->header_len[0] = 51;
285 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
286 p = oggstream->header[0];
288 return AVERROR(ENOMEM);
289 bytestream_put_byte(&p, 0x7F);
290 bytestream_put_buffer(&p, "FLAC", 4);
291 bytestream_put_byte(&p, 1); // major version
292 bytestream_put_byte(&p, 0); // minor version
293 bytestream_put_be16(&p, 1); // headers packets without this one
294 bytestream_put_buffer(&p, "fLaC", 4);
295 bytestream_put_byte(&p, 0x00); // streaminfo
296 bytestream_put_be24(&p, 34);
297 bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
299 // second packet: VorbisComment
300 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
302 return AVERROR(ENOMEM);
303 oggstream->header[1] = p;
304 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
305 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
310 #define SPEEX_HEADER_SIZE 80
312 static int ogg_build_speex_headers(AVCodecContext *avctx,
313 OGGStreamContext *oggstream, int bitexact,
318 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
321 // first packet: Speex header
322 p = av_mallocz(SPEEX_HEADER_SIZE);
324 return AVERROR(ENOMEM);
325 oggstream->header[0] = p;
326 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
327 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
328 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
330 // second packet: VorbisComment
331 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
333 return AVERROR(ENOMEM);
334 oggstream->header[1] = p;
339 #define OPUS_HEADER_SIZE 19
341 static int ogg_build_opus_headers(AVCodecContext *avctx,
342 OGGStreamContext *oggstream, int bitexact,
347 if (avctx->extradata_size < OPUS_HEADER_SIZE)
350 /* first packet: Opus header */
351 p = av_mallocz(avctx->extradata_size);
353 return AVERROR(ENOMEM);
354 oggstream->header[0] = p;
355 oggstream->header_len[0] = avctx->extradata_size;
356 bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
358 /* second packet: VorbisComment */
359 p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
361 return AVERROR(ENOMEM);
362 oggstream->header[1] = p;
363 bytestream_put_buffer(&p, "OpusTags", 8);
368 static int ogg_write_header(AVFormatContext *s)
370 OGGStreamContext *oggstream;
373 for (i = 0; i < s->nb_streams; i++) {
374 AVStream *st = s->streams[i];
375 unsigned serial_num = i;
377 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
378 if (st->codec->codec_id == AV_CODEC_ID_OPUS)
379 /* Opus requires a fixed 48kHz clock */
380 avpriv_set_pts_info(st, 64, 1, 48000);
382 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
383 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
384 avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
385 if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
386 st->codec->codec_id != AV_CODEC_ID_THEORA &&
387 st->codec->codec_id != AV_CODEC_ID_SPEEX &&
388 st->codec->codec_id != AV_CODEC_ID_FLAC &&
389 st->codec->codec_id != AV_CODEC_ID_OPUS) {
390 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
394 if (!st->codec->extradata || !st->codec->extradata_size) {
395 av_log(s, AV_LOG_ERROR, "No extradata present\n");
398 oggstream = av_mallocz(sizeof(*oggstream));
399 oggstream->page.stream_index = i;
401 if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
403 serial_num = av_get_random_seed();
404 for (j = 0; j < i; j++) {
405 OGGStreamContext *sc = s->streams[j]->priv_data;
406 if (serial_num == sc->serial_num)
410 oggstream->serial_num = serial_num;
412 st->priv_data = oggstream;
413 if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
414 int err = ogg_build_flac_headers(st->codec, oggstream,
415 st->codec->flags & CODEC_FLAG_BITEXACT,
418 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
419 av_freep(&st->priv_data);
422 } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
423 int err = ogg_build_speex_headers(st->codec, oggstream,
424 st->codec->flags & CODEC_FLAG_BITEXACT,
427 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
428 av_freep(&st->priv_data);
431 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
432 int err = ogg_build_opus_headers(st->codec, oggstream,
433 st->codec->flags & CODEC_FLAG_BITEXACT,
436 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
437 av_freep(&st->priv_data);
442 const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
443 int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
444 int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
446 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
447 st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
448 oggstream->header, oggstream->header_len) < 0) {
449 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
450 av_freep(&st->priv_data);
454 p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
455 &oggstream->header_len[1], &s->metadata,
457 oggstream->header[1] = p;
459 return AVERROR(ENOMEM);
461 bytestream_put_byte(&p, header_type);
462 bytestream_put_buffer(&p, cstr, 6);
464 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
465 /** KFGSHIFT is the width of the less significant section of the granule position
466 The less significant section is the frame count since the last keyframe */
467 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
468 oggstream->vrev = oggstream->header[0][9];
469 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
470 oggstream->kfgshift, oggstream->vrev);
475 for (j = 0; j < s->nb_streams; j++) {
476 OGGStreamContext *oggstream = s->streams[j]->priv_data;
477 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
478 oggstream->header_len[0], 0, 1);
479 oggstream->page.flags |= 2; // bos
480 ogg_buffer_page(s, oggstream);
482 for (j = 0; j < s->nb_streams; j++) {
483 AVStream *st = s->streams[j];
484 OGGStreamContext *oggstream = st->priv_data;
485 for (i = 1; i < 3; i++) {
486 if (oggstream && oggstream->header_len[i])
487 ogg_buffer_data(s, st, oggstream->header[i],
488 oggstream->header_len[i], 0, 1);
490 ogg_buffer_page(s, oggstream);
495 static void ogg_write_pages(AVFormatContext *s, int flush)
497 OGGContext *ogg = s->priv_data;
498 OGGPageList *next, *p;
503 for (p = ogg->page_list; p; ) {
504 OGGStreamContext *oggstream =
505 s->streams[p->page.stream_index]->priv_data;
506 if (oggstream->page_count < 2 && !flush)
508 ogg_write_page(s, &p->page,
509 flush && oggstream->page_count == 1 ? 4 : 0); // eos
517 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
519 AVStream *st = s->streams[pkt->stream_index];
520 OGGStreamContext *oggstream = st->priv_data;
524 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
525 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
527 if (pkt->flags & AV_PKT_FLAG_KEY)
528 oggstream->last_kf_pts = pts;
529 pframe_count = pts - oggstream->last_kf_pts;
530 // prevent frame count from overflow if key frame flag is not set
531 if (pframe_count >= (1<<oggstream->kfgshift)) {
532 oggstream->last_kf_pts += pframe_count;
535 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
536 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS)
537 granule = pkt->pts + pkt->duration + av_rescale_q(st->codec->delay, (AVRational){ 1, st->codec->sample_rate }, st->time_base);
539 granule = pkt->pts + pkt->duration;
541 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
545 ogg_write_pages(s, 0);
547 oggstream->last_granule = granule;
552 static int ogg_write_trailer(AVFormatContext *s)
556 /* flush current page */
557 for (i = 0; i < s->nb_streams; i++)
558 ogg_buffer_page(s, s->streams[i]->priv_data);
560 ogg_write_pages(s, 1);
562 for (i = 0; i < s->nb_streams; i++) {
563 AVStream *st = s->streams[i];
564 OGGStreamContext *oggstream = st->priv_data;
565 if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
566 st->codec->codec_id == AV_CODEC_ID_SPEEX ||
567 st->codec->codec_id == AV_CODEC_ID_OPUS) {
568 av_free(oggstream->header[0]);
570 av_freep(&oggstream->header[1]);
571 av_freep(&st->priv_data);
576 AVOutputFormat ff_ogg_muxer = {
578 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
579 .mime_type = "application/ogg",
580 .extensions = "ogg,ogv,spx,opus",
581 .priv_data_size = sizeof(OGGContext),
582 .audio_codec = AV_CODEC_ID_FLAC,
583 .video_codec = AV_CODEC_ID_THEORA,
584 .write_header = ogg_write_header,
585 .write_packet = ogg_write_packet,
586 .write_trailer = ogg_write_trailer,
587 .priv_class = &ogg_muxer_class,