Statistics
| Branch: | Revision:

ffmpeg / libavformat / oggenc.c @ 521d434f

History | View | Annotate | Download (15.6 KB)

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, int framing_bit)
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) + framing_bit;
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
    if (framing_bit)
225
        bytestream_put_byte(&p, 1);
226

    
227
    *header_len = size;
228
    return p0;
229
}
230

    
231
static int ogg_build_flac_headers(AVCodecContext *avctx,
232
                                  OGGStreamContext *oggstream, int bitexact,
233
                                  AVMetadata *m)
234
{
235
    enum FLACExtradataFormat format;
236
    uint8_t *streaminfo;
237
    uint8_t *p;
238

    
239
    if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
240
        return -1;
241

    
242
    // first packet: STREAMINFO
243
    oggstream->header_len[0] = 51;
244
    oggstream->header[0] = av_mallocz(51); // per ogg flac specs
245
    p = oggstream->header[0];
246
    if (!p)
247
        return AVERROR(ENOMEM);
248
    bytestream_put_byte(&p, 0x7F);
249
    bytestream_put_buffer(&p, "FLAC", 4);
250
    bytestream_put_byte(&p, 1); // major version
251
    bytestream_put_byte(&p, 0); // minor version
252
    bytestream_put_be16(&p, 1); // headers packets without this one
253
    bytestream_put_buffer(&p, "fLaC", 4);
254
    bytestream_put_byte(&p, 0x00); // streaminfo
255
    bytestream_put_be24(&p, 34);
256
    bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
257

    
258
    // second packet: VorbisComment
259
    p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
260
    if (!p)
261
        return AVERROR(ENOMEM);
262
    oggstream->header[1] = p;
263
    bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
264
    bytestream_put_be24(&p, oggstream->header_len[1] - 4);
265

    
266
    return 0;
267
}
268

    
269
#define SPEEX_HEADER_SIZE 80
270

    
271
static int ogg_build_speex_headers(AVCodecContext *avctx,
272
                                   OGGStreamContext *oggstream, int bitexact,
273
                                   AVMetadata *m)
274
{
275
    uint8_t *p;
276

    
277
    if (avctx->extradata_size < SPEEX_HEADER_SIZE)
278
        return -1;
279

    
280
    // first packet: Speex header
281
    p = av_mallocz(SPEEX_HEADER_SIZE);
282
    if (!p)
283
        return AVERROR(ENOMEM);
284
    oggstream->header[0] = p;
285
    oggstream->header_len[0] = SPEEX_HEADER_SIZE;
286
    bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
287
    AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
288

    
289
    // second packet: VorbisComment
290
    p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
291
    if (!p)
292
        return AVERROR(ENOMEM);
293
    oggstream->header[1] = p;
294

    
295
    return 0;
296
}
297

    
298
static int ogg_write_header(AVFormatContext *s)
299
{
300
    OGGStreamContext *oggstream;
301
    int i, j;
302

    
303
    for (i = 0; i < s->nb_streams; i++) {
304
        AVStream *st = s->streams[i];
305
        unsigned serial_num = i;
306

    
307
        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
308
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
309
        else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
310
            av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
311
        if (st->codec->codec_id != CODEC_ID_VORBIS &&
312
            st->codec->codec_id != CODEC_ID_THEORA &&
313
            st->codec->codec_id != CODEC_ID_SPEEX  &&
314
            st->codec->codec_id != CODEC_ID_FLAC) {
315
            av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
316
            return -1;
317
        }
318

    
319
        if (!st->codec->extradata || !st->codec->extradata_size) {
320
            av_log(s, AV_LOG_ERROR, "No extradata present\n");
321
            return -1;
322
        }
323
        oggstream = av_mallocz(sizeof(*oggstream));
324
        oggstream->page.stream_index = i;
325

    
326
        if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
327
            do {
328
                serial_num = av_get_random_seed();
329
                for (j = 0; j < i; j++) {
330
                    OGGStreamContext *sc = s->streams[j]->priv_data;
331
                    if (serial_num == sc->serial_num)
332
                        break;
333
                }
334
            } while (j < i);
335
        oggstream->serial_num = serial_num;
336

    
337
        st->priv_data = oggstream;
338
        if (st->codec->codec_id == CODEC_ID_FLAC) {
339
            int err = ogg_build_flac_headers(st->codec, oggstream,
340
                                             st->codec->flags & CODEC_FLAG_BITEXACT,
341
                                             s->metadata);
342
            if (err) {
343
                av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
344
                av_freep(&st->priv_data);
345
                return err;
346
            }
347
        } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
348
            int err = ogg_build_speex_headers(st->codec, oggstream,
349
                                              st->codec->flags & CODEC_FLAG_BITEXACT,
350
                                              s->metadata);
351
            if (err) {
352
                av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
353
                av_freep(&st->priv_data);
354
                return err;
355
            }
356
        } else {
357
            uint8_t *p;
358
            char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
359
            int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
360
            int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
361

    
362
            if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
363
                                      st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
364
                                      oggstream->header, oggstream->header_len) < 0) {
365
                av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
366
                av_freep(&st->priv_data);
367
                return -1;
368
            }
