Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskaenc.c @ 316d6c15

History | View | Annotate | Download (37.7 KB)

1
/*
2
 * Matroska muxer
3
 * Copyright (c) 2007 David Conrad
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 "avformat.h"
23
#include "riff.h"
24
#include "isom.h"
25
#include "matroska.h"
26
#include "avc.h"
27
#include "flacenc.h"
28
#include "libavutil/intreadwrite.h"
29
#include "libavutil/md5.h"
30
#include "libavcodec/xiph.h"
31
#include "libavcodec/mpeg4audio.h"
32

    
33
typedef struct ebml_master {
34
    int64_t         pos;                ///< absolute offset in the file where the master's elements start
35
    int             sizebytes;          ///< how many bytes were reserved for the size
36
} ebml_master;
37

    
38
typedef struct mkv_seekhead_entry {
39
    unsigned int    elementid;
40
    uint64_t        segmentpos;
41
} mkv_seekhead_entry;
42

    
43
typedef struct mkv_seekhead {
44
    int64_t                 filepos;
45
    int64_t                 segment_offset;     ///< the file offset to the beginning of the segment
46
    int                     reserved_size;      ///< -1 if appending to file
47
    int                     max_entries;
48
    mkv_seekhead_entry      *entries;
49
    int                     num_entries;
50
} mkv_seekhead;
51

    
52
typedef struct {
53
    uint64_t        pts;
54
    int             tracknum;
55
    int64_t         cluster_pos;        ///< file offset of the cluster containing the block
56
} mkv_cuepoint;
57

    
58
typedef struct {
59
    int64_t         segment_offset;
60
    mkv_cuepoint    *entries;
61
    int             num_entries;
62
} mkv_cues;
63

    
64
typedef struct {
65
    int             write_dts;
66
} mkv_track;
67

    
68
#define MODE_MATROSKAv2 0x01
69
#define MODE_WEBM       0x02
70

    
71
typedef struct MatroskaMuxContext {
72
    int             mode;
73
    ByteIOContext   *dyn_bc;
74
    ebml_master     segment;
75
    int64_t         segment_offset;
76
    int64_t         segment_uid;
77
    ebml_master     cluster;
78
    int64_t         cluster_pos;        ///< file offset of the current cluster
79
    int64_t         cluster_pts;
80
    int64_t         duration_offset;
81
    int64_t         duration;
82
    mkv_seekhead    *main_seekhead;
83
    mkv_seekhead    *cluster_seekhead;
84
    mkv_cues        *cues;
85
    mkv_track       *tracks;
86

    
87
    struct AVMD5    *md5_ctx;
88
    unsigned int    audio_buffer_size;
89
    AVPacket        cur_audio_pkt;
90
} MatroskaMuxContext;
91

    
92

    
93
/** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
94
 * offset, 4 bytes for target EBML ID */
95
#define MAX_SEEKENTRY_SIZE 21
96

    
97
/** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
98
 * 8-byte uint max */
99
#define MAX_CUETRACKPOS_SIZE 22
100

    
101
/** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
102
#define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
103

    
104

    
105
static int ebml_id_size(unsigned int id)
106
{
107
    return (av_log2(id+1)-1)/7+1;
108
}
109

    
110
static void put_ebml_id(ByteIOContext *pb, unsigned int id)
111
{
112
    int i = ebml_id_size(id);
113
    while (i--)
114
        put_byte(pb, id >> (i*8));
115
}
116

    
117
/**
118
 * Write an EBML size meaning "unknown size".
119
 *
120
 * @param bytes The number of bytes the size should occupy (maximum: 8).
121
 */
122
static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
123
{
124
    assert(bytes <= 8);
125
    put_byte(pb, 0x1ff >> bytes);
126
    while (--bytes)
127
        put_byte(pb, 0xff);
128
}
129

    
130
/**
131
 * Calculate how many bytes are needed to represent a given number in EBML.
132
 */
133
static int ebml_num_size(uint64_t num)
134
{
135
    int bytes = 1;
136
    while ((num+1) >> bytes*7) bytes++;
137
    return bytes;
138
}
139

    
140
/**
141
 * Write a number in EBML variable length format.
142
 *
143
 * @param bytes The number of bytes that need to be used to write the number.
144
 *              If zero, any number of bytes can be used.
145
 */
