Statistics
| Branch: | Revision:

ffmpeg / libavformat / matroskaenc.c @ f59d8ff8

History | View | Annotate | Download (40.9 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 "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 = url_ftell(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(url_ftell(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){ url_ftell(pb), bytes };
228
}
229

    
230
static void end_ebml_master(AVIOContext *pb, ebml_master master)
231
{
232
    int64_t pos = url_ftell(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 = url_ftell(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 = url_ftell(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 - url_ftell(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 = url_ftell(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
    int sri;
442

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

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

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

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

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

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

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

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

    
512
        ff_put_wav_header(dyn_cp, codec);
513
    }
514

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

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

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

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

    
544
        if (!bit_depth)
545
            bit_depth = av_get_bits_per_sample_fmt(codec->sample_fmt);
546

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

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

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

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

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

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

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

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

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

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

    
614
            case AVMEDIA_TYPE_AUDIO:
615
                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
616

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

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

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

    
641
        end_ebml_master(pb, track);
642

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

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

    
658
    if (!s->nb_chapters)
659
        return 0;
660

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

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

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

    
694
static void mkv_write_simpletag(AVIOContext *pb, AVMetadataTag *t)
695
{
696
    uint8_t *key = av_strdup(t->key);
697
    uint8_t *p   = key;
698
    const uint8_t *lang = NULL;
699
    ebml_master tag;
700

    
701
    if ((p = strrchr(p, '-')) &&
702
        (lang = av_convert_lang_to(p + 1, AV_LANG_ISO639_2_BIBL)))
703
        *p = 0;
704

    
705
    p = key;
706
    while (*p) {
707
        if (*p == ' ')
708
            *p = '_';
709
        else if (*p >= 'a' && *p <= 'z')
710
            *p -= 'a' - 'A';
711
        p++;
712
    }
713

    
714
    tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);
715
    put_ebml_string(pb, MATROSKA_ID_TAGNAME, key);
716
    if (lang)
717
        put_ebml_string(pb, MATROSKA_ID_TAGLANG, lang);
718
    put_ebml_string(pb, MATROSKA_ID_TAGSTRING, t->value);
719
    end_ebml_master(pb, tag);
720

    
721
    av_freep(&key);
722
}
723

    
724
static int mkv_write_tag(AVFormatContext *s, AVMetadata *m, unsigned int elementid,
725
                         unsigned int uid, ebml_master *tags)
726
{
727
    MatroskaMuxContext *mkv = s->priv_data;
728
    ebml_master tag, targets;
729
    AVMetadataTag *t = NULL;
730
    int ret;
731

    
732
    if (!tags->pos) {
733
        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TAGS, url_ftell(s->pb));
734
        if (ret < 0) return ret;
735

    
736
        *tags = start_ebml_master(s->pb, MATROSKA_ID_TAGS, 0);
737
    }
738

    
739
    tag     = start_ebml_master(s->pb, MATROSKA_ID_TAG,        0);
740
    targets = start_ebml_master(s->pb, MATROSKA_ID_TAGTARGETS, 0);
741
    if (elementid)
742
        put_ebml_uint(s->pb, elementid, uid);
743
    end_ebml_master(s->pb, targets);
744

    
745
    while ((t = av_metadata_get(m, "", t, AV_METADATA_IGNORE_SUFFIX)))
746
        if (strcasecmp(t->key, "title"))
747
            mkv_write_simpletag(s->pb, t);
748

    
749
    end_ebml_master(s->pb, tag);
750
    return 0;
751
}
752

    
753
static int mkv_write_tags(AVFormatContext *s)
754
{
755
    ebml_master tags = {0};
756
    int i, ret;
757

    
758
    ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);
759

    
760
    if (av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX)) {
761
        ret = mkv_write_tag(s, s->metadata, 0, 0, &tags);
762
        if (ret < 0) return ret;
763
    }
764

    
765
    for (i = 0; i < s->nb_streams; i++) {
766
        AVStream *st = s->streams[i];
767

    
768
        if (!av_metadata_get(st->metadata, "", 0, AV_METADATA_IGNORE_SUFFIX))
769
            continue;
770

    
771
        ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &tags);
772
        if (ret < 0) return ret;
773
    }
774

    
775
    for (i = 0; i < s->nb_chapters; i++) {
776
        AVChapter *ch = s->chapters[i];
777

    
778
        if (!av_metadata_get(ch->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
779
            continue;
780

    
781
        ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id, &tags);
782
        if (ret < 0) return ret;
783
    }
784

    
785
    if (tags.pos)
786
        end_ebml_master(s->pb, tags);
787
    return 0;
788
}
789

    
790
static int mkv_write_header(AVFormatContext *s)
791
{
792
    MatroskaMuxContext *mkv = s->priv_data;
793
    AVIOContext *pb = s->pb;
794
    ebml_master ebml_header, segment_info;
795
    AVMetadataTag *tag;
796
    int ret, i;
797

    
798
    if (!strcmp(s->oformat->name, "webm")) mkv->mode = MODE_WEBM;
799
    else                                   mkv->mode = MODE_MATROSKAv2;
800

    
801
    mkv->tracks = av_mallocz(s->nb_streams * sizeof(*mkv->tracks));
802
    if (!mkv->tracks)
803
        return AVERROR(ENOMEM);
804

    
805
    ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
806
    put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
807
    put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
808
    put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
809
    put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
810
    put_ebml_string (pb, EBML_ID_DOCTYPE            , s->oformat->name);
811
    put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
812
    put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
813
    end_ebml_master(pb, ebml_header);
814

    
815
    mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
816
    mkv->segment_offset = url_ftell(pb);
817

    
818
    // we write 2 seek heads - one at the end of the file to point to each
819
    // cluster, and one at the beginning to point to all other level one
820
    // elements (including the seek head at the end of the file), which
821
    // isn't more than 10 elements if we only write one of each other
822
    // currently defined level 1 element
823
    mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
824
    if (!mkv->main_seekhead)
825
        return AVERROR(ENOMEM);
826

    
827
    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
828
    if (ret < 0) return ret;
829

    
830
    segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
831
    put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
832
    if ((tag = av_metadata_get(s->metadata, "title", NULL, 0)))
833
        put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);
834
    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
835
        uint32_t segment_uid[4];
836
        AVLFG lfg;
837

    
838
        av_lfg_init(&lfg, av_get_random_seed());
839

    
840
        for (i = 0; i < 4; i++)
841
            segment_uid[i] = av_lfg_get(&lfg);
842

    
843
        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
844
        put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
845
        put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
846
    }
