]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/matroskaenc.c
Write codecprivate to a dynamic buffer so that seeking isn't required
[frescor/ffmpeg.git] / libavformat / matroskaenc.c
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 "md5.h"
24 #include "riff.h"
25 #include "xiph.h"
26 #include "matroska.h"
27
28 typedef struct ebml_master {
29     offset_t        pos;                ///< absolute offset in the file where the master's elements start
30     int             sizebytes;          ///< how many bytes were reserved for the size
31 } ebml_master;
32
33 typedef struct mkv_seekhead_entry {
34     unsigned int    elementid;
35     uint64_t        segmentpos;
36 } mkv_seekhead_entry;
37
38 typedef struct mkv_seekhead {
39     offset_t                filepos;
40     offset_t                segment_offset;     ///< the file offset to the beginning of the segment
41     int                     reserved_size;      ///< -1 if appending to file
42     int                     max_entries;
43     mkv_seekhead_entry      *entries;
44     int                     num_entries;
45 } mkv_seekhead;
46
47 typedef struct {
48     uint64_t        pts;
49     int             tracknum;
50     offset_t        cluster_pos;        ///< file offset of the cluster containing the block
51 } mkv_cuepoint;
52
53 typedef struct {
54     offset_t        segment_offset;
55     mkv_cuepoint    *entries;
56     int             num_entries;
57 } mkv_cues;
58
59 typedef struct MatroskaMuxContext {
60     ebml_master     segment;
61     offset_t        segment_offset;
62     offset_t        segment_uid;
63     ebml_master     cluster;
64     offset_t        cluster_pos;        ///< file offset of the current cluster
65     uint64_t        cluster_pts;
66     offset_t        duration_offset;
67     uint64_t        duration;
68     mkv_seekhead    *main_seekhead;
69     mkv_seekhead    *cluster_seekhead;
70     mkv_cues        *cues;
71
72     struct AVMD5    *md5_ctx;
73 } MatroskaMuxContext;
74
75
76 /** 2 bytes * 3 for EBML IDs, 3 1-byte EBML lengths, 8 bytes for 64 bit
77  * offset, 4 bytes for target EBML ID */
78 #define MAX_SEEKENTRY_SIZE 21
79
80 /** per-cuepoint-track - 3 1-byte EBML IDs, 3 1-byte EBML sizes, 2
81  * 8-byte uint max */
82 #define MAX_CUETRACKPOS_SIZE 22
83
84 /** per-cuepoint - 2 1-byte EBML IDs, 2 1-byte EBML sizes, 8-byte uint max */
85 #define MAX_CUEPOINT_SIZE(num_tracks) 12 + MAX_CUETRACKPOS_SIZE*num_tracks
86
87
88 static int ebml_id_size(unsigned int id)
89 {
90     return (av_log2(id+1)-1)/7+1;
91 }
92
93 static void put_ebml_id(ByteIOContext *pb, unsigned int id)
94 {
95     int i = ebml_id_size(id);
96     while (i--)
97         put_byte(pb, id >> (i*8));
98 }
99
100 /**
101  * Write an EBML size meaning "unknown size"
102  *
103  * @param bytes The number of bytes the size should occupy. Maximum of 8.
104  */
105 static void put_ebml_size_unknown(ByteIOContext *pb, int bytes)
106 {
107     assert(bytes <= 8);
108     put_byte(pb, 0x1ff >> bytes);
109     while (--bytes)
110         put_byte(pb, 0xff);
111 }
112
113 /**
114  * Calculate how many bytes are needed to represent a given size in EBML.
115  */
116 static int ebml_size_bytes(uint64_t size)
117 {
118     int bytes = 1;
119     while ((size+1) >> bytes*7) bytes++;
120     return bytes;
121 }
122
123 /**
124  * Write a size in EBML variable length format.
125  *
126  * @param bytes The number of bytes that need to be used to write the size.
127  *              If zero, any number of bytes can be used.
128  */
129 static void put_ebml_size(ByteIOContext *pb, uint64_t size, int bytes)
130 {
131     int i, needed_bytes = ebml_size_bytes(size);
132
133     // sizes larger than this are currently undefined in EBML
134     // so write "unknown" size
135     if (size >= (1ULL<<56)-1) {
136         put_ebml_size_unknown(pb, 1);
137         return;
138     }
139
140     if (bytes == 0)
141         // don't care how many bytes are used, so use the min
142         bytes = needed_bytes;
143     // the bytes needed to write the given size would exceed the bytes
144     // that we need to use, so write unknown size. This shouldn't happen.
145     assert(bytes >= needed_bytes);
146
147     size |= 1ULL << bytes*7;
148     for (i = bytes - 1; i >= 0; i--)
149         put_byte(pb, size >> i*8);
150 }
151
152 static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
153 {
154     int i, bytes = 1;
155     while (val >> bytes*8) bytes++;
156
157     put_ebml_id(pb, elementid);
158     put_ebml_size(pb, bytes, 0);
159     for (i = bytes - 1; i >= 0; i--)
160         put_byte(pb, val >> i*8);
161 }
162
163 static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
164 {
165     put_ebml_id(pb, elementid);
166     put_ebml_size(pb, 8, 0);
167     put_be64(pb, av_dbl2int(val));
168 }
169
170 static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
171                             const uint8_t *buf, int size)
172 {
173     put_ebml_id(pb, elementid);
174     put_ebml_size(pb, size, 0);
175     put_buffer(pb, buf, size);
176 }
177
178 static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
179 {
180     put_ebml_binary(pb, elementid, str, strlen(str));
181 }
182
183 /**
184  * Writes a void element of a given size. Useful for reserving space in
185  * the file to be written to later.
186  *
187  * @param size The number of bytes to reserve, which must be at least 2.
188  */
189 static void put_ebml_void(ByteIOContext *pb, uint64_t size)
190 {
191     offset_t currentpos = url_ftell(pb);
192
193     assert(size >= 2);
194
195     put_ebml_id(pb, EBML_ID_VOID);
196     // we need to subtract the length needed to store the size from the
197     // size we need to reserve so 2 cases, we use 8 bytes to store the
198     // size if possible, 1 byte otherwise
199     if (size < 10)
200         put_ebml_size(pb, size-1, 0);
201     else
202         put_ebml_size(pb, size-9, 8);
203     url_fseek(pb, currentpos + size, SEEK_SET);
204 }
205
206 static ebml_master start_ebml_master(ByteIOContext *pb, unsigned int elementid, uint64_t expectedsize)
207 {
208     int bytes = expectedsize ? ebml_size_bytes(expectedsize) : 8;
209     put_ebml_id(pb, elementid);
210     put_ebml_size_unknown(pb, bytes);
211     return (ebml_master){ url_ftell(pb), bytes };
212 }
213
214 static void end_ebml_master(ByteIOContext *pb, ebml_master master)
215 {
216     offset_t pos = url_ftell(pb);
217
218     url_fseek(pb, master.pos - master.sizebytes, SEEK_SET);
219     put_ebml_size(pb, pos - master.pos, master.sizebytes);
220     url_fseek(pb, pos, SEEK_SET);
221 }
222
223 static void put_xiph_size(ByteIOContext *pb, int size)
224 {
225     int i;
226     for (i = 0; i < size / 255; i++)
227         put_byte(pb, 255);
228     put_byte(pb, size % 255);
229 }
230
231 /**
232  * Initialize a mkv_seekhead element to be ready to index level 1 Matroska
233  * elements. If a maximum number of elements is specified, enough space
234  * will be reserved at the current file location to write a seek head of
235  * that size.
236  *
237  * @param segment_offset The absolute offset to the position in the file
238  *                       where the segment begins
239  * @param numelements the maximum number of elements that will be indexed
240  *                    by this seek head, 0 if unlimited.
241  */
242 static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, offset_t segment_offset, int numelements)
243 {
244     mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
245     if (new_seekhead == NULL)
246         return NULL;
247
248     new_seekhead->segment_offset = segment_offset;
249
250     if (numelements > 0) {
251         new_seekhead->filepos = url_ftell(pb);
252         // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID
253         // and size, and 3 bytes to guarantee that an EBML void element
254         // will fit afterwards
255         new_seekhead->reserved_size = numelements * MAX_SEEKENTRY_SIZE + 13;
256         new_seekhead->max_entries = numelements;
257         put_ebml_void(pb, new_seekhead->reserved_size);
258     }
259     return new_seekhead;
260 }
261
262 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
263 {
264     mkv_seekhead_entry *entries = seekhead->entries;
265
266     // don't store more elements than we reserved space for
267     if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
268         return -1;
269
270     entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
271     if (entries == NULL)
272         return AVERROR(ENOMEM);
273
274     entries[seekhead->num_entries  ].elementid = elementid;
275     entries[seekhead->num_entries++].segmentpos = filepos - seekhead->segment_offset;
276
277     seekhead->entries = entries;
278     return 0;
279 }
280
281 /**
282  * Write the seek head to the file and free it. If a maximum number of
283  * elements was specified to mkv_start_seekhead(), the seek head will
284  * be written at the location reserved for it. Otherwise, it is written
285  * at the current location in the file.
286  *
287  * @return the file offset where the seekhead was written
288  */
289 static offset_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
290 {
291     ebml_master metaseek, seekentry;
292     offset_t currentpos;
293     int i;
294
295     currentpos = url_ftell(pb);
296
297     if (seekhead->reserved_size > 0)
298         url_fseek(pb, seekhead->filepos, SEEK_SET);
299
300     metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD, seekhead->reserved_size);
301     for (i = 0; i < seekhead->num_entries; i++) {
302         mkv_seekhead_entry *entry = &seekhead->entries[i];
303
304         seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY, MAX_SEEKENTRY_SIZE);
305
306         put_ebml_id(pb, MATROSKA_ID_SEEKID);
307         put_ebml_size(pb, ebml_id_size(entry->elementid), 0);
308         put_ebml_id(pb, entry->elementid);
309
310         put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
311         end_ebml_master(pb, seekentry);
312     }
313     end_ebml_master(pb, metaseek);
314
315     if (seekhead->reserved_size > 0) {
316         uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
317         put_ebml_void(pb, remaining);
318         url_fseek(pb, currentpos, SEEK_SET);
319
320         currentpos = seekhead->filepos;
321     }
322     av_free(seekhead->entries);
323     av_free(seekhead);
324
325     return currentpos;
326 }
327
328 static mkv_cues * mkv_start_cues(offset_t segment_offset)
329 {
330     mkv_cues *cues = av_mallocz(sizeof(mkv_cues));
331     if (cues == NULL)
332         return NULL;
333
334     cues->segment_offset = segment_offset;
335     return cues;
336 }
337
338 static int mkv_add_cuepoint(mkv_cues *cues, AVPacket *pkt, offset_t cluster_pos)
339 {
340     mkv_cuepoint *entries = cues->entries;
341
342     entries = av_realloc(entries, (cues->num_entries + 1) * sizeof(mkv_cuepoint));
343     if (entries == NULL)
344         return AVERROR(ENOMEM);
345
346     entries[cues->num_entries  ].pts = pkt->pts;
347     entries[cues->num_entries  ].tracknum = pkt->stream_index + 1;
348     entries[cues->num_entries++].cluster_pos = cluster_pos - cues->segment_offset;
349
350     cues->entries = entries;
351     return 0;
352 }
353
354 static offset_t mkv_write_cues(ByteIOContext *pb, mkv_cues *cues, int num_tracks)
355 {
356     ebml_master cues_element;
357     offset_t currentpos;
358     int i, j;
359
360     currentpos = url_ftell(pb);
361     cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);
362
363     for (i = 0; i < cues->num_entries; i++) {
364         ebml_master cuepoint, track_positions;
365         mkv_cuepoint *entry = &cues->entries[i];
366         uint64_t pts = entry->pts;
367
368         cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));
369         put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);
370
371         // put all the entries from different tracks that have the exact same
372         // timestamp into the same CuePoint
373         for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {
374             track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);
375             put_ebml_uint(pb, MATROSKA_ID_CUETRACK          , entry[j].tracknum   );
376             put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);
377             end_ebml_master(pb, track_positions);
378         }
379         i += j - 1;
380         end_ebml_master(pb, cuepoint);
381     }
382     end_ebml_master(pb, cues_element);
383
384     av_free(cues->entries);
385     av_free(cues);
386     return currentpos;
387 }
388
389 static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
390 {
391     uint8_t *header_start[3];
392     int header_len[3];
393     int first_header_size;
394     int j;
395
396     if (codec->codec_id == CODEC_ID_VORBIS)
397         first_header_size = 30;
398     else
399         first_header_size = 42;
400
401     if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
402                               first_header_size, header_start, header_len) < 0) {
403         av_log(codec, AV_LOG_ERROR, "Extradata corrupt.\n");
404         return -1;
405     }
406
407     put_byte(pb, 2);                    // number packets - 1
408     for (j = 0; j < 2; j++) {
409         put_xiph_size(pb, header_len[j]);
410     }
411     for (j = 0; j < 3; j++)
412         put_buffer(pb, header_start[j], header_len[j]);
413
414     return 0;
415 }
416
417 #define FLAC_STREAMINFO_SIZE 34
418
419 static int put_flac_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
420 {
421     // if the extradata_size is greater than FLAC_STREAMINFO_SIZE,
422     // assume that it's in Matroska's format already
423     if (codec->extradata_size < FLAC_STREAMINFO_SIZE) {
424         av_log(codec, AV_LOG_ERROR, "Invalid FLAC extradata\n");
425         return -1;
426     } else if (codec->extradata_size == FLAC_STREAMINFO_SIZE) {
427         // only the streaminfo packet
428         put_byte(pb, 0);
429         put_xiph_size(pb, codec->extradata_size);
430         av_log(codec, AV_LOG_ERROR, "Only one packet\n");
431     }
432     put_buffer(pb, codec->extradata, codec->extradata_size);
433     return 0;
434 }
435
436 static void get_aac_sample_rates(AVCodecContext *codec, int *sample_rate, int *output_sample_rate)
437 {
438     static const int aac_sample_rates[] = {
439         96000, 88200, 64000, 48000, 44100, 32000,
440         24000, 22050, 16000, 12000, 11025,  8000,
441     };
442     int sri;
443
444     if (codec->extradata_size < 2) {
445         av_log(codec, AV_LOG_WARNING, "no AAC extradata, unable to determine samplerate\n");
446         return;
447     }
448
449     sri = ((codec->extradata[0] << 1) & 0xE) | (codec->extradata[1] >> 7);
450     if (sri > 12) {
451         av_log(codec, AV_LOG_WARNING, "AAC samplerate index out of bounds\n");
452         return;
453     }
454     *sample_rate = aac_sample_rates[sri];
455
456     // if sbr, get output sample rate as well
457     if (codec->extradata_size == 5) {
458         sri = (codec->extradata[4] >> 3) & 0xF;
459         if (sri > 12) {
460             av_log(codec, AV_LOG_WARNING, "AAC output samplerate index out of bounds\n");
461             return;
462         }
463         *output_sample_rate = aac_sample_rates[sri];
464     }
465 }
466
467 static int mkv_write_codecprivate(ByteIOContext *pb, AVCodecContext *codec, int native_id)
468 {
469     ByteIOContext dyn_cp;
470     uint8_t *codecpriv;
471     int ret = 0, codecpriv_size;
472
473     url_open_dyn_buf(&dyn_cp);
474
475     if (native_id) {
476         if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA) {
477             ret = put_xiph_codecpriv(&dyn_cp, codec);
478         } else if (codec->codec_id == CODEC_ID_FLAC) {
479             ret = put_flac_codecpriv(&dyn_cp, codec);
480         } else if (codec->extradata_size) {
481             put_buffer(&dyn_cp, codec->extradata, codec->extradata_size);
482         }
483     } else if (codec->codec_type == CODEC_TYPE_VIDEO) {
484         if (!codec->codec_tag)
485             codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
486
487         put_bmp_header(&dyn_cp, codec, codec_bmp_tags, 0);
488
489     } else if (codec->codec_type == CODEC_TYPE_AUDIO) {
490         codec->codec_tag = codec_get_tag(codec_wav_tags, codec->codec_id);
491         if (!codec->codec_tag) {
492             av_log(codec, AV_LOG_ERROR, "no wav codec id found");
493             ret = -1;
494         }
495
496         put_wav_header(&dyn_cp, codec);
497     }
498
499     codecpriv_size = url_close_dyn_buf(&dyn_cp, &codecpriv);
500     if (codecpriv_size)
501         put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv, codecpriv_size);
502     av_free(codecpriv);
503     return ret;
504 }
505
506 static int mkv_write_tracks(AVFormatContext *s)
507 {
508     MatroskaMuxContext *mkv = s->priv_data;
509     ByteIOContext *pb = &s->pb;
510     ebml_master tracks;
511     int i, j, ret;
512
513     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb));
514     if (ret < 0) return ret;
515
516     tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);
517     for (i = 0; i < s->nb_streams; i++) {
518         AVStream *st = s->streams[i];
519         AVCodecContext *codec = st->codec;
520         ebml_master subinfo, track;
521         int native_id = 0;
522         int bit_depth = av_get_bits_per_sample(codec->codec_id);
523         int sample_rate = codec->sample_rate;
524         int output_sample_rate = 0;
525
526         if (!bit_depth)
527             bit_depth = av_get_bits_per_sample_format(codec->sample_fmt);
528
529         if (codec->codec_id == CODEC_ID_AAC)
530             get_aac_sample_rates(codec, &sample_rate, &output_sample_rate);
531
532         track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);
533         put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);
534         put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);
535         put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
536
537         if (st->language[0])
538             put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
539         else
540             put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, "und");
541
542         // look for a codec id string specific to mkv to use,
543         // if none are found, use AVI codes
544         for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
545             if (ff_mkv_codec_tags[j].id == codec->codec_id) {
546                 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
547                 native_id = 1;
548                 break;
549             }
550         }
551
552         switch (codec->codec_type) {
553             case CODEC_TYPE_VIDEO:
554                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
555
556                 if (!native_id) {
557                     // if there is no mkv-specific codec id, use VFW mode
558                     put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
559                 }
560                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);
561                 // XXX: interlace flag?
562                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
563                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
564                 if (codec->sample_aspect_ratio.num) {
565                     AVRational dar = av_mul_q(codec->sample_aspect_ratio,
566                                     (AVRational){codec->width, codec->height});
567                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , dar.num);
568                     put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, dar.den);
569                 }
570                 end_ebml_master(pb, subinfo);
571                 break;
572
573             case CODEC_TYPE_AUDIO:
574                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
575
576                 if (!native_id) {
577                     // no mkv-specific ID, use ACM mode
578                     put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_AUDIO_ACM);
579                 }
580                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);
581                 put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);
582                 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);
583                 if (output_sample_rate)
584                     put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);
585                 if (bit_depth)
586                     put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);
587                 end_ebml_master(pb, subinfo);
588                 break;
589
590             case CODEC_TYPE_SUBTITLE:
591                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);
592                 break;
593             default:
594                 av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.");
595                 break;
596         }
597         ret = mkv_write_codecprivate(pb, codec, native_id);
598         if (ret < 0) return ret;
599
600         end_ebml_master(pb, track);
601
602         // ms precision is the de-facto standard timescale for mkv files
603         av_set_pts_info(st, 64, 1, 1000);
604     }
605     end_ebml_master(pb, tracks);
606     return 0;
607 }
608
609 static int mkv_write_header(AVFormatContext *s)
610 {
611     MatroskaMuxContext *mkv = s->priv_data;
612     ByteIOContext *pb = &s->pb;
613     ebml_master ebml_header, segment_info;
614     int ret;
615
616     mkv->md5_ctx = av_mallocz(av_md5_size);
617     av_md5_init(mkv->md5_ctx);
618
619     ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);
620     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
621     put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
622     put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
623     put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
624     put_ebml_string (pb, EBML_ID_DOCTYPE            ,  "matroska");
625     put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
626     put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
627     end_ebml_master(pb, ebml_header);
628
629     mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);
630     mkv->segment_offset = url_ftell(pb);
631
632     // we write 2 seek heads - one at the end of the file to point to each
633     // cluster, and one at the beginning to point to all other level one
634     // elements (including the seek head at the end of the file), which
635     // isn't more than 10 elements if we only write one of each other
636     // currently defined level 1 element
637     mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
638     mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
639     if (mkv->main_seekhead == NULL || mkv->cluster_seekhead == NULL)
640         return AVERROR(ENOMEM);
641
642     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb));
643     if (ret < 0) return ret;
644
645     segment_info = start_ebml_master(pb, MATROSKA_ID_INFO, 0);
646     put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
647     if (strlen(s->title))
648         put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
649     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
650         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , LIBAVFORMAT_IDENT);
651         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
652
653         // reserve space to write the segment UID later
654         mkv->segment_uid = url_ftell(pb);
655         put_ebml_void(pb, 19);
656     }
657
658     // reserve space for the duration
659     mkv->duration = 0;
660     mkv->duration_offset = url_ftell(pb);
661     put_ebml_void(pb, 11);                  // assumes double-precision float to be written
662     end_ebml_master(pb, segment_info);
663
664     ret = mkv_write_tracks(s);
665     if (ret < 0) return ret;
666
667     ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
668     if (ret < 0) return ret;
669
670     mkv->cluster_pos = url_ftell(pb);
671     mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
672     put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
673     mkv->cluster_pts = 0;
674
675     mkv->cues = mkv_start_cues(mkv->segment_offset);
676     if (mkv->cues == NULL)
677         return AVERROR(ENOMEM);
678
679     return 0;
680 }
681
682 static int mkv_block_size(AVPacket *pkt)
683 {
684     int size = 4;           // track num + timecode + flags
685     return size + pkt->size;
686 }
687
688 static int mkv_blockgroup_size(AVPacket *pkt)
689 {
690     int size = mkv_block_size(pkt);
691     size += ebml_size_bytes(size);
692     size += 2;              // EBML ID for block and block duration
693     size += 8;              // max size of block duration
694     size += ebml_size_bytes(size);
695     size += 1;              // blockgroup EBML ID
696     return size;
697 }
698
699 static void mkv_write_block(AVFormatContext *s, unsigned int blockid, AVPacket *pkt, int flags)
700 {
701     MatroskaMuxContext *mkv = s->priv_data;
702     ByteIOContext *pb = &s->pb;
703
704     av_log(s, AV_LOG_DEBUG, "Writing block at offset %" PRIu64 ", size %d, "
705            "pts %" PRId64 ", dts %" PRId64 ", duration %d, flags %d\n",
706            url_ftell(pb), pkt->size, pkt->pts, pkt->dts, pkt->duration, flags);
707     put_ebml_id(pb, blockid);
708     put_ebml_size(pb, mkv_block_size(pkt), 0);
709     put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
710     put_be16(pb, pkt->pts - mkv->cluster_pts);
711     put_byte(pb, flags);
712     put_buffer(pb, pkt->data, pkt->size);
713 }
714
715 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
716 {
717     MatroskaMuxContext *mkv = s->priv_data;
718     ByteIOContext *pb = &s->pb;
719     AVCodecContext *codec = s->streams[pkt->stream_index]->codec;
720     int keyframe = !!(pkt->flags & PKT_FLAG_KEY);
721     int ret;
722
723     // start a new cluster every 5 MB or 5 sec
724     if (url_ftell(pb) > mkv->cluster_pos + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
725         av_log(s, AV_LOG_DEBUG, "Starting new cluster at offset %" PRIu64
726                " bytes, pts %" PRIu64 "\n", url_ftell(pb), pkt->pts);
727         end_ebml_master(pb, mkv->cluster);
728
729         ret = mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb));
730         if (ret < 0) return ret;
731
732         mkv->cluster_pos = url_ftell(pb);
733         mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER, 0);
734         put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
735         mkv->cluster_pts = pkt->pts;
736         av_md5_update(mkv->md5_ctx, pkt->data, FFMIN(200, pkt->size));
737     }
738
739     if (codec->codec_type != CODEC_TYPE_SUBTITLE) {
740         mkv_write_block(s, MATROSKA_ID_SIMPLEBLOCK, pkt, keyframe << 7);
741     } else {
742         ebml_master blockgroup = start_ebml_master(pb, MATROSKA_ID_BLOCKGROUP, mkv_blockgroup_size(pkt));
743         mkv_write_block(s, MATROSKA_ID_BLOCK, pkt, 0);
744         put_ebml_uint(pb, MATROSKA_ID_DURATION, pkt->duration);
745         end_ebml_master(pb, blockgroup);
746     }
747
748     if (codec->codec_type == CODEC_TYPE_VIDEO && keyframe) {
749         ret = mkv_add_cuepoint(mkv->cues, pkt, mkv->cluster_pos);
750         if (ret < 0) return ret;
751     }
752
753     mkv->duration = FFMAX(mkv->duration, pkt->pts + pkt->duration);
754     return 0;
755 }
756
757 static int mkv_write_trailer(AVFormatContext *s)
758 {
759     MatroskaMuxContext *mkv = s->priv_data;
760     ByteIOContext *pb = &s->pb;
761     offset_t currentpos, second_seekhead, cuespos;
762     int ret;
763
764     end_ebml_master(pb, mkv->cluster);
765
766     cuespos = mkv_write_cues(pb, mkv->cues, s->nb_streams);
767     second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
768
769     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES    , cuespos);
770     if (ret < 0) return ret;
771     ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
772     if (ret < 0) return ret;
773     mkv_write_seekhead(pb, mkv->main_seekhead);
774
775     // update the duration
776     av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);
777     currentpos = url_ftell(pb);
778     url_fseek(pb, mkv->duration_offset, SEEK_SET);
779     put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
780
781     // write the md5sum of some frames as the segment UID
782     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
783         uint8_t segment_uid[16];
784         av_md5_final(mkv->md5_ctx, segment_uid);
785         url_fseek(pb, mkv->segment_uid, SEEK_SET);
786         put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);
787     }
788     url_fseek(pb, currentpos, SEEK_SET);
789
790     end_ebml_master(pb, mkv->segment);
791     av_free(mkv->md5_ctx);
792     return 0;
793 }
794
795 AVOutputFormat matroska_muxer = {
796     "matroska",
797     "Matroska File Format",
798     "video/x-matroska",
799     "mkv",
800     sizeof(MatroskaMuxContext),
801     CODEC_ID_MP2,
802     CODEC_ID_MPEG4,
803     mkv_write_header,
804     mkv_write_packet,
805     mkv_write_trailer,
806     .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
807     .subtitle_codec = CODEC_ID_TEXT,
808 };
809
810 AVOutputFormat matroska_audio_muxer = {
811     "matroska",
812     "Matroska File Format",
813     "audio/x-matroska",
814     "mka",
815     sizeof(MatroskaMuxContext),
816     CODEC_ID_MP2,
817     CODEC_ID_NONE,
818     mkv_write_header,
819     mkv_write_packet,
820     mkv_write_trailer,
821     .codec_tag = (const AVCodecTag*[]){codec_wav_tags, 0},
822 };