Remove commented out variable, and fix bug in mk_laceXiph().
[libmkv.git] / src / matroska.c
blob47fd71292fc7f43387cc6739a76430219d1125c2
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, unsigned 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 = malloc(sizeof(*w));
70 if (w == NULL)
71 return NULL;
73 memset(w, 0, sizeof(*w));
75 w->root = mk_createContext(w, NULL, 0);
76 if (w->root == NULL) {
77 free(w);
78 return NULL;
81 if ((w->cues = mk_createContext(w, w->root, 0x1c53bb6b)) == NULL) // Cues
83 mk_destroyContexts(w);
84 free(w);
85 return NULL;
88 w->fp = fopen(filename, "wb");
89 if (w->fp == NULL) {
90 mk_destroyContexts(w);
91 free(w);
92 return NULL;
95 w->timescale = timescale;
96 w->vlc_compat = vlc_compat;
98 return w;
101 int mk_writeHeader(mk_Writer *w, const char *writingApp) {
102 mk_Context *c;
104 if (w->wrote_header)
105 return -1;
107 if ((c = mk_createContext(w, w->root, 0x1a45dfa3)) == NULL) // EBML
108 return -1;
109 CHECK(mk_writeUInt(c, 0x4286, 1)); // EBMLVersion
110 CHECK(mk_writeUInt(c, 0x42f7, 1)); // EBMLReadVersion
111 CHECK(mk_writeUInt(c, 0x42f2, 4)); // EBMLMaxIDLength
112 CHECK(mk_writeUInt(c, 0x42f3, 8)); // EBMLMaxSizeLength
113 CHECK(mk_writeStr(c, 0x4282, "matroska")); // DocType
114 CHECK(mk_writeUInt(c, 0x4287, 1)); // DocTypeVersion
115 CHECK(mk_writeUInt(c, 0x4285, 1)); // DocTypeReadversion
116 CHECK(mk_closeContext(c, 0));
118 if ((c = mk_createContext(w, w->root, 0x18538067)) == NULL) // Segment
119 return -1;
120 CHECK(mk_flushContextID(c));
121 w->segment_ptr = c->d_cur;
122 CHECK(mk_closeContext(c, &w->segment_ptr));
124 if (w->vlc_compat)
126 CHECK(mk_writeVoid(w->root, 256)); // 256 bytes should be enough room for our Seek entries.
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 % 5 == 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));
286 track->in_frame = 0;
287 track->prev_frame_tc_scaled = w->cluster.tc_scaled + delta;
289 if (w->cluster.context->d_cur > CLSIZE)
290 CHECK(mk_closeCluster(w));
292 return 0;
295 int mk_startFrame(mk_Writer *w, mk_Track *track) {
296 if (mk_flushFrame(w, track) < 0)
297 return -1;
299 track->in_frame = 1;
300 track->frame.keyframe = 0;
301 track->frame.lacing = MK_LACING_NONE;
302 track->frame.lacing_num_frames = 0;
303 track->frame.lacing_sizes = NULL;
305 return 0;
308 int mk_setFrameFlags(mk_Writer *w, mk_Track *track, int64_t timestamp, unsigned keyframe) {
309 if (!track->in_frame)
310 return -1;
312 track->frame.timecode = timestamp;
313 track->frame.keyframe = keyframe != 0;
315 if (track->max_frame_tc < timestamp)
316 track->max_frame_tc = timestamp;
318 return 0;
321 int mk_setFrameLacing(mk_Writer *w, mk_Track *track, uint8_t lacing, uint8_t num_frames, uint32_t sizes[]) {
322 if (!track->in_frame)
323 return -1;
324 track->frame.lacing_sizes = calloc(num_frames, sizeof(uint32_t));
326 track->frame.lacing = lacing;
327 track->frame.lacing_num_frames = num_frames;
328 memcpy(track->frame.lacing_sizes, sizes, num_frames);
330 return 0;
333 int mk_addFrameData(mk_Writer *w, mk_Track *track, const void *data, unsigned size) {
334 if (!track->in_frame)
335 return -1;
337 if (track->frame.data == NULL)
338 if ((track->frame.data = mk_createContext(w, NULL, 0)) == NULL)
339 return -1;
341 return mk_appendContextData(track->frame.data, data, size);
344 /* The offset of the SeekHead is returned in *pointer. */
345 int mk_writeSeek(mk_Writer *w, int64_t *pointer) {
346 mk_Context *c, *s;
347 int64_t seekhead_ptr;
349 if ((c = mk_createContext(w, w->root, 0x114d9b74)) == NULL) // SeekHead
350 return -1;
351 if (pointer != NULL)
352 seekhead_ptr = ftell(w->fp);
353 if (w->seek_data.seekhead) {
354 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
355 return -1;
356 CHECK(mk_writeUInt(s, 0x53ab, 0x114d9b74)); // SeekID
357 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.seekhead)); // SeekPosition
358 CHECK(mk_closeContext(s, 0));
360 if (w->seek_data.segmentinfo) {
361 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
362 return -1;
363 CHECK(mk_writeUInt(s, 0x53ab, 0x1549a966)); // SeekID
364 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.segmentinfo)); // SeekPosition
365 CHECK(mk_closeContext(s, 0));
367 if (w->seek_data.tracks) {
368 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
369 return -1;
370 CHECK(mk_writeUInt(s, 0x53ab, 0x1654ae6b)); // SeekID
371 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.tracks)); // SeekPosition
372 CHECK(mk_closeContext(s, 0));
374 if (w->seek_data.cues) {
375 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
376 return -1;
377 CHECK(mk_writeUInt(s, 0x53ab, 0x1c53bb6b)); // SeekID
378 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.cues)); // SeekPosition
379 CHECK(mk_closeContext(s, 0));
381 if (w->seek_data.attachments) {
382 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
383 return -1;
384 CHECK(mk_writeUInt(s, 0x53ab, 0x1941a469)); // SeekID
385 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.attachments)); // SeekPosition
386 CHECK(mk_closeContext(s, 0));
388 if (w->seek_data.chapters) {
389 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
390 return -1;
391 CHECK(mk_writeUInt(s, 0x53ab, 0x1043a770)); // SeekID
392 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.chapters)); // SeekPosition
393 CHECK(mk_closeContext(s, 0));
395 if (w->seek_data.tags) {
396 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
397 return -1;
398 CHECK(mk_writeUInt(s, 0x53ab, 0x1254c367)); // SeekID
399 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.tags)); // SeekPosition
400 CHECK(mk_closeContext(s, 0));
402 CHECK(mk_closeContext(c, 0));
404 if (pointer != NULL)
405 *pointer = seekhead_ptr;
407 return 0;
410 int mk_close(mk_Writer *w) {
411 int i, ret = 0;
412 mk_Track *tk;
413 int64_t max_frame_tc = w->tracks_arr[0]->max_frame_tc;
415 for (i = w->num_tracks - 1; i >= 0; i--)
417 tk = w->tracks_arr[i];
418 w->tracks_arr[i] = NULL;
419 if (mk_flushFrame(w, tk) < 0)
420 ret = -1;
421 free(tk);
422 tk = NULL;
425 if (mk_closeCluster(w) < 0)
426 ret = -1;
428 if (w->chapters != NULL)
430 w->seek_data.chapters = ftell(w->fp) - w->segment_ptr;
431 mk_writeChapters(w);
432 if (mk_flushContextData(w->root) < 0)
433 ret = -1;
436 w->seek_data.cues = ftell(w->fp) - w->segment_ptr;
437 if (w->cue_point.context != NULL)
438 if (mk_closeContext(w->cue_point.context, 0) < 0)
439 ret = -1;
440 if (mk_closeContext(w->cues, 0) < 0)
441 ret = -1;
442 if (mk_flushContextData(w->root) < 0)
443 ret = -1;
445 if (w->wrote_header) {
446 if (w->vlc_compat)
447 fseek(w->fp, w->segment_ptr, SEEK_SET);
449 if (mk_writeSeek(w, &w->seek_data.seekhead) < 0)
450 ret = -1;
451 w->seek_data.seekhead -= w->segment_ptr;
453 if (w->vlc_compat)
455 if (mk_flushContextData(w->root) < 0)
456 ret = -1;
457 if (mk_writeVoid(w->root, (256 - (ftell(w->fp) - w->segment_ptr))) < 0)
458 ret = -1;
461 if (mk_flushContextData(w->root) < 0)
462 ret = -1;
464 if (!w->vlc_compat)
466 int i = w->seek_data.segmentinfo;
467 w->seek_data.segmentinfo = 0;
468 w->seek_data.tracks = 0;
469 w->seek_data.cues = 0;
470 w->seek_data.chapters = 0;
471 w->seek_data.attachments = 0;
472 w->seek_data.tags = 0;
473 fseek(w->fp, w->segment_ptr, SEEK_SET);
474 if (mk_writeSeek(w, NULL) < 0 ||
475 mk_flushContextData(w->root) < 0)
476 ret = -1;
477 if (((i + w->segment_ptr) - ftell(w->fp) - 2) > 1)
478 if (mk_writeVoid(w->root, (i + w->segment_ptr) - ftell(w->fp) - 2) < 0 ||
479 mk_flushContextData(w->root) < 0)
480 ret = -1;
483 fseek(w->fp, w->duration_ptr, SEEK_SET);
484 if (mk_writeFloatRaw(w->root, (float)((double)(max_frame_tc+w->def_duration) / w->timescale)) < 0 ||
485 mk_flushContextData(w->root) < 0)
486 ret = -1;
489 if (mk_closeContext(w->root, 0) < 1)
490 ret = -1;
491 mk_destroyContexts(w);
492 fclose(w->fp);
493 free(w->tracks_arr);
494 free(w);
496 return ret;