847

    
848
    // reserve space for the duration
849
    mkv->duration = 0;
850
    mkv->duration_offset = url_ftell(pb);
851
    put_ebml_void(pb, 11);                  // assumes double-precision float to be written
852
    end_ebml_master(pb, segment_info);
853

    
854
    ret = mkv_write_tracks(s);
855
    if (ret < 0) return ret;
856

    
857
    if (mkv->mode != MODE_WEBM) {
858
        ret = mkv_write_chapters(s);
859
        if (ret < 0) return ret;
860

    
861
        ret = mkv_write_tags(s);
862
        if (ret < 0) return ret;
863
    }
864

    
865
    if (url_is_streamed(s->pb))
866
        mkv_write_seekhead(pb, mkv->main_seekhead);
867

    
868
    mkv->cues = mkv_start_cues(mkv->segment_offset);
869
    if (mkv->cues == NULL)
870
        return AVERROR(ENOMEM);
871

    
872
    av_init_packet(&mkv->cur_audio_pkt);
873
    mkv->cur_audio_pkt.size = 0;
874
    mkv->audio_buffer_size  = 0;
875

    
876
    put_flush_packet(pb);
877
    return 0;
878
}
879

    
880
static int mkv_blockgroup_size(int pkt_size)
881
{
882
    int size = pkt_size + 4;
883
    size += ebml_num_size(size);
884
    size += 2;              // EBML ID for block and block duration
885
    size += 8;              // max size of block duration
886
    size += ebml_num_size(size);
887
    size += 1;              // blockgroup EBML ID
888
    return size;
889
}
890

    
891
static int ass_get_duration(const uint8_t *p)
892
{
893
    int sh, sm, ss, sc, eh, em, es, ec;
894
    uint64_t start, end;
895

    
896
    if (sscanf(p, "%*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d",
897
               &sh, &sm, &ss, &sc, &eh, &em, &es, &ec) != 8)
898
        return 0;
899
    start = 3600000*sh + 60000*sm + 1000*ss + 10*sc;
900
    end   = 3600000*eh + 60000*em + 1000*es + 10*ec;
901
    return end - start;
902
}
903

    
904
static int mkv_write_ass_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
905
{
906
    MatroskaMuxContext *mkv = s->priv_data;
907
    int i, layer = 0, max_duration = 0, size, line_size, data_size = pkt->size;
908
    uint8_t *start, *end, *data = pkt->data;
909
    ebml_master blockgroup;
910
    char buffer[2048];
911

    
912
    while (data_size) {
913
        int duration = ass_get_duration(data);
914
        max_duration = FFMAX(duration, max_duration);
915
        end = memchr(data, '\n', data_size);
916
        size = line_size = end ? end-data+1 : data_size;
917
        size -= end ? (end[-1]=='\r')+1 : 0;
918
        start = data;
919
        for (i=0; i<3; i++, start++)
920
            if (!(start = memchr(start, ',', size-(start-data))))
921
                return max_duration;
922
        size -= start - data;
923
        sscanf(data, "Dialogue: %d,", &layer);
924
        i = snprintf(buffer, sizeof(buffer), "%"PRId64",%d,",
925
                     s->streams[pkt->stream_index]->nb_frames++, layer);
926
        size = FFMIN(i+size, sizeof(buffer));
927
        memcpy(buffer+i, start, size-i);
928

    
929
        av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
930
               "pts %" PRId64 ", duration %d\n",
931
               url_ftell(pb), size, pkt->pts, duration);
932
        blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(size));
