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, { 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 == 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 static int ogg_write_header(AVFormatContext *s)
341 OGGStreamContext *oggstream;
344 for (i = 0; i < s->nb_streams; i++) {
345 AVStream *st = s->streams[i];
346 unsigned serial_num = i;
348 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
349 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
350 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
351 avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
352 if (st->codec->codec_id != CODEC_ID_VORBIS &&
353 st->codec->codec_id != CODEC_ID_THEORA &&
354 st->codec->codec_id != CODEC_ID_SPEEX &&
355 st->codec->codec_id != CODEC_ID_FLAC) {
356 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
360 if (!st->codec->extradata || !st->codec->extradata_size) {
361 av_log(s, AV_LOG_ERROR, "No extradata present\n");
364 oggstream = av_mallocz(sizeof(*oggstream));
365 oggstream->page.stream_index = i;
367 if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
369 serial_num = av_get_random_seed();
370 for (j = 0; j < i; j++) {
371 OGGStreamContext *sc = s->streams[j]->priv_data;
372 if (serial_num == sc->serial_num)
376 oggstream->serial_num = serial_num;
378 st->priv_data = oggstream;
379 if (st->codec->codec_id == CODEC_ID_FLAC) {
380 int err = ogg_build_flac_headers(st->codec, oggstream,
381 st->codec->flags & CODEC_FLAG_BITEXACT,
384 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
385 av_freep(&st->priv_data);
388 } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
389 int err = ogg_build_speex_headers(st->codec, oggstream,
390 st->codec->flags & CODEC_FLAG_BITEXACT,
393 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
394 av_freep(&st->priv_data);
399 const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
400 int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
401 int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
403 if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
404 st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
405 oggstream->header, oggstream->header_len) < 0) {
406 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
407 av_freep(&st->priv_data);
411 p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
412 &oggstream->header_len[1], &s->metadata,
414 oggstream->header[1] = p;
416 return AVERROR(ENOMEM);
418 bytestream_put_byte(&p, header_type);
419 bytestream_put_buffer(&p, cstr, 6);
421 if (st->codec->codec_id == CODEC_ID_THEORA) {
422 /** KFGSHIFT is the width of the less significant section of the granule position
423 The less significant section is the frame count since the last keyframe */
424 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
425 oggstream->vrev = oggstream->header[0][9];
426 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
427 oggstream->kfgshift, oggstream->vrev);
432 for (j = 0; j < s->nb_streams; j++) {
433 OGGStreamContext *oggstream = s->streams[j]->priv_data;
434 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
435 oggstream->header_len[0], 0, 1);
436 oggstream->page.flags |= 2; // bos
437 ogg_buffer_page(s, oggstream);
439 for (j = 0; j < s->nb_streams; j++) {
440 AVStream *st = s->streams[j];
441 OGGStreamContext *oggstream = st->priv_data;
442 for (i = 1; i < 3; i++) {
443 if (oggstream && oggstream->header_len[i])
444 ogg_buffer_data(s, st, oggstream->header[i],
445 oggstream->header_len[i], 0, 1);
447 ogg_buffer_page(s, oggstream);
452 static void ogg_write_pages(AVFormatContext *s, int flush)
454 OGGContext *ogg = s->priv_data;
455 OGGPageList *next, *p;
460 for (p = ogg->page_list; p; ) {
461 OGGStreamContext *oggstream =
462 s->streams[p->page.stream_index]->priv_data;
463 if (oggstream->page_count < 2 && !flush)
465 ogg_write_page(s, &p->page,
466 flush && oggstream->page_count == 1 ? 4 : 0); // eos
474 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
476 AVStream *st = s->streams[pkt->stream_index];
477 OGGStreamContext *oggstream = st->priv_data;
481 if (st->codec->codec_id == CODEC_ID_THEORA) {
482 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
484 if (pkt->flags & AV_PKT_FLAG_KEY)
485 oggstream->last_kf_pts = pts;
486 pframe_count = pts - oggstream->last_kf_pts;
487 // prevent frame count from overflow if key frame flag is not set
488 if (pframe_count >= (1<<oggstream->kfgshift)) {
489 oggstream->last_kf_pts += pframe_count;
492 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
494 granule = pkt->pts + pkt->duration;
496 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
500 ogg_write_pages(s, 0);
502 oggstream->last_granule = granule;
507 static int ogg_write_trailer(AVFormatContext *s)
511 /* flush current page */
512 for (i = 0; i < s->nb_streams; i++)
513 ogg_buffer_page(s, s->streams[i]->priv_data);
515 ogg_write_pages(s, 1);
517 for (i = 0; i < s->nb_streams; i++) {
518 AVStream *st = s->streams[i];
519 OGGStreamContext *oggstream = st->priv_data;
520 if (st->codec->codec_id == CODEC_ID_FLAC ||
521 st->codec->codec_id == CODEC_ID_SPEEX) {
522 av_free(oggstream->header[0]);
524 av_freep(&oggstream->header[1]);
525 av_freep(&st->priv_data);
530 AVOutputFormat ff_ogg_muxer = {
532 .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
533 .mime_type = "application/ogg",
534 .extensions = "ogg,ogv,spx",
535 .priv_data_size = sizeof(OGGContext),
536 .audio_codec = CODEC_ID_FLAC,
537 .video_codec = CODEC_ID_THEORA,
538 .write_header = ogg_write_header,
539 .write_packet = ogg_write_packet,
540 .write_trailer = ogg_write_trailer,
541 .priv_class = &ogg_muxer_class,