Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskaenc.c @ 91819763

History | View | Annotate | Download (40.5 KB)

1
/*
2
 * Matroska muxer
3
 * Copyright (c) 2007 David Conrad
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav 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
 * Libav 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 Libav; 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 "avlanguage.h"
29
#include "libavutil/samplefmt.h"
30
#include "libavutil/intreadwrite.h"
31
#include "libavutil/random_seed.h"
32
#include "libavutil/lfg.h"
33
#include "libavcodec/xiph.h"
34
#include "libavcodec/mpeg4audio.h"
35
#include <strings.h>
36

    
37
typedef struct ebml_master {
38
    int64_t         pos;                ///< absolute offset in the file where the master's elements start
39
    int             sizebytes;          ///< how many bytes were reserved for the size
40
} ebml_master;
41

    
42
typedef struct mkv_seekhead_entry {
43
    unsigned int    elementid;
44
    uint64_t        segmentpos;
45
} mkv_seekhead_entry;
46

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

    
56
typedef struct {
57
    uint64_t        pts;
58
    int             tracknum;
59
    int64_t         cluster_pos;        ///< file offset of the cluster containing the block
60
} mkv_cuepoint;
61

    
62
typedef struct {
63
    int64_t         segment_offset;
64
    mkv_cuepoint    *entries;
65
    int             num_entries;
66
} mkv_cues;
67

    
68
typedef struct {
69
    int             write_dts;
70
} mkv_track;
71

    
72
#define MODE_MATROSKAv2 0x01
73
#define MODE_WEBM       0x02
74

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

    
89
    unsigned int    audio_buffer_size;
90
    AVPacket        cur_audio_pkt;
91
} MatroskaMuxContext;
92

    
93

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

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

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

    
105

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

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

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

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

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

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

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

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

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

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

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

    
185
static void put_ebml_binary(AVIOContext *pb, unsigned int elementid,
186
                            const void *buf, int size)
187
{
188
    put_ebml_id(pb, elementid);
189
    put_ebml_num(pb, size, 0);
190
    avio_write(pb, buf, size);
191
}
192

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

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

    
208
    assert(size >= 2);
209

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

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

    
230
static void end_ebml_master(AVIOContext *pb, ebml_master master)
231
{
232
    int64_t pos = avio_tell(pb);
233

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

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

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

    
265
    new_seekhead->segment_offset = segment_offset;
266

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

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

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

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

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

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

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

    
313
    currentpos = avio_tell(pb);
314

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

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

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

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

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

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

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

    
344
    return currentpos;
345
}
346

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

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

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

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

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

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

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

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

    
382
    currentpos = avio_tell(pb);
383
    cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
384

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

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

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

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

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

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

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

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

    
436
    return 0;
437
}
438

    
439
static void get_aac_sample_rates(AVFormatContext *s, AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
440
{
441
    MPEG4AudioConfig mp4ac;
442

    
443
    if (ff_mpeg4audio_get_config(&mp4ac, codec->extradata, codec->extradata_size) < 0) {
444
        av_log(s, AV_LOG_WARNING, "Error parsing AAC extradata, unable to determine samplerate.\n");
445
        return;
446
    }
447

    
448
    *sample_rate        = mp4ac.sample_rate;
449
    *output_sample_rate = mp4ac.ext_sample_rate;
450
}
451

    
452
static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb, AVCodecContext *codec, int native_id, int qt_id)
453
{
454
    AVIOContext *dyn_cp;
455
    uint8_t *codecpriv;
456
    int ret, codecpriv_size;
457

    
458
    ret = avio_open_dyn_buf(&dyn_cp);
459
    if(ret < 0)
460
        return ret;
461

    
462
    if (native_id) {
463
        if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA)
464
            ret = put_xiph_codecpriv(s, dyn_cp, codec);
465
        else if (codec->codec_id == CODEC_ID_FLAC)
466
            ret = ff_flac_write_header(dyn_cp, codec, 1);
467
        else if (codec->codec_id == CODEC_ID_H264)
468
            ret = ff_isom_write_avcc(dyn_cp, codec->extradata, codec->extradata_size);
469
        else if (codec->extradata_size)
470
            avio_write(dyn_cp, codec->extradata, codec->extradata_size);
471
    } else if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
472
        if (qt_id) {
473
            if (!codec->codec_tag)
474
                codec->codec_tag = ff_codec_get_tag(codec_movvideo_tags, codec->codec_id);
475
            if (codec->extradata_size)
476
                avio_write(dyn_cp, codec->extradata, codec->extradata_size);
477
        } else {
478
            if (!codec->codec_tag)
479
                codec->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags, codec->codec_id);
480
            if (!codec->codec_tag) {
481
                av_log(s, AV_LOG_ERROR, "No bmp codec ID found.\n");
482
                ret = -1;
483
            }
484

    
485
            ff_put_bmp_header(dyn_cp, codec, ff_codec_bmp_tags, 0);
486
        }
487

    
488
    } else if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
489
        unsigned int tag;
490
        tag = ff_codec_get_tag(ff_codec_wav_tags, codec->codec_id);
491
        if (!tag) {
492
            av_log(s, AV_LOG_ERROR, "No wav codec ID found.\n");
493
            ret = -1;
494
        }
495
        if (!codec->codec_tag)
496
            codec->codec_tag = tag;
497

    
498
        ff_put_wav_header(dyn_cp, codec);
499
    }
500

    
501
    codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);
502
    if (codecpriv_size)
503
        put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
504
    av_free(codecpriv);
505
    return ret;
506
}
507

    
508
static int mkv_write_tracks(AVFormatContext *s)
509
{
510
    MatroskaMuxContext *mkv = s->priv_data;
511
    AVIOContext *pb = s->pb;
512
    ebml_master tracks;
513
    int i, j, ret;
514

    
515
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));
516
    if (ret < 0) return ret;
517

    
518
    tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
519
    for (i = 0; i < s->nb_streams; i++) {
520
        AVStream *st = s->streams[i];
521
        AVCodecContext *codec = st->codec;
522
        ebml_master subinfo, track;
523
        int native_id = 0;
524
        int qt_id = 0;
525
        int bit_depth = av_get_bits_per_sample(codec->codec_id);
526
        int sample_rate = codec->sample_rate;
527
        int output_sample_rate = 0;
528
        AVMetadataTag *tag;
529

    
530
        if (!bit_depth)
531
            bit_depth = av_get_bits_per_sample_fmt(codec->sample_fmt);
532

    
533
        if (codec->codec_id == CODEC_ID_AAC)
534
            get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);
535

    
536
        track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
537
        put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);
538
        put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);
539
        put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
540

    
541
        if ((tag = av_metadata_get(st->metadata, "title", NULL, 0)))
542
            put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);
543
        tag = av_metadata_get(st->metadata, "language", NULL, 0);
544
        put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");
545

    
546
        if (st->disposition)
547
            put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));
548

    
549
        // look for a codec ID string specific to mkv to use,
550
        // if none are found, use AVI codes
551
        for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
552
            if (ff_mkv_codec_tags[j].id == codec->codec_id) {
553
                put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
554
                native_id = 1;
555
                break;
556
            }
557
        }
558

    
559
        if (mkv->mode == MODE_WEBM && !(codec->codec_id == CODEC_ID_VP8 ||
560
                                        codec->codec_id == CODEC_ID_VORBIS)) {
561
            av_log(s, AV_LOG_ERROR,
562
                   "Only VP8 video and Vorbis audio are supported for WebM.\n");
563
            return AVERROR(EINVAL);
564
        }
565

    
566
        switch (codec->codec_type) {
567
            case AVMEDIA_TYPE_VIDEO:
568
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
569
                put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);
570

    
571
                if (!native_id &&
572
                      ff_codec_get_tag(codec_movvideo_tags, codec->codec_id) &&
573
                    (!ff_codec_get_tag(ff_codec_bmp_tags,   codec->codec_id)
574
                     || codec->codec_id == CODEC_ID_SVQ1
575
                     || codec->codec_id == CODEC_ID_SVQ3
576
                     || codec->codec_id == CODEC_ID_CINEPAK))
577
                    qt_id = 1;
578

    
579
                if (qt_id)
580
                    put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");
581
                else if (!native_id) {
582
                    // if there is no mkv-specific codec ID, use VFW mode
583
                    put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");
584
                    mkv->tracks[i].write_dts = 1;
585
                }
586

    
587
                subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
588
                // XXX: interlace flag?
589
                put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
590
                put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
591
                if (st->sample_aspect_ratio.num) {
592
                    int d_width = codec->width*av_q2d(st->sample_aspect_ratio);
593
                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);
594
                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);
595
                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYUNIT, 3);
596
                }
597
                end_ebml_master(pb, subinfo);
598
                break;
599

    
600
            case AVMEDIA_TYPE_AUDIO:
601
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
602

    
603
                if (!native_id)
604
                    // no mkv-specific ID, use ACM mode
605
                    put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");
606

    
607
                subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
608
                put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);
609
                put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
610
                if (output_sample_rate)
611
                    put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
612
                if (bit_depth)
613
                    put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
614
                end_ebml_master(pb, subinfo);
615
                break;
616

    
617
            case AVMEDIA_TYPE_SUBTITLE:
618
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
619
                break;
620
            default:
621
                av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.");
622
                break;
623
        }
624
        ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);
625
        if (ret < 0) return ret;
626

    
627
        end_ebml_master(pb, track);
628

    
629
        // ms precision is the de-facto standard timescale for mkv files
630
        av_set_pts_info(st, 64, 1, 1000);
631
    }
632
    end_ebml_master(pb, tracks);
633
    return 0;
634
}
635

    
636
static int mkv_write_chapters(AVFormatContext *s)
637
{
638
    MatroskaMuxContext *mkv = s->priv_data;
639
    AVIOContext *pb = s->pb;
640
    ebml_master chapters, editionentry;
641
    AVRational scale = {1, 1E9};
642
    int i, ret;
643

    
644
    if (!s->nb_chapters)
645
        return 0;
646

    
647
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));
648
    if (ret < 0) return ret;
649

    
650
    chapters     = start_ebml_master(pb, MATROSKA_ID_CHAPTERS    , 0);
651
    editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);
652
    put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);
653
    put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);
654
    for (i = 0; i < s->nb_chapters; i++) {
655
        ebml_master chapteratom, chapterdisplay;
656
        AVChapter *c     = s->chapters[i];
657
        AVMetadataTag *t = NULL;
658

    
659
        chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);
660
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);
661
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,
662
                      av_rescale_q(c->start, c->time_base, scale));
663
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,
664
                      av_rescale_q(c->end,   c->time_base, scale));
665
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);
666
        put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);
667
        if ((t = av_metadata_get(c->metadata, "title", NULL, 0))) {
668
            chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);
669
            put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);
670
            put_ebml_string(pb, MATROSKA_ID_CHAPLANG  , "und");
671
            end_ebml_master(pb, chapterdisplay);
672
        }
673
        end_ebml_master(pb, chapteratom);
674
    }
675
    end_ebml_master(pb, editionentry);
676
    end_ebml_master(pb, chapters);
677
    return 0;
678
}
679

    
680
static void mkv_write_simpletag(AVIOContext *pb, AVMetadataTag *t)
681
{
682
    uint8_t *key = av_strdup(t->key);
683
    uint8_t *p   = key;
684
    const uint8_t *lang = NULL;
685
    ebml_master tag;
686

    
687
    if ((p = strrchr(p, '-')) &&
688
        (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
689
        *p = 0;
690

    
691
    p = key;
692
    while (*p) {
693
        if (*p == ' ')
694
            *p = '_';
695
        else if (*p >= 'a' && *p <= 'z')
696
            *p -= 'a' - 'A';
697
        p++;
698
    }
699

    
700
    tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
701
    put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
702
    if (lang)
703
        put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
704
    put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
705
    end_ebml_master(pb, tag);
706

    
707
    av_freep(&key);
708
}
709

    
710
static int mkv_write_tag(AVFormatContext *s, AVMetadata *m, unsigned int elementid,
711
                         unsigned int uid, ebml_master *tags)
712
{
713
    MatroskaMuxContext *mkv = s->priv_data;
714
    ebml_master tag, targets;
715
    AVMetadataTag *t = NULL;
716
    int ret;
717

    
718
    if (!tags->pos) {
719
        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, avio_tell(s->pb));
720
        if (ret < 0) return ret;
721

    
722
        *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
723
    }
724

    
725
    tag     = start_ebml_master(s->pb, MATROSKA_ID_TAG,        0);
726
    targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
727
    if (elementid)
728
        put_ebml_uint(s->pb, elementid, uid);
729
    end_ebml_master(s->pb, targets);
730

    
731
    while ((t = av_metadata_get(m, "", t, AV_METADATA_IGNORE_SUFFIX)))
732
        if (strcasecmp(t->key, "title"))
733
            mkv_write_simpletag(s->pb, t);
734

    
735
    end_ebml_master(s->pb, tag);
736
    return 0;
737
}
738

    
739
static int mkv_write_tags(AVFormatContext *s)
740
{
741
    ebml_master tags = {0};
742
    int i, ret;
743

    
744
    ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
745

    
746
    if (av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX)) {
747
        ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
748
        if (ret < 0) return ret;
749
    }
750

    
751
    for (i = 0; i < s->nb_streams; i++) {
752
        AVStream *st = s->streams[i];
753

    
754
        if (!av_metadata_get(st->metadata, "", 0, AV_METADATA_IGNORE_SUFFIX))
755
            continue;
756

    
757
        ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
758
        if (ret < 0) return ret;
759
    }
760

    
761
    for (i = 0; i < s->nb_chapters; i++) {
762
        AVChapter *ch = s->chapters[i];
763

    
764
        if (!av_metadata_get(ch->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
765
            continue;
766

    
767
        ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
768
        if (ret < 0) return ret;
769
    }
770

    
771
    if (tags.pos)
772
        end_ebml_master(s->pb, tags);
773
    return 0;
774
}
775

    
776
static int mkv_write_header(AVFormatContext *s)
777
{
778
    MatroskaMuxContext *mkv = s->priv_data;
779
    AVIOContext *pb = s->pb;
780
    ebml_master ebml_header, segment_info;
781
    AVMetadataTag *tag;
782
    int ret, i;
783

    
784
    if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
785
    else                                   mkv->mode = MODE_MATROSKAv2;
786

    
787
    mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
788
    if (!mkv->tracks)
789
        return AVERROR(ENOMEM);
790

    
791
    ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
792
    put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
793
    put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
794
    put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
795
    put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
796
    put_ebml_string (pb, EBML_ID_DOCTYPE            , s->oformat->name);
797
    put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
798
    put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
799
    end_ebml_master(pb, ebml_header);
800

    
801
    mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
802
    mkv->segment_offset = avio_tell(pb);
803

    
804
    // we write 2 seek heads - one at the end of the file to point to each
805
    // cluster, and one at the beginning to point to all other level one
806
    // elements (including the seek head at the end of the file), which
807
    // isn't more than 10 elements if we only write one of each other
808
    // currently defined level 1 element
809
    mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
810
    if (!mkv->main_seekhead)
811
        return AVERROR(ENOMEM);
812

    
813
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));
814
    if (ret < 0) return ret;
815

    
816
    segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
817
    put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
818
    if ((tag = av_metadata_get(s->metadata, "title", NULL, 0)))
819
        put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
820
    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
821
        uint32_t segment_uid[4];
822
        AVLFG lfg;
823

    
824
        av_lfg_init(&lfg, av_get_random_seed());
825

    
826
        for (i = 0; i < 4; i++)
827
            segment_uid[i] = av_lfg_get(&lfg);
828

    
829
        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
830
        put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
831
        put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
832
    }
833

    
834
    // reserve space for the duration
835
    mkv->duration = 0;
836
    mkv->duration_offset = avio_tell(pb);
837
    put_ebml_void(pb, 11);                  // assumes double-precision float to be written
838
    end_ebml_master(pb, segment_info);
839

    
840
    ret = mkv_write_tracks(s);
841
    if (ret < 0) return ret;
842

    
843
    if (mkv->mode != MODE_WEBM) {
844
        ret = mkv_write_chapters(s);
845
        if (ret < 0) return ret;
846

    
847
        ret = mkv_write_tags(s);
848
        if (ret < 0) return ret;
849
    }
850

    
851
    if (!s->pb->seekable)
852
        mkv_write_seekhead(pb, mkv->main_seekhead);
853

    
854
    mkv->cues = mkv_start_cues(mkv->segment_offset);
855
    if (mkv->cues == NULL)
856
        return AVERROR(ENOMEM);
857

    
858
    av_init_packet(&mkv->cur_audio_pkt);
859
    mkv->cur_audio_pkt.size = 0;
860
    mkv->audio_buffer_size  = 0;
861

    
862
    avio_flush(pb);
863
    return 0;
864
}
865

    
866
static int mkv_blockgroup_size(int pkt_size)
867
{
868
    int size = pkt_size + 4;
869
    size += ebml_num_size(size);
870
    size += 2;              // EBML ID for block and block duration
871
    size += 8;              // max size of block duration
872
    size += ebml_num_size(size);
873
    size += 1;              // blockgroup EBML ID
874
    return size;
875
}
876

    
877
static int ass_get_duration(const uint8_t *p)
878
{
879
    int sh, sm, ss, sc, eh, em, es, ec;
880
    uint64_t start, end;
881

    
882
    if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
883
               &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
884
        return 0;
885
    start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
886
    end   = 3600000*eh + 60000*em + 1000*es + 10*ec;
887
    return end - start;
888
}
889

    
890
static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
891
{
892
    MatroskaMuxContext *mkv = s->priv_data;
893
    int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
894
    uint8_t *start, *end, *data = pkt->data;
895
    ebml_master blockgroup;
896
    char buffer[2048];
897

    
898
    while (data_size) {
899
        int duration = ass_get_duration(data);
900
        max_duration = FFMAX(duration, max_duration);
901
        end = memchr(data, '\n', data_size);
902
        size = line_size = end ? end-data+1 : data_size;
903
        size -= end ? (end[-1]=='\r')+1 : 0;
904
        start = data;
905
        for (i=0; i<3; i++, start++)
906
            if (!(start = memchr(start, ',', size-(start-data))))
907
                return max_duration;
908
        size -= start - data;
909
        sscanf(data, "Dialogue: %d,", &layer);
910
        i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
911
                     s->streams[pkt->stream_index]->nb_frames++, layer);
912
        size = FFMIN(i+size, sizeof(buffer));
913
        memcpy(buffer+i, start, size-i);
914

    
915
        av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
916
               "pts %" PRId64 ", duration %d\n",
917
               avio_tell(pb), size, pkt->pts, duration);
918
        blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
919
        put_ebml_id(pb, MATROSKA_ID_BLOCK);
920
        put_ebml_num(pb, size+4, 0);
921
        avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
922
        avio_wb16(pb, pkt->pts - mkv->cluster_pts);
923
        avio_w8(pb, 0);
924
        avio_write(pb, buffer, size);
925
        put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
926
        end_ebml_master(pb, blockgroup);
927

    
928
        data += line_size;
929
        data_size -= line_size;
930
    }
931

    
932
    return max_duration;
933
}
934

    
935
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
936
                            unsigned int blockid, AVPacket *pkt, int flags)
937
{
938
    MatroskaMuxContext *mkv = s->priv_data;
939
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
940
    uint8_t *data = NULL;
941
    int size = pkt->size;
942
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
943

    
944
    av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
945
           "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
946
           avio_tell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
947
    if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
948
        (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
949
        ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
950
    else
951
        data = pkt->data;
952
    put_ebml_id(pb, blockid);
953
    put_ebml_num(pb, size+4, 0);
954
    avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
955
    avio_wb16(pb, ts - mkv->cluster_pts);
956
    avio_w8(pb, flags);
957
    avio_write(pb, data, size);
958
    if (data != pkt->data)
959
        av_free(data);
960
}
961

    
962
static int srt_get_duration(uint8_t **buf)
963
{
964
    int i, duration = 0;
965

    
966
    for (i=0; i<2 && !duration; i++) {
967
        int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
968
        if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
969
                   &s_hour, &s_min, &s_sec, &s_hsec,
970
                   &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
971
            s_min  +=   60*s_hour;      e_min  +=   60*e_hour;
972
            s_sec  +=   60*s_min;       e_sec  +=   60*e_min;
973
            s_hsec += 1000*s_sec;       e_hsec += 1000*e_sec;
974
            duration = e_hsec - s_hsec;
975
        }
976
        *buf += strcspn(*buf, "\n") + 1;
977
    }
978
    return duration;
979
}
980

    
981
static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
982
{
983
    ebml_master blockgroup;
984
    AVPacket pkt2 = *pkt;
985
    int64_t duration = srt_get_duration(&pkt2.data);
986
    pkt2.size -= pkt2.data - pkt->data;
987

    
988
    blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
989
                                   mkv_blockgroup_size(pkt2.size));
990
    mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
991
    put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
992
    end_ebml_master(pb, blockgroup);
993

    
994
    return duration;
995
}
996

    
997
static void mkv_flush_dynbuf(AVFormatContext *s)
998
{
999
    MatroskaMuxContext *mkv = s->priv_data;
1000
    int bufsize;
1001
    uint8_t *dyn_buf;
1002

    
1003
    if (!mkv->dyn_bc)
1004
        return;
1005

    
1006
    bufsize = avio_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1007
    avio_write(s->pb, dyn_buf, bufsize);
1008
    av_free(dyn_buf);
1009
    mkv->dyn_bc = NULL;
1010
}
1011

    
1012
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1013
{
1014
    MatroskaMuxContext *mkv = s->priv_data;
1015
    AVIOContext *pb = s->pb;
1016
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1017
    int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1018
    int duration = pkt->duration;
1019
    int ret;
1020
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1021

    
1022
    if (ts == AV_NOPTS_VALUE) {
1023
        av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1024
        return AVERROR(EINVAL);
1025
    }
1026

    
1027
    if (!s->pb->seekable) {
1028
        if (!mkv->dyn_bc)
1029
            avio_open_dyn_buf(&mkv->dyn_bc);
1030
        pb = mkv->dyn_bc;
1031
    }
1032

    
1033
    if (!mkv->cluster_pos) {
1034
        mkv->cluster_pos = avio_tell(s->pb);
1035
        mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1036
        put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1037
        mkv->cluster_pts = FFMAX(0, ts);
1038
    }
1039

    
1040
    if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1041
        mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1042
    } else if (codec->codec_id == CODEC_ID_SSA) {
1043
        duration = mkv_write_ass_blocks(s, pb, pkt);
1044
    } else if (codec->codec_id == CODEC_ID_SRT) {
1045
        duration = mkv_write_srt_blocks(s, pb, pkt);
1046
    } else {
1047
        ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
1048
        duration = pkt->convergence_duration;
1049
        mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1050
        put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1051
        end_ebml_master(pb, blockgroup);
1052
    }
1053

    
1054
    if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1055
        ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
1056
        if (ret < 0) return ret;
1057
    }
1058

    
1059
    mkv->duration = FFMAX(mkv->duration, ts + duration);
1060
    return 0;
1061
}
1062

    
1063
static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
1064
{
1065
    uint8_t *data           = mkv->cur_audio_pkt.data;
1066
    mkv->cur_audio_pkt      = *pkt;
1067
    mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
1068
    if (!mkv->cur_audio_pkt.data)
1069
        return AVERROR(ENOMEM);
1070

    
1071
    memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
1072
    mkv->cur_audio_pkt.size = pkt->size;
1073
    return 0;
1074
}
1075

    
1076
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1077
{
1078
    MatroskaMuxContext *mkv = s->priv_data;
1079
    AVIOContext *pb = s->pb->seekable ? s->pb : mkv->dyn_bc;
1080
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1081
    int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1082
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1083
    int cluster_size = avio_tell(pb) - (s->pb->seekable ? mkv->cluster_pos : 0);
1084

    
1085
    // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1086
    // after 4k and on a keyframe
1087
    if (mkv->cluster_pos &&
1088
        ((!s->pb->seekable && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
1089
         ||                      cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
1090
         || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
1091
        av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1092
               " bytes, pts %" PRIu64 "\n", avio_tell(pb), ts);
1093
        end_ebml_master(pb, mkv->cluster);
1094
        mkv->cluster_pos = 0;
1095
        if (mkv->dyn_bc)
1096
            mkv_flush_dynbuf(s);
1097
    }
1098

    
1099
    // check if we have an audio packet cached
1100
    if (mkv->cur_audio_pkt.size > 0) {
1101
        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1102
        mkv->cur_audio_pkt.size = 0;
1103
        if (ret < 0) {
1104
            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1105
            return ret;
1106
        }
1107
    }
1108

    
1109
    // buffer an audio packet to ensure the packet containing the video
1110
    // keyframe's timecode is contained in the same cluster for WebM
1111
    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
1112
        ret = mkv_copy_packet(mkv, pkt);
1113
    else
1114
        ret = mkv_write_packet_internal(s, pkt);
1115
    return ret;
1116
}
1117

    
1118
static int mkv_write_trailer(AVFormatContext *s)
1119
{
1120
    MatroskaMuxContext *mkv = s->priv_data;
1121
    AVIOContext *pb = s->pb;
1122
    int64_t currentpos, cuespos;
1123
    int ret;
1124

    
1125
    // check if we have an audio packet cached
1126
    if (mkv->cur_audio_pkt.size > 0) {
1127
        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1128
        mkv->cur_audio_pkt.size = 0;
1129
        if (ret < 0) {
1130
            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1131
            return ret;
1132
        }
1133
    }
1134

    
1135
    if (mkv->dyn_bc) {
1136
        end_ebml_master(mkv->dyn_bc, mkv->cluster);
1137
        mkv_flush_dynbuf(s);
1138
    } else if (mkv->cluster_pos) {
1139
        end_ebml_master(pb, mkv->cluster);
1140
    }
1141

    
1142
    if (pb->seekable) {
1143
        if (mkv->cues->num_entries) {
1144
            cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1145

    
1146
            ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES, cuespos);
1147
            if (ret < 0) return ret;
1148
        }
1149

    
1150
        mkv_write_seekhead(pb, mkv->main_seekhead);
1151

    
1152
        // update the duration
1153
        av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1154
        currentpos = avio_tell(pb);
1155
        avio_seek(pb, mkv->duration_offset, SEEK_SET);
1156
        put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1157

    
1158
        avio_seek(pb, currentpos, SEEK_SET);
1159
    }
1160

    
1161
    end_ebml_master(pb, mkv->segment);
1162
    av_free(mkv->tracks);
1163
    av_destruct_packet(&mkv->cur_audio_pkt);
1164
    avio_flush(pb);
1165
    return 0;
1166
}
1167

    
1168
#if CONFIG_MATROSKA_MUXER
1169
AVOutputFormat ff_matroska_muxer = {
1170
    "matroska",
1171
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1172
    "video/x-matroska",
1173
    "mkv",
1174
    sizeof(MatroskaMuxContext),
1175
    CODEC_ID_MP2,
1176
    CODEC_ID_MPEG4,
1177
    mkv_write_header,
1178
    mkv_write_packet,
1179
    mkv_write_trailer,
1180
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1181
    .codec_tag = (const AVCodecTag* const []){ff_codec_bmp_tags, ff_codec_wav_tags, 0},
1182
    .subtitle_codec = CODEC_ID_TEXT,
1183
};
1184
#endif
1185

    
1186
#if CONFIG_WEBM_MUXER
1187
AVOutputFormat ff_webm_muxer = {
1188
    "webm",
1189
    NULL_IF_CONFIG_SMALL("WebM file format"),
1190
    "video/webm",
1191
    "webm",
1192
    sizeof(MatroskaMuxContext),
1193
    CODEC_ID_VORBIS,
1194
    CODEC_ID_VP8,
1195
    mkv_write_header,
1196
    mkv_write_packet,
1197
    mkv_write_trailer,
1198
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1199
};
1200
#endif
1201

    
1202
#if CONFIG_MATROSKA_AUDIO_MUXER
1203
AVOutputFormat ff_matroska_audio_muxer = {
1204
    "matroska",
1205
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1206
    "audio/x-matroska",
1207
    "mka",
1208
    sizeof(MatroskaMuxContext),
1209
    CODEC_ID_MP2,
1210
    CODEC_ID_NONE,
1211
    mkv_write_header,
1212
    mkv_write_packet,
1213
    mkv_write_trailer,
1214
    .flags = AVFMT_GLOBALHEADER,
1215
    .codec_tag = (const AVCodecTag* const []){ff_codec_wav_tags, 0},
1216
};
1217
#endif