933
        put_ebml_id(pb, MATROSKA_ID_BLOCK);
934
        put_ebml_num(pb, size+4, 0);
935
        avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
936
        avio_wb16(pb, pkt->pts - mkv->cluster_pts);
937
        avio_w8(pb, 0);
938
        avio_write(pb, buffer, size);
939
        put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
940
        end_ebml_master(pb, blockgroup);
941

    
942
        data += line_size;
943
        data_size -= line_size;
944
    }
945

    
946
    return max_duration;
947
}
948

    
949
static void mkv_write_block(AVFormatContext *s, AVIOContext *pb,
950
                            unsigned int blockid, AVPacket *pkt, int flags)
951
{
952
    MatroskaMuxContext *mkv = s->priv_data;
953
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
954
    uint8_t *data = NULL;
955
    int size = pkt->size;
956
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
957

    
958
    av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
959
           "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
960
           url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
961
    if (codec->codec_id == CODEC_ID_H264 && codec->extradata_size > 0 &&
962
        (AV_RB24(codec->extradata) == 1 || AV_RB32(codec->extradata) == 1))
963
        ff_avc_parse_nal_units_buf(pkt->data, &data, &size);
964
    else
965
        data = pkt->data;
966
    put_ebml_id(pb, blockid);
967
    put_ebml_num(pb, size+4, 0);
968
    avio_w8(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
969
    avio_wb16(pb, ts - mkv->cluster_pts);
970
    avio_w8(pb, flags);
971
    avio_write(pb, data, size);
972
    if (data != pkt->data)
973
        av_free(data);
974
}
975

    
976
static int srt_get_duration(uint8_t **buf)
977
{
978
    int i, duration = 0;
979

    
980
    for (i=0; i<2 && !duration; i++) {
981
        int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;
982
        if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",
983
                   &s_hour, &s_min, &s_sec, &s_hsec,
984
                   &e_hour, &e_min, &e_sec, &e_hsec) == 8) {
985
            s_min  +=   60*s_hour;      e_min  +=   60*e_hour;
986
            s_sec  +=   60*s_min;       e_sec  +=   60*e_min;
987
            s_hsec += 1000*s_sec;       e_hsec += 1000*e_sec;
988
            duration = e_hsec - s_hsec;
989
        }
990
        *buf += strcspn(*buf, "\n") + 1;
991
    }
992
    return duration;
993
}
994

    
995
static int mkv_write_srt_blocks(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)
996
{
997
    ebml_master blockgroup;
998
    AVPacket pkt2 = *pkt;
999
    int64_t duration = srt_get_duration(&pkt2.data);
1000
    pkt2.size -= pkt2.data - pkt->data;
1001

    
1002
    blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP,
1003
                                   mkv_blockgroup_size(pkt2.size));
1004
    mkv_write_block(s, pb, MATROSKA_ID_BLOCK, &pkt2, 0);
1005
    put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1006
    end_ebml_master(pb, blockgroup);
1007

    
1008
    return duration;
