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