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