146
static void put_ebml_num(ByteIOContext *pb, uint64_t num, int bytes)
147
{
148
    int i, needed_bytes = ebml_num_size(num);
149

    
150
    // sizes larger than this are currently undefined in EBML
151
    assert(num < (1ULL<<56)-1);
152

    
153
    if (bytes == 0)
154
        // don't care how many bytes are used, so use the min
155
        bytes = needed_bytes;
156
    // the bytes needed to write the given size would exceed the bytes
157
    // that we need to use, so write unknown size. This shouldn't happen.
158
    assert(bytes >= needed_bytes);
159

    
160
    num |= 1ULL << bytes*7;
161
    for (i = bytes - 1; i >= 0; i--)
162
        put_byte(pb, num >> i*8);
163
}
164

    
165
static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
166
{
167
    int i, bytes = 1;
168
    uint64_t tmp = val;
169
    while (tmp>>=8) bytes++;
170

    
171
    put_ebml_id(pb, elementid);
172
    put_ebml_num(pb, bytes, 0);
173
    for (i = bytes - 1; i >= 0; i--)
174
        put_byte(pb, val >> i*8);
175
}
176

    
177
static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
178
{
179
    put_ebml_id(pb, elementid);
180
    put_ebml_num(pb, 8, 0);
181
    put_be64(pb, av_dbl2int(val));
182
}
183

    
184
static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
185
                            const uint8_t *buf, int size)
186
{
187
    put_ebml_id(pb, elementid);
188
    put_ebml_num(pb, size, 0);
189
    put_buffer(pb, buf, size);
190
}
191

    
192
static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
193
{
194
    put_ebml_binary(pb, elementid, str, strlen(str));
195
}
196

    
197
/**
198
 * Writes a void element of a given size. Useful for reserving space in
199
 * the file to be written to later.
200
 *
201
 * @param size The number of bytes to reserve, which must be at least 2.
202
 */
203
static void put_ebml_void(ByteIOContext *pb, uint64_t size)
204
{
205
    int64_t currentpos = url_ftell(pb);
206

    
207
    assert(size >= 2);
208

    
209
    put_ebml_id(pb, EBML_ID_VOID);
210
    // we need to subtract the length needed to store the size from the
211
    // size we need to reserve so 2 cases, we use 8 bytes to store the
212
    // size if possible, 1 byte otherwise
213
    if (size < 10)
214
        put_ebml_num(pb, size-1, 0);
215
    else
216
        put_ebml_num(pb, size-9, 8);
217
    while(url_ftell(pb) < currentpos + size)
218
        put_byte(pb, 0);
219
}
220

    
221
static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
222
{
223
    int bytes = expectedsize ? ebml_num_size(expectedsize) : 8;
224
    put_ebml_id(pb, elementid);
225
    put_ebml_size_unknown(pb, bytes);
226
    return (ebml_master){ url_ftell(pb), bytes };
227
}
228

    
229
static void end_ebml_master(ByteIOContext *pb, ebml_master master)
230
{
231
    int64_t pos = url_ftell(pb);
232

    
233
    if (url_fseek(pb, master.pos - master.sizebytes, SEEK_SET) < 0)
234
        return;
235
    put_ebml_num(pb, pos - master.pos, master.sizebytes);
236
    url_fseek(pb, pos, SEEK_SET);
237
}
238

    
239
static void put_xiph_size(ByteIOContext *pb, int size)
240
{
241
    int i;
242
    for (i = 0; i < size / 255; i++)
243
        put_byte(pb, 255);
244
    put_byte(pb, size % 255);
245
}
246

    
247
/**
248
 * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
249
 * elements. If a maximum number of elements is specified, enough space
250
 * will be reserved at the current file location to write a seek head of
251
 * that size.
252
 *
253
 * @param segment_offset The absolute offset to the position in the file
254
 *                       where the segment begins.
255
 * @param numelements The maximum number of elements that will be indexed
256
 *                    by this seek head, 0 if unlimited.
257
 */
258
static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, int64_t segment_offset, int numelements)
259
{
260
    mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
261
    if (new_seekhead == NULL)
262
        return NULL;
263

    
264
    new_seekhead->segment_offset = segment_offset;
265

    
266
    if (numelements > 0) {
267
        new_seekhead->filepos = url_ftell(pb);
268
        // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
269
        // and size, and 3 bytes to guarantee that an EBML void element
270
        // will fit afterwards
271
        new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
272
        new_seekhead->max_entries = numelements;
273
        put_ebml_void(pb, new_seekhead->reserved_size);
274
    }
275
    return new_seekhead;
276
}
277

    
278
static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
279
{
280
    mkv_seekhead_entry *entries = seekhead->entries;
281

    
282
    // don't store more elements than we reserved space for
283
    if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
284
        return -1;
285

    
286
    entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
287
    if (entries == NULL)
288
        return AVERROR(ENOMEM);
289

    
290
    entries[seekhead->num_entries  ].elementid = elementid;
291
    entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
292

    
293
    seekhead->entries = entries;
294
    return 0;
295
}
296

    
297
/**
298
 * Write the seek head to the file and free it. If a maximum number of
299
 * elements was specified to mkv_start_seekhead(), the seek head will
300
 * be written at the location reserved for it. Otherwise, it is written
301
 * at the current location in the file.
302
 *
303
 * @return The file offset where the seekhead was written,
304
 * -1 if an error occurred.
305
 */
