Prefix all _demuxer, _muxer, _protocol from libavformat and libavdevice.
[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/random_seed.h"
24 #include "libavcodec/xiph.h"
25 #include "libavcodec/bytestream.h"
26 #include "libavcodec/flac.h"
27 #include "avformat.h"
28 #include "internal.h"
29 #include "vorbiscomment.h"
30
31 #define MAX_PAGE_SIZE 65025
32
33 typedef struct {
34     int64_t granule;
35     int stream_index;
36     uint8_t flags;
37     uint8_t segments_count;
38     uint8_t segments[255];
39     uint8_t data[MAX_PAGE_SIZE];
40     uint16_t size;
41 } OGGPage;
42
43 typedef struct {
44     unsigned page_counter;
45     uint8_t *header[3];
46     int header_len[3];
47     /** for theora granule */
48     int kfgshift;
49     int64_t last_kf_pts;
50     int vrev;
51     int eos;
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
56 } OGGStreamContext;
57
58 typedef struct OGGPageList {
59     OGGPage page;
60     struct OGGPageList *next;
61 } OGGPageList;
62
63 typedef struct {
64     OGGPageList *page_list;
65 } OGGContext;
66
67 static void ogg_update_checksum(AVFormatContext *s, ByteIOContext *pb, int64_t crc_offset)
68 {
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);
74 }
75
76 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
77 {
78     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
79     ByteIOContext *pb;
80     int64_t crc_offset;
81     int ret, size;
82     uint8_t *buf;
83
84     ret = url_open_dyn_buf(&pb);
85     if (ret < 0)
86         return ret;
87     init_checksum(pb, ff_crc04C11DB7_update, 0);
88     put_tag(pb, "OggS");
89     put_byte(pb, 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);
99
100     ogg_update_checksum(s, pb, crc_offset);
101     put_flush_packet(pb);
102
103     size = url_close_dyn_buf(pb, &buf);
104     if (size < 0)
105         return size;
106
107     put_buffer(s->pb, buf, size);
108     put_flush_packet(s->pb);
109     av_free(buf);
110     oggstream->page_count--;
111     return 0;
112 }
113
114 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
115 {
116     if (oggstream->kfgshift)
117         return (granule>>oggstream->kfgshift) +
118             (granule & ((1<<oggstream->kfgshift)-1));
119     else
120         return granule;
121 }
122
123 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
124 {
125     AVStream *st2 = s->streams[next->stream_index];
126     AVStream *st  = s->streams[page->stream_index];
127     int64_t next_granule, cur_granule;
128
129     if (next->granule == -1 || page->granule == -1)
130         return 0;
131
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;
137 }
138
139 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
140 {
141     oggstream->page.granule = -1;
142     oggstream->page.flags = 0;
143     oggstream->page.segments_count = 0;
144     oggstream->page.size = 0;
145     return 0;
146 }
147
148 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
149 {
150     OGGContext *ogg = s->priv_data;
151     OGGPageList **p = &ogg->page_list;
152     OGGPageList *l = av_mallocz(sizeof(*l));
153
154     if (!l)
155         return AVERROR(ENOMEM);
156     l->page = oggstream->page;
157
158     oggstream->page_count++;
159     ogg_reset_cur_page(oggstream);
160
161     while (*p) {
162         if (ogg_compare_granule(s, &(*p)->page, &l->page))
163             break;
164         p = &(*p)->next;
165     }
166     l->next = *p;
167     *p = l;
168
169     return 0;
170 }
171
172 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
173                            uint8_t *data, unsigned size, int64_t granule)
174 {
175     OGGStreamContext *oggstream = st->priv_data;
176     int total_segments = size / 255 + 1;
177     uint8_t *p = data;
178     int i, segments, len, flush = 0;
179
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);
186         flush = 1;
187     }
188
189     for (i = 0; i < total_segments; ) {
190         OGGPage *page = &oggstream->page;
191
192         segments = FFMIN(total_segments - i, 255 - page->segments_count);
193
194         if (i && !page->segments_count)
195             page->flags |= 1; // continued packet
196
197         memset(page->segments+page->segments_count, 255, segments - 1);
198         page->segments_count += segments - 1;
199
200         len = FFMIN(size, segments*255);
201         page->segments[page->segments_count++] = len - (segments-1)*255;
202         memcpy(page->data+page->size, p, len);
203         p += len;
204         size -= len;
205         i += segments;
206         page->size += len;
207
208         if (i == total_segments)
209             page->granule = granule;
210
211         if (page->segments_count == 255) {
212             ogg_buffer_page(s, oggstream);
213         }
214     }
215
216     if (flush && oggstream->page.granule != -1)
217         ogg_buffer_page(s, oggstream);
218
219     return 0;
220 }
221
222 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
223                                         int *header_len, AVMetadata **m, int framing_bit)
224 {
225     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
226     int size;
227     uint8_t *p, *p0;
228     unsigned int count;
229
230     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
231
232     size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
233     p = av_mallocz(size);
234     if (!p)
235         return NULL;
236     p0 = p;
237
238     p += offset;
239     ff_vorbiscomment_write(&p, m, vendor, count);
240     if (framing_bit)
241         bytestream_put_byte(&p, 1);
242
243     *header_len = size;
244     return p0;
245 }
246
247 static int ogg_build_flac_headers(AVCodecContext *avctx,
248                                   OGGStreamContext *oggstream, int bitexact,
249                                   AVMetadata **m)
250 {
251     enum FLACExtradataFormat format;
252     uint8_t *streaminfo;
253     uint8_t *p;
254
255     if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
256         return -1;
257
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];
262     if (!p)
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);
273
274     // second packet: VorbisComment
275     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
276     if (!p)
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);
281
282     return 0;
283 }
284
285 #define SPEEX_HEADER_SIZE 80
286
287 static int ogg_build_speex_headers(AVCodecContext *avctx,
288                                    OGGStreamContext *oggstream, int bitexact,
289                                    AVMetadata **m)
290 {
291     uint8_t *p;
292
293     if (avctx->extradata_size < SPEEX_HEADER_SIZE)
294         return -1;
295
296     // first packet: Speex header
297     p = av_mallocz(SPEEX_HEADER_SIZE);
298     if (!p)
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
304
305     // second packet: VorbisComment
306     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
307     if (!p)
308         return AVERROR(ENOMEM);
309     oggstream->header[1] = p;
310
311     return 0;
312 }
313
314 static int ogg_write_header(AVFormatContext *s)
315 {
316     OGGStreamContext *oggstream;
317     int i, j;
318
319     for (i = 0; i < s->nb_streams; i++) {
320         AVStream *st = s->streams[i];
321         unsigned serial_num = i;
322
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);
332             return -1;
333         }
334
335         if (!st->codec->extradata || !st->codec->extradata_size) {
336             av_log(s, AV_LOG_ERROR, "No extradata present\n");
337             return -1;
338         }
339         oggstream = av_mallocz(sizeof(*oggstream));
340         oggstream->page.stream_index = i;
341
342         if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
343             do {
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)
348                         break;
349                 }
350             } while (j < i);
351         oggstream->serial_num = serial_num;
352
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,
357                                              &s->metadata);
358             if (err) {
359                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
360                 av_freep(&st->priv_data);
361                 return err;
362             }
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,
366                                               &s->metadata);
367             if (err) {
368                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
369                 av_freep(&st->priv_data);
370                 return err;
371             }
372         } else {
373             uint8_t *p;
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;
377
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);
383                 return -1;
384             }
385
386             p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
387                                         &oggstream->header_len[1], &s->metadata,
388                                         framing_bit);
389             if (!p)
390                 return AVERROR(ENOMEM);
391
392             oggstream->header[1] = p;
393             bytestream_put_byte(&p, header_type);
394             bytestream_put_buffer(&p, cstr, 6);
395
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);
403             }
404         }
405     }
406
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);
413     }
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);
421         }
422         ogg_buffer_page(s, oggstream);
423     }
424     return 0;
425 }
426
427 static void ogg_write_pages(AVFormatContext *s, int flush)
428 {
429     OGGContext *ogg = s->priv_data;
430     OGGPageList *next, *p;
431
432     if (!ogg->page_list)
433         return;
434
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)
439             break;
440         ogg_write_page(s, &p->page,
441                        flush && oggstream->page_count == 1 ? 4 : 0); // eos
442         next = p->next;
443         av_freep(&p);
444         p = next;
445     }
446     ogg->page_list = p;
447 }
448
449 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
450 {
451     AVStream *st = s->streams[pkt->stream_index];
452     OGGStreamContext *oggstream = st->priv_data;
453     int ret;
454     int64_t granule;
455
456     if (st->codec->codec_id == CODEC_ID_THEORA) {
457         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
458         int pframe_count;
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;
465             pframe_count = 0;
466         }
467         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
468     } else
469         granule = pkt->pts + pkt->duration;
470
471     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
472     if (ret < 0)
473         return ret;
474
475     ogg_write_pages(s, 0);
476
477     oggstream->last_granule = granule;
478
479     return 0;
480 }
481
482 static int ogg_write_trailer(AVFormatContext *s)
483 {
484     int i;
485
486     /* flush current page */
487     for (i = 0; i < s->nb_streams; i++)
488         ogg_buffer_page(s, s->streams[i]->priv_data);
489
490     ogg_write_pages(s, 1);
491
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]);
499         }
500         av_freep(&st->priv_data);
501     }
502     return 0;
503 }
504
505 AVOutputFormat ff_ogg_muxer = {
506     "ogg",
507     NULL_IF_CONFIG_SMALL("Ogg"),
508     "application/ogg",
509     "ogg,ogv,spx",
510     sizeof(OGGContext),
511     CODEC_ID_FLAC,
512     CODEC_ID_THEORA,
513     ogg_write_header,
514     ogg_write_packet,
515     ogg_write_trailer,
516 };