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