306
static int64_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
307
{
308
    ebml_master metaseek, seekentry;
309
    int64_t currentpos;
310
    int i;
311

    
312
    currentpos = url_ftell(pb);
313

    
314
    if (seekhead->reserved_size > 0)
315
        if (url_fseek(pb, seekhead->filepos, SEEK_SET) < 0)
316
            return -1;
317

    
318
    metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
319
    for (i = 0; i < seekhead->num_entries; i++) {
320
        mkv_seekhead_entry *entry = &seekhead->entries[i];
321

    
322
        seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
323

    
324
        put_ebml_id(pb, MATROSKA_ID_SEEKID);
325
        put_ebml_num(pb, ebml_id_size(entry->elementid), 0);
326
        put_ebml_id(pb, entry->elementid);
327

    
328
        put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
329
        end_ebml_master(pb, seekentry);
330
    }
331
    end_ebml_master(pb, metaseek);
332

    
333
    if (seekhead->reserved_size > 0) {
334
        uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
335
        put_ebml_void(pb, remaining);
336
        url_fseek(pb, currentpos, SEEK_SET);
337

    
338
        currentpos = seekhead->filepos;
339
    }
340
    av_free(seekhead->entries);
341
    av_free(seekhead);
342

    
343
    return currentpos;
344
}
345

    
346
static mkv_cues * mkv_start_cues(int64_t segment_offset)
347
{
348
    mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
349
    if (cues == NULL)
350
        return NULL;
351

    
352
    cues->segment_offset = segment_offset;
353
    return cues;
354
}
355

    
356
static int mkv_add_cuepoint(mkv_cues *cues, int stream, int64_t ts, int64_t cluster_pos)
357
{
358
    mkv_cuepoint *entries = cues->entries;
359

    
360
    entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
361
    if (entries == NULL)
362
        return AVERROR(ENOMEM);
363

    
364
    if (ts < 0)
365
        return 0;
366

    
367
    entries[cues->num_entries  ].pts = ts;
368
    entries[cues->num_entries  ].tracknum = stream + 1;
369
    entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
370

    
371
    cues->entries = entries;
372
    return 0;
373
}
374

    
375
static int64_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
376
{
377
    ebml_master cues_element;
378
    int64_t currentpos;
379
    int i, j;
380

    
381
    currentpos = url_ftell(pb);
382
    cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
383

    
384
    for (i = 0; i < cues->num_entries; i++) {
385
        ebml_master cuepoint, track_positions;
386
        mkv_cuepoint *entry = &cues->entries[i];
387
        uint64_t pts = entry->pts;
388

    
389
        cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
390
        put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
391

    
392
        // put all the entries from different tracks that have the exact same
393
        // timestamp into the same CuePoint
394
        for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
395
            track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
396
            put_ebml_uint(pb, MATROSKA_ID_CUETRACK          , entry[j].tracknum   );
397
            put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
398
            end_ebml_master(pb, track_positions);
399
        }
400
        i += j - 1;
401
        end_ebml_master(pb, cuepoint);
402
    }
403
    end_ebml_master(pb, cues_element);
404

    
405
    av_free(cues->entries);
406
    av_free(cues);
407
    return currentpos;
408
}
409

    
410
static int put_xiph_codecpriv(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec)
411
{
412
    uint8_t *header_start[3];
413
    int header_len[3];
414
    int first_header_size;
415
    int j;
416

    
417
    if (codec->codec_id == CODEC_ID_VORBIS)
418
        first_header_size = 30;
419
    else
420
        first_header_size = 42;
421

    
422
    if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
423
                              first_header_size, header_start, header_len) < 0) {
424
        av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
425
        return -1;
426
    }
427

    
428
    put_byte(pb, 2);                    // number packets - 1