1009
}
1010

    
1011
static void mkv_flush_dynbuf(AVFormatContext *s)
1012
{
1013
    MatroskaMuxContext *mkv = s->priv_data;
1014
    int bufsize;
1015
    uint8_t *dyn_buf;
1016

    
1017
    if (!mkv->dyn_bc)
1018
        return;
1019

    
1020
    bufsize = url_close_dyn_buf(mkv->dyn_bc, &dyn_buf);
1021
    avio_write(s->pb, dyn_buf, bufsize);
1022
    av_free(dyn_buf);
1023
    mkv->dyn_bc = NULL;
1024
}
1025

    
1026
static int mkv_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
1027
{
1028
    MatroskaMuxContext *mkv = s->priv_data;
1029
    AVIOContext *pb = s->pb;
1030
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1031
    int keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1032
    int duration = pkt->duration;
1033
    int ret;
1034
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1035

    
1036
    if (ts == AV_NOPTS_VALUE) {
1037
        av_log(s, AV_LOG_ERROR, "Can't write packet with unknown timestamp\n");
1038
        return AVERROR(EINVAL);
1039
    }
1040

    
1041
    if (url_is_streamed(s->pb)) {
1042
        if (!mkv->dyn_bc)
1043
            url_open_dyn_buf(&mkv->dyn_bc);
1044
        pb = mkv->dyn_bc;
1045
    }
1046

    
1047
    if (!mkv->cluster_pos) {
1048
        mkv->cluster_pos = url_ftell(s->pb);
1049
        mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
1050
        put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, FFMAX(0, ts));
1051
        mkv->cluster_pts = FFMAX(0, ts);
1052
    }
1053

    
1054
    if (codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1055
        mkv_write_block(s, pb, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
1056
    } else if (codec->codec_id == CODEC_ID_SSA) {
1057
        duration = mkv_write_ass_blocks(s, pb, pkt);
1058
    } else if (codec->codec_id == CODEC_ID_SRT) {
1059
        duration = mkv_write_srt_blocks(s, pb, pkt);
1060
    } else {
1061
        ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt->size));
1062
        duration = pkt->convergence_duration;
1063
        mkv_write_block(s, pb, MATROSKA_ID_BLOCK, pkt, 0);
1064
        put_ebml_uint(pb, MATROSKA_ID_BLOCKDURATION, duration);
1065
        end_ebml_master(pb, blockgroup);
1066
    }
1067

    
1068
    if (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe) {
1069
        ret = mkv_add_cuepoint(mkv->cues, pkt->stream_index, ts, mkv->cluster_pos);
1070
        if (ret < 0) return ret;
1071
    }
1072

    
1073
    mkv->duration = FFMAX(mkv->duration, ts + duration);
1074
    return 0;
1075
}
1076

    
1077
static int mkv_copy_packet(MatroskaMuxContext *mkv, const AVPacket *pkt)
1078
{
1079
    uint8_t *data           = mkv->cur_audio_pkt.data;
1080
    mkv->cur_audio_pkt      = *pkt;
1081
    mkv->cur_audio_pkt.data = av_fast_realloc(data, &mkv->audio_buffer_size, pkt->size);
1082
    if (!mkv->cur_audio_pkt.data)
1083
        return AVERROR(ENOMEM);
1084

    
1085
    memcpy(mkv->cur_audio_pkt.data, pkt->data, pkt->size);
1086
    mkv->cur_audio_pkt.size = pkt->size;
1087
    return 0;
1088
}
1089

    
1090
static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
1091
{
1092
    MatroskaMuxContext *mkv = s->priv_data;
1093
    AVIOContext *pb = url_is_streamed(s->pb) ? mkv->dyn_bc : s->pb;
1094
    AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
1095
    int ret, keyframe = !!(pkt->flags & AV_PKT_FLAG_KEY);
1096
    int64_t ts = mkv->tracks[pkt->stream_index].write_dts ? pkt->dts : pkt->pts;
1097
    int cluster_size = url_ftell(pb) - (url_is_streamed(s->pb) ? 0 : mkv->cluster_pos);
1098

    
1099
    // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or
1100
    // after 4k and on a keyframe
1101
    if (mkv->cluster_pos &&
1102
        ((url_is_streamed(s->pb) && (cluster_size > 32*1024 || ts > mkv->cluster_pts + 1000))
1103
         ||                      cluster_size > 5*1024*1024 || ts > mkv->cluster_pts + 5000
1104
         || (codec->codec_type == AVMEDIA_TYPE_VIDEO && keyframe && cluster_size > 4*1024))) {
1105
        av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
1106
               " bytes, pts %" PRIu64 "\n", url_ftell(pb), ts);
1107
        end_ebml_master(pb, mkv->cluster);
1108
        mkv->cluster_pos = 0;
1109
        if (mkv->dyn_bc)
1110
            mkv_flush_dynbuf(s);
1111
    }
