8svx: decode directly to the user-provided AVFrame
[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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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/mathematics.h"
24 #include "libavutil/opt.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 start_granule;
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     int64_t pref_duration;      ///< preferred page duration (0 => fill all segments)
72 } OGGContext;
73
74 #define OFFSET(x) offsetof(OGGContext, x)
75 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
76
77 static const AVOption options[] = {
78     { "pagesize", "preferred page size in bytes (deprecated)",
79         OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
80     { "page_duration", "preferred page duration, in microseconds",
81         OFFSET(pref_duration), AV_OPT_TYPE_INT, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
82     { NULL },
83 };
84
85 static const AVClass ogg_muxer_class = {
86     .class_name = "Ogg muxer",
87     .item_name  = av_default_item_name,
88     .option     = options,
89     .version    = LIBAVUTIL_VERSION_INT,
90 };
91
92
93 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
94 {
95     int64_t pos = avio_tell(pb);
96     uint32_t checksum = ffio_get_checksum(pb);
97     avio_seek(pb, crc_offset, SEEK_SET);
98     avio_wb32(pb, checksum);
99     avio_seek(pb, pos, SEEK_SET);
100 }
101
102 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
103 {
104     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
105     AVIOContext *pb;
106     int64_t crc_offset;
107     int ret, size;
108     uint8_t *buf;
109
110     ret = avio_open_dyn_buf(&pb);
111     if (ret < 0)
112         return ret;
113     ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
114     ffio_wfourcc(pb, "OggS");
115     avio_w8(pb, 0);
116     avio_w8(pb, page->flags | extra_flags);
117     avio_wl64(pb, page->granule);
118     avio_wl32(pb, oggstream->serial_num);
119     avio_wl32(pb, oggstream->page_counter++);
120     crc_offset = avio_tell(pb);
121     avio_wl32(pb, 0); // crc
122     avio_w8(pb, page->segments_count);
123     avio_write(pb, page->segments, page->segments_count);
124     avio_write(pb, page->data, page->size);
125
126     ogg_update_checksum(s, pb, crc_offset);
127     avio_flush(pb);
128
129     size = avio_close_dyn_buf(pb, &buf);
130     if (size < 0)
131         return size;
132
133     avio_write(s->pb, buf, size);
134     avio_flush(s->pb);
135     av_free(buf);
136     oggstream->page_count--;
137     return 0;
138 }
139
140 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
141 {
142     if (oggstream->kfgshift)
143         return (granule>>oggstream->kfgshift) +
144             (granule & ((1<<oggstream->kfgshift)-1));
145     else
146         return granule;
147 }
148
149 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
150 {
151     AVStream *st2 = s->streams[next->stream_index];
152     AVStream *st  = s->streams[page->stream_index];
153     int64_t next_granule, cur_granule;
154
155     if (next->granule == -1 || page->granule == -1)
156         return 0;
157
158     next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
159                                 st2->time_base, AV_TIME_BASE_Q);
160     cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
161                                 st ->time_base, AV_TIME_BASE_Q);
162     return next_granule > cur_granule;
163 }
164
165 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
166 {
167     oggstream->page.granule = -1;
168     oggstream->page.flags = 0;
169     oggstream->page.segments_count = 0;
170     oggstream->page.size = 0;
171     return 0;
172 }
173
174 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
175 {
176     OGGContext *ogg = s->priv_data;
177     OGGPageList **p = &ogg->page_list;
178     OGGPageList *l = av_mallocz(sizeof(*l));
179
180     if (!l)
181         return AVERROR(ENOMEM);
182     l->page = oggstream->page;
183
184     oggstream->page.start_granule = oggstream->page.granule;
185     oggstream->page_count++;
186     ogg_reset_cur_page(oggstream);
187
188     while (*p) {
189         if (ogg_compare_granule(s, &(*p)->page, &l->page))
190             break;
191         p = &(*p)->next;
192     }
193     l->next = *p;
194     *p = l;
195
196     return 0;
197 }
198
199 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
200                            uint8_t *data, unsigned size, int64_t granule,
201                            int header)
202 {
203     OGGStreamContext *oggstream = st->priv_data;
204     OGGContext *ogg = s->priv_data;
205     int total_segments = size / 255 + 1;
206     uint8_t *p = data;
207     int i, segments, len, flush = 0;
208
209     // Handles VFR by flushing page because this frame needs to have a timestamp
210     if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
211         ogg_granule_to_timestamp(oggstream, granule) >
212         ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
213         if (oggstream->page.granule != -1)
214             ogg_buffer_page(s, oggstream);
215         flush = 1;
216     }
217
218     // avoid a continued page
219     if (!header && oggstream->page.size > 0 &&
220         MAX_PAGE_SIZE - oggstream->page.size < size) {
221         ogg_buffer_page(s, oggstream);
222     }
223
224     for (i = 0; i < total_segments; ) {
225         OGGPage *page = &oggstream->page;
226
227         segments = FFMIN(total_segments - i, 255 - page->segments_count);
228
229         if (i && !page->segments_count)
230             page->flags |= 1; // continued packet
231
232         memset(page->segments+page->segments_count, 255, segments - 1);
233         page->segments_count += segments - 1;
234
235         len = FFMIN(size, segments*255);
236         page->segments[page->segments_count++] = len - (segments-1)*255;
237         memcpy(page->data+page->size, p, len);
238         p += len;
239         size -= len;
240         i += segments;
241         page->size += len;
242
243         if (i == total_segments)
244             page->granule = granule;
245
246         if (!header) {
247             AVStream *st = s->streams[page->stream_index];
248
249             int64_t start = av_rescale_q(page->start_granule, st->time_base,
250                                          AV_TIME_BASE_Q);
251             int64_t next  = av_rescale_q(page->granule, st->time_base,
252                                          AV_TIME_BASE_Q);
253
254             if (page->segments_count == 255 ||
255                 (ogg->pref_size     > 0 && page->size   >= ogg->pref_size) ||
256                 (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
257                 ogg_buffer_page(s, oggstream);
258             }
259         }
260     }
261
262     if (flush && oggstream->page.granule != -1)
263         ogg_buffer_page(s, oggstream);
264
265     return 0;
266 }
267
268 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
269                                         int *header_len, AVDictionary **m, int framing_bit)
270 {
271     const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
272     int size;
273     uint8_t *p, *p0;
274     unsigned int count;
275
276     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
277
278     size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
279     p = av_mallocz(size);
280     if (!p)
281         return NULL;
282     p0 = p;
283
284     p += offset;
285     ff_vorbiscomment_write(&p, m, vendor, count);
286     if (framing_bit)
287         bytestream_put_byte(&p, 1);
288
289     *header_len = size;
290     return p0;
291 }
292
293 static int ogg_build_flac_headers(AVCodecContext *avctx,
294                                   OGGStreamContext *oggstream, int bitexact,
295                                   AVDictionary **m)
296 {
297     enum FLACExtradataFormat format;
298     uint8_t *streaminfo;
299     uint8_t *p;
300
301     if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
302         return -1;
303
304     // first packet: STREAMINFO
305     oggstream->header_len[0] = 51;
306     oggstream->header[0] = av_mallocz(51); // per ogg flac specs
307     p = oggstream->header[0];
308     if (!p)
309         return AVERROR(ENOMEM);
310     bytestream_put_byte(&p, 0x7F);
311     bytestream_put_buffer(&p, "FLAC", 4);
312     bytestream_put_byte(&p, 1); // major version
313     bytestream_put_byte(&p, 0); // minor version
314     bytestream_put_be16(&p, 1); // headers packets without this one
315     bytestream_put_buffer(&p, "fLaC", 4);
316     bytestream_put_byte(&p, 0x00); // streaminfo
317     bytestream_put_be24(&p, 34);
318     bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
319
320     // second packet: VorbisComment
321     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
322     if (!p)
323         return AVERROR(ENOMEM);
324     oggstream->header[1] = p;
325     bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
326     bytestream_put_be24(&p, oggstream->header_len[1] - 4);
327
328     return 0;
329 }
330
331 #define SPEEX_HEADER_SIZE 80
332
333 static int ogg_build_speex_headers(AVCodecContext *avctx,
334                                    OGGStreamContext *oggstream, int bitexact,
335                                    AVDictionary **m)
336 {
337     uint8_t *p;
338
339     if (avctx->extradata_size < SPEEX_HEADER_SIZE)
340         return -1;
341
342     // first packet: Speex header
343     p = av_mallocz(SPEEX_HEADER_SIZE);
344     if (!p)
345         return AVERROR(ENOMEM);
346     oggstream->header[0] = p;
347     oggstream->header_len[0] = SPEEX_HEADER_SIZE;
348     bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
349     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
350
351     // second packet: VorbisComment
352     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
353     if (!p)
354         return AVERROR(ENOMEM);
355     oggstream->header[1] = p;
356
357     return 0;
358 }
359
360 #define OPUS_HEADER_SIZE 19
361
362 static int ogg_build_opus_headers(AVCodecContext *avctx,
363                                   OGGStreamContext *oggstream, int bitexact,
364                                   AVDictionary **m)
365 {
366     uint8_t *p;
367
368     if (avctx->extradata_size < OPUS_HEADER_SIZE)
369         return -1;
370
371     /* first packet: Opus header */
372     p = av_mallocz(avctx->extradata_size);
373     if (!p)
374         return AVERROR(ENOMEM);
375     oggstream->header[0] = p;
376     oggstream->header_len[0] = avctx->extradata_size;
377     bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
378
379     /* second packet: VorbisComment */
380     p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
381     if (!p)
382         return AVERROR(ENOMEM);
383     oggstream->header[1] = p;
384     bytestream_put_buffer(&p, "OpusTags", 8);
385
386     return 0;
387 }
388
389 static int ogg_write_header(AVFormatContext *s)
390 {
391     OGGContext *ogg = s->priv_data;
392     OGGStreamContext *oggstream;
393     int i, j;
394
395     if (ogg->pref_size)
396         av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
397
398     for (i = 0; i < s->nb_streams; i++) {
399         AVStream *st = s->streams[i];
400         unsigned serial_num = i;
401
402         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
403             if (st->codec->codec_id == AV_CODEC_ID_OPUS)
404                 /* Opus requires a fixed 48kHz clock */
405                 avpriv_set_pts_info(st, 64, 1, 48000);
406             else
407                 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
408         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
409             avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
410         if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
411             st->codec->codec_id != AV_CODEC_ID_THEORA &&
412             st->codec->codec_id != AV_CODEC_ID_SPEEX  &&
413             st->codec->codec_id != AV_CODEC_ID_FLAC   &&
414             st->codec->codec_id != AV_CODEC_ID_OPUS) {
415             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
416             return -1;
417         }
418
419         if (!st->codec->extradata || !st->codec->extradata_size) {
420             av_log(s, AV_LOG_ERROR, "No extradata present\n");
421             return -1;
422         }
423         oggstream = av_mallocz(sizeof(*oggstream));
424         oggstream->page.stream_index = i;
425
426         if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
427             do {
428                 serial_num = av_get_random_seed();
429                 for (j = 0; j < i; j++) {
430                     OGGStreamContext *sc = s->streams[j]->priv_data;
431                     if (serial_num == sc->serial_num)
432                         break;
433                 }
434             } while (j < i);
435         oggstream->serial_num = serial_num;
436
437         st->priv_data = oggstream;
438         if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
439             int err = ogg_build_flac_headers(st->codec, oggstream,
440                                              st->codec->flags & CODEC_FLAG_BITEXACT,
441                                              &s->metadata);
442             if (err) {
443                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
444                 av_freep(&st->priv_data);
445                 return err;
446             }
447         } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
448             int err = ogg_build_speex_headers(st->codec, oggstream,
449                                               st->codec->flags & CODEC_FLAG_BITEXACT,
450                                               &s->metadata);
451             if (err) {
452                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
453                 av_freep(&st->priv_data);
454                 return err;
455             }
456         } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
457             int err = ogg_build_opus_headers(st->codec, oggstream,
458                                              st->codec->flags & CODEC_FLAG_BITEXACT,
459                                              &s->metadata);
460             if (err) {
461                 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
462                 av_freep(&st->priv_data);
463                 return err;
464             }
465         } else {
466             uint8_t *p;
467             const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
468             int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
469             int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
470
471             if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
472                                       st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
473                                       oggstream->header, oggstream->header_len) < 0) {
474                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
475                 av_freep(&st->priv_data);
476                 return -1;
477             }
478
479             p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
480                                         &oggstream->header_len[1], &s->metadata,
481                                         framing_bit);
482             oggstream->header[1] = p;
483             if (!p)
484                 return AVERROR(ENOMEM);
485
486             bytestream_put_byte(&p, header_type);
487             bytestream_put_buffer(&p, cstr, 6);
488
489             if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
490                 /** KFGSHIFT is the width of the less significant section of the granule position
491                     The less significant section is the frame count since the last keyframe */
492                 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
493                 oggstream->vrev = oggstream->header[0][9];
494                 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
495                        oggstream->kfgshift, oggstream->vrev);
496             }
497         }
498     }
499
500     for (j = 0; j < s->nb_streams; j++) {
501         OGGStreamContext *oggstream = s->streams[j]->priv_data;
502         ogg_buffer_data(s, s->streams[j], oggstream->header[0],
503                         oggstream->header_len[0], 0, 1);
504         oggstream->page.flags |= 2; // bos
505         ogg_buffer_page(s, oggstream);
506     }
507     for (j = 0; j < s->nb_streams; j++) {
508         AVStream *st = s->streams[j];
509         OGGStreamContext *oggstream = st->priv_data;
510         for (i = 1; i < 3; i++) {
511             if (oggstream && oggstream->header_len[i])
512                 ogg_buffer_data(s, st, oggstream->header[i],
513                                 oggstream->header_len[i], 0, 1);
514         }
515         ogg_buffer_page(s, oggstream);
516     }
517
518     oggstream->page.start_granule = AV_NOPTS_VALUE;
519
520     return 0;
521 }
522
523 static void ogg_write_pages(AVFormatContext *s, int flush)
524 {
525     OGGContext *ogg = s->priv_data;
526     OGGPageList *next, *p;
527
528     if (!ogg->page_list)
529         return;
530
531     for (p = ogg->page_list; p; ) {
532         OGGStreamContext *oggstream =
533             s->streams[p->page.stream_index]->priv_data;
534         if (oggstream->page_count < 2 && !flush)
535             break;
536         ogg_write_page(s, &p->page,
537                        flush && oggstream->page_count == 1 ? 4 : 0); // eos
538         next = p->next;
539         av_freep(&p);
540         p = next;
541     }
542     ogg->page_list = p;
543 }
544
545 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
546 {
547     AVStream *st = s->streams[pkt->stream_index];
548     OGGStreamContext *oggstream = st->priv_data;
549     int ret;
550     int64_t granule;
551
552     if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
553         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
554         int pframe_count;
555         if (pkt->flags & AV_PKT_FLAG_KEY)
556             oggstream->last_kf_pts = pts;
557         pframe_count = pts - oggstream->last_kf_pts;
558         // prevent frame count from overflow if key frame flag is not set
559         if (pframe_count >= (1<<oggstream->kfgshift)) {
560             oggstream->last_kf_pts += pframe_count;
561             pframe_count = 0;
562         }
563         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
564     } else if (st->codec->codec_id == AV_CODEC_ID_OPUS)
565         granule = pkt->pts + pkt->duration + av_rescale_q(st->codec->delay, (AVRational){ 1, st->codec->sample_rate }, st->time_base);
566     else
567         granule = pkt->pts + pkt->duration;
568
569     if (oggstream->page.start_granule == AV_NOPTS_VALUE)
570         oggstream->page.start_granule = pkt->pts;
571
572     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
573     if (ret < 0)
574         return ret;
575
576     ogg_write_pages(s, 0);
577
578     oggstream->last_granule = granule;
579
580     return 0;
581 }
582
583 static int ogg_write_trailer(AVFormatContext *s)
584 {
585     int i;
586
587     /* flush current page if needed */
588     for (i = 0; i < s->nb_streams; i++) {
589         OGGStreamContext *oggstream = s->streams[i]->priv_data;
590
591         if (oggstream->page.size > 0)
592             ogg_buffer_page(s, oggstream);
593     }
594
595     ogg_write_pages(s, 1);
596
597     for (i = 0; i < s->nb_streams; i++) {
598         AVStream *st = s->streams[i];
599         OGGStreamContext *oggstream = st->priv_data;
600         if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
601             st->codec->codec_id == AV_CODEC_ID_SPEEX ||
602             st->codec->codec_id == AV_CODEC_ID_OPUS) {
603             av_free(oggstream->header[0]);
604         }
605         av_freep(&oggstream->header[1]);
606         av_freep(&st->priv_data);
607     }
608     return 0;
609 }
610
611 AVOutputFormat ff_ogg_muxer = {
612     .name              = "ogg",
613     .long_name         = NULL_IF_CONFIG_SMALL("Ogg"),
614     .mime_type         = "application/ogg",
615     .extensions        = "ogg,ogv,spx,opus",
616     .priv_data_size    = sizeof(OGGContext),
617     .audio_codec       = AV_CODEC_ID_FLAC,
618     .video_codec       = AV_CODEC_ID_THEORA,
619     .write_header      = ogg_write_header,
620     .write_packet      = ogg_write_packet,
621     .write_trailer     = ogg_write_trailer,
622     .priv_class        = &ogg_muxer_class,
623 };