429
    for (j = 0; j < 2; j++) {
430
        put_xiph_size(pb, header_len[j]);
431
    }
432
    for (j = 0; j < 3; j++)
433
        put_buffer(pb, header_start[j], header_len[j]);
434

    
435
    return 0;
436
}
437

    
438
static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
439
{
440
    int sri;
441

    
442
    if (codec->extradata_size < 2) {
443
        av_log(s, AV_LOG_WARNING, "No AAC extradata, unable to determine samplerate.\n");
444
        return;
445
    }
446

    
447
    sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
448
    if (sri > 12) {
449
        av_log(s, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
450
        return;
451
    }
452
    *sample_rate = ff_mpeg4audio_sample_rates[sri];
453

    
454
    // if sbr, get output sample rate as well
455
    if (codec->extradata_size == 5) {
456
        sri = (codec->extradata[4] >> 3) & 0xF;
457
        if (sri > 12) {
458
            av_log(s, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
459
            return;
460
        }
461
        *output_sample_rate = ff_mpeg4audio_sample_rates[sri];
462
    }
463
}
464

    
465
static int mkv_write_codecprivate(AVFormatContext *s, ByteIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
466
{
467
    ByteIOContext *dyn_cp;
468
    uint8_t *codecpriv;
469
    int ret, codecpriv_size;
470

    
471
    ret = url_open_dyn_buf(&dyn_cp);
472
    if(ret < 0)
473
        return ret;
474

    
475
    if (native_id) {
476
        if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
477
            ret = put_xiph_codecpriv(s, dyn_cp, codec);
478
        else if (codec->codec_id == CODEC_ID_FLAC)
479
            ret = ff_flac_write_header(dyn_cp, codec, 1);
480
        else if (codec->codec_id == CODEC_ID_H264)
481
            ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
482
        else if (codec->extradata_size)
483
            put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
484
    } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
485
        if (qt_id) {
486
            if (!codec->codec_tag)
487
                codec->codec_tag = ff_codec_get_tag(codec_movvideo_tags, codec->codec_id);
488
            if (codec->extradata_size)
489
                put_buffer(dyn_cp, codec->extradata, codec->extradata_size);
490
        } else {
491
            if (!codec->codec_tag)
492
                codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
493
            if (!codec->codec_tag) {
494
                av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
495
                ret = -1;
496
            }
497

    
498
            ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
499
        }
500

    
501
    } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
502
        unsigned int tag;
503
        tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
504
        if (!tag) {
505
            av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
506
            ret = -1;
507
        }
508
        if (!codec->codec_tag)
509
            codec->codec_tag = tag;
510

    
511
        ff_put_wav_header(dyn_cp, codec);
512
    }
513

    
514
    codecpriv_size = url_close_dyn_buf(dyn_cp, &codecpriv);
515
    if (codecpriv_size)
516
        put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
517
    av_free(codecpriv);
518
    return ret;
519
}
520

    
521
static int mkv_write_tracks(AVFormatContext *s)
522
{
523
    MatroskaMuxContext *mkv = s->priv_data;
524
    ByteIOContext *pb = s->pb;
525
    ebml_master tracks;
526
    int i, j, ret;
527

    
528
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb));
529
    if (ret < 0) return ret;
530

    
531
    tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
532
    for (i = 0; i < s->nb_streams; i++) {
533
        AVStream *st = s->streams[i];
534
        AVCodecContext *codec = st->codec;
535
        ebml_master subinfo, track;
536
        int native_id = 0;
537
        int qt_id = 0;
538
        int bit_depth = av_get_bits_per_sample(codec->codec_id);
539
        int sample_rate = codec->sample_rate;
540
        int output_sample_rate = 0;
541
        AVMetadataTag *tag;
542

    
543
        if (!bit_depth)
544
            bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
545

    
546
        if (codec->codec_id == CODEC_ID_AAC)
547
            get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
548

    
549
        track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
550
        put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);
551
        put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);
552
        put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
553

    
554
        if ((tag = av_metadata_get(st->metadata, "title", NULL, 0)))
555
            put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
556
        tag = av_metadata_get(st->metadata, "language", NULL, 0);
557
        put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
558

    
559
        if (st->disposition)
560
            put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
561

    
562
        // look for a codec ID string specific to mkv to use,
563
        // if none are found, use AVI codes
564
        for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
565
            if (ff_mkv_codec_tags[j].id == codec->codec_id) {
566
                put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
567
                native_id = 1;
568
                break;
569
            }
570
        }