369

    
370
            p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
371
                                        &oggstream->header_len[1], s->metadata,
372
                                        framing_bit);
373
            if (!p)
374
                return AVERROR(ENOMEM);
375

    
376
            oggstream->header[1] = p;
377
            bytestream_put_byte(&p, header_type);
378
            bytestream_put_buffer(&p, cstr, 6);
379

    
380
            if (st->codec->codec_id == CODEC_ID_THEORA) {
381
                /** KFGSHIFT is the width of the less significant section of the granule position
382
                    The less significant section is the frame count since the last keyframe */
383
                oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
384
                oggstream->vrev = oggstream->header[0][9];
385
                av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
386
                       oggstream->kfgshift, oggstream->vrev);
387
            }
388
        }
389
    }
390

    
391
    for (j = 0; j < s->nb_streams; j++) {
392
        OGGStreamContext *oggstream = s->streams[j]->priv_data;
393
        ogg_buffer_data(s, s->streams[j], oggstream->header[0],
394
                        oggstream->header_len[0], 0);
395
        oggstream->page.flags |= 2; // bos
396
        ogg_buffer_page(s, oggstream);
397
    }
398
    for (j = 0; j < s->nb_streams; j++) {
399
        AVStream *st = s->streams[j];
400
        OGGStreamContext *oggstream = st->priv_data;
401
        for (i = 1; i < 3; i++) {
402
            if (oggstream && oggstream->header_len[i])
403
                ogg_buffer_data(s, st, oggstream->header[i],
404
                                oggstream->header_len[i], 0);
405
        }
406
        ogg_buffer_page(s, oggstream);
407
    }
408
    return 0;
409
}
410

    
411
static void ogg_write_pages(AVFormatContext *s, int flush)
412
{
413
    OGGContext *ogg = s->priv_data;
414
    OGGPageList *next, *p;
415

    
416
    if (!ogg->page_list)
417
        return;
418

    
419
    for (p = ogg->page_list; p; ) {
420
        OGGStreamContext *oggstream =
421
            s->streams[p->page.stream_index]->priv_data;
422
        if (oggstream->page_count < 2 && !flush)
423
            break;
424
        ogg_write_page(s, &p->page,
425
                       flush && oggstream->page_count == 1 ? 4 : 0); // eos
426
        next = p->next;
427
        av_freep(&p);
428
        p = next;
429
    }
430
    ogg->page_list = p;
431
}
432

    
433
static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
434
{
435
    AVStream *st = s->streams[pkt->stream_index];
436
    OGGStreamContext *oggstream = st->priv_data;
437
    int ret;
438
    int64_t granule;
439

    
440
    if (st->codec->codec_id == CODEC_ID_THEORA) {
441
        int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
442
        int pframe_count;
443
        if (pkt->flags & AV_PKT_FLAG_KEY)
444
            oggstream->last_kf_pts = pts;
445
        pframe_count = pts - oggstream->last_kf_pts;
446
        // prevent frame count from overflow if key frame flag is not set
447
        if (pframe_count >= (1<<oggstream->kfgshift)) {
448
            oggstream->last_kf_pts += pframe_count;
449
            pframe_count = 0;
450
        }
451
        granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
452
    } else
453
        granule = pkt->pts + pkt->duration;
454

    
455
    ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
456
    if (ret < 0)
457
        return ret;
458

    
459
    ogg_write_pages(s, 0);
460

    
461
    return 0;
462
}
463

    
464
static int ogg_write_trailer(AVFormatContext *s)
465
{
466
    int i;
467

    
468
    /* flush current page */
469
    for (i = 0; i < s->nb_streams; i++)
470
        ogg_buffer_page(s, s->streams[i]->priv_data);
471

    
472
    ogg_write_pages(s, 1);
473

    
474
    for (i = 0; i < s->nb_streams; i++) {
475
        AVStream *st = s->streams[i];
476
        OGGStreamContext *oggstream = st->priv_data;
477
        if (st->codec->codec_id == CODEC_ID_FLAC ||
478
            st->codec->codec_id == CODEC_ID_SPEEX) {
479
            av_free(oggstream->header[0]);
480
            av_free(oggstream->header[1]);
481
        }
482
        av_freep(&st->priv_data);
483
    }
484
    return 0;
485
}
486

    
487
AVOutputFormat ogg_muxer = {
488
    "ogg",
489
    NULL_IF_CONFIG_SMALL("Ogg"),
490
    "application/ogg",
491
    "ogg,ogv,spx",
492
    sizeof(OGGContext),
493
    CODEC_ID_FLAC,
494
    CODEC_ID_THEORA,
495
    ogg_write_header,
496
    ogg_write_packet,
497
    ogg_write_trailer,
498
    .metadata_conv = ff_vorbiscomment_metadata_conv,
499
};