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