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/random_seed.h"
24 #include "libavcodec/xiph.h"
25 #include "libavcodec/bytestream.h"
26 #include "libavcodec/flac.h"
29 #include "vorbiscomment.h"
31 #define MAX_PAGE_SIZE 65025
37 uint8_t segments_count;
38 uint8_t segments[255];
39 uint8_t data[MAX_PAGE_SIZE];
44 unsigned page_counter;
47 /** for theora granule */
52 unsigned page_count; ///< number of page buffered
53 OGGPage page; ///< current page
54 unsigned serial_num; ///< serial number
55 int64_t last_granule; ///< last packet granule
58 typedef struct OGGPageList {
60 struct OGGPageList *next;
64 OGGPageList *page_list;
67 static void ogg_update_checksum(AVFormatContext *s, ByteIOContext *pb, int64_t crc_offset)
69 int64_t pos = url_ftell(pb);
70 uint32_t checksum = get_checksum(pb);
71 url_fseek(pb, crc_offset, SEEK_SET);
72 put_be32(pb, checksum);
73 url_fseek(pb, pos, SEEK_SET);
76 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
78 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
84 ret = url_open_dyn_buf(&pb);
87 init_checksum(pb, ff_crc04C11DB7_update, 0);
90 put_byte(pb, page->flags | extra_flags);
91 put_le64(pb, page->granule);
92 put_le32(pb, oggstream->serial_num);
93 put_le32(pb, oggstream->page_counter++);
94 crc_offset = url_ftell(pb);
95 put_le32(pb, 0); // crc
96 put_byte(pb, page->segments_count);
97 put_buffer(pb, page->segments, page->segments_count);
98 put_buffer(pb, page->data, page->size);
100 ogg_update_checksum(s, pb, crc_offset);
101 put_flush_packet(pb);
103 size = url_close_dyn_buf(pb, &buf);
107 put_buffer(s->pb, buf, size);
108 put_flush_packet(s->pb);
110 oggstream->page_count--;
114 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
116 if (oggstream->kfgshift)
117 return (granule>>oggstream->kfgshift) +
118 (granule & ((1<<oggstream->kfgshift)-1));
123 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
125 AVStream *st2 = s->streams[next->stream_index];
126 AVStream *st = s->streams[page->stream_index];
127 int64_t next_granule, cur_granule;
129 if (next->granule == -1 || page->granule == -1)
132 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
133 st2->time_base, AV_TIME_BASE_Q);
134 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
135 st ->time_base, AV_TIME_BASE_Q);
136 return next_granule > cur_granule;
139 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
141 oggstream->page.granule = -1;
142 oggstream->page.flags = 0;
143 oggstream->page.segments_count = 0;
144 oggstream->page.size = 0;
148 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
150 OGGContext *ogg = s->priv_data;
151 OGGPageList **p = &ogg->page_list;
152 OGGPageList *l = av_mallocz(sizeof(*l));
155 return AVERROR(ENOMEM);
156 l->page = oggstream->page;
158 oggstream->page_count++;
159 ogg_reset_cur_page(oggstream);
162 if (ogg_compare_granule(s, &(*p)->page, &l->page))
172 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
173 uint8_t *data, unsigned size, int64_t granule)
175 OGGStreamContext *oggstream = st->priv_data;
176 int total_segments = size / 255 + 1;
178 int i, segments, len, flush = 0;
180 // Handles VFR by flushing page because this frame needs to have a timestamp
181 if (st->codec->codec_id == CODEC_ID_THEORA &&
182 ogg_granule_to_timestamp(oggstream, granule) >
183 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
184 if (oggstream->page.granule != -1)
185 ogg_buffer_page(s, oggstream);
189 for (i = 0; i < total_segments; ) {
190 OGGPage *page = &oggstream->page;
192 segments = FFMIN(total_segments - i, 255 - page->segments_count);
194 if (i && !page->segments_count)
195 page->flags |= 1; // continued packet
197 memset(page->segments+page->segments_count, 255, segments - 1);
198 page->segments_count += segments - 1;
200 len = FFMIN(size, segments*255);
201 page->segments[page->segments_count++] = len - (segments-1)*255;
202 memcpy(page->data+page->size, p, len);
208 if (i == total_segments)
209 page->granule = granule;
211 if (page->segments_count == 255) {
212 ogg_buffer_page(s, oggstream);
216 if (flush && oggstream->page.granule != -1)
217 ogg_buffer_page(s, oggstream);
222 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
223 int *header_len, AVMetadata **m, int framing_bit)
225 const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
230 ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
232 size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
233 p = av_mallocz(size);
239 ff_vorbiscomment_write(&p, m, vendor, count);
241 bytestream_put_byte(&p, 1);
247 static int ogg_build_flac_headers(AVCodecContext *avctx,
248 OGGStreamContext *oggstream, int bitexact,
251 enum FLACExtradataFormat format;
255 if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
258 // first packet: STREAMINFO
259 oggstream->header_len[0] = 51;
260 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
261 p = oggstream->header[0];
263 return AVERROR(ENOMEM);
264 bytestream_put_byte(&p, 0x7F);
265 bytestream_put_buffer(&p, "FLAC", 4);
266 bytestream_put_byte(&p, 1); // major version
267 bytestream_put_byte(&p, 0); // minor version
268 bytestream_put_be16(&p, 1); // headers packets without this one
269 bytestream_put_buffer(&p, "fLaC", 4);
270 bytestream_put_byte(&p, 0x00); // streaminfo
271 bytestream_put_be24(&p, 34);
272 bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
274 // second packet: VorbisComment
275 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
277 return AVERROR(ENOMEM);
278 oggstream->header[1] = p;
279 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
280 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
285 #define SPEEX_HEADER_SIZE 80
287 static int ogg_build_speex_headers(AVCodecContext *avctx,
288 OGGStreamContext *oggstream, int bitexact,
293 if (avctx->extradata_size < SPEEX_HEADER_SIZE)
296 // first packet: Speex header
297 p = av_mallocz(SPEEX_HEADER_SIZE);
299 return AVERROR(ENOMEM);
300 oggstream->header[0] = p;
301 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
302 bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
303 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
305 // second packet: VorbisComment
306 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
308 return AVERROR(ENOMEM);
309 oggstream->header[1] = p;
314 static int ogg_write_header(AVFormatContext *s)
316 OGGStreamContext *oggstream;
319 for (i = 0; i < s->nb_streams; i++) {
320 AVStream *st = s->streams[i];
321 unsigned serial_num = i;
323 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
324 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
325 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
326 av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
327 if (st->codec->codec_id != CODEC_ID_VORBIS &&
328 st->codec->codec_id != CODEC_ID_THEORA &&
329 st->codec->codec_id != CODEC_ID_SPEEX &&
330 st->codec->codec_id != CODEC_ID_FLAC) {
331 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
335 if (!st->codec->extradata || !st->codec->extradata_size) {
336 av_log(s, AV_LOG_ERROR, "No extradata present\n");
339 oggstream = av_mallocz(sizeof(*oggstream));
340 oggstream->page.stream_index = i;
342 if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
344 serial_num = av_get_random_seed();
345 for (j = 0; j < i; j++) {
346 OGGStreamContext *sc = s->streams[j]->priv_data;
347 if (serial_num == sc->serial_num)
351 oggstream->serial_num = serial_num;
353 st->priv_data = oggstream;
354 if (st->codec->codec_id == CODEC_ID_FLAC) {
355 int err = ogg_build_flac_headers(st->codec, oggstream,
356 st->codec->flags & CODEC_FLAG_BITEXACT,
359 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
360 av_freep(&st->priv_data);
363 } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
364 int err = ogg_build_speex_headers(st->codec, oggstream,
365 st->codec->flags & CODEC_FLAG_BITEXACT,
368 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
369 av_freep(&st->priv_data);
374 const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
375 int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
376 int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
378 if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
379 st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
380 oggstream->header, oggstream->header_len) < 0) {
381 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
382 av_freep(&st->priv_data);
386 p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
387 &oggstream->header_len[1], &s->metadata,
390 return AVERROR(ENOMEM);
392 oggstream->header[1] = p;
393 bytestream_put_byte(&p, header_type);
394 bytestream_put_buffer(&p, cstr, 6);
396 if (st->codec->codec_id == CODEC_ID_THEORA) {
397 /** KFGSHIFT is the width of the less significant section of the granule position
398 The less significant section is the frame count since the last keyframe */
399 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
400 oggstream->vrev = oggstream->header[0][9];
401 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
402 oggstream->kfgshift, oggstream->vrev);
407 for (j = 0; j < s->nb_streams; j++) {
408 OGGStreamContext *oggstream = s->streams[j]->priv_data;
409 ogg_buffer_data(s, s->streams[j], oggstream->header[0],
410 oggstream->header_len[0], 0);
411 oggstream->page.flags |= 2; // bos
412 ogg_buffer_page(s, oggstream);
414 for (j = 0; j < s->nb_streams; j++) {
415 AVStream *st = s->streams[j];
416 OGGStreamContext *oggstream = st->priv_data;
417 for (i = 1; i < 3; i++) {
418 if (oggstream && oggstream->header_len[i])
419 ogg_buffer_data(s, st, oggstream->header[i],
420 oggstream->header_len[i], 0);
422 ogg_buffer_page(s, oggstream);
427 static void ogg_write_pages(AVFormatContext *s, int flush)
429 OGGContext *ogg = s->priv_data;
430 OGGPageList *next, *p;
435 for (p = ogg->page_list; p; ) {
436 OGGStreamContext *oggstream =
437 s->streams[p->page.stream_index]->priv_data;
438 if (oggstream->page_count < 2 && !flush)
440 ogg_write_page(s, &p->page,
441 flush && oggstream->page_count == 1 ? 4 : 0); // eos
449 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
451 AVStream *st = s->streams[pkt->stream_index];
452 OGGStreamContext *oggstream = st->priv_data;
456 if (st->codec->codec_id == CODEC_ID_THEORA) {
457 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
459 if (pkt->flags & AV_PKT_FLAG_KEY)
460 oggstream->last_kf_pts = pts;
461 pframe_count = pts - oggstream->last_kf_pts;
462 // prevent frame count from overflow if key frame flag is not set
463 if (pframe_count >= (1<<oggstream->kfgshift)) {
464 oggstream->last_kf_pts += pframe_count;
467 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
469 granule = pkt->pts + pkt->duration;
471 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
475 ogg_write_pages(s, 0);
477 oggstream->last_granule = granule;
482 static int ogg_write_trailer(AVFormatContext *s)
486 /* flush current page */
487 for (i = 0; i < s->nb_streams; i++)
488 ogg_buffer_page(s, s->streams[i]->priv_data);
490 ogg_write_pages(s, 1);
492 for (i = 0; i < s->nb_streams; i++) {
493 AVStream *st = s->streams[i];
494 OGGStreamContext *oggstream = st->priv_data;
495 if (st->codec->codec_id == CODEC_ID_FLAC ||
496 st->codec->codec_id == CODEC_ID_SPEEX) {
497 av_free(oggstream->header[0]);
498 av_free(oggstream->header[1]);
500 av_freep(&st->priv_data);
505 AVOutputFormat ff_ogg_muxer = {
507 NULL_IF_CONFIG_SMALL("Ogg"),