1112

    
1113
    // check if we have an audio packet cached
1114
    if (mkv->cur_audio_pkt.size > 0) {
1115
        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1116
        mkv->cur_audio_pkt.size = 0;
1117
        if (ret < 0) {
1118
            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1119
            return ret;
1120
        }
1121
    }
1122

    
1123
    // buffer an audio packet to ensure the packet containing the video
1124
    // keyframe's timecode is contained in the same cluster for WebM
1125
    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
1126
        ret = mkv_copy_packet(mkv, pkt);
1127
    else
1128
        ret = mkv_write_packet_internal(s, pkt);
1129
    return ret;
1130
}
1131

    
1132
static int mkv_write_trailer(AVFormatContext *s)
1133
{
1134
    MatroskaMuxContext *mkv = s->priv_data;
1135
    AVIOContext *pb = s->pb;
1136
    int64_t currentpos, cuespos;
1137
    int ret;
1138

    
1139
    // check if we have an audio packet cached
1140
    if (mkv->cur_audio_pkt.size > 0) {
1141
        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt);
1142
        mkv->cur_audio_pkt.size = 0;
1143
        if (ret < 0) {
1144
            av_log(s, AV_LOG_ERROR, "Could not write cached audio packet ret:%d\n", ret);
1145
            return ret;
1146
        }
1147
    }
1148

    
1149
    if (mkv->dyn_bc) {
1150
        end_ebml_master(mkv->dyn_bc, mkv->cluster);
1151
        mkv_flush_dynbuf(s);
1152
    } else if (mkv->cluster_pos) {
1153
        end_ebml_master(pb, mkv->cluster);
1154
    }
1155

    
1156
    if (!url_is_streamed(pb)) {
1157
        cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
1158

    
1159
        ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES    , cuespos);
1160
        if (ret < 0) return ret;
1161
        mkv_write_seekhead(pb, mkv->main_seekhead);
1162

    
1163
        // update the duration
1164
        av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
1165
        currentpos = url_ftell(pb);
1166
        avio_seek(pb, mkv->duration_offset, SEEK_SET);
1167
        put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
1168

    
1169
        avio_seek(pb, currentpos, SEEK_SET);
1170
    }
1171

    
1172
    end_ebml_master(pb, mkv->segment);
1173
    av_free(mkv->tracks);
1174
    av_destruct_packet(&mkv->cur_audio_pkt);
1175
    put_flush_packet(pb);
1176
    return 0;
1177
}
1178

    
1179
#if CONFIG_MATROSKA_MUXER
1180
AVOutputFormat ff_matroska_muxer = {
1181
    "matroska",
1182
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1183
    "video/x-matroska",
1184
    "mkv",
1185
    sizeof(MatroskaMuxContext),
1186
    CODEC_ID_MP2,
1187
    CODEC_ID_MPEG4,
1188
    mkv_write_header,
1189
    mkv_write_packet,
1190
    mkv_write_trailer,
1191
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1192
    .codec_tag = (const AVCodecTag* const []){ff_codec_bmp_tags, ff_codec_wav_tags, 0},
1193
    .subtitle_codec = CODEC_ID_TEXT,
1194
};
1195
#endif
1196

    
1197
#if CONFIG_WEBM_MUXER
1198
AVOutputFormat ff_webm_muxer = {
1199
    "webm",
1200
    NULL_IF_CONFIG_SMALL("WebM file format"),
1201
    "video/webm",
1202
    "webm",
1203
    sizeof(MatroskaMuxContext),
1204
    CODEC_ID_VORBIS,
1205
    CODEC_ID_VP8,
1206
    mkv_write_header,
1207
    mkv_write_packet,
1208
    mkv_write_trailer,
1209
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1210
};
1211
#endif
1212

    
1213
#if CONFIG_MATROSKA_AUDIO_MUXER
1214
AVOutputFormat ff_matroska_audio_muxer = {
1215
    "matroska",
1216
    NULL_IF_CONFIG_SMALL("Matroska file format"),
1217
    "audio/x-matroska",
1218
    "mka",
1219
    sizeof(MatroskaMuxContext),
1220
    CODEC_ID_MP2,
1221
    CODEC_ID_NONE,
1222
    mkv_write_header,
1223
    mkv_write_packet,
1224
    mkv_write_trailer,
1225
    .flags = AVFMT_GLOBALHEADER,
1226
    .codec_tag = (const AVCodecTag* const []){ff_codec_wav_tags, 0},
1227
};
1228
#endif