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