In ogg muxer, pack multiple frames into one page, much lower overhead
[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 "libavcodec/xiph.h"
24 #include "libavcodec/bytestream.h"
25 #include "libavcodec/flac.h"
26 #include "avformat.h"
27 #include "internal.h"
28 #include "vorbiscomment.h"
29
30 #define MAX_PAGE_SIZE 65025
31
32 typedef struct {
33     int64_t granule;
34     int stream_index;
35     uint8_t flags;
36     uint8_t segments_count;
37     uint8_t segments[255];
38     uint8_t data[MAX_PAGE_SIZE];
39     uint16_t size;
40 } OGGPage;
41
42 typedef struct {
43     int64_t duration;
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 } OGGStreamContext;
55
56 typedef struct OGGPageList {
57     OGGPage page;
58     struct OGGPageList *next;
59 } OGGPageList;
60
61 typedef struct {
62     OGGPageList *page_list;
63 } OGGContext;
64
65 static void ogg_update_checksum(AVFormatContext *s, int64_t crc_offset)
66 {
67     int64_t pos = url_ftell(s->pb);
68     uint32_t checksum = get_checksum(s->pb);
69     url_fseek(s->pb, crc_offset, SEEK_SET);
70     put_be32(s->pb, checksum);
71     url_fseek(s->pb, pos, SEEK_SET);
72 }
73
74 static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
75 {
76     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
77     int64_t crc_offset;
78
79     init_checksum(s->pb, ff_crc04C11DB7_update, 0);
80     put_tag(s->pb, "OggS");
81     put_byte(s->pb, 0);
82     put_byte(s->pb, page->flags | extra_flags);
83     put_le64(s->pb, page->granule);
84     put_le32(s->pb, page->stream_index);
85     put_le32(s->pb, oggstream->page_counter++);
86     crc_offset = url_ftell(s->pb);
87     put_le32(s->pb, 0); // crc
88     put_byte(s->pb, page->segments_count);
89     put_buffer(s->pb, page->segments, page->segments_count);
90     put_buffer(s->pb, page->data, page->size);
91
92     ogg_update_checksum(s, crc_offset);
93     put_flush_packet(s->pb);
94     oggstream->page_count--;
95 }
96
97 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, OGGPage *page)
98 {
99     if (oggstream->kfgshift)
100         return (page->granule>>oggstream->kfgshift) +
101             (page->granule & ((1<<oggstream->kfgshift)-1));
102     else
103         return page->granule;
104 }
105
106 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
107 {
108     AVStream *st2 = s->streams[next->stream_index];
109     AVStream *st  = s->streams[page->stream_index];
110     int64_t next_granule, cur_granule;
111
112     if (next->granule == -1 || page->granule == -1)
113         return 0;
114
115     next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next),
116                                 st2->time_base, AV_TIME_BASE_Q);
117     cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page),
118                                 st ->time_base, AV_TIME_BASE_Q);
119     return next_granule > cur_granule;
120 }
121
122 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
123 {
124     oggstream->page.granule = -1;
125     oggstream->page.flags = 0;
126     oggstream->page.segments_count = 0;
127     oggstream->page.size = 0;
128     return 0;
129 }
130
131 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
132 {
133     OGGContext *ogg = s->priv_data;
134     OGGPageList **p = &ogg->page_list;
135     OGGPageList *l = av_mallocz(sizeof(*l));
136
137     if (!l)
138         return AVERROR(ENOMEM);
139     l->page = oggstream->page;
140
141     oggstream->page_count++;
142     ogg_reset_cur_page(oggstream);
143
144     while (*p) {
145         if (ogg_compare_granule(s, &(*p)->page, &l->page))
146             break;
147         p = &(*p)->next;
148     }
149     l->next = *p;
150     *p = l;
151
152     return 0;
153 }
154
155 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
156                            uint8_t *data, unsigned size, int64_t granule)
157 {
158     OGGStreamContext *oggstream = st->priv_data;
159     int total_segments = size / 255 + 1;
160     uint8_t *p = data;
161     int i, segments, len;
162
163     for (i = 0; i < total_segments; ) {
164         OGGPage *page = &oggstream->page;
165
166         segments = FFMIN(total_segments - i, 255 - page->segments_count);
167
168         if (i && !page->segments_count)
169             page->flags |= 1; // continued packet
170
171         memset(page->segments+page->segments_count, 255, segments - 1);
172         page->segments_count += segments - 1;
173
174         len = FFMIN(size, segments*255);
175         page->segments[page->segments_count++] = len - (segments-1)*255;
176         memcpy(page->data+page->size, p, len);
177         p += len;
178         size -= len;
179         i += segments;
180         page->size += len;
181
182         if (i == total_segments)
183             page->granule = granule;
184
185         if (page->segments_count == 255) {
186             ogg_buffer_page(s, oggstream);
187         }
188     }
189     return 0;
190 }
191
192 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
193                                         int *header_len, AVMetadata *m)
194 {
195     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
196     int size;
197     uint8_t *p, *p0;
198     unsigned int count;
199
200     size = offset + ff_vorbiscomment_length(m, vendor, &count);
201     p = av_mallocz(size);
202     if (!p)
203         return NULL;
204     p0 = p;
205
206     p += offset;
207     ff_vorbiscomment_write(&p, m, vendor, count);
208
209     *header_len = size;
210     return p0;
211 }
212
213 static int ogg_build_flac_headers(AVCodecContext *avctx,
214                                   OGGStreamContext *oggstream, int bitexact,
215                                   AVMetadata *m)
216 {
217     enum FLACExtradataFormat format;
218     uint8_t *streaminfo;
219     uint8_t *p;
220
221     if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
222         return -1;
223
224     // first packet: STREAMINFO
225     oggstream->header_len[0] = 51;
226     oggstream->header[0] = av_mallocz(51); // per ogg flac specs
227     p = oggstream->header[0];
228     if (!p)
229         return AVERROR(ENOMEM);
230     bytestream_put_byte(&p, 0x7F);
231     bytestream_put_buffer(&p, "FLAC", 4);
232     bytestream_put_byte(&p, 1); // major version
233     bytestream_put_byte(&p, 0); // minor version
234     bytestream_put_be16(&p, 1); // headers packets without this one
235     bytestream_put_buffer(&p, "fLaC", 4);
236     bytestream_put_byte(&p, 0x00); // streaminfo
237     bytestream_put_be24(&p, 34);
238     bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
239
240     // second packet: VorbisComment
241     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m);
242     if (!p)
243         return AVERROR(ENOMEM);
244     oggstream->header[1] = p;
245     bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
246     bytestream_put_be24(&p, oggstream->header_len[1] - 4);
247
248     return 0;
249 }
250
251 #define SPEEX_HEADER_SIZE 80
252
253 static int ogg_build_speex_headers(AVCodecContext *avctx,
254                                    OGGStreamContext *oggstream, int bitexact,
255                                    AVMetadata *m)
256 {
257     uint8_t *p;
258
259     if (avctx->extradata_size < SPEEX_HEADER_SIZE)
260         return -1;
261
262     // first packet: Speex header
263     p = av_mallocz(SPEEX_HEADER_SIZE);
264     if (!p)
265         return AVERROR(ENOMEM);
266     oggstream->header[0] = p;
267     oggstream->header_len[0] = SPEEX_HEADER_SIZE;
268     bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
269     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
270
271     // second packet: VorbisComment
272     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m);
273     if (!p)
274         return AVERROR(ENOMEM);
275     oggstream->header[1] = p;
276
277     return 0;
278 }
279
280 static int ogg_write_header(AVFormatContext *s)
281 {
282     OGGStreamContext *oggstream;
283     int i, j;
284     for (i = 0; i < s->nb_streams; i++) {
285         AVStream *st = s->streams[i];
286         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
287             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
288         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
289             av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
290         if (st->codec->codec_id != CODEC_ID_VORBIS &&
291             st->codec->codec_id != CODEC_ID_THEORA &&
292             st->codec->codec_id != CODEC_ID_SPEEX  &&
293             st->codec->codec_id != CODEC_ID_FLAC) {
294             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
295             return -1;
296         }
297
298         if (!st->codec->extradata || !st->codec->extradata_size) {
299             av_log(s, AV_LOG_ERROR, "No extradata present\n");
300             return -1;
301         }
302         oggstream = av_mallocz(sizeof(*oggstream));
303         oggstream->page.stream_index = i;
304         st->priv_data = oggstream;
305         if (st->codec->codec_id == CODEC_ID_FLAC) {
306             int err = ogg_build_flac_headers(st->codec, oggstream,
307                                              st->codec->flags & CODEC_FLAG_BITEXACT,
308                                              s->metadata);
309             if (err) {
310                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
311                 av_freep(&st->priv_data);
312                 return err;
313             }
314         } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
315             int err = ogg_build_speex_headers(st->codec, oggstream,
316                                               st->codec->flags & CODEC_FLAG_BITEXACT,
317                                               s->metadata);
318             if (err) {
319                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
320                 av_freep(&st->priv_data);
321                 return err;
322             }
323         } else {
324             if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
325                                       st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
326                                       oggstream->header, oggstream->header_len) < 0) {
327                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
328                 av_freep(&st->priv_data);
329                 return -1;
330             }
331             if (st->codec->codec_id == CODEC_ID_THEORA) {
332                 /** KFGSHIFT is the width of the less significant section of the granule position
333                     The less significant section is the frame count since the last keyframe */
334                 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
335                 oggstream->vrev = oggstream->header[0][9];
336                 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
337                        oggstream->kfgshift, oggstream->vrev);
338             }
339         }
340     }
341
342     for (j = 0; j < s->nb_streams; j++) {
343         OGGStreamContext *oggstream = s->streams[j]->priv_data;
344         ogg_buffer_data(s, s->streams[j], oggstream->header[0],
345                         oggstream->header_len[0], 0);
346         oggstream->page.flags |= 2; // bos
347         ogg_buffer_page(s, oggstream);
348     }
349     for (j = 0; j < s->nb_streams; j++) {
350         AVStream *st = s->streams[j];
351         OGGStreamContext *oggstream = st->priv_data;
352         for (i = 1; i < 3; i++) {
353             if (oggstream && oggstream->header_len[i])
354                 ogg_buffer_data(s, st, oggstream->header[i],
355                                 oggstream->header_len[i], 0);
356         }
357         ogg_buffer_page(s, oggstream);
358     }
359     return 0;
360 }
361
362 static void ogg_write_pages(AVFormatContext *s, int flush)
363 {
364     OGGContext *ogg = s->priv_data;
365     OGGPageList *next, *p;
366
367     if (!ogg->page_list)
368         return;
369
370     for (p = ogg->page_list; p; ) {
371         OGGStreamContext *oggstream =
372             s->streams[p->page.stream_index]->priv_data;
373         if (oggstream->page_count < 2 && !flush)
374             break;
375         ogg_write_page(s, &p->page,
376                        flush && oggstream->page_count == 1 ? 4 : 0); // eos
377         next = p->next;
378         av_freep(&p);
379         p = next;
380     }
381     ogg->page_list = p;
382 }
383
384 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
385 {
386     AVStream *st = s->streams[pkt->stream_index];
387     OGGStreamContext *oggstream = st->priv_data;
388     int ret;
389     int64_t granule;
390
391     if (st->codec->codec_id == CODEC_ID_THEORA) {
392         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
393         int pframe_count;
394         if (pkt->flags & AV_PKT_FLAG_KEY)
395             oggstream->last_kf_pts = pts;
396         pframe_count = pts - oggstream->last_kf_pts;
397         // prevent frame count from overflow if key frame flag is not set
398         if (pframe_count >= (1<<oggstream->kfgshift)) {
399             oggstream->last_kf_pts += pframe_count;
400             pframe_count = 0;
401         }
402         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
403     } else
404         granule = pkt->pts + pkt->duration;
405     oggstream->duration = granule;
406
407     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
408     if (ret < 0)
409         return ret;
410
411     ogg_write_pages(s, 0);
412
413     return 0;
414 }
415
416 static int ogg_write_trailer(AVFormatContext *s)
417 {
418     int i;
419
420     /* flush current page */
421     for (i = 0; i < s->nb_streams; i++)
422         ogg_buffer_page(s, s->streams[i]->priv_data);
423
424     ogg_write_pages(s, 1);
425
426     for (i = 0; i < s->nb_streams; i++) {
427         AVStream *st = s->streams[i];
428         OGGStreamContext *oggstream = st->priv_data;
429         if (st->codec->codec_id == CODEC_ID_FLAC ||
430             st->codec->codec_id == CODEC_ID_SPEEX) {
431             av_free(oggstream->header[0]);
432             av_free(oggstream->header[1]);
433         }
434         av_freep(&st->priv_data);
435     }
436     return 0;
437 }
438
439 AVOutputFormat ogg_muxer = {
440     "ogg",
441     NULL_IF_CONFIG_SMALL("Ogg"),
442     "application/ogg",
443     "ogg,ogv,spx",
444     sizeof(OGGContext),
445     CODEC_ID_FLAC,
446     CODEC_ID_THEORA,
447     ogg_write_header,
448     ogg_write_packet,
449     ogg_write_trailer,
450     .metadata_conv = ff_vorbiscomment_metadata_conv,
451 };