571

    
572
        if (mkv->mode == MODE_WEBM && !(codec->codec_id == CODEC_ID_VP8 ||
573
                                        codec->codec_id == CODEC_ID_VORBIS)) {
574
            av_log(s, AV_LOG_ERROR,
575
                   "Only VP8 video and Vorbis audio are supported for WebM.\n");
576
            return AVERROR(EINVAL);
577
        }
578

    
579
        switch (codec->codec_type) {
580
            case AVMEDIA_TYPE_VIDEO:
581
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
582
                put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
583

    
584
                if (!native_id &&
585
                      ff_codec_get_tag(codec_movvideo_tags, codec->codec_id) &&
586
                    (!ff_codec_get_tag(ff_codec_bmp_tags,   codec->codec_id)
587
                     || codec->codec_id == CODEC_ID_SVQ1
588
                     || codec->codec_id == CODEC_ID_SVQ3
589
                     || codec->codec_id == CODEC_ID_CINEPAK))
590
                    qt_id = 1;
591

    
592
                if (qt_id)
593
                    put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
594
                else if (!native_id) {
595
                    // if there is no mkv-specific codec ID, use VFW mode
596
                    put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
597
                    mkv->tracks[i].write_dts = 1;
598
                }
599

    
600
                subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
601
                // XXX: interlace flag?
602
                put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
603
                put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
604
                if (st->sample_aspect_ratio.num) {
605
                    int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
606
                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
607
                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
608
                }
609
                end_ebml_master(pb, subinfo);
610
                break;
611

    
612
            case AVMEDIA_TYPE_AUDIO:
613
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
614

    
615
                if (!native_id)
616
                    // no mkv-specific ID, use ACM mode
617
                    put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
618

    
619
                subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
620
                put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);
621
                put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
622
                if (output_sample_rate)
623
                    put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
624
                if (bit_depth)
625
                    put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
626
                end_ebml_master(pb, subinfo);
627
                break;
628

    
629
            case AVMEDIA_TYPE_SUBTITLE:
630
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
631
                break;
632
            default:
633
                av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.");
634
                break;
635
        }
636
        ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
637
        if (ret < 0) return ret;
638

    
639
        end_ebml_master(pb, track);
640

    
641
        // ms precision is the de-facto standard timescale for mkv files
642
        av_set_pts_info(st, 64, 1, 1000);
643
    }
644
    end_ebml_master(pb, tracks);
645
    return 0;
646
}
647

    
648
static int mkv_write_chapters(AVFormatContext *s)
649
{
650
    MatroskaMuxContext *mkv = s->priv_data;
651
    ByteIOContext *pb = s->pb;
652
    ebml_master chapters, editionentry;
653
    AVRational scale = {1, 1E9};
654
    int i, ret;
655

    
656
    if (!s->nb_chapters)
657
        return 0;
658

    
659
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, url_ftell(pb));
660
    if (ret < 0) return ret;
661

    
662
    chapters     = start_ebml_master(pb, MATROSKA_ID_CHAPTERS    , 0);
663
    editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
664
    put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
665
    put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
666
    for (i = 0; i < s->nb_chapters; i++) {
667
        ebml_master chapteratom, chapterdisplay;
668
        AVChapter *c     = s->chapters[i];
669
        AVMetadataTag *t = NULL;
670

    
671
        chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
672
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
673
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
674
                      av_rescale_q(c->start, c->time_base, scale));
675
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
676
                      av_rescale_q(c->end,   c->time_base, scale));
677
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
678
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
679
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
680
            chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
681
            put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
682
            put_ebml_string(pb, MATROSKA_ID_CHAPLANG  , "und");
683
            end_ebml_master(pb, chapterdisplay);
684
        }
685
        end_ebml_master(pb, chapteratom);
686
    }
687
    end_ebml_master(pb, editionentry);
688
    end_ebml_master(pb, chapters);
689
    return 0;
