Support R10g in mov.
[ffmpeg.git] / libavformat / oggenc.c
1 /*
2  * Ogg muxer
3  * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include "libavutil/crc.h"
23 #include "libavutil/opt.h"
24 #include "libavutil/random_seed.h"
25 #include "libavcodec/xiph.h"
26 #include "libavcodec/bytestream.h"
27 #include "libavcodec/flac.h"
28 #include "avformat.h"
29 #include "avio_internal.h"
30 #include "internal.h"
31 #include "vorbiscomment.h"
32
33 #define MAX_PAGE_SIZE 65025
34
35 typedef struct {
36     int64_t granule;
37     int stream_index;
38     uint8_t flags;
39     uint8_t segments_count;
40     uint8_t segments[255];
41     uint8_t data[MAX_PAGE_SIZE];
42     uint16_t size;
43 } OGGPage;
44
45 typedef struct {
46     unsigned page_counter;
47     uint8_t *header[3];
48     int header_len[3];
49     /** for theora granule */
50     int kfgshift;
51     int64_t last_kf_pts;
52     int vrev;
53     int eos;
54     unsigned page_count; ///< number of page buffered
55     OGGPage page; ///< current page
56     unsigned serial_num; ///< serial number
57     int64_t last_granule; ///< last packet granule
58 } OGGStreamContext;
59
60 typedef struct OGGPageList {
61     OGGPage page;
62     struct OGGPageList *next;
63 } OGGPageList;
64
65 typedef struct {
66     const AVClass *class;
67     OGGPageList *page_list;
68     int pref_size; ///< preferred page size (0 => fill all segments)
69 } OGGContext;
70
71
72 static const AVOption options[] = {
73     { "oggpagesize", "Set preferred Ogg page size.",
74       offsetof(OGGContext, pref_size), FF_OPT_TYPE_INT, 0, 0, MAX_PAGE_SIZE, AV_OPT_FLAG_ENCODING_PARAM},
75     { NULL },
76 };
77
78 static const AVClass ogg_muxer_class = {
79     "Ogg muxer",
80     av_default_item_name,
81     options,
82     LIBAVUTIL_VERSION_INT,
83 };
84
85
86 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
87 {
88     int64_t pos = avio_tell(pb);
89     uint32_t checksum = ffio_get_checksum(pb);
90     avio_seek(pb, crc_offset, SEEK_SET);
91     avio_wb32(pb, checksum);
92     avio_seek(pb, pos, SEEK_SET);
93 }
94
95 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
96 {
97     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
98     AVIOContext *pb;
99     int64_t crc_offset;
100     int ret, size;
101     uint8_t *buf;
102
103     ret = avio_open_dyn_buf(&pb);
104     if (ret < 0)
105         return ret;
106     ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
107     ffio_wfourcc(pb, "OggS");
108     avio_w8(pb, 0);
109     avio_w8(pb, page->flags | extra_flags);
110     avio_wl64(pb, page->granule);
111     avio_wl32(pb, oggstream->serial_num);
112     avio_wl32(pb, oggstream->page_counter++);
113     crc_offset = avio_tell(pb);
114     avio_wl32(pb, 0); // crc
115     avio_w8(pb, page->segments_count);
116     avio_write(pb, page->segments, page->segments_count);
117     avio_write(pb, page->data, page->size);
118
119     ogg_update_checksum(s, pb, crc_offset);
120     avio_flush(pb);
121
122     size = avio_close_dyn_buf(pb, &buf);
123     if (size < 0)
124         return size;
125
126     avio_write(s->pb, buf, size);
127     avio_flush(s->pb);
128     av_free(buf);
129     oggstream->page_count--;
130     return 0;
131 }
132
133 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
134 {
135     if (oggstream->kfgshift)
136         return (granule>>oggstream->kfgshift) +
137             (granule & ((1<<oggstream->kfgshift)-1));
138     else
139         return granule;
140 }
141
142 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
143 {
144     AVStream *st2 = s->streams[next->stream_index];
145     AVStream *st  = s->streams[page->stream_index];
146     int64_t next_granule, cur_granule;
147
148     if (next->granule == -1 || page->granule == -1)
149         return 0;
150
151     next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
152                                 st2->time_base, AV_TIME_BASE_Q);
153     cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
154                                 st ->time_base, AV_TIME_BASE_Q);
155     return next_granule > cur_granule;
156 }
157
158 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
159 {
160     oggstream->page.granule = -1;
161     oggstream->page.flags = 0;
162     oggstream->page.segments_count = 0;
163     oggstream->page.size = 0;
164     return 0;
165 }
166
167 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
168 {
169     OGGContext *ogg = s->priv_data;
170     OGGPageList **p = &ogg->page_list;
171     OGGPageList *l = av_mallocz(sizeof(*l));
172
173     if (!l)
174         return AVERROR(ENOMEM);
175     l->page = oggstream->page;
176
177     oggstream->page_count++;
178     ogg_reset_cur_page(oggstream);
179
180     while (*p) {
181         if (ogg_compare_granule(s, &(*p)->page, &l->page))
182             break;
183         p = &(*p)->next;
184     }
185     l->next = *p;
186     *p = l;
187
188     return 0;
189 }
190
191 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
192                            uint8_t *data, unsigned size, int64_t granule)
193 {
194     OGGStreamContext *oggstream = st->priv_data;
195     OGGContext *ogg = s->priv_data;
196     int total_segments = size / 255 + 1;
197     uint8_t *p = data;
198     int i, segments, len, flush = 0;
199
200     // Handles VFR by flushing page because this frame needs to have a timestamp
201     if (st->codec->codec_id == CODEC_ID_THEORA &&
202         ogg_granule_to_timestamp(oggstream, granule) >
203         ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
204         if (oggstream->page.granule != -1)
205             ogg_buffer_page(s, oggstream);
206         flush = 1;
207     }
208
209     for (i = 0; i < total_segments; ) {
210         OGGPage *page = &oggstream->page;
211
212         segments = FFMIN(total_segments - i, 255 - page->segments_count);
213
214         if (i && !page->segments_count)
215             page->flags |= 1; // continued packet
216
217         memset(page->segments+page->segments_count, 255, segments - 1);
218         page->segments_count += segments - 1;
219
220         len = FFMIN(size, segments*255);
221         page->segments[page->segments_count++] = len - (segments-1)*255;
222         memcpy(page->data+page->size, p, len);
223         p += len;
224         size -= len;
225         i += segments;
226         page->size += len;
227
228         if (i == total_segments)
229             page->granule = granule;
230
231         if(page->segments_count == 255 ||
232            (ogg->pref_size > 0 && page->size >= ogg->pref_size)) {
233            ogg_buffer_page(s, oggstream);
234         }
235     }
236
237     if (flush && oggstream->page.granule != -1)
238         ogg_buffer_page(s, oggstream);
239
240     return 0;
241 }
242
243 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
244                                         int *header_len, AVMetadata **m, int framing_bit)
245 {
246     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
247     int size;
248     uint8_t *p, *p0;
249     unsigned int count;
250
251     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
252
253     size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
254     p = av_mallocz(size);
255     if (!p)
256         return NULL;
257     p0 = p;
258
259     p += offset;
260     ff_vorbiscomment_write(&p, m, vendor, count);
261     if (framing_bit)
262         bytestream_put_byte(&p, 1);
263
264     *header_len = size;
265     return p0;
266 }
267
268 static int ogg_build_flac_headers(AVCodecContext *avctx,
269                                   OGGStreamContext *oggstream, int bitexact,
270                                   AVMetadata **m)
271 {
272     enum FLACExtradataFormat format;
273     uint8_t *streaminfo;
274     uint8_t *p;
275
276     if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
277         return -1;
278
279     // first packet: STREAMINFO
280     oggstream->header_len[0] = 51;
281     oggstream->header[0] = av_mallocz(51); // per ogg flac specs
282     p = oggstream->header[0];
283     if (!p)
284         return AVERROR(ENOMEM);
285     bytestream_put_byte(&p, 0x7F);
286     bytestream_put_buffer(&p, "FLAC", 4);
287     bytestream_put_byte(&p, 1); // major version
288     bytestream_put_byte(&p, 0); // minor version
289     bytestream_put_be16(&p, 1); // headers packets without this one
290     bytestream_put_buffer(&p, "fLaC", 4);
291     bytestream_put_byte(&p, 0x00); // streaminfo
292     bytestream_put_be24(&p, 34);
293     bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
294
295     // second packet: VorbisComment
296     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
297     if (!p)
298         return AVERROR(ENOMEM);
299     oggstream->header[1] = p;
300     bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
301     bytestream_put_be24(&p, oggstream->header_len[1] - 4);
302
303     return 0;
304 }
305
306 #define SPEEX_HEADER_SIZE 80
307
308 static int ogg_build_speex_headers(AVCodecContext *avctx,
309                                    OGGStreamContext *oggstream, int bitexact,
310                                    AVMetadata **m)
311 {
312     uint8_t *p;
313
314     if (avctx->extradata_size < SPEEX_HEADER_SIZE)
315         return -1;
316
317     // first packet: Speex header
318     p = av_mallocz(SPEEX_HEADER_SIZE);
319     if (!p)
320         return AVERROR(ENOMEM);
321     oggstream->header[0] = p;
322     oggstream->header_len[0] = SPEEX_HEADER_SIZE;
323     bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
324     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
325
326     // second packet: VorbisComment
327     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
328     if (!p)
329         return AVERROR(ENOMEM);
330     oggstream->header[1] = p;
331
332     return 0;
333 }
334
335 static int ogg_write_header(AVFormatContext *s)
336 {
337     OGGStreamContext *oggstream;
338     int i, j;
339
340     for (i = 0; i < s->nb_streams; i++) {
341         AVStream *st = s->streams[i];
342         unsigned serial_num = i;
343
344         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
345             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
346         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
347             av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
348         if (st->codec->codec_id != CODEC_ID_VORBIS &&
349             st->codec->codec_id != CODEC_ID_THEORA &&
350             st->codec->codec_id != CODEC_ID_SPEEX  &&
351             st->codec->codec_id != CODEC_ID_FLAC) {
352             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
353             return -1;
354         }
355
356         if (!st->codec->extradata || !st->codec->extradata_size) {
357             av_log(s, AV_LOG_ERROR, "No extradata present\n");
358             return -1;
359         }
360         oggstream = av_mallocz(sizeof(*oggstream));
361         oggstream->page.stream_index = i;
362
363         if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
364             do {
365                 serial_num = av_get_random_seed();
366                 for (j = 0; j < i; j++) {
367                     OGGStreamContext *sc = s->streams[j]->priv_data;
368                     if (serial_num == sc->serial_num)
369                         break;
370                 }
371             } while (j < i);
372         oggstream->serial_num = serial_num;
373
374         st->priv_data = oggstream;
375         if (st->codec->codec_id == CODEC_ID_FLAC) {
376             int err = ogg_build_flac_headers(st->codec, oggstream,
377                                              st->codec->flags & CODEC_FLAG_BITEXACT,
378                                              &s->metadata);
379             if (err) {
380                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
381                 av_freep(&st->priv_data);
382                 return err;
383             }
384         } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
385             int err = ogg_build_speex_headers(st->codec, oggstream,
386                                               st->codec->flags & CODEC_FLAG_BITEXACT,
387                                               &s->metadata);
388             if (err) {
389                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
390                 av_freep(&st->priv_data);
391                 return err;
392             }
393         } else {
394             uint8_t *p;
395             const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
396             int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
397             int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
398
399             if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
400                                       st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
401                                       oggstream->header, oggstream->header_len) < 0) {
402                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
403                 av_freep(&st->priv_data);
404                 return -1;
405             }
406
407             p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
408                                         &oggstream->header_len[1], &s->metadata,
409                                         framing_bit);
410             if (!p)
411                 return AVERROR(ENOMEM);
412
413             oggstream->header[1] = p;
414             bytestream_put_byte(&p, header_type);
415             bytestream_put_buffer(&p, cstr, 6);
416
417             if (st->codec->codec_id == CODEC_ID_THEORA) {
418                 /** KFGSHIFT is the width of the less significant section of the granule position
419                     The less significant section is the frame count since the last keyframe */
420                 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
421                 oggstream->vrev = oggstream->header[0][9];
422                 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
423                        oggstream->kfgshift, oggstream->vrev);
424             }
425         }
426     }
427
428     for (j = 0; j < s->nb_streams; j++) {
429         OGGStreamContext *oggstream = s->streams[j]->priv_data;
430         ogg_buffer_data(s, s->streams[j], oggstream->header[0],
431                         oggstream->header_len[0], 0);
432         oggstream->page.flags |= 2; // bos
433         ogg_buffer_page(s, oggstream);
434     }
435     for (j = 0; j < s->nb_streams; j++) {
436         AVStream *st = s->streams[j];
437         OGGStreamContext *oggstream = st->priv_data;
438         for (i = 1; i < 3; i++) {
439             if (oggstream && oggstream->header_len[i])
440                 ogg_buffer_data(s, st, oggstream->header[i],
441                                 oggstream->header_len[i], 0);
442         }
443         ogg_buffer_page(s, oggstream);
444     }
445     return 0;
446 }
447
448 static void ogg_write_pages(AVFormatContext *s, int flush)
449 {
450     OGGContext *ogg = s->priv_data;
451     OGGPageList *next, *p;
452
453     if (!ogg->page_list)
454         return;
455
456     for (p = ogg->page_list; p; ) {
457         OGGStreamContext *oggstream =
458             s->streams[p->page.stream_index]->priv_data;
459         if (oggstream->page_count < 2 && !flush)
460             break;
461         ogg_write_page(s, &p->page,
462                        flush && oggstream->page_count == 1 ? 4 : 0); // eos
463         next = p->next;
464         av_freep(&p);
465         p = next;
466     }
467     ogg->page_list = p;
468 }
469
470 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
471 {
472     AVStream *st = s->streams[pkt->stream_index];
473     OGGStreamContext *oggstream = st->priv_data;
474     int ret;
475     int64_t granule;
476
477     if (st->codec->codec_id == CODEC_ID_THEORA) {
478         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
479         int pframe_count;
480         if (pkt->flags & AV_PKT_FLAG_KEY)
481             oggstream->last_kf_pts = pts;
482         pframe_count = pts - oggstream->last_kf_pts;
483         // prevent frame count from overflow if key frame flag is not set
484         if (pframe_count >= (1<<oggstream->kfgshift)) {
485             oggstream->last_kf_pts += pframe_count;
486             pframe_count = 0;
487         }
488         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
489     } else
490         granule = pkt->pts + pkt->duration;
491
492     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
493     if (ret < 0)
494         return ret;
495
496     ogg_write_pages(s, 0);
497
498     oggstream->last_granule = granule;
499
500     return 0;
501 }
502
503 static int ogg_write_trailer(AVFormatContext *s)
504 {
505     int i;
506
507     /* flush current page */
508     for (i = 0; i < s->nb_streams; i++)
509         ogg_buffer_page(s, s->streams[i]->priv_data);
510
511     ogg_write_pages(s, 1);
512
513     for (i = 0; i < s->nb_streams; i++) {
514         AVStream *st = s->streams[i];
515         OGGStreamContext *oggstream = st->priv_data;
516         if (st->codec->codec_id == CODEC_ID_FLAC ||
517             st->codec->codec_id == CODEC_ID_SPEEX) {
518             av_free(oggstream->header[0]);
519             av_free(oggstream->header[1]);
520         }
521         av_freep(&st->priv_data);
522     }
523     return 0;
524 }
525
526 AVOutputFormat ff_ogg_muxer = {
527     "ogg",
528     NULL_IF_CONFIG_SMALL("Ogg"),
529     "application/ogg",
530     "ogg,ogv,spx",
531     sizeof(OGGContext),
532     CODEC_ID_FLAC,
533     CODEC_ID_THEORA,
534     ogg_write_header,
535     ogg_write_packet,
536     ogg_write_trailer,
537     .priv_class = &ogg_muxer_class,
538 };