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