]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/matroskaenc.c
Floats aren't used enough to justify writing any with single precision
[frescor/ffmpeg.git] / libavformat / matroskaenc.c
1 /*
2  * Matroska file 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 "xiph.h"
25 #include "matroska.h"
26
27 typedef struct mkv_seekhead_entry {
28     unsigned int    elementid;
29     uint64_t        segmentpos;
30 } mkv_seekhead_entry;
31
32 typedef struct mkv_seekhead {
33     offset_t                filepos;
34     offset_t                segment_offset;     ///< the file offset to the beginning of the segment
35     int                     reserved_size;      ///< -1 if appending to file
36     int                     max_entries;
37     mkv_seekhead_entry      *entries;
38     int                     num_entries;
39 } mkv_seekhead;
40
41 typedef struct {
42     uint64_t        pts;
43     int             tracknum;
44     offset_t        cluster_pos;        ///< file offset of the cluster containing the block
45 } mkv_cuepoint;
46
47 typedef struct {
48     offset_t        segment_offset;
49     mkv_cuepoint    *entries;
50     int             num_entries;
51 } mkv_cues;
52
53 typedef struct MatroskaMuxContext {
54     offset_t        segment;
55     offset_t        segment_offset;
56     offset_t        cluster;
57     offset_t        cluster_pos;        ///< file offset of the current cluster
58     uint64_t        cluster_pts;
59     offset_t        duration_offset;
60     uint64_t        duration;
61     mkv_seekhead    *main_seekhead;
62     mkv_seekhead    *cluster_seekhead;
63     mkv_cues        *cues;
64 } MatroskaMuxContext;
65
66 static void put_ebml_id(ByteIOContext *pb, unsigned int id)
67 {
68     if (id >= 0x3fffff)
69         put_byte(pb, id >> 24);
70     if (id >= 0x7fff)
71         put_byte(pb, id >> 16);
72     if (id >= 0xff)
73         put_byte(pb, id >> 8);
74     put_byte(pb, id);
75 }
76
77 static int ebml_id_size(unsigned int id)
78 {
79     return (av_log2(id+1)-1)/7+1;
80 }
81
82 // XXX: test this thoroughly and get rid of minbytes hack (currently needed to
83 // use up all of the space reserved in start_ebml_master)
84 static void put_ebml_size(ByteIOContext *pb, uint64_t size, int minbytes)
85 {
86     int bytes = minbytes;
87
88     // sizes larger than this are currently undefined in EBML
89     // so write "unknown" size
90     size = FFMIN(size, (1ULL<<56)-1);
91
92     while (size >> (bytes*7 + 7)) bytes++;
93
94     put_byte(pb, (0x80 >> bytes) | (size >> bytes*8));
95     for (bytes -= 1; bytes >= 0; bytes--)
96         put_byte(pb, size >> bytes*8);
97 }
98
99 static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
100 {
101     int bytes = 1;
102     while (val >> bytes*8) bytes++;
103
104     put_ebml_id(pb, elementid);
105     put_ebml_size(pb, bytes, 0);
106     for (bytes -= 1; bytes >= 0; bytes--)
107         put_byte(pb, val >> bytes*8);
108 }
109
110 static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
111 {
112     put_ebml_id(pb, elementid);
113     put_ebml_size(pb, 8, 0);
114     put_be64(pb, av_dbl2int(val));
115 }
116
117 static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
118                             const uint8_t *buf, int size)
119 {
120     put_ebml_id(pb, elementid);
121     put_ebml_size(pb, size, 0);
122     put_buffer(pb, buf, size);
123 }
124
125 static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
126 {
127     put_ebml_binary(pb, elementid, str, strlen(str));
128 }
129
130 // this reserves exactly the amount of space specified by size, which must be at least 2
131 static void put_ebml_void(ByteIOContext *pb, uint64_t size)
132 {
133     offset_t currentpos = url_ftell(pb);
134
135     if (size < 2)
136         return;
137
138     put_ebml_id(pb, EBML_ID_VOID);
139     // we need to subtract the length needed to store the size from the size we need to reserve
140     // so 2 cases, we use 8 bytes to store the size if possible, 1 byte otherwise
141     if (size < 10)
142         put_ebml_size(pb, size-1, 0);
143     else
144         put_ebml_size(pb, size-9, 7);
145     url_fseek(pb, currentpos + size, SEEK_SET);
146 }
147
148 static offset_t start_ebml_master(ByteIOContext *pb, unsigned int elementid)
149 {
150     put_ebml_id(pb, elementid);
151     // XXX: this always reserves the maximum needed space to store any size value
152     // we should be smarter (additional parameter for expected size?)
153     put_ebml_size(pb, (1ULL<<56)-1, 0);     // largest unknown size
154     return url_ftell(pb);
155 }
156
157 static void end_ebml_master(ByteIOContext *pb, offset_t start)
158 {
159     offset_t pos = url_ftell(pb);
160
161     url_fseek(pb, start - 8, SEEK_SET);
162     put_ebml_size(pb, pos - start, 7);
163     url_fseek(pb, pos, SEEK_SET);
164 }
165
166 // initializes a mkv_seekhead element to be ready to index level 1 matroska elements
167 // if numelements is greater than 0, it reserves enough space for that many elements
168 // at the current file position and writes the seekhead there, otherwise the seekhead
169 // will be appended to the file when end_mkv_seekhead() is called
170 static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, offset_t segment_offset, int numelements)
171 {
172     mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
173     if (new_seekhead == NULL)
174         return NULL;
175
176     new_seekhead->segment_offset = segment_offset;
177
178     if (numelements > 0) {
179         new_seekhead->filepos = url_ftell(pb);
180         // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID and size,
181         // and 3 bytes to guarantee that an EBML void element will fit afterwards
182         // XXX: 28 bytes right now because begin_ebml_master() reserves more than necessary
183         new_seekhead->reserved_size = numelements * 28 + 13;
184         new_seekhead->max_entries = numelements;
185         put_ebml_void(pb, new_seekhead->reserved_size);
186     }
187     return new_seekhead;
188 }
189
190 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
191 {
192     mkv_seekhead_entry *entries = seekhead->entries;
193     int new_entry = seekhead->num_entries;
194
195     // don't store more elements than we reserved space for
196     if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
197         return -1;
198
199     entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
200     if (entries == NULL)
201         return -1;
202
203     entries[new_entry].elementid = elementid;
204     entries[new_entry].segmentpos = filepos - seekhead->segment_offset;
205
206     seekhead->entries = entries;
207     seekhead->num_entries++;
208
209     return 0;
210 }
211
212 // returns the file offset where the seekhead was written and frees the seekhead
213 static offset_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
214 {
215     offset_t metaseek, seekentry, currentpos;
216     int i;
217
218     currentpos = url_ftell(pb);
219
220     if (seekhead->reserved_size > 0)
221         url_fseek(pb, seekhead->filepos, SEEK_SET);
222
223     metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD);
224     for (i = 0; i < seekhead->num_entries; i++) {
225         mkv_seekhead_entry *entry = &seekhead->entries[i];
226
227         seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY);
228
229         put_ebml_id(pb, MATROSKA_ID_SEEKID);
230         put_ebml_size(pb, ebml_id_size(entry->elementid), 0);
231         put_ebml_id(pb, entry->elementid);
232
233         put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
234         end_ebml_master(pb, seekentry);
235     }
236     end_ebml_master(pb, metaseek);
237
238     if (seekhead->reserved_size > 0) {
239         uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
240         put_ebml_void(pb, remaining);
241         url_fseek(pb, currentpos, SEEK_SET);
242
243         currentpos = seekhead->filepos;
244     }
245     av_free(seekhead->entries);
246     av_free(seekhead);
247
248     return currentpos;
249 }
250
251 static mkv_cues * mkv_start_cues(offset_t segment_offset)
252 {
253     mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
254     if (cues == NULL)
255         return NULL;
256
257     cues->segment_offset = segment_offset;
258     return cues;
259 }
260
261 static int mkv_add_cuepoint(mkv_cues *cues, AVPacket *pkt, offset_t cluster_pos)
262 {
263     mkv_cuepoint *entries = cues->entries;
264     int new_entry = cues->num_entries;
265
266     entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
267     if (entries == NULL)
268         return -1;
269
270     entries[new_entry].pts = pkt->pts;
271     entries[new_entry].tracknum = pkt->stream_index + 1;
272     entries[new_entry].cluster_pos = cluster_pos - cues->segment_offset;
273
274     cues->entries = entries;
275     cues->num_entries++;
276     return 0;
277 }
278
279 static offset_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues)
280 {
281     offset_t currentpos, cues_element;
282     int i, j;
283
284     currentpos = url_ftell(pb);
285     cues_element = start_ebml_master(pb, MATROSKA_ID_CUES);
286
287     for (i = 0; i < cues->num_entries; i++) {
288         offset_t cuepoint, track_positions;
289         mkv_cuepoint *entry = &cues->entries[i];
290         uint64_t pts = entry->pts;
291
292         cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY);
293         put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
294
295         // put all the entries from different tracks that have the exact same
296         // timestamp into the same CuePoint
297         for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
298             track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION);
299             put_ebml_uint(pb, MATROSKA_ID_CUETRACK          , entry[j].tracknum   );
300             put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
301             end_ebml_master(pb, track_positions);
302         }
303         i += j - 1;
304         end_ebml_master(pb, cuepoint);
305     }
306     end_ebml_master(pb, cues_element);
307
308     av_free(cues->entries);
309     av_free(cues);
310     return currentpos;
311 }
312
313 static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
314 {
315     offset_t codecprivate;
316     uint8_t *header_start[3];
317     int header_len[3];
318     int first_header_size;
319     int j, k;
320
321     if (codec->codec_id == CODEC_ID_VORBIS)
322         first_header_size = 30;
323     else
324         first_header_size = 42;
325
326     if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
327                               first_header_size, header_start, header_len) < 0) {
328         av_log(codec, AV_LOG_ERROR, "Extradata corrupt.\n");
329         return -1;
330     }
331
332     codecprivate = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
333     put_byte(pb, 2);                    // number packets - 1
334     for (j = 0; j < 2; j++) {
335         for (k = 0; k < header_len[j] / 255; k++)
336             put_byte(pb, 255);
337         put_byte(pb, header_len[j] % 255);
338     }
339     for (j = 0; j < 3; j++)
340         put_buffer(pb, header_start[j], header_len[j]);
341     end_ebml_master(pb, codecprivate);
342
343     return 0;
344 }
345
346 static void get_aac_sample_rates(AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
347 {
348     static const int aac_sample_rates[] = {
349         96000, 88200, 64000, 48000, 44100, 32000,
350         24000, 22050, 16000, 12000, 11025,  8000,
351     };
352     int sri;
353
354     if (codec->extradata_size < 2) {
355         av_log(codec, AV_LOG_WARNING, "no aac extradata, unable to determine sample rate\n");
356         return;
357     }
358
359     sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
360     if (sri > 12) {
361         av_log(codec, AV_LOG_WARNING, "aac samplerate index out of bounds\n");
362         return;
363     }
364     *sample_rate = aac_sample_rates[sri];
365
366     // if sbr, get output sample rate as well
367     if (codec->extradata_size == 5) {
368         sri = (codec->extradata[4] >> 3) & 0xF;
369         if (sri > 12) {
370             av_log(codec, AV_LOG_WARNING, "aac output samplerate index out of bounds\n");
371             return;
372         }
373         *output_sample_rate = aac_sample_rates[sri];
374     }
375 }
376
377 static int mkv_write_tracks(AVFormatContext *s)
378 {
379     MatroskaMuxContext *mkv = s->priv_data;
380     ByteIOContext *pb = &s->pb;
381     offset_t tracks;
382     int i, j;
383
384     if (mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb)) < 0)
385         return -1;
386
387     tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS);
388     for (i = 0; i < s->nb_streams; i++) {
389         AVStream *st = s->streams[i];
390         AVCodecContext *codec = st->codec;
391         offset_t subinfo, track;
392         int native_id = 0;
393         int bit_depth = av_get_bits_per_sample(codec->codec_id);
394         int sample_rate = codec->sample_rate;
395         int output_sample_rate = 0;
396
397         if (codec->codec_id == CODEC_ID_AAC)
398             get_aac_sample_rates(codec, &sample_rate, &output_sample_rate);
399
400         track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY);
401         put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);
402         put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);
403         put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
404
405         if (st->language[0])
406             put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
407
408         // look for a codec id string specific to mkv to use, if none are found, use AVI codes
409         for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
410             if (ff_mkv_codec_tags[j].id == codec->codec_id) {
411                 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
412                 native_id = 1;
413                 break;
414             }
415         }
416
417         // XXX: CodecPrivate for vorbis, theora, aac, native mpeg4, ...
418         if (native_id) {
419             if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA) {
420                 if (put_xiph_codecpriv(pb, codec) < 0)
421                     return -1;
422             } else if (codec->extradata_size) {
423                 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codec->extradata, codec->extradata_size);
424             }
425         }
426
427         switch (codec->codec_type) {
428             case CODEC_TYPE_VIDEO:
429                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
430
431                 if (!native_id) {
432                     offset_t bmp_header;
433                     // if there is no mkv-specific codec id, use VFW mode
434                     if (!codec->codec_tag)
435                         codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
436
437                     put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
438                     bmp_header = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
439                     put_bmp_header(pb, codec, codec_bmp_tags, 0);
440                     end_ebml_master(pb, bmp_header);
441                 }
442                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO);
443                 // XXX: interlace flag?
444                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
445                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
446                 // XXX: display width/height
447                 end_ebml_master(pb, subinfo);
448                 break;
449
450             case CODEC_TYPE_AUDIO:
451                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
452
453                 if (!native_id) {
454                     offset_t wav_header;
455                     // no mkv-specific ID, use ACM mode
456                     codec->codec_tag = codec_get_tag(codec_wav_tags, codec->codec_id);
457                     if (!codec->codec_tag) {
458                         av_log(s, AV_LOG_ERROR, "no codec id found for stream %d", i);
459                         return -1;
460                     }
461
462                     put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_AUDIO_ACM);
463                     wav_header = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
464                     put_wav_header(pb, codec);
465                     end_ebml_master(pb, wav_header);
466                 }
467                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO);
468                 put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);
469                 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
470                 if (output_sample_rate)
471                     put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
472                 if (bit_depth)
473                     put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
474                 end_ebml_master(pb, subinfo);
475                 break;
476
477                 case CODEC_TYPE_SUBTITLE:
478                     put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
479                     break;
480             default:
481                 av_log(s, AV_LOG_ERROR, "Only audio and video are supported for Matroska.");
482                 break;
483         }
484         end_ebml_master(pb, track);
485
486         // ms precision is the de-facto standard timescale for mkv files
487         av_set_pts_info(st, 64, 1, 1000);
488     }
489     end_ebml_master(pb, tracks);
490     return 0;
491 }
492
493 static int mkv_write_header(AVFormatContext *s)
494 {
495     MatroskaMuxContext *mkv = s->priv_data;
496     ByteIOContext *pb = &s->pb;
497     offset_t ebml_header, segment_info;
498
499     ebml_header = start_ebml_master(pb, EBML_ID_HEADER);
500     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
501     put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
502     put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
503     put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
504     put_ebml_string (pb, EBML_ID_DOCTYPE            ,  "matroska");
505     put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
506     put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
507     end_ebml_master(pb, ebml_header);
508
509     mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT);
510     mkv->segment_offset = url_ftell(pb);
511
512     // we write 2 seek heads - one at the end of the file to point to each cluster, and
513     // one at the beginning to point to all other level one elements (including the seek
514     // head at the end of the file), which isn't more than 10 elements if we only write one
515     // of each other currently defined level 1 element
516     mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
517     mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
518
519     if (mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb)) < 0)
520         return -1;
521
522     segment_info = start_ebml_master(pb, MATROSKA_ID_INFO);
523     put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
524     if (strlen(s->title))
525         put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
526     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
527         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
528         // XXX: both are required; something better for writing app?
529         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
530     }
531     // XXX: segment UID
532     // reserve space for the duration
533     mkv->duration = 0;
534     mkv->duration_offset = url_ftell(pb);
535     put_ebml_void(pb, 11);                  // assumes double-precision float to be written
536     end_ebml_master(pb, segment_info);
537
538     if (mkv_write_tracks(s) < 0)
539         return -1;
540
541     if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
542         return -1;
543
544     mkv->cluster_pos = url_ftell(pb);
545     mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
546     put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
547     mkv->cluster_pts = 0;
548
549     mkv->cues = mkv_start_cues(mkv->segment_offset);
550     if (mkv->cues == NULL)
551         return -1;
552
553     return 0;
554 }
555
556 static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *pkt, int flags)
557 {
558     MatroskaMuxContext *mkv = s->priv_data;
559     ByteIOContext *pb = &s->pb;
560
561     put_ebml_id(pb, blockid);
562     put_ebml_size(pb, pkt->size + 4, 0);
563     put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
564     put_be16(pb, pkt->pts - mkv->cluster_pts);
565     put_byte(pb, flags);
566     put_buffer(pb, pkt->data, pkt->size);
567 }
568
569 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
570 {
571     MatroskaMuxContext *mkv = s->priv_data;
572     ByteIOContext *pb = &s->pb;
573     AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
574     int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
575
576     // start a new cluster every 5 MB or 5 sec
577     if (url_ftell(pb) > mkv->cluster + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
578         end_ebml_master(pb, mkv->cluster);
579
580         if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
581             return -1;
582
583         mkv->cluster_pos = url_ftell(pb);
584         mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
585         put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
586         mkv->cluster_pts = pkt->pts;
587     }
588
589     if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
590         mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
591     } else {
592         offset_t blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP);
593         mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
594         put_ebml_uint(pb, MATROSKA_ID_DURATION, pkt->duration);
595         end_ebml_master(pb, blockgroup);
596     }
597
598     if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
599         if (mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos) < 0)
600             return -1;
601     }
602
603     mkv->duration = pkt->pts + pkt->duration;
604     return 0;
605 }
606
607 static int mkv_write_trailer(AVFormatContext *s)
608 {
609     MatroskaMuxContext *mkv = s->priv_data;
610     ByteIOContext *pb = &s->pb;
611     offset_t currentpos, second_seekhead, cuespos;
612
613     end_ebml_master(pb, mkv->cluster);
614
615     cuespos = mkv_write_cues(pb, mkv->cues);
616     second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
617
618     mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES    , cuespos);
619     mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
620     mkv_write_seekhead(pb, mkv->main_seekhead);
621
622     // update the duration
623     currentpos = url_ftell(pb);
624     url_fseek(pb, mkv->duration_offset, SEEK_SET);
625     put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
626     url_fseek(pb, currentpos, SEEK_SET);
627
628     end_ebml_master(pb, mkv->segment);
629     return 0;
630 }
631
632 AVOutputFormat matroska_muxer = {
633     "matroska",
634     "Matroska File Format",
635     "video/x-matroska",
636     "mkv",
637     sizeof(MatroskaMuxContext),
638     CODEC_ID_MP2,
639     CODEC_ID_MPEG4,
640     mkv_write_header,
641     mkv_write_packet,
642     mkv_write_trailer,
643     .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
644 };