]> git.sesse.net Git - ffmpeg/blob - libavformat/matroskaenc.c
put_ebml_void()
[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 MatroskaMuxContext {
28     offset_t    segment;
29     offset_t    cluster;
30     uint64_t    cluster_pts;
31 } MatroskaMuxContext;
32
33 static void put_ebml_id(ByteIOContext *pb, unsigned int id)
34 {
35     if (id >= 0x3fffff)
36         put_byte(pb, id >> 24);
37     if (id >= 0x7fff)
38         put_byte(pb, id >> 16);
39     if (id >= 0xff)
40         put_byte(pb, id >> 8);
41     put_byte(pb, id);
42 }
43
44 // XXX: test this thoroughly and get rid of minbytes hack (currently needed to
45 // use up all of the space reserved in start_ebml_master)
46 static void put_ebml_size(ByteIOContext *pb, uint64_t size, int minbytes)
47 {
48     int bytes = minbytes;
49
50     // sizes larger than this are currently undefined in EBML
51     // so write "unknown" size
52     size = FFMIN(size, (1ULL<<56)-1);
53
54     while (size >> (bytes*7 + 7)) bytes++;
55
56     put_byte(pb, (0x80 >> bytes) | (size >> bytes*8));
57     for (bytes -= 1; bytes >= 0; bytes--)
58         put_byte(pb, size >> bytes*8);
59 }
60
61 static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)
62 {
63     int bytes = 1;
64     while (val >> bytes*8) bytes++;
65
66     put_ebml_id(pb, elementid);
67     put_ebml_size(pb, bytes, 0);
68     for (bytes -= 1; bytes >= 0; bytes--)
69         put_byte(pb, val >> bytes*8);
70 }
71
72 static void put_ebml_float(ByteIOContext *pb, unsigned int elementid, double val)
73 {
74     // XXX: single-precision floats?
75     put_ebml_id(pb, elementid);
76     put_ebml_size(pb, 8, 0);
77     put_be64(pb, av_dbl2int(val));
78 }
79
80 static void put_ebml_binary(ByteIOContext *pb, unsigned int elementid,
81                             const uint8_t *buf, int size)
82 {
83     put_ebml_id(pb, elementid);
84     put_ebml_size(pb, size, 0);
85     put_buffer(pb, buf, size);
86 }
87
88 static void put_ebml_string(ByteIOContext *pb, unsigned int elementid, const char *str)
89 {
90     put_ebml_binary(pb, elementid, str, strlen(str));
91 }
92
93 // this reserves exactly the amount of space specified by size, which must be at least 2
94 static void put_ebml_void(ByteIOContext *pb, uint64_t size)
95 {
96     offset_t currentpos = url_ftell(pb);
97
98     if (size < 2)
99         return;
100
101     put_ebml_id(pb, EBML_ID_VOID);
102     // we need to subtract the length needed to store the size from the size we need to reserve
103     // so 2 cases, we use 8 bytes to store the size if possible, 1 byte otherwise
104     if (size < 10)
105         put_ebml_size(pb, size-1, 0);
106     else
107         put_ebml_size(pb, size-9, 7);
108     url_fseek(pb, currentpos + size, SEEK_SET);
109 }
110
111 static offset_t start_ebml_master(ByteIOContext *pb, unsigned int elementid)
112 {
113     put_ebml_id(pb, elementid);
114     // XXX: this always reserves the maximum needed space to store any size value
115     // we should be smarter (additional parameter for expected size?)
116     put_ebml_size(pb, (1ULL<<56)-1, 0);     // largest unknown size
117     return url_ftell(pb);
118 }
119
120 static void end_ebml_master(ByteIOContext *pb, offset_t start)
121 {
122     offset_t pos = url_ftell(pb);
123
124     url_fseek(pb, start - 8, SEEK_SET);
125     put_ebml_size(pb, pos - start, 7);
126     url_fseek(pb, pos, SEEK_SET);
127 }
128
129
130 static int mkv_write_header(AVFormatContext *s)
131 {
132     MatroskaMuxContext *mkv = s->priv_data;
133     ByteIOContext *pb = &s->pb;
134     offset_t ebml_header, segment_info, tracks;
135     int i, j, k;
136
137     ebml_header = start_ebml_master(pb, EBML_ID_HEADER);
138     put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);
139     put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);
140     put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);
141     put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);
142     put_ebml_string (pb, EBML_ID_DOCTYPE            ,  "matroska");
143     put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,           2);
144     put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);
145     end_ebml_master(pb, ebml_header);
146
147     mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT);
148
149     segment_info = start_ebml_master(pb, MATROSKA_ID_INFO);
150     put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);
151     if (strlen(s->title))
152         put_ebml_string(pb, MATROSKA_ID_TITLE, s->title);
153     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
154         put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);
155         // XXX: both are required; something better for writing app?
156         put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);
157     }
158     // XXX: segment UID and duration
159     end_ebml_master(pb, segment_info);
160
161     tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS);
162     for (i = 0; i < s->nb_streams; i++) {
163         AVStream *st = s->streams[i];
164         AVCodecContext *codec = st->codec;
165         offset_t subinfo, track;
166         int native_id = 0;
167
168         track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY);
169         put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);
170         put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);
171         put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)
172
173         if (st->language[0])
174             put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, st->language);
175
176         // look for a codec id string specific to mkv to use, if none are found, use AVI codes
177         for (j = 0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++) {
178             if (ff_mkv_codec_tags[j].id == codec->codec_id) {
179                 put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);
180                 native_id = 1;
181                 break;
182             }
183         }
184
185         // XXX: CodecPrivate for vorbis, theora, aac, native mpeg4, ...
186         if (native_id) {
187             offset_t codecprivate;
188
189             if (codec->codec_id == CODEC_ID_VORBIS || codec->codec_id == CODEC_ID_THEORA) {
190                 uint8_t *header_start[3];
191                 int header_len[3];
192                 int first_header_size;
193
194                 if (codec->codec_id == CODEC_ID_VORBIS)
195                     first_header_size = 30;
196                 else
197                     first_header_size = 42;
198
199                 if (ff_split_xiph_headers(codec->extradata, codec->extradata_size,
200                                           first_header_size, header_start, header_len) < 0) {
201                     av_log(s, AV_LOG_ERROR, "Extradata corrupt.\n");
202                     return -1;
203                 }
204
205                 codecprivate = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
206                 put_byte(pb, 2);                    // number packets - 1
207                 for (j = 0; j < 2; j++) {
208                     for (k = 0; k < header_len[j] / 255; k++)
209                         put_byte(pb, 255);
210                     put_byte(pb, header_len[j] % 255);
211                 }
212                 for (j = 0; j < 3; j++)
213                     put_buffer(pb, header_start[j], header_len[j]);
214                 end_ebml_master(pb, codecprivate);
215             } else {
216                 put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codec->extradata, codec->extradata_size);
217             }
218         }
219
220         switch (codec->codec_type) {
221             case CODEC_TYPE_VIDEO:
222                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);
223
224                 if (!native_id) {
225                     offset_t bmp_header;
226                     // if there is no mkv-specific codec id, use VFW mode
227                     if (!codec->codec_tag)
228                         codec->codec_tag = codec_get_tag(codec_bmp_tags, codec->codec_id);
229
230                     put_ebml_string(pb, MATROSKA_ID_CODECID, MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC);
231                     // XXX: codec private isn't a master; is there a better way to re-use put_bmp_header?
232                     bmp_header = start_ebml_master(pb, MATROSKA_ID_CODECPRIVATE);
233                     put_bmp_header(pb, codec, codec_bmp_tags, 0);
234                     end_ebml_master(pb, bmp_header);
235                 }
236                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO);
237                 // XXX: interlace flag?
238                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);
239                 put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);
240                 // XXX: display width/height
241                 end_ebml_master(pb, subinfo);
242                 break;
243
244             case CODEC_TYPE_AUDIO:
245                 put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);
246
247                 // XXX: A_MS/ACM
248                 subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO);
249                 put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);
250                 put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, codec->sample_rate);
251                 // XXX: output sample freq (for sbr) and bitdepth (for pcm)
252                 end_ebml_master(pb, subinfo);
253                 break;
254
255             default:
256                 av_log(s, AV_LOG_ERROR, "Only audio and video are supported for Matroska.");
257                 break;
258         }
259         end_ebml_master(pb, track);
260
261         // ms precision is the de-facto standard timescale for mkv files
262         av_set_pts_info(st, 64, 1, 1000);
263     }
264     end_ebml_master(pb, tracks);
265
266     mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
267     put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, 0);
268     mkv->cluster_pts = 0;
269
270     return 0;
271 }
272
273 static int mkv_write_packet(AVFormatContext *s, AVPacket *pkt)
274 {
275     MatroskaMuxContext *mkv = s->priv_data;
276     ByteIOContext *pb = &s->pb;
277     offset_t block;
278
279     // start a new cluster every 5 MB or 5 sec
280     if (url_ftell(pb) > mkv->cluster + 5*1024*1024 || pkt->pts > mkv->cluster_pts + 5000) {
281         end_ebml_master(pb, mkv->cluster);
282         mkv->cluster = start_ebml_master(pb, MATROSKA_ID_CLUSTER);
283         put_ebml_uint(pb, MATROSKA_ID_CLUSTERTIMECODE, pkt->pts);
284         mkv->cluster_pts = pkt->pts;
285     }
286
287     block = start_ebml_master(pb, MATROSKA_ID_SIMPLEBLOCK);
288     put_byte(pb, 0x80 | (pkt->stream_index + 1));     // this assumes stream_index is less than 126
289     put_be16(pb, pkt->pts - mkv->cluster_pts);
290     put_byte(pb, !!(pkt->flags & PKT_FLAG_KEY));
291     put_buffer(pb, pkt->data, pkt->size);
292     end_ebml_master(pb, block);
293     return 0;
294 }
295
296 static int mkv_write_trailer(AVFormatContext *s)
297 {
298     MatroskaMuxContext *mkv = s->priv_data;
299     ByteIOContext *pb = &s->pb;
300     end_ebml_master(pb, mkv->cluster);
301     end_ebml_master(pb, mkv->segment);
302     return 0;
303 }
304
305 AVOutputFormat matroska_muxer = {
306     "matroska",
307     "Matroska File Format",
308     "video/x-matroska",
309     "mkv",
310     sizeof(MatroskaMuxContext),
311     CODEC_ID_MP2,
312     CODEC_ID_MPEG4,
313     mkv_write_header,
314     mkv_write_packet,
315     mkv_write_trailer,
316     .codec_tag = (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
317 };