]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskaenc.c
3ded87a5d41fb298ef5f2d952d84a1a0e7091a05
[ffmpeg] / 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 MatroskaMuxContext {
42     offset_t    segment;
43     offset_t    segment_offset;
44     offset_t    cluster;
45     uint64_t    cluster_pts;
46     offset_t    duration_offset;
47     uint64_t    duration;
48     mkv_seekhead    *main_seekhead;
49     mkv_seekhead    *cluster_seekhead;
50 } MatroskaMuxContext;
51
52 static void put_ebml_id(ByteIOContext *pb, unsigned int id)
53 {
54     if (id >= 0x3fffff)
55         put_byte(pb, id >> 24);
56     if (id >= 0x7fff)
57         put_byte(pb, id >> 16);
58     if (id >= 0xff)
59         put_byte(pb, id >> 8);
60     put_byte(pb, id);
61 }
62
63 static int ebml_id_size(unsigned int id)
64 {
65     if (id >= 0x3fffff)
66         return 4;
67     if (id >= 0x7fff)
68         return 3;
69     if (id >= 0xff)
70         return 2;
71     return 1;
72 }
73
74 // XXX: test this thoroughly and get rid of minbytes hack (currently needed to
75 // use up all of the space reserved in start_ebml_master)
76 static void put_ebml_size(ByteIOContext *pb, uint64_t size, int minbytes)
77 {
78     int bytes = minbytes;
79
80     // sizes larger than this are currently undefined in EBML
81     // so write "unknown" size
82     size = FFMIN(size, (1ULL<<56)-1);
83
84     while (size >> (bytes*7 + 7)) bytes++;
85
86     put_byte(pb, (0x80 >> bytes) | (size >> bytes*8));
87     for (bytes -= 1; bytes >= 0; bytes--)
88         put_byte(pb, size >> bytes*8);
89 }
90
91 static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
92 {
93     int bytes = 1;
94     while (val >> bytes*8) bytes++;
95
96     put_ebml_id(pb, elementid);
97     put_ebml_size(pb, bytes, 0);
98     for (bytes -= 1; bytes >= 0; bytes--)
99         put_byte(pb, val >> bytes*8);
100 }
101
102 static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
103 {
104     // XXX: single-precision floats?
105     put_ebml_id(pb, elementid);
106     put_ebml_size(pb, 8, 0);
107     put_be64(pb, av_dbl2int(val));
108 }
109
110 static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
111                             const uint8_t *buf, int size)
112 {
113     put_ebml_id(pb, elementid);
114     put_ebml_size(pb, size, 0);
115     put_buffer(pb, buf, size);
116 }
117
118 static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
119 {
120     put_ebml_binary(pb, elementid, str, strlen(str));
121 }
122
123 // this reserves exactly the amount of space specified by size, which must be at least 2
124 static void put_ebml_void(ByteIOContext *pb, uint64_t size)
125 {
126     offset_t currentpos = url_ftell(pb);
127
128     if (size < 2)
129         return;
130
131     put_ebml_id(pb, EBML_ID_VOID);
132     // we need to subtract the length needed to store the size from the size we need to reserve
133     // so 2 cases, we use 8 bytes to store the size if possible, 1 byte otherwise
134     if (size < 10)
135         put_ebml_size(pb, size-1, 0);
136     else
137         put_ebml_size(pb, size-9, 7);
138     url_fseek(pb, currentpos + size, SEEK_SET);
139 }
140
141 static offset_t start_ebml_master(ByteIOContext *pb, unsigned int elementid)
142 {
143     put_ebml_id(pb, elementid);
144     // XXX: this always reserves the maximum needed space to store any size value
145     // we should be smarter (additional parameter for expected size?)
146     put_ebml_size(pb, (1ULL<<56)-1, 0);     // largest unknown size
147     return url_ftell(pb);
148 }
149
150 static void end_ebml_master(ByteIOContext *pb, offset_t start)
151 {
152     offset_t pos = url_ftell(pb);
153
154     url_fseek(pb, start - 8, SEEK_SET);
155     put_ebml_size(pb, pos - start, 7);
156     url_fseek(pb, pos, SEEK_SET);
157 }
158
159 // initializes a mkv_seekhead element to be ready to index level 1 matroska elements
160 // if numelements is greater than 0, it reserves enough space for that many elements
161 // at the current file position and writes the seekhead there, otherwise the seekhead
162 // will be appended to the file when end_mkv_seekhead() is called
163 static mkv_seekhead * mkv_start_seekhead(ByteIOContext *pb, offset_t segment_offset, int numelements)
164 {
165     mkv_seekhead *new_seekhead = av_mallocz(sizeof(mkv_seekhead));
166     if (new_seekhead == NULL)
167         return NULL;
168
169     new_seekhead->segment_offset = segment_offset;
170
171     if (numelements > 0) {
172         new_seekhead->filepos = url_ftell(pb);
173         // 21 bytes max for a seek entry, 10 bytes max for the SeekHead ID and size,
174         // and 3 bytes to guarantee that an EBML void element will fit afterwards
175         // XXX: 28 bytes right now because begin_ebml_master() reserves more than necessary
176         new_seekhead->reserved_size = numelements * 28 + 13;
177         new_seekhead->max_entries = numelements;
178         put_ebml_void(pb, new_seekhead->reserved_size);
179     }
180     return new_seekhead;
181 }
182
183 static int mkv_add_seekhead_entry(mkv_seekhead *seekhead, unsigned int elementid, uint64_t filepos)
184 {
185     mkv_seekhead_entry *entries = seekhead->entries;
186     int new_entry = seekhead->num_entries;
187
188     // don't store more elements than we reserved space for
189     if (seekhead->max_entries > 0 && seekhead->max_entries <= seekhead->num_entries)
190         return -1;
191
192     entries = av_realloc(entries, (seekhead->num_entries + 1) * sizeof(mkv_seekhead_entry));
193     if (entries == NULL)
194         return -1;
195
196     entries[new_entry].elementid = elementid;
197     entries[new_entry].segmentpos = filepos - seekhead->segment_offset;
198
199     seekhead->entries = entries;
200     seekhead->num_entries++;
201
202     return 0;
203 }
204
205 // returns the file offset where the seekhead was written and frees the seekhead
206 static offset_t mkv_write_seekhead(ByteIOContext *pb, mkv_seekhead *seekhead)
207 {
208     offset_t metaseek, seekentry, currentpos;
209     int i;
210
211     currentpos = url_ftell(pb);
212
213     if (seekhead->reserved_size > 0)
214         url_fseek(pb, seekhead->filepos, SEEK_SET);
215
216     metaseek = start_ebml_master(pb, MATROSKA_ID_SEEKHEAD);
217     for (i = 0; i < seekhead->num_entries; i++) {
218         mkv_seekhead_entry *entry = &seekhead->entries[i];
219
220         seekentry = start_ebml_master(pb, MATROSKA_ID_SEEKENTRY);
221
222         put_ebml_id(pb, MATROSKA_ID_SEEKID);
223         put_ebml_size(pb, ebml_id_size(entry->elementid), 0);
224         put_ebml_id(pb, entry->elementid);
225
226         put_ebml_uint(pb, MATROSKA_ID_SEEKPOSITION, entry->segmentpos);
227         end_ebml_master(pb, seekentry);
228     }
229     end_ebml_master(pb, metaseek);
230
231     if (seekhead->reserved_size > 0) {
232         uint64_t remaining = seekhead->filepos + seekhead->reserved_size - url_ftell(pb);
233         put_ebml_void(pb, remaining);
234         url_fseek(pb, currentpos, SEEK_SET);
235
236         currentpos = seekhead->filepos;
237     }
238     av_free(seekhead->entries);
239     av_free(seekhead);
240
241     return currentpos;
242 }
243
244 static int put_xiph_codecpriv(ByteIOContext *pb, AVCodecContext *codec)
245 {
246     offset_t codecprivate;
247     uint8_t *header_start[3];
248     int header_len[3];
249     int first_header_size;
250     int j, k;
251
252     if (codec->codec_id == CODEC_ID_VORBIS)
253         first_header_size = 30;
254     else
255         first_header_size = 42;
256
257     if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
258                               first_header_size, header_start, header_len) < 0) {
259         av_log(codec, AV_LOG_ERROR, "Extradata corrupt.\n");
260         return -1;
261     }
262
263     codecprivate = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
264     put_byte(pb, 2);                    // number packets - 1
265     for (j = 0; j < 2; j++) {
266         for (k = 0; k < header_len[j] / 255; k++)
267             put_byte(pb, 255);
268         put_byte(pb, header_len[j] % 255);
269     }
270     for (j = 0; j < 3; j++)
271         put_buffer(pb, header_start[j], header_len[j]);
272     end_ebml_master(pb, codecprivate);
273
274     return 0;
275 }
276
277 static int mkv_write_tracks(AVFormatContext *s)
278 {
279     MatroskaMuxContext *mkv = s->priv_data;
280     ByteIOContext *pb = &s->pb;
281     offset_t tracks;
282     int i, j;
283
284     if (mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, url_ftell(pb)) < 0)
285         return -1;
286
287     tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS);
288     for (i = 0; i < s->nb_streams; i++) {
289         AVStream *st = s->streams[i];
290         AVCodecContext *codec = st->codec;
291         offset_t subinfo, track;
292         int native_id = 0;
293
294         track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY);
295         put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);
296         put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);
297         put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
298
299         if (st->language[0])
300             put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
301
302         // look for a codec id string specific to mkv to use, if none are found, use AVI codes
303         for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
304             if (ff_mkv_codec_tags[j].id == codec->codec_id) {
305                 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
306                 native_id = 1;
307                 break;
308             }
309         }
310
311         // XXX: CodecPrivate for vorbis, theora, aac, native mpeg4, ...
312         if (native_id) {
313             if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA) {
314                 if (put_xiph_codecpriv(pb, codec) < 0)
315                     return -1;
316             } else {
317                 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codec->extradata, codec->extradata_size);
318             }
319         }
320
321         switch (codec->codec_type) {
322             case CODEC_TYPE_VIDEO:
323                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
324
325                 if (!native_id) {
326                     offset_t bmp_header;
327                     // if there is no mkv-specific codec id, use VFW mode
328                     if (!codec->codec_tag)
329                         codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
330
331                     put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
332                     // XXX: codec private isn't a master; is there a better way to re-use put_bmp_header?
333                     bmp_header = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
334                     put_bmp_header(pb, codec, codec_bmp_tags, 0);
335                     end_ebml_master(pb, bmp_header);
336                 }
337                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO);
338                 // XXX: interlace flag?
339                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
340                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
341                 // XXX: display width/height
342                 end_ebml_master(pb, subinfo);
343                 break;
344
345             case CODEC_TYPE_AUDIO:
346                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
347
348                 // XXX: A_MS/ACM
349                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO);
350                 put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);
351                 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, codec->sample_rate);
352                 // XXX: output sample freq (for sbr) and bitdepth (for pcm)
353                 end_ebml_master(pb, subinfo);
354                 break;
355
356             default:
357                 av_log(s, AV_LOG_ERROR, "Only audio and video are supported for Matroska.");
358                 break;
359         }
360         end_ebml_master(pb, track);
361
362         // ms precision is the de-facto standard timescale for mkv files
363         av_set_pts_info(st, 64, 1, 1000);
364     }
365     end_ebml_master(pb, tracks);
366     return 0;
367 }
368
369 static int mkv_write_header(AVFormatContext *s)
370 {
371     MatroskaMuxContext *mkv = s->priv_data;
372     ByteIOContext *pb = &s->pb;
373     offset_t ebml_header, segment_info;
374
375     ebml_header = start_ebml_master(pb, EBML_ID_HEADER);
376     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
377     put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
378     put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
379     put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
380     put_ebml_string (pb, EBML_ID_DOCTYPE            ,  "matroska");
381     put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
382     put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
383     end_ebml_master(pb, ebml_header);
384
385     mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT);
386     mkv->segment_offset = url_ftell(pb);
387
388     // we write 2 seek heads - one at the end of the file to point to each cluster, and
389     // one at the beginning to point to all other level one elements (including the seek
390     // head at the end of the file), which isn't more than 10 elements if we only write one
391     // of each other currently defined level 1 element
392     mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);
393     mkv->cluster_seekhead = mkv_start_seekhead(pb, mkv->segment_offset, 0);
394
395     if (mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, url_ftell(pb)) < 0)
396         return -1;
397
398     segment_info = start_ebml_master(pb, MATROSKA_ID_INFO);
399     put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
400     if (strlen(s->title))
401         put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
402     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
403         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
404         // XXX: both are required; something better for writing app?
405         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
406     }
407     // XXX: segment UID
408     // reserve space for the duration
409     mkv->duration = 0;
410     mkv->duration_offset = url_ftell(pb);
411     put_ebml_void(pb, 11);                  // assumes double-precision float to be written
412     end_ebml_master(pb, segment_info);
413
414     if (mkv_write_tracks(s) < 0)
415         return -1;
416
417     if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
418         return -1;
419
420     mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
421     put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
422     mkv->cluster_pts = 0;
423
424     return 0;
425 }
426
427 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
428 {
429     MatroskaMuxContext *mkv = s->priv_data;
430     ByteIOContext *pb = &s->pb;
431     offset_t block;
432
433     // start a new cluster every 5 MB or 5 sec
434     if (url_ftell(pb) > mkv->cluster + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
435         end_ebml_master(pb, mkv->cluster);
436
437         if (mkv_add_seekhead_entry(mkv->cluster_seekhead, MATROSKA_ID_CLUSTER, url_ftell(pb)) < 0)
438             return -1;
439
440         mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
441         put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
442         mkv->cluster_pts = pkt->pts;
443     }
444
445     block = start_ebml_master(pb, MATROSKA_ID_SIMPLEBLOCK);
446     put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
447     put_be16(pb, pkt->pts - mkv->cluster_pts);
448     put_byte(pb, !!(pkt->flags & PKT_FLAG_KEY));
449     put_buffer(pb, pkt->data, pkt->size);
450     end_ebml_master(pb, block);
451
452     mkv->duration = pkt->pts + pkt->duration;
453     return 0;
454 }
455
456 static int mkv_write_trailer(AVFormatContext *s)
457 {
458     MatroskaMuxContext *mkv = s->priv_data;
459     ByteIOContext *pb = &s->pb;
460     offset_t currentpos, second_seekhead;
461
462     end_ebml_master(pb, mkv->cluster);
463
464     second_seekhead = mkv_write_seekhead(pb, mkv->cluster_seekhead);
465     mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_SEEKHEAD, second_seekhead);
466     mkv_write_seekhead(pb, mkv->main_seekhead);
467
468     // update the duration
469     currentpos = url_ftell(pb);
470     url_fseek(pb, mkv->duration_offset, SEEK_SET);
471     put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);
472     url_fseek(pb, currentpos, SEEK_SET);
473
474     end_ebml_master(pb, mkv->segment);
475     return 0;
476 }
477
478 AVOutputFormat matroska_muxer = {
479     "matroska",
480     "Matroska File Format",
481     "video/x-matroska",
482     "mkv",
483     sizeof(MatroskaMuxContext),
484     CODEC_ID_MP2,
485     CODEC_ID_MPEG4,
486     mkv_write_header,
487     mkv_write_packet,
488     mkv_write_trailer,
489     .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
490 };