Lacing fixups.
[libmkv.git] / src / matroska.c
blob49266c7a8faa36706a4b18f387574912c724a234
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 - 1;
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->keyframe = 0;
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 w->seek_data.chapters = ftell(w->fp) - w->segment_ptr;
432 mk_writeChapters(w);
433 if (mk_flushContextData(w->root) < 0)
434 ret = -1;
437 w->seek_data.cues = ftell(w->fp) - w->segment_ptr;
438 if (w->cue_point.context != NULL)
439 if (mk_closeContext(w->cue_point.context, 0) < 0)
440 ret = -1;
441 if (mk_closeContext(w->cues, 0) < 0)
442 ret = -1;
443 if (mk_flushContextData(w->root) < 0)
444 ret = -1;
446 if (w->wrote_header) {
447 if (w->vlc_compat)
448 fseek(w->fp, w->segment_ptr, SEEK_SET);
450 if (mk_writeSeek(w, &w->seek_data.seekhead) < 0)
451 ret = -1;
452 w->seek_data.seekhead -= w->segment_ptr;
454 if (w->vlc_compat)
456 if (mk_flushContextData(w->root) < 0)
457 ret = -1;
458 if (mk_writeVoid(w->root, (256 - (ftell(w->fp) - w->segment_ptr))) < 0)
459 ret = -1;
462 if (mk_flushContextData(w->root) < 0)
463 ret = -1;
465 if (!w->vlc_compat)
467 int i = w->seek_data.segmentinfo;
468 w->seek_data.segmentinfo = 0;
469 w->seek_data.tracks = 0;
470 w->seek_data.cues = 0;
471 w->seek_data.chapters = 0;
472 w->seek_data.attachments = 0;
473 w->seek_data.tags = 0;
474 fseek(w->fp, w->segment_ptr, SEEK_SET);
475 if (mk_writeSeek(w, NULL) < 0 ||
476 mk_flushContextData(w->root) < 0)
477 ret = -1;
478 if (((i + w->segment_ptr) - ftell(w->fp) - 2) > 1)
479 if (mk_writeVoid(w->root, (i + w->segment_ptr) - ftell(w->fp) - 2) < 0 ||
480 mk_flushContextData(w->root) < 0)
481 ret = -1;
484 fseek(w->fp, w->duration_ptr, SEEK_SET);
485 if (mk_writeFloatRaw(w->root, (float)((double)(max_frame_tc+w->def_duration) / w->timescale)) < 0 ||
486 mk_flushContextData(w->root) < 0)
487 ret = -1;
490 if (mk_closeContext(w->root, 0) < 1)
491 ret = -1;
492 mk_destroyContexts(w);
493 fclose(w->fp);
494 free(w->tracks_arr);
495 free(w);
497 return ret;