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