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