Switch to calloc in mk_createWriter, so we don't have to do a memset.
[libmkv.git] / src / matroska.c
blob4b10c001f201ab0d467181490aa1cf26696a3cdc
1 /*****************************************************************************
2 * matroska.c:
3 *****************************************************************************
4 * Copyright (C) 2005 x264 project
5 * $Id: $
7 * Authors: Mike Matsnev
8 * Nathan Caldwell
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
23 *****************************************************************************/
24 #include "libmkv.h"
25 #include "matroska.h"
26 #include "config.h"
28 int mk_writeVoid(mk_Context *c, uint64_t length) {
29 char *c_void = calloc(length, sizeof(char));
31 CHECK(mk_writeID(c, 0xec));
32 CHECK(mk_writeSize(c, length));
33 CHECK(mk_appendContextData(c, c_void, length));
34 free(c_void);
35 return 0;
38 char *mk_laceXiph(uint64_t *sizes, uint8_t num_frames, uint64_t *output_size) {
39 unsigned i, j;
40 uint64_t offset = 0;
41 uint64_t alloc_size = num_frames * 6; // Complete guess. We'll realloc if we need more space, though.
42 char *laced = calloc(alloc_size, sizeof(char));
43 if (laced == NULL)
44 return NULL;
46 laced[offset++] = num_frames;
47 for (i = 0; i < num_frames; i++)
49 for (j = sizes[i]; j >= 255 ; j -= 255)
51 laced[offset++] = 255;
52 if (offset + 1 >= alloc_size) {
53 int avg_sz = offset / (i - 1); // Compute approximate average bytes/frame
54 alloc_size += avg_sz * (num_frames - i); // Add our average + number of frames left to size
55 if ((laced = realloc(laced, alloc_size)) == NULL)
56 return NULL;
59 laced[offset++] = j;
62 if (output_size != NULL)
63 *output_size = offset;
65 return laced;
68 mk_Writer *mk_createWriter(const char *filename, int64_t timescale, uint8_t vlc_compat) {
69 mk_Writer *w = calloc(1, sizeof(*w));
70 if (w == NULL)
71 return NULL;
73 w->root = mk_createContext(w, NULL, 0);
74 if (w->root == NULL) {
75 free(w);
76 return NULL;
79 if ((w->cues = mk_createContext(w, w->root, 0x1c53bb6b)) == NULL) // Cues
81 mk_destroyContexts(w);
82 free(w);
83 return NULL;
86 w->fp = fopen(filename, "wb");
87 if (w->fp == NULL) {
88 mk_destroyContexts(w);
89 free(w);
90 return NULL;
93 w->timescale = timescale;
94 w->vlc_compat = vlc_compat;
96 return w;
99 int mk_writeHeader(mk_Writer *w, const char *writingApp) {
100 mk_Context *c;
102 if (w->wrote_header)
103 return -1;
105 if ((c = mk_createContext(w, w->root, 0x1a45dfa3)) == NULL) // EBML
106 return -1;
107 CHECK(mk_writeUInt(c, 0x4286, 1)); // EBMLVersion
108 CHECK(mk_writeUInt(c, 0x42f7, 1)); // EBMLReadVersion
109 CHECK(mk_writeUInt(c, 0x42f2, 4)); // EBMLMaxIDLength
110 CHECK(mk_writeUInt(c, 0x42f3, 8)); // EBMLMaxSizeLength
111 CHECK(mk_writeStr(c, 0x4282, "matroska")); // DocType
112 CHECK(mk_writeUInt(c, 0x4287, 1)); // DocTypeVersion
113 CHECK(mk_writeUInt(c, 0x4285, 1)); // DocTypeReadversion
114 CHECK(mk_closeContext(c, 0));
116 if ((c = mk_createContext(w, w->root, 0x18538067)) == NULL) // Segment
117 return -1;
118 CHECK(mk_flushContextID(c));
119 w->segment_ptr = c->d_cur;
120 CHECK(mk_closeContext(c, &w->segment_ptr));
122 if (w->vlc_compat)
124 CHECK(mk_writeVoid(w->root, 0x100)); // 256 bytes should be enough room for our Seek entries.
125 CHECK(mk_writeVoid(w->root, 0x800)); // 2048 bytes for Chapters.
126 CHECK(mk_writeVoid(w->root, 0x1000)); // 4096 bytes for Cues.
127 } else
129 w->seek_data.seekhead = 0x80000000;
130 CHECK(mk_writeSeek(w, &w->seekhead_ptr));
131 w->seek_data.seekhead = 0;
134 if ((c = mk_createContext(w, w->root, 0x1549a966)) == NULL) // SegmentInfo
135 return -1;
136 w->seek_data.segmentinfo = w->root->d_cur - w->segment_ptr;
137 CHECK(mk_writeStr(c, 0x4d80, PACKAGE_STRING)); // MuxingApp
138 CHECK(mk_writeStr(c, 0x5741, writingApp)); // WritingApp
139 CHECK(mk_writeUInt(c, 0x2ad7b1, w->timescale)); // TimecodeScale
140 CHECK(mk_writeFloat(c, 0x4489, 0)); // Duration
141 w->duration_ptr = c->d_cur - 4;
142 CHECK(mk_closeContext(c, &w->duration_ptr));
144 w->seek_data.tracks = w->root->d_cur - w->segment_ptr;
146 if (w->tracks) {
147 CHECK(mk_closeContext(w->tracks, 0));
150 CHECK(mk_flushContextData(w->root));
152 w->wrote_header = 1;
153 w->def_duration = w->tracks_arr[0]->default_duration;
154 return 0;
157 static int mk_closeCluster(mk_Writer *w) {
158 if (w->cluster.context == NULL)
159 return 0;
160 w->cluster.count++;
161 CHECK(mk_closeContext(w->cluster.context, 0));
162 w->cluster.context = NULL;
163 CHECK(mk_flushContextData(w->root));
164 return 0;
167 int mk_flushFrame(mk_Writer *w, mk_Track *track) {
168 mk_Context *c;
169 int64_t delta, ref = 0;
170 unsigned fsize, bgsize;
171 uint8_t flags, c_delta_flags[2];
172 int i;
173 char *laced = NULL;
174 uint64_t length = 0;
176 if (!track->in_frame)
177 return 0;
179 delta = track->frame.timecode/w->timescale - w->cluster.tc_scaled;
180 if (delta > 32767ll || delta < -32768ll)
181 CHECK(mk_closeCluster(w));
183 if (w->cluster.context == NULL) {
184 w->cluster.tc_scaled = track->frame.timecode / w->timescale;
185 w->cluster.context = mk_createContext(w, w->root, 0x1f43b675); // Cluster
186 if (w->cluster.context == NULL)
187 return -1;
189 w->cluster.pointer = ftell(w->fp) - w->segment_ptr;
191 CHECK(mk_writeUInt(w->cluster.context, 0xe7, w->cluster.tc_scaled)); // Cluster Timecode
193 delta = 0;
194 w->cluster.block_count = 0;
196 if ((w->cluster.count % 15) == 0) {
197 for(i = 0; i < w->num_tracks; i++)
198 w->tracks_arr[i]->cue_flag = 1;
202 fsize = track->frame.data ? track->frame.data->d_cur : 0;
203 bgsize = fsize + 4 + mk_ebmlSizeSize(fsize + 4) + 1;
204 if (!track->frame.keyframe) {
205 ref = track->prev_frame_tc_scaled - w->cluster.tc_scaled - delta;
206 bgsize += 1 + 1 + mk_ebmlSIntSize(ref);
209 CHECK(mk_writeID(w->cluster.context, 0xa0)); // BlockGroup
210 CHECK(mk_writeSize(w->cluster.context, bgsize));
211 CHECK(mk_writeID(w->cluster.context, 0xa1)); // Block
213 switch (track->frame.lacing) {
214 case MK_LACING_XIPH:
215 laced = mk_laceXiph(track->frame.lacing_sizes, track->frame.lacing_num_frames, &length);
216 break;
217 case MK_LACING_EBML:
218 length += mk_ebmlSizeSize(track->frame.lacing_sizes[0]) + 1;
219 for (i = 1; i < track->frame.lacing_num_frames; i++)
220 length += mk_ebmlSizeSize(track->frame.lacing_sizes[i] << 1);
221 break;
222 case MK_LACING_FIXED:
224 laced = calloc(1, sizeof(char));
225 laced[0] = track->frame.lacing_num_frames;
226 ++length;
228 break;
231 CHECK(mk_writeSize(w->cluster.context, fsize + 4 + length));
232 CHECK(mk_writeSize(w->cluster.context, track->track_id)); // track number
234 w->cluster.block_count++;
236 c_delta_flags[0] = delta >> 8;
237 c_delta_flags[1] = delta;
238 CHECK(mk_appendContextData(w->cluster.context, c_delta_flags, 2));
240 flags = ( track->frame.keyframe << 8 ) | track->frame.lacing;
241 CHECK(mk_appendContextData(w->cluster.context, &flags, 1));
242 if (track->frame.lacing) {
243 if (track->frame.lacing == MK_LACING_EBML) {
244 CHECK(mk_appendContextData(w->cluster.context, &track->frame.lacing_num_frames, 1));
245 CHECK(mk_writeSize(w->cluster.context, track->frame.lacing_sizes[0]));
246 for (i = 1; i < track->frame.lacing_num_frames; i++)
248 CHECK(mk_writeSSize(w->cluster.context, track->frame.lacing_sizes[i] - track->frame.lacing_sizes[i-1]));
250 } else if (length > 0 && laced != NULL) {
251 CHECK(mk_appendContextData(w->cluster.context, laced, length));
252 free(laced);
253 laced = NULL;
257 if (track->frame.data) {
258 CHECK(mk_appendContextData(w->cluster.context, track->frame.data->data, track->frame.data->d_cur));
259 track->frame.data->d_cur = 0;
261 if (!track->frame.keyframe)
262 CHECK(mk_writeSInt(w->cluster.context, 0xfb, ref)); // ReferenceBlock
264 if (track->cue_flag && track->frame.keyframe) {
265 if (w->cue_point.timecode != track->frame.timecode) {
266 if (w->cue_point.context != NULL) {
267 CHECK(mk_closeContext(w->cue_point.context, 0));
268 w->cue_point.context = NULL;
271 if (w->cue_point.context == NULL) {
272 if ((w->cue_point.context = mk_createContext(w, w->cues, 0xbb)) == NULL) // CuePoint
273 return -1;
274 CHECK(mk_writeUInt(w->cue_point.context, 0xb3, track->frame.timecode)); // CueTime
275 w->cue_point.timecode = track->frame.timecode;
278 if ((c = mk_createContext(w, w->cue_point.context, 0xb7)) == NULL) // CueTrackPositions
279 return -1;
280 CHECK(mk_writeUInt(c, 0xf7, track->track_id)); // CueTrack
281 CHECK(mk_writeUInt(c, 0xf1, w->cluster.pointer)); // CueClusterPosition
282 CHECK(mk_writeUInt(c, 0x5378, w->cluster.block_count)); // CueBlockNumber
283 CHECK(mk_closeContext(c, 0));
284 track->cue_flag = 0;
287 track->in_frame = 0;
288 track->prev_frame_tc_scaled = w->cluster.tc_scaled + delta;
290 if (w->cluster.context->d_cur > CLSIZE)
291 CHECK(mk_closeCluster(w));
293 return 0;
296 int mk_startFrame(mk_Writer *w, mk_Track *track) {
297 if (mk_flushFrame(w, track) < 0)
298 return -1;
300 track->in_frame = 1;
301 track->frame.keyframe = 0;
302 track->frame.lacing = MK_LACING_NONE;
303 track->frame.lacing_num_frames = 0;
304 track->frame.lacing_sizes = NULL;
306 return 0;
309 int mk_setFrameFlags(mk_Writer *w, mk_Track *track, int64_t timestamp, unsigned keyframe) {
310 if (!track->in_frame)
311 return -1;
313 track->frame.timecode = timestamp;
314 track->frame.keyframe = keyframe != 0;
316 if (track->max_frame_tc < timestamp)
317 track->max_frame_tc = timestamp;
319 return 0;
322 int mk_setFrameLacing(mk_Writer *w, mk_Track *track, uint8_t lacing, uint8_t num_frames, uint32_t sizes[]) {
323 if (!track->in_frame)
324 return -1;
325 track->frame.lacing_sizes = calloc(num_frames, sizeof(uint32_t));
327 track->frame.lacing = lacing;
328 track->frame.lacing_num_frames = num_frames;
329 memcpy(track->frame.lacing_sizes, sizes, num_frames);
331 return 0;
334 int mk_addFrameData(mk_Writer *w, mk_Track *track, const void *data, unsigned size) {
335 if (!track->in_frame)
336 return -1;
338 if (track->frame.data == NULL)
339 if ((track->frame.data = mk_createContext(w, NULL, 0)) == NULL)
340 return -1;
342 return mk_appendContextData(track->frame.data, data, size);
345 /* The offset of the SeekHead is returned in *pointer. */
346 int mk_writeSeek(mk_Writer *w, int64_t *pointer) {
347 mk_Context *c, *s;
348 int64_t seekhead_ptr;
350 if ((c = mk_createContext(w, w->root, 0x114d9b74)) == NULL) // SeekHead
351 return -1;
352 if (pointer != NULL)
353 seekhead_ptr = ftell(w->fp);
354 if (w->seek_data.seekhead) {
355 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
356 return -1;
357 CHECK(mk_writeUInt(s, 0x53ab, 0x114d9b74)); // SeekID
358 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.seekhead)); // SeekPosition
359 CHECK(mk_closeContext(s, 0));
361 if (w->seek_data.segmentinfo) {
362 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
363 return -1;
364 CHECK(mk_writeUInt(s, 0x53ab, 0x1549a966)); // SeekID
365 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.segmentinfo)); // SeekPosition
366 CHECK(mk_closeContext(s, 0));
368 if (w->seek_data.tracks) {
369 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
370 return -1;
371 CHECK(mk_writeUInt(s, 0x53ab, 0x1654ae6b)); // SeekID
372 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.tracks)); // SeekPosition
373 CHECK(mk_closeContext(s, 0));
375 if (w->seek_data.cues) {
376 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
377 return -1;
378 CHECK(mk_writeUInt(s, 0x53ab, 0x1c53bb6b)); // SeekID
379 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.cues)); // SeekPosition
380 CHECK(mk_closeContext(s, 0));
382 if (w->seek_data.attachments) {
383 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
384 return -1;
385 CHECK(mk_writeUInt(s, 0x53ab, 0x1941a469)); // SeekID
386 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.attachments)); // SeekPosition
387 CHECK(mk_closeContext(s, 0));
389 if (w->seek_data.chapters) {
390 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
391 return -1;
392 CHECK(mk_writeUInt(s, 0x53ab, 0x1043a770)); // SeekID
393 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.chapters)); // SeekPosition
394 CHECK(mk_closeContext(s, 0));
396 if (w->seek_data.tags) {
397 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
398 return -1;
399 CHECK(mk_writeUInt(s, 0x53ab, 0x1254c367)); // SeekID
400 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.tags)); // SeekPosition
401 CHECK(mk_closeContext(s, 0));
403 CHECK(mk_closeContext(c, 0));
405 if (pointer != NULL)
406 *pointer = seekhead_ptr;
408 return 0;
411 int mk_close(mk_Writer *w) {
412 int i, ret = 0;
413 mk_Track *tk;
414 int64_t max_frame_tc = w->tracks_arr[0]->max_frame_tc;
416 for (i = w->num_tracks - 1; i >= 0; i--)
418 tk = w->tracks_arr[i];
419 w->tracks_arr[i] = NULL;
420 if (mk_flushFrame(w, tk) < 0)
421 ret = -1;
422 free(tk);
423 tk = NULL;
426 if (mk_closeCluster(w) < 0)
427 ret = -1;
429 if (w->chapters != NULL)
431 if (w->vlc_compat)
432 fseek(w->fp, w->segment_ptr + 0x103, SEEK_SET);
433 w->seek_data.chapters = ftell(w->fp) - w->segment_ptr;
434 mk_writeChapters(w);
435 if (w->vlc_compat) {
436 if (mk_flushContextData(w->root) < 0)
437 ret = -1;
438 if (mk_writeVoid(w->root, (0x800 - (ftell(w->fp) - w->segment_ptr))) < 0)
439 ret = -1;
441 if (mk_flushContextData(w->root) < 0)
442 ret = -1;
445 w->seek_data.cues = ftell(w->fp) - w->segment_ptr;
446 if (w->cue_point.context != NULL)
447 if (mk_closeContext(w->cue_point.context, 0) < 0)
448 ret = -1;
449 // if (w->vlc_compat)
450 // fseek(w->fp, w->segment_ptr + 259 + 2051, SEEK_SET);
451 if (mk_closeContext(w->cues, 0) < 0)
452 ret = -1;
453 if (w->vlc_compat) {
454 if (mk_flushContextData(w->root) < 0)
455 ret = -1;
456 if (mk_writeVoid(w->root, (0x1000 - (ftell(w->fp) - w->segment_ptr))) < 0)
457 ret = -1;
459 if (mk_flushContextData(w->root) < 0)
460 ret = -1;
462 if (w->wrote_header) {
463 if (w->vlc_compat)
464 fseek(w->fp, w->segment_ptr, SEEK_SET);
466 if (mk_writeSeek(w, &w->seek_data.seekhead) < 0)
467 ret = -1;
468 w->seek_data.seekhead -= w->segment_ptr;
470 if (w->vlc_compat)
472 if (mk_flushContextData(w->root) < 0)
473 ret = -1;
474 if (mk_writeVoid(w->root, (256 - (ftell(w->fp) - w->segment_ptr))) < 0)
475 ret = -1;
478 if (mk_flushContextData(w->root) < 0)
479 ret = -1;
481 if (!w->vlc_compat)
483 int i = w->seek_data.segmentinfo;
484 w->seek_data.segmentinfo = 0;
485 w->seek_data.tracks = 0;
486 w->seek_data.cues = 0;
487 w->seek_data.chapters = 0;
488 w->seek_data.attachments = 0;
489 w->seek_data.tags = 0;
490 fseek(w->fp, w->segment_ptr, SEEK_SET);
491 if (mk_writeSeek(w, NULL) < 0 ||
492 mk_flushContextData(w->root) < 0)
493 ret = -1;
494 if (((i + w->segment_ptr) - ftell(w->fp) - 2) > 1)
495 if (mk_writeVoid(w->root, (i + w->segment_ptr) - ftell(w->fp) - 2) < 0 ||
496 mk_flushContextData(w->root) < 0)
497 ret = -1;
500 fseek(w->fp, w->duration_ptr, SEEK_SET);
501 if (mk_writeFloatRaw(w->root, (float)((double)(max_frame_tc+w->def_duration) / w->timescale)) < 0 ||
502 mk_flushContextData(w->root) < 0)
503 ret = -1;
506 if (mk_closeContext(w->root, 0) < 1)
507 ret = -1;
508 mk_destroyContexts(w);
509 fclose(w->fp);
510 free(w->tracks_arr);
511 free(w);
513 return ret;