]> git.sesse.net Git - ffmpeg/blob - libavformat/oggenc.c
Make CDXL palette opaque.
[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/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), AV_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 int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
135 {
136     return oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1));
137 }
138
139 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
140 {
141     if (oggstream->kfgshift)
142         return (granule>>oggstream->kfgshift) +
143             (granule & ((1<<oggstream->kfgshift)-1));
144     else
145         return granule;
146 }
147
148 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
149 {
150     AVStream *st2 = s->streams[next->stream_index];
151     AVStream *st  = s->streams[page->stream_index];
152     int64_t next_granule, cur_granule;
153
154     if (next->granule == -1 || page->granule == -1)
155         return 0;
156
157     next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
158                                 st2->time_base, AV_TIME_BASE_Q);
159     cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
160                                 st ->time_base, AV_TIME_BASE_Q);
161     return next_granule > cur_granule;
162 }
163
164 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
165 {
166     oggstream->page.granule = -1;
167     oggstream->page.flags = 0;
168     oggstream->page.segments_count = 0;
169     oggstream->page.size = 0;
170     return 0;
171 }
172
173 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
174 {
175     OGGContext *ogg = s->priv_data;
176     OGGPageList **p = &ogg->page_list;
177     OGGPageList *l = av_mallocz(sizeof(*l));
178
179     if (!l)
180         return AVERROR(ENOMEM);
181     l->page = oggstream->page;
182
183     oggstream->page_count++;
184     ogg_reset_cur_page(oggstream);
185
186     while (*p) {
187         if (ogg_compare_granule(s, &(*p)->page, &l->page))
188             break;
189         p = &(*p)->next;
190     }
191     l->next = *p;
192     *p = l;
193
194     return 0;
195 }
196
197 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
198                            uint8_t *data, unsigned size, int64_t granule)
199 {
200     OGGStreamContext *oggstream = st->priv_data;
201     OGGContext *ogg = s->priv_data;
202     int total_segments = size / 255 + 1;
203     uint8_t *p = data;
204     int i, segments, len, flush = 0;
205
206     // Handles VFR by flushing page because this frame needs to have a timestamp
207     // For theora, keyframes also need to have a timestamp to correctly mark
208     // them as such, otherwise seeking will not work correctly at the very
209     // least with old libogg versions.
210     // Do not try to flush empty packets though, that will create broken files.
211     if (st->codec->codec_id == CODEC_ID_THEORA &&
212         oggstream->page.size &&
213         (ogg_granule_to_timestamp(oggstream, granule) >
214          ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
215          ogg_key_granule(oggstream, granule))) {
216         if (oggstream->page.granule != -1)
217             ogg_buffer_page(s, oggstream);
218         flush = 1;
219     }
220
221     for (i = 0; i < total_segments; ) {
222         OGGPage *page = &oggstream->page;
223
224         segments = FFMIN(total_segments - i, 255 - page->segments_count);
225
226         if (i && !page->segments_count)
227             page->flags |= 1; // continued packet
228
229         memset(page->segments+page->segments_count, 255, segments - 1);
230         page->segments_count += segments - 1;
231
232         len = FFMIN(size, segments*255);
233         page->segments[page->segments_count++] = len - (segments-1)*255;
234         memcpy(page->data+page->size, p, len);
235         p += len;
236         size -= len;
237         i += segments;
238         page->size += len;
239
240         if (i == total_segments)
241             page->granule = granule;
242
243         if(page->segments_count == 255 ||
244            (ogg->pref_size > 0 && page->size >= ogg->pref_size)) {
245            ogg_buffer_page(s, oggstream);
246         }
247     }
248
249     if (flush && oggstream->page.granule != -1)
250         ogg_buffer_page(s, oggstream);
251
252     return 0;
253 }
254
255 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
256                                         int *header_len, AVDictionary **m, int framing_bit)
257 {
258     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
259     int size;
260     uint8_t *p, *p0;
261     unsigned int count;
262
263     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
264
265     size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
266     p = av_mallocz(size);
267     if (!p)
268         return NULL;
269     p0 = p;
270
271     p += offset;
272     ff_vorbiscomment_write(&p, m, vendor, count);
273     if (framing_bit)
274         bytestream_put_byte(&p, 1);
275
276     *header_len = size;
277     return p0;
278 }
279
280 static int ogg_build_flac_headers(AVCodecContext *avctx,
281                                   OGGStreamContext *oggstream, int bitexact,
282                                   AVDictionary **m)
283 {
284     enum FLACExtradataFormat format;
285     uint8_t *streaminfo;
286     uint8_t *p;
287
288     if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
289         return -1;
290
291     // first packet: STREAMINFO
292     oggstream->header_len[0] = 51;
293     oggstream->header[0] = av_mallocz(51); // per ogg flac specs
294     p = oggstream->header[0];
295     if (!p)
296         return AVERROR(ENOMEM);
297     bytestream_put_byte(&p, 0x7F);
298     bytestream_put_buffer(&p, "FLAC", 4);
299     bytestream_put_byte(&p, 1); // major version
300     bytestream_put_byte(&p, 0); // minor version
301     bytestream_put_be16(&p, 1); // headers packets without this one
302     bytestream_put_buffer(&p, "fLaC", 4);
303     bytestream_put_byte(&p, 0x00); // streaminfo
304     bytestream_put_be24(&p, 34);
305     bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
306
307     // second packet: VorbisComment
308     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
309     if (!p)
310         return AVERROR(ENOMEM);
311     oggstream->header[1] = p;
312     bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
313     bytestream_put_be24(&p, oggstream->header_len[1] - 4);
314
315     return 0;
316 }
317
318 #define SPEEX_HEADER_SIZE 80
319
320 static int ogg_build_speex_headers(AVCodecContext *avctx,
321                                    OGGStreamContext *oggstream, int bitexact,
322                                    AVDictionary **m)
323 {
324     uint8_t *p;
325
326     if (avctx->extradata_size < SPEEX_HEADER_SIZE)
327         return -1;
328
329     // first packet: Speex header
330     p = av_mallocz(SPEEX_HEADER_SIZE);
331     if (!p)
332         return AVERROR(ENOMEM);
333     oggstream->header[0] = p;
334     oggstream->header_len[0] = SPEEX_HEADER_SIZE;
335     bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
336     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
337
338     // second packet: VorbisComment
339     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
340     if (!p)
341         return AVERROR(ENOMEM);
342     oggstream->header[1] = p;
343
344     return 0;
345 }
346
347 static int ogg_write_header(AVFormatContext *s)
348 {
349     OGGStreamContext *oggstream;
350     int i, j;
351
352     for (i = 0; i < s->nb_streams; i++) {
353         AVStream *st = s->streams[i];
354         unsigned serial_num = i;
355
356         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
357             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
358         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
359             avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
360         if (st->codec->codec_id != CODEC_ID_VORBIS &&
361             st->codec->codec_id != CODEC_ID_THEORA &&
362             st->codec->codec_id != CODEC_ID_SPEEX  &&
363             st->codec->codec_id != CODEC_ID_FLAC) {
364             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
365             return -1;
366         }
367
368         if (!st->codec->extradata || !st->codec->extradata_size) {
369             av_log(s, AV_LOG_ERROR, "No extradata present\n");
370             return -1;
371         }
372         oggstream = av_mallocz(sizeof(*oggstream));
373         oggstream->page.stream_index = i;
374
375         if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
376             do {
377                 serial_num = av_get_random_seed();
378                 for (j = 0; j < i; j++) {
379                     OGGStreamContext *sc = s->streams[j]->priv_data;
380                     if (serial_num == sc->serial_num)
381                         break;
382                 }
383             } while (j < i);
384         oggstream->serial_num = serial_num;
385
386         st->priv_data = oggstream;
387         if (st->codec->codec_id == CODEC_ID_FLAC) {
388             int err = ogg_build_flac_headers(st->codec, oggstream,
389                                              st->codec->flags & CODEC_FLAG_BITEXACT,
390                                              &s->metadata);
391             if (err) {
392                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
393                 av_freep(&st->priv_data);
394                 return err;
395             }
396         } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
397             int err = ogg_build_speex_headers(st->codec, oggstream,
398                                               st->codec->flags & CODEC_FLAG_BITEXACT,
399                                               &s->metadata);
400             if (err) {
401                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
402                 av_freep(&st->priv_data);
403                 return err;
404             }
405         } else {
406             uint8_t *p;
407             const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
408             int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
409             int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
410
411             if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
412                                       st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
413                                       oggstream->header, oggstream->header_len) < 0) {
414                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
415                 av_freep(&st->priv_data);
416                 return -1;
417             }
418
419             p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
420                                         &oggstream->header_len[1], &s->metadata,
421                                         framing_bit);
422             if (!p)
423                 return AVERROR(ENOMEM);
424
425             oggstream->header[1] = p;
426             bytestream_put_byte(&p, header_type);
427             bytestream_put_buffer(&p, cstr, 6);
428
429             if (st->codec->codec_id == CODEC_ID_THEORA) {
430                 /** KFGSHIFT is the width of the less significant section of the granule position
431                     The less significant section is the frame count since the last keyframe */
432                 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
433                 oggstream->vrev = oggstream->header[0][9];
434                 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
435                        oggstream->kfgshift, oggstream->vrev);
436             }
437         }
438     }
439
440     for (j = 0; j < s->nb_streams; j++) {
441         OGGStreamContext *oggstream = s->streams[j]->priv_data;
442         ogg_buffer_data(s, s->streams[j], oggstream->header[0],
443                         oggstream->header_len[0], 0);
444         oggstream->page.flags |= 2; // bos
445         ogg_buffer_page(s, oggstream);
446     }
447     for (j = 0; j < s->nb_streams; j++) {
448         AVStream *st = s->streams[j];
449         OGGStreamContext *oggstream = st->priv_data;
450         for (i = 1; i < 3; i++) {
451             if (oggstream && oggstream->header_len[i])
452                 ogg_buffer_data(s, st, oggstream->header[i],
453                                 oggstream->header_len[i], 0);
454         }
455         ogg_buffer_page(s, oggstream);
456     }
457     return 0;
458 }
459
460 static void ogg_write_pages(AVFormatContext *s, int flush)
461 {
462     OGGContext *ogg = s->priv_data;
463     OGGPageList *next, *p;
464
465     if (!ogg->page_list)
466         return;
467
468     for (p = ogg->page_list; p; ) {
469         OGGStreamContext *oggstream =
470             s->streams[p->page.stream_index]->priv_data;
471         if (oggstream->page_count < 2 && !flush)
472             break;
473         ogg_write_page(s, &p->page,
474                        flush && oggstream->page_count == 1 ? 4 : 0); // eos
475         next = p->next;
476         av_freep(&p);
477         p = next;
478     }
479     ogg->page_list = p;
480 }
481
482 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
483 {
484     AVStream *st = s->streams[pkt->stream_index];
485     OGGStreamContext *oggstream = st->priv_data;
486     int ret;
487     int64_t granule;
488
489     if (st->codec->codec_id == CODEC_ID_THEORA) {
490         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
491         int pframe_count;
492         if (pkt->flags & AV_PKT_FLAG_KEY)
493             oggstream->last_kf_pts = pts;
494         pframe_count = pts - oggstream->last_kf_pts;
495         // prevent frame count from overflow if key frame flag is not set
496         if (pframe_count >= (1<<oggstream->kfgshift)) {
497             oggstream->last_kf_pts += pframe_count;
498             pframe_count = 0;
499         }
500         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
501     } else
502         granule = pkt->pts + pkt->duration;
503
504     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
505     if (ret < 0)
506         return ret;
507
508     ogg_write_pages(s, 0);
509
510     oggstream->last_granule = granule;
511
512     return 0;
513 }
514
515 static int ogg_write_trailer(AVFormatContext *s)
516 {
517     int i;
518
519     /* flush current page */
520     for (i = 0; i < s->nb_streams; i++)
521         ogg_buffer_page(s, s->streams[i]->priv_data);
522
523     ogg_write_pages(s, 1);
524
525     for (i = 0; i < s->nb_streams; i++) {
526         AVStream *st = s->streams[i];
527         OGGStreamContext *oggstream = st->priv_data;
528         if (st->codec->codec_id == CODEC_ID_FLAC ||
529             st->codec->codec_id == CODEC_ID_SPEEX) {
530             av_freep(&oggstream->header[0]);
531             av_freep(&oggstream->header[1]);
532         }
533         else
534             av_freep(&oggstream->header[1]);
535         av_freep(&st->priv_data);
536     }
537     return 0;
538 }
539
540 AVOutputFormat ff_ogg_muxer = {
541     .name              = "ogg",
542     .long_name         = NULL_IF_CONFIG_SMALL("Ogg"),
543     .mime_type         = "application/ogg",
544     .extensions        = "ogg,ogv,spx",
545     .priv_data_size    = sizeof(OGGContext),
546     .audio_codec       = CODEC_ID_FLAC,
547     .video_codec       = CODEC_ID_THEORA,
548     .write_header      = ogg_write_header,
549     .write_packet      = ogg_write_packet,
550     .write_trailer     = ogg_write_trailer,
551     .priv_class = &ogg_muxer_class,
552 };