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
22 #include "libavutil/crc.h"
23 #include "libavutil/opt.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/random_seed.h"
27 #include "libavcodec/xiph.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavcodec/flac.h"
31 #include "avio_internal.h"
33 #include "vorbiscomment.h"
35 #define MAX_PAGE_SIZE 65025
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)
73 #define OFFSET(x) offsetof(OGGContext, x)
74 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
76 static const AVOption options[] = {
77 { "oggpagesize", "Set preferred Ogg page size.",
78 offsetof(OGGContext, pref_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, MAX_PAGE_SIZE, AV_OPT_FLAG_ENCODING_PARAM},
79 { "pagesize", "preferred page size in bytes",
80 OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
84 static const AVClass ogg_muxer_class = {
85 .class_name = "Ogg muxer",
86 .item_name = av_default_item_name,
88 .version = LIBAVUTIL_VERSION_INT,
92 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
94 int64_t pos = avio_tell(pb);
95 uint32_t checksum = ffio_get_checksum(pb);
96 avio_seek(pb, crc_offset, SEEK_SET);
97 avio_wb32(pb, checksum);
98 avio_seek(pb, pos, SEEK_SET);
101 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
103 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
109 ret = avio_open_dyn_buf(&pb);
112 ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
113 ffio_wfourcc(pb, "OggS");
115 avio_w8(pb, page->flags | extra_flags);
116 avio_wl64(pb, page->granule);
117 avio_wl32(pb, oggstream->serial_num);
118 avio_wl32(pb, oggstream->page_counter++);
119 crc_offset = avio_tell(pb);
120 avio_wl32(pb, 0); // crc
121 avio_w8(pb, page->segments_count);
122 avio_write(pb, page->segments, page->segments_count);
123 avio_write(pb, page->data, page->size);
125 ogg_update_checksum(s, pb, crc_offset);
128 size = avio_close_dyn_buf(pb, &buf);
132 avio_write(s->pb, buf, size);
135 oggstream->page_count--;
139 static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
141 return oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1));
144 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
146 if (oggstream->kfgshift)
147 return (granule>>oggstream->kfgshift) +
148 (granule & ((1<<oggstream->kfgshift)-1));
153 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
155 AVStream *st2 = s->streams[next->stream_index];
156 AVStream *st = s->streams[page->stream_index];
157 int64_t next_granule, cur_granule;
159 if (next->granule == -1 || page->granule == -1)
162 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
163 st2->time_base, AV_TIME_BASE_Q);
164 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
165 st ->time_base, AV_TIME_BASE_Q);
166 return next_granule > cur_granule;
169 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
171 oggstream->page.granule = -1;
172 oggstream->page.flags = 0;
173 oggstream->page.segments_count = 0;
174 oggstream->page.size = 0;
178 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
180 OGGContext *ogg = s->priv_data;
181 OGGPageList **p = &ogg->page_list;
182 OGGPageList *l = av_mallocz(sizeof(*l));
185 return AVERROR(ENOMEM);
186 l->page = oggstream->page;
188 oggstream->page_count++;
189 ogg_reset_cur_page(oggstream);
192 if (ogg_compare_granule(s, &(*p)->page, &l->page))
202 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
203 uint8_t *data, unsigned size, int64_t granule,
206 OGGStreamContext *oggstream = st->priv_data;
207 OGGContext *ogg = s->priv_data;
208 int total_segments = size / 255 + 1;
210 int i, segments, len, flush = 0;
212 // Handles VFR by flushing page because this frame needs to have a timestamp
213 // For theora, keyframes also need to have a timestamp to correctly mark
214 // them as such, otherwise seeking will not work correctly at the very
215 // least with old libogg versions.
216 // Do not try to flush header packets though, that will create broken files.
217 if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
218 (ogg_granule_to_timestamp(oggstream, granule) >
219 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
220 ogg_key_granule(oggstream, granule))) {
221 if (oggstream->page.granule != -1)
222 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;
248 if (!header && (page->segments_count == 255 ||
249 (ogg->pref_size > 0 && page->size >= ogg->pref_size))) {
250 ogg_buffer_page(s, oggstream);
254 if (flush && oggstream->page.granule != -1)
255 ogg_buffer_page(s, oggstream);
260 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
261 int *header_len, AVDictionary **m, int framing_bit)
263 const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
268 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
270 size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
271 p = av_mallocz(size);
277 ff_vorbiscomment_write(&p, m, vendor, count);
279 bytestream_put_byte(&p, 1);
285 static int ogg_build_flac_headers(AVCodecContext *avctx,
286 OGGStreamContext *oggstream, int bitexact,
289 enum FLACExtradataFormat format;
293 if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
296 // first packet: STREAMINFO
297 oggstream->header_len[0] = 51;
298 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
299 p = oggstream->header[0];
301 return AVERROR(ENOMEM);
302 bytestream_put_byte(&p, 0x7F);
303 bytestream_put_buffer(&p, "FLAC", 4);
304 bytestream_put_byte(&p, 1); // major version
305 bytestream_put_byte(&p, 0); // minor version
306 bytestream_put_be16(&p, 1); // headers packets without this one
307 bytestream_put_buffer(&p, "fLaC", 4);
308 bytestream_put_byte(&p, 0x00); // streaminfo
309 bytestream_put_be24(&p, 34);
310 bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
312 // second packet: VorbisComment
313 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
315 return AVERROR(ENOMEM);
316 oggstream->header[1] = p;
317 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
318 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
323 #define SPEEX_HEADER_SIZE 80
325 static int ogg_build_speex_headers(AVCodecContext *avctx,
326 OGGStreamContext *oggstream, int bitexact,
331 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
334 // first packet: Speex header
335 p = av_mallocz(SPEEX_HEADER_SIZE);
337 return AVERROR(ENOMEM);
338 oggstream->header[0] = p;
339 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
340 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
341 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
343 // second packet: VorbisComment
344 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
346 return AVERROR(ENOMEM);
347 oggstream->header[1] = p;
352 static int ogg_write_header(AVFormatContext *s)
354 OGGStreamContext *oggstream;
357 for (i = 0; i < s->nb_streams; i++) {
358 AVStream *st = s->streams[i];
359 unsigned serial_num = i;
361 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
362 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
363 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
364 avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
365 if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
366 st->codec->codec_id != AV_CODEC_ID_THEORA &&
367 st->codec->codec_id != AV_CODEC_ID_SPEEX &&
368 st->codec->codec_id != AV_CODEC_ID_FLAC) {
369 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
373 if (!st->codec->extradata || !st->codec->extradata_size) {
374 av_log(s, AV_LOG_ERROR, "No extradata present\n");
377 oggstream = av_mallocz(sizeof(*oggstream));
378 oggstream->page.stream_index = i;
380 if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
382 serial_num = av_get_random_seed();
383 for (j = 0; j < i; j++) {
384 OGGStreamContext *sc = s->streams[j]->priv_data;
385 if (serial_num == sc->serial_num)
389 oggstream->serial_num = serial_num;
391 st->priv_data = oggstream;
392 if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
393 int err = ogg_build_flac_headers(st->codec, oggstream,
394 st->codec->flags & CODEC_FLAG_BITEXACT,
397 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
398 av_freep(&st->priv_data);
401 } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
402 int err = ogg_build_speex_headers(st->codec, oggstream,
403 st->codec->flags & CODEC_FLAG_BITEXACT,
406 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
407 av_freep(&st->priv_data);
412 const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
413 int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
414 int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
416 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
417 st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
418 oggstream->header, oggstream->header_len) < 0) {
419 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
420 av_freep(&st->priv_data);
424 p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
425 &oggstream->header_len[1], &s->metadata,
427 oggstream->header[1] = p;
429 return AVERROR(ENOMEM);
431 bytestream_put_byte(&p, header_type);
432 bytestream_put_buffer(&p, cstr, 6);
434 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
435 /** KFGSHIFT is the width of the less significant section of the granule position
436 The less significant section is the frame count since the last keyframe */
437 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
438 oggstream->vrev = oggstream->header[0][9];
439 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
440 oggstream->kfgshift, oggstream->vrev);
445 for (j = 0; j < s->nb_streams; j++) {
446 OGGStreamContext *oggstream = s->streams[j]->priv_data;
447 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
448 oggstream->header_len[0], 0, 1);
449 oggstream->page.flags |= 2; // bos
450 ogg_buffer_page(s, oggstream);
452 for (j = 0; j < s->nb_streams; j++) {
453 AVStream *st = s->streams[j];
454 OGGStreamContext *oggstream = st->priv_data;
455 for (i = 1; i < 3; i++) {
456 if (oggstream && oggstream->header_len[i])
457 ogg_buffer_data(s, st, oggstream->header[i],
458 oggstream->header_len[i], 0, 1);
460 ogg_buffer_page(s, oggstream);
465 static void ogg_write_pages(AVFormatContext *s, int flush)
467 OGGContext *ogg = s->priv_data;
468 OGGPageList *next, *p;
473 for (p = ogg->page_list; p; ) {
474 OGGStreamContext *oggstream =
475 s->streams[p->page.stream_index]->priv_data;
476 if (oggstream->page_count < 2 && !flush)
478 ogg_write_page(s, &p->page,
479 flush && oggstream->page_count == 1 ? 4 : 0); // eos
487 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
489 AVStream *st = s->streams[pkt->stream_index];
490 OGGStreamContext *oggstream = st->priv_data;
494 if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
495 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
497 if (pkt->flags & AV_PKT_FLAG_KEY)
498 oggstream->last_kf_pts = pts;
499 pframe_count = pts - oggstream->last_kf_pts;
500 // prevent frame count from overflow if key frame flag is not set
501 if (pframe_count >= (1<<oggstream->kfgshift)) {
502 oggstream->last_kf_pts += pframe_count;
505 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
507 granule = pkt->pts + pkt->duration;
509 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
513 ogg_write_pages(s, 0);
515 oggstream->last_granule = granule;
520 static int ogg_write_trailer(AVFormatContext *s)
524 /* flush current page */
525 for (i = 0; i < s->nb_streams; i++)
526 ogg_buffer_page(s, s->streams[i]->priv_data);
528 ogg_write_pages(s, 1);
530 for (i = 0; i < s->nb_streams; i++) {
531 AVStream *st = s->streams[i];
532 OGGStreamContext *oggstream = st->priv_data;
533 if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
534 st->codec->codec_id == AV_CODEC_ID_SPEEX) {
535 av_freep(&oggstream->header[0]);
537 av_freep(&oggstream->header[1]);
538 av_freep(&st->priv_data);
543 AVOutputFormat ff_ogg_muxer = {
545 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
546 .mime_type = "application/ogg",
547 .extensions = "ogg,ogv,spx",
548 .priv_data_size = sizeof(OGGContext),
549 .audio_codec = AV_CODEC_ID_FLAC,
550 .video_codec = AV_CODEC_ID_THEORA,
551 .write_header = ogg_write_header,
552 .write_packet = ogg_write_packet,
553 .write_trailer = ogg_write_trailer,
554 .priv_class = &ogg_muxer_class,