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