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
37 int64_t start_granule;
41 uint8_t segments_count;
42 uint8_t segments[255];
43 uint8_t data[MAX_PAGE_SIZE];
48 unsigned page_counter;
51 /** for theora granule */
56 unsigned page_count; ///< number of page buffered
57 OGGPage page; ///< current page
58 unsigned serial_num; ///< serial number
59 int64_t last_granule; ///< last packet granule
62 typedef struct OGGPageList {
64 struct OGGPageList *next;
69 OGGPageList *page_list;
70 int pref_size; ///< preferred page size (0 => fill all segments)
71 int64_t pref_duration; ///< preferred page duration (0 => fill all segments)
74 #define OFFSET(x) offsetof(OGGContext, x)
75 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
77 static const AVOption options[] = {
78 { "pagesize", "preferred page size in bytes (deprecated)",
79 OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
80 { "page_duration", "preferred page duration, in microseconds",
81 OFFSET(pref_duration), AV_OPT_TYPE_INT, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
85 static const AVClass ogg_muxer_class = {
86 .class_name = "Ogg muxer",
87 .item_name = av_default_item_name,
89 .version = LIBAVUTIL_VERSION_INT,
93 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
95 int64_t pos = avio_tell(pb);
96 uint32_t checksum = ffio_get_checksum(pb);
97 avio_seek(pb, crc_offset, SEEK_SET);
98 avio_wb32(pb, checksum);
99 avio_seek(pb, pos, SEEK_SET);
102 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
104 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
110 ret = avio_open_dyn_buf(&pb);
113 ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
114 ffio_wfourcc(pb, "OggS");
116 avio_w8(pb, page->flags | extra_flags);
117 avio_wl64(pb, page->granule);
118 avio_wl32(pb, oggstream->serial_num);
119 avio_wl32(pb, oggstream->page_counter++);
120 crc_offset = avio_tell(pb);
121 avio_wl32(pb, 0); // crc
122 avio_w8(pb, page->segments_count);
123 avio_write(pb, page->segments, page->segments_count);
124 avio_write(pb, page->data, page->size);
126 ogg_update_checksum(s, pb, crc_offset);
129 size = avio_close_dyn_buf(pb, &buf);
133 avio_write(s->pb, buf, size);
136 oggstream->page_count--;
140 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
142 if (oggstream->kfgshift)
143 return (granule>>oggstream->kfgshift) +
144 (granule & ((1<<oggstream->kfgshift)-1));
149 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
151 AVStream *st2 = s->streams[next->stream_index];
152 AVStream *st = s->streams[page->stream_index];
153 int64_t next_granule, cur_granule;
155 if (next->granule == -1 || page->granule == -1)
158 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
159 st2->time_base, AV_TIME_BASE_Q);
160 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
161 st ->time_base, AV_TIME_BASE_Q);
162 return next_granule > cur_granule;
165 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
167 oggstream->page.granule = -1;
168 oggstream->page.flags = 0;
169 oggstream->page.segments_count = 0;
170 oggstream->page.size = 0;
174 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
176 OGGContext *ogg = s->priv_data;
177 OGGPageList **p = &ogg->page_list;
178 OGGPageList *l = av_mallocz(sizeof(*l));
181 return AVERROR(ENOMEM);
182 l->page = oggstream->page;
184 oggstream->page.start_granule = oggstream->page.granule;
185 oggstream->page_count++;
186 ogg_reset_cur_page(oggstream);
189 if (ogg_compare_granule(s, &(*p)->page, &l->page))
199 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
200 uint8_t *data, unsigned size, int64_t granule,
203 OGGStreamContext *oggstream = st->priv_data;
204 OGGContext *ogg = s->priv_data;
205 int total_segments = size / 255 + 1;
207 int i, segments, len, flush = 0;
209 // Handles VFR by flushing page because this frame needs to have a timestamp
210 if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
211 ogg_granule_to_timestamp(oggstream, granule) >
212 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
213 if (oggstream->page.granule != -1)
214 ogg_buffer_page(s, oggstream);
218 // avoid a continued page
219 if (!header && oggstream->page.size > 0 &&
220 MAX_PAGE_SIZE - oggstream->page.size < size) {
221 ogg_buffer_page(s, oggstream);
224 for (i = 0; i < total_segments; ) {
225 OGGPage *page = &oggstream->page;
227 segments = FFMIN(total_segments - i, 255 - page->segments_count);
229 if (i && !page->segments_count)
230 page->flags |= 1; // continued packet
232 memset(page->segments+page->segments_count, 255, segments - 1);
233 page->segments_count += segments - 1;
235 len = FFMIN(size, segments*255);
236 page->segments[page->segments_count++] = len - (segments-1)*255;
237 memcpy(page->data+page->size, p, len);
243 if (i == total_segments)
244 page->granule = granule;
247 AVStream *st = s->streams[page->stream_index];
249 int64_t start = av_rescale_q(page->start_granule, st->time_base,
251 int64_t next = av_rescale_q(page->granule, st->time_base,
254 if (page->segments_count == 255 ||
255 (ogg->pref_size > 0 && page->size >= ogg->pref_size) ||
256 (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
257 ogg_buffer_page(s, oggstream);
262 if (flush && oggstream->page.granule != -1)
263 ogg_buffer_page(s, oggstream);
268 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
269 int *header_len, AVDictionary **m, int framing_bit)
271 const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
276 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
278 size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
279 p = av_mallocz(size);
285 ff_vorbiscomment_write(&p, m, vendor, count);
287 bytestream_put_byte(&p, 1);
293 static int ogg_build_flac_headers(AVCodecContext *avctx,
294 OGGStreamContext *oggstream, int bitexact,
297 enum FLACExtradataFormat format;
301 if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
304 // first packet: STREAMINFO
305 oggstream->header_len[0] = 51;
306 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
307 p = oggstream->header[0];
309 return AVERROR(ENOMEM);
310 bytestream_put_byte(&p, 0x7F);
311 bytestream_put_buffer(&p, "FLAC", 4);
312 bytestream_put_byte(&p, 1); // major version
313 bytestream_put_byte(&p, 0); // minor version
314 bytestream_put_be16(&p, 1); // headers packets without this one
315 bytestream_put_buffer(&p, "fLaC", 4);
316 bytestream_put_byte(&p, 0x00); // streaminfo
317 bytestream_put_be24(&p, 34);
318 bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
320 // second packet: VorbisComment
321 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
323 return AVERROR(ENOMEM);
324 oggstream->header[1] = p;
325 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
326 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
331 #define SPEEX_HEADER_SIZE 80
333 static int ogg_build_speex_headers(AVCodecContext *avctx,
334 OGGStreamContext *oggstream, int bitexact,
339 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
342 // first packet: Speex header
343 p = av_mallocz(SPEEX_HEADER_SIZE);
345 return AVERROR(ENOMEM);
346 oggstream->header[0] = p;
347 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
348 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
349 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
351 // second packet: VorbisComment
352 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
354 return AVERROR(ENOMEM);
355 oggstream->header[1] = p;
360 #define OPUS_HEADER_SIZE 19
362 static int ogg_build_opus_headers(AVCodecContext *avctx,
363 OGGStreamContext *oggstream, int bitexact,
368 if (avctx->extradata_size < OPUS_HEADER_SIZE)
371 /* first packet: Opus header */
372 p = av_mallocz(avctx->extradata_size);
374 return AVERROR(ENOMEM);
375 oggstream->header[0] = p;
376 oggstream->header_len[0] = avctx->extradata_size;
377 bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
379 /* second packet: VorbisComment */
380 p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
382 return AVERROR(ENOMEM);
383 oggstream->header[1] = p;
384 bytestream_put_buffer(&p, "OpusTags", 8);
389 static int ogg_write_header(AVFormatContext *s)
391 OGGContext *ogg = s->priv_data;
392 OGGStreamContext *oggstream;
396 av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
398 for (i = 0; i < s->nb_streams; i++) {
399 AVStream *st = s->streams[i];
400 unsigned serial_num = i;
402 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
403 if (st->codec->codec_id == AV_CODEC_ID_OPUS)
404 /* Opus requires a fixed 48kHz clock */
405 avpriv_set_pts_info(st, 64, 1, 48000);
407 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
408 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
409 avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
410 if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
411 st->codec->codec_id != AV_CODEC_ID_THEORA &&
412 st->codec->codec_id != AV_CODEC_ID_SPEEX &&
413 st->codec->codec_id != AV_CODEC_ID_FLAC &&
414 st->codec->codec_id != AV_CODEC_ID_OPUS) {
415 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
419 if (!st->codec->extradata || !st->codec->extradata_size) {
420 av_log(s, AV_LOG_ERROR, "No extradata present\n");
423 oggstream = av_mallocz(sizeof(*oggstream));
424 oggstream->page.stream_index = i;
426 if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
428 serial_num = av_get_random_seed();
429 for (j = 0; j < i; j++) {
430 OGGStreamContext *sc = s->streams[j]->priv_data;
431 if (serial_num == sc->serial_num)
435 oggstream->serial_num = serial_num;
437 st->priv_data = oggstream;
438 if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
439 int err = ogg_build_flac_headers(st->codec, oggstream,
440 st->codec->flags & CODEC_FLAG_BITEXACT,
443 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
444 av_freep(&st->priv_data);
447 } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
448 int err = ogg_build_speex_headers(st->codec, oggstream,
449 st->codec->flags & CODEC_FLAG_BITEXACT,
452 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
453 av_freep(&st->priv_data);
456 } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
457 int err = ogg_build_opus_headers(st->codec, oggstream,
458 st->codec->flags & CODEC_FLAG_BITEXACT,
461 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
462 av_freep(&st->priv_data);
467 const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
468 int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
469 int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
471 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
472 st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
473 oggstream->header, oggstream->header_len) < 0) {
474 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
475 av_freep(&st->priv_data);
479 p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
480 &oggstream->header_len[1], &s->metadata,
482 oggstream->header[1] = p;
484 return AVERROR(ENOMEM);
486 bytestream_put_byte(&p, header_type);
487 bytestream_put_buffer(&p, cstr, 6);
489 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
490 /** KFGSHIFT is the width of the less significant section of the granule position
491 The less significant section is the frame count since the last keyframe */
492 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
493 oggstream->vrev = oggstream->header[0][9];
494 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
495 oggstream->kfgshift, oggstream->vrev);
500 for (j = 0; j < s->nb_streams; j++) {
501 OGGStreamContext *oggstream = s->streams[j]->priv_data;
502 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
503 oggstream->header_len[0], 0, 1);
504 oggstream->page.flags |= 2; // bos
505 ogg_buffer_page(s, oggstream);
507 for (j = 0; j < s->nb_streams; j++) {
508 AVStream *st = s->streams[j];
509 OGGStreamContext *oggstream = st->priv_data;
510 for (i = 1; i < 3; i++) {
511 if (oggstream && oggstream->header_len[i])
512 ogg_buffer_data(s, st, oggstream->header[i],
513 oggstream->header_len[i], 0, 1);
515 ogg_buffer_page(s, oggstream);
518 oggstream->page.start_granule = AV_NOPTS_VALUE;
523 static void ogg_write_pages(AVFormatContext *s, int flush)
525 OGGContext *ogg = s->priv_data;
526 OGGPageList *next, *p;
531 for (p = ogg->page_list; p; ) {
532 OGGStreamContext *oggstream =
533 s->streams[p->page.stream_index]->priv_data;
534 if (oggstream->page_count < 2 && !flush)
536 ogg_write_page(s, &p->page,
537 flush && oggstream->page_count == 1 ? 4 : 0); // eos
545 static int ogg_write_packet(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 + av_rescale_q(st->codec->delay, (AVRational){ 1, st->codec->sample_rate }, st->time_base);
567 granule = pkt->pts + pkt->duration;
569 if (oggstream->page.start_granule == AV_NOPTS_VALUE)
570 oggstream->page.start_granule = pkt->pts;
572 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
576 ogg_write_pages(s, 0);
578 oggstream->last_granule = granule;
583 static int ogg_write_trailer(AVFormatContext *s)
587 /* flush current page if needed */
588 for (i = 0; i < s->nb_streams; i++) {
589 OGGStreamContext *oggstream = s->streams[i]->priv_data;
591 if (oggstream->page.size > 0)
592 ogg_buffer_page(s, oggstream);
595 ogg_write_pages(s, 1);
597 for (i = 0; i < s->nb_streams; i++) {
598 AVStream *st = s->streams[i];
599 OGGStreamContext *oggstream = st->priv_data;
600 if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
601 st->codec->codec_id == AV_CODEC_ID_SPEEX ||
602 st->codec->codec_id == AV_CODEC_ID_OPUS) {
603 av_free(oggstream->header[0]);
605 av_freep(&oggstream->header[1]);
606 av_freep(&st->priv_data);
611 AVOutputFormat ff_ogg_muxer = {
613 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
614 .mime_type = "application/ogg",
615 .extensions = "ogg,ogv,spx,opus",
616 .priv_data_size = sizeof(OGGContext),
617 .audio_codec = AV_CODEC_ID_FLAC,
618 .video_codec = AV_CODEC_ID_THEORA,
619 .write_header = ogg_write_header,
620 .write_packet = ogg_write_packet,
621 .write_trailer = ogg_write_trailer,
622 .priv_class = &ogg_muxer_class,