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