690
}
691

    
692
static int mkv_write_header(AVFormatContext *s)
693
{
694
    MatroskaMuxContext *mkv = s->priv_data;
695
    ByteIOContext *pb = s->pb;
696
    ebml_master ebml_header, segment_info;
697
    AVMetadataTag *tag;
698
    int ret;
699

    
700
    if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
701
    else                                   mkv->mode = MODE_MATROSKAv2;
702

    
703
    mkv->md5_ctx = av_mallocz(av_md5_size);
704
    av_md5_init(mkv->md5_ctx);
705
    mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
706

    
707
    ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
708
    put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
709
    put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
710
    put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
711
    put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
712
    put_ebml_string (pb, EBML_ID_DOCTYPE            , s->oformat->name);
713
    put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
714
    put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
715
    end_ebml_master(pb, ebml_header);
716

    
717
    mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
718
    mkv->segment_offset = url_ftell(pb);
719

    
720
    // we write 2 seek heads - one at the end of the file to point to each
721
    // cluster, and one at the beginning to point to all other level one
722
    // elements (including the seek head at the end of the file), which
723
    // isn't more than 10 elements if we only write one of each other
724
    // currently defined level 1 element
725
    mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
726
    mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
727
    if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
728
        return AVERROR(ENOMEM);
729

    
730
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
731
    if (ret < 0) return ret;
732

    
733
    segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
734
    put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
735
    if ((tag = av_metadata_get(s->metadata, "title", NULL, 0)))
736
        put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
737
    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
738
        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
739
        put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
740

    
741
        // reserve space to write the segment UID later
742
        mkv->segment_uid = url_ftell(pb);
743
        put_ebml_void(pb, 19);
744
    }
745

    
746
    // reserve space for the duration
747
    mkv->duration = 0;
748
    mkv->duration_offset = url_ftell(pb);
749
    put_ebml_void(pb, 11);                  // assumes double-precision float to be written
750
    end_ebml_master(pb, segment_info);
751

    
752
    ret = mkv_write_tracks(s);
753
    if (ret < 0) return ret;
754

    
755
    if (mkv->mode != MODE_WEBM) {
756
        ret = mkv_write_chapters(s);
757
        if (ret < 0) return ret;
758
    }
759

    
760
    if (url_is_streamed(s->pb))
761
        mkv_write_seekhead(pb, mkv->main_seekhead);
762

    
763
    mkv->cues = mkv_start_cues(mkv->segment_offset);
764
    if (mkv->cues == NULL)
765
        return AVERROR(ENOMEM);
766

    
767
    av_init_packet(&mkv->cur_audio_pkt);
768
    mkv->cur_audio_pkt.size = 0;
769
    mkv->audio_buffer_size  = 0;
770

    
771
    put_flush_packet(pb);
772
    return 0;
773
}
774

    
775
static int mkv_blockgroup_size(int pkt_size)
776
{
777
    int size = pkt_size + 4;
778
    size += ebml_num_size(size);
779
    size += 2;              // EBML ID for block and block duration
780
    size += 8;              // max size of block duration
781
    size += ebml_num_size(size);
782
    size += 1;              // blockgroup EBML ID
783
    return size;
784
}
785

    
786
static int ass_get_duration(const uint8_t *p)
787
{
788
    int sh, sm, ss, sc, eh, em, es, ec;
789
    uint64_t start, end;
790

    
791
    if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
792
               &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
793
        return 0;
794
    start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
795
    end   = 3600000*eh + 60000*em + 1000*es + 10*ec;
796
    return end - start;
797
}
798

    
799
static int mkv_write_ass_blocks(AVFormatContext *s, ByteIOContext *pb, AVPacket *pkt)
800
{
801
    MatroskaMuxContext *mkv = s->priv_data;
802
    int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
803
    uint8_t *start, *end, *data = pkt->data;
804
    ebml_master blockgroup;
805
    char buffer[2048];
806

    
807
    while (data_size) {
808
        int duration = ass_get_duration(data);
809
        max_duration = FFMAX(duration, max_duration);
810
        end = memchr(data, '\n', data_size);
811
        size = line_size = end ? end-data+1 : data_size;
812
        size -= end ? (end[-1]=='\r')+1 : 0;
813
        start = data;
814
        for (i=0; i<3; i++, start++)
815
            if (!(start = memchr(start, ',', size-(start-data))))
816
                return max_duration;
817
        size -= start - data;
818
        sscanf(data, "Dialogue: %d,", &layer);
819
        i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
820
                     s->streams[pkt->stream_index]->nb_frames++, layer);
821
        size = FFMIN(i+size, sizeof(buffer));
822
        memcpy(buffer+i, start, size-i);
823

    
824
        av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
825
               "pts %" PRId64 ", duration %d\n",
826
               url_ftell(pb), size, pkt->pts, duration);
827
        blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
828
        put_ebml_id(pb, MATROSKA_ID_BLOCK);
829
        put_ebml_num(pb, size+4, 0);
830
        put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
831
        put_be16(pb, pkt->pts - mkv->cluster_pts);
832
        put_byte(pb, 0);
833
        put_buffer(pb, buffer, size);
834
        put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
835
        end_ebml_master(pb, blockgroup);
836

    
837
        data += line_size;
838
        data_size -= line_size;
839
    }
840

    
841
    return max_duration;
842
}
843

    
844
static void mkv_write_block(AVFormatContext *s, ByteIOContext *pb,
845
                            unsigned int blockid, AVPacket *pkt, int flags)
846
{
847
    MatroskaMuxContext *mkv = s->priv_data;
848
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
849
    uint8_t *data = NULL;
850
    int size = pkt->size;
851
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
852

    
853
    av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
854
           "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
855
           url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
856
    if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
857
        (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
858
        ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
859
    else
860
        data = pkt->data;
861
    put_ebml_id(pb, blockid);
862
    put_ebml_num(pb, size+4, 0);
863
    put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
864
    put_be16(pb, ts - mkv->cluster_pts);
865
    put_byte(pb, flags);
866
    put_buffer(pb, data, size);
867
    if (data != pkt->data)
868
        av_free(data);
869
}
870

    
871
static void mkv_flush_dynbuf(AVFormatContext *s)
872
{
873
    MatroskaMuxContext *mkv = s->priv_data;
874
    int bufsize;
875
    uint8_t *dyn_buf;
876

    
877
    if (!mkv->dyn_bc)
878
        return;
879

    
880
    bufsize = url_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
881
    put_buffer(s->pb, dyn_buf, bufsize);
882
    av_free(dyn_buf);
883
    mkv->dyn_bc = NULL;
884
}
885

    
886
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
887
{
888
    MatroskaMuxContext *mkv = s->priv_data;
889
    ByteIOContext *pb = s->pb;
890
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
891
    int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
892
    int duration = pkt->duration;
893
    int ret;
894
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
895

    
896
    if (ts == AV_NOPTS_VALUE) {
897
        av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
898
        return AVERROR(EINVAL);
899
    }
900

    
901
    if (url_is_streamed(s->pb)) {
902
        if (!mkv->dyn_bc)
903
            url_open_dyn_buf(&mkv->dyn_bc);
904
        pb = mkv->dyn_bc;
905
    }
906

    
907
    if (!mkv->cluster_pos) {
908
        ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
909
        if (ret < 0) return ret;
910

    
911
        mkv->cluster_pos = url_ftell(s->pb);
912
        mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
913
        put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
914
        mkv->cluster_pts = FFMAX(0, ts);
915
        av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
916
    }
917

    
918
    if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
919
        mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
920
    } else if (codec->codec_id == CODEC_ID_SSA) {
921
        duration = mkv_write_ass_blocks(s, pb, pkt);
922
    } else {
923
        ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
924
        duration = pkt->convergence_duration;
925
        mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
926
        put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
927
        end_ebml_master(pb, blockgroup);
928
    }
929

    
930
    if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
931
        ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
932
        if (ret < 0) return ret;
933
    }
934

    
935
    mkv->duration = FFMAX(mkv->duration, ts + duration);
936
    return 0;
937
}
938

    
939
static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
940
{
941
    uint8_t *data           = mkv->cur_audio_pkt.data;
942
    mkv->cur_audio_pkt      = *pkt;
943
    mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
944
    if (!mkv->cur_audio_pkt.data)
945
        return AVERROR(ENOMEM);
946

    
947
    memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
948
    mkv->cur_audio_pkt.size = pkt->size;
949
    return 0;
950
}
951

    
952
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
953
{
954
    MatroskaMuxContext *mkv = s->priv_data;
955
    ByteIOContext *pb = url_is_streamed(s->pb) ? mkv->dyn_bc : s->pb;
956
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
957
    int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
958
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
959
    int cluster_size = url_ftell(pb) - (url_is_streamed(s->pb) ? 0 : mkv->cluster_pos);
960

    
961
    // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
962
    // after 4k and on a keyframe
963
    if (mkv->cluster_pos &&
964
        ((url_is_streamed(s->pb) && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
965
         ||                      cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
966
         || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
967
        av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
968
               " bytes, pts %" PRIu64 "\n", url_ftell(pb), ts);
969
        end_ebml_master(pb, mkv->cluster);
970
        mkv->cluster_pos = 0;
971
        if (mkv->dyn_bc)
972
            mkv_flush_dynbuf(s);
973
    }
974

    
975
    // check if we have an audio packet cached
976
    if (mkv->cur_audio_pkt.size > 0) {
977
        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
978
        mkv->cur_audio_pkt.size = 0;
979
        if (ret < 0) {
980
            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
981
            return ret;
982
        }
983
    }
984

    
985
    // buffer an audio packet to ensure the packet containing the video
986
    // keyframe's timecode is contained in the same cluster for WebM
987
    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
988
        ret = mkv_copy_packet(mkv, pkt);
989
    else
990
        ret = mkv_write_packet_internal(s, pkt);
991
    return ret;
992
}
993

    
994
static int mkv_write_trailer(AVFormatContext *s)
995
{
996
    MatroskaMuxContext *mkv = s->priv_data;
997
    ByteIOContext *pb = s->pb;
998
    int64_t currentpos, second_seekhead, cuespos;
999
    int ret;
1000

    
1001
    // check if we have an audio packet cached
1002
    if (mkv->cur_audio_pkt.size > 0) {
1003
        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1004
        mkv->cur_audio_pkt.size = 0;
1005
        if (ret < 0) {
1006
            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1007
            return ret;
1008
        }
1009
    }
1010

    
1011
    if (mkv->dyn_bc) {
1012
        end_ebml_master(mkv->dyn_bc, mkv->cluster);
1013
        mkv_flush_dynbuf(s);
1014
    } else if (mkv->cluster_pos) {
1015
        end_ebml_master(pb, mkv->cluster);
1016
    }
1017

    
1018
    if (!url_is_streamed(pb)) {
1019
        cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1020
        second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
1021

    
1022
        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES    , cuespos);
1023
        if (ret < 0) return ret;
1024
        if (second_seekhead >= 0) {
1025
            ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
1026
            if (ret < 0) return ret;
1027
        }
1028
        mkv_write_seekhead(pb, mkv->main_seekhead);
1029

    
1030
        // update the duration
1031
        av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1032
        currentpos = url_ftell(pb);
1033
        url_fseek(pb, mkv->duration_offset, SEEK_SET);
1034
        put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1035

    
1036
        // write the md5sum of some frames as the segment UID
1037
        if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
1038
            uint8_t segment_uid[16];
1039
            av_md5_final(mkv->md5_ctx, segment_uid);
1040
            url_fseek(pb, mkv->segment_uid, SEEK_SET);
1041
            put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
1042
        }
1043
        url_fseek(pb, currentpos, SEEK_SET);
1044
    }
1045

    
1046
    end_ebml_master(pb, mkv->segment);
1047
    av_free(mkv->md5_ctx);
1048
    av_free(mkv->tracks);
1049
    av_destruct_packet(&mkv->cur_audio_pkt);
1050
    put_flush_packet(pb);
1051
    return 0;
1052
}
1053

    
1054
#if CONFIG_MATROSKA_MUXER
1055
AVOutputFormat matroska_muxer = {
1056
    "matroska",
1057
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1058
    "video/x-matroska",
1059
    "mkv",
1060
    sizeof(MatroskaMuxContext),
1061
    CODEC_ID_MP2,
1062
    CODEC_ID_MPEG4,
1063
    mkv_write_header,
1064
    mkv_write_packet,
1065
    mkv_write_trailer,
1066
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1067
    .codec_tag = (const AVCodecTag* const []){ff_codec_bmp_tags, ff_codec_wav_tags, 0},
1068
    .subtitle_codec = CODEC_ID_TEXT,
1069
};
1070
#endif
1071

    
1072
#if CONFIG_WEBM_MUXER
1073
AVOutputFormat webm_muxer = {
1074
    "webm",
1075
    NULL_IF_CONFIG_SMALL("WebM file format"),
1076
    "video/webm",
1077
    "webm",
1078
    sizeof(MatroskaMuxContext),
1079
    CODEC_ID_VORBIS,
1080
    CODEC_ID_VP8,
1081
    mkv_write_header,
1082
    mkv_write_packet,
1083
    mkv_write_trailer,
1084
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1085
};
1086
#endif
1087

    
1088
#if CONFIG_MATROSKA_AUDIO_MUXER
1089
AVOutputFormat matroska_audio_muxer = {
1090
    "matroska",
1091
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1092
    "audio/x-matroska",
1093
    "mka",
1094
    sizeof(MatroskaMuxContext),
1095
    CODEC_ID_MP2,
1096
    CODEC_ID_NONE,
1097
    mkv_write_header,
1098
    mkv_write_packet,
1099
    mkv_write_trailer,
1100
    .flags = AVFMT_GLOBALHEADER,
1101
    .codec_tag = (const AVCodecTag* const []){ff_codec_wav_tags, 0},
1102
};
1103
#endif