Implement mk_writeSeek(), and switch mk_writeSeekHead to use it.
[libmkv.git] / src / matroska.c
blob96a5abbfe3966684f91d5eaffa944633de8ca604
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_seekFile(mk_Writer *w, uint64_t pos) {
29 if (fseek(w->fp, pos, SEEK_SET))
30 return -1;
32 w->f_pos = pos;
34 if (pos > w->f_eof)
35 w->f_eof = pos;
37 return 0;
40 int mk_writeVoid(mk_Context *c, uint64_t length) {
41 char *c_void = calloc(length, sizeof(char));
43 CHECK(mk_writeID(c, 0xec));
44 CHECK(mk_writeSize(c, length));
45 CHECK(mk_appendContextData(c, c_void, length));
46 free(c_void);
47 return 0;
50 char *mk_laceXiph(uint64_t *sizes, uint8_t num_frames, uint64_t *output_size) {
51 unsigned i, j;
52 uint64_t offset = 0;
53 uint64_t alloc_size = num_frames * 6; // Complete guess. We'll realloc if we need more space, though.
54 char *laced = calloc(alloc_size, sizeof(char));
55 if (laced == NULL)
56 return NULL;
58 laced[offset++] = num_frames;
59 for (i = 0; i < num_frames; i++)
61 for (j = sizes[i]; j >= 255 ; j -= 255)
63 laced[offset++] = 255;
64 if (offset + 1 >= alloc_size) {
65 int avg_sz = offset / (i - 1); // Compute approximate average bytes/frame
66 alloc_size += avg_sz * (num_frames - i); // Add our average + number of frames left to size
67 if ((laced = realloc(laced, alloc_size)) == NULL)
68 return NULL;
71 laced[offset++] = j;
74 if (output_size != NULL)
75 *output_size = offset;
77 return laced;
80 mk_Writer *mk_createWriter(const char *filename, int64_t timescale, uint8_t vlc_compat) {
81 mk_Writer *w = calloc(1, sizeof(*w));
82 if (w == NULL)
83 return NULL;
85 w->root = mk_createContext(w, NULL, 0);
86 if (w->root == NULL) {
87 free(w);
88 return NULL;
91 if ((w->cues = mk_createContext(w, w->root, 0x1c53bb6b)) == NULL) // Cues
93 mk_destroyContexts(w);
94 free(w);
95 return NULL;
98 w->fp = fopen(filename, "wb");
99 if (w->fp == NULL) {
100 mk_destroyContexts(w);
101 free(w);
102 return NULL;
105 w->timescale = timescale;
106 w->vlc_compat = vlc_compat;
108 return w;
111 int mk_writeHeader(mk_Writer *w, const char *writingApp) {
112 mk_Context *c;
114 if (w->wrote_header)
115 return -1;
117 if ((c = mk_createContext(w, w->root, 0x1a45dfa3)) == NULL) // EBML
118 return -1;
119 CHECK(mk_writeUInt(c, 0x4286, 1)); // EBMLVersion
120 CHECK(mk_writeUInt(c, 0x42f7, 1)); // EBMLReadVersion
121 CHECK(mk_writeUInt(c, 0x42f2, 4)); // EBMLMaxIDLength
122 CHECK(mk_writeUInt(c, 0x42f3, 8)); // EBMLMaxSizeLength
123 CHECK(mk_writeStr(c, 0x4282, "matroska")); // DocType
124 CHECK(mk_writeUInt(c, 0x4287, 1)); // DocTypeVersion
125 CHECK(mk_writeUInt(c, 0x4285, 1)); // DocTypeReadversion
126 CHECK(mk_closeContext(c, 0));
128 if ((c = mk_createContext(w, w->root, 0x18538067)) == NULL) // Segment
129 return -1;
130 CHECK(mk_flushContextID(c));
131 w->segment_ptr = c->d_cur;
132 CHECK(mk_closeContext(c, &w->segment_ptr));
134 if (w->vlc_compat) {
135 CHECK(mk_writeVoid(w->root, 0x100)); // 256 bytes should be enough room for our Seek entries.
136 CHECK(mk_writeVoid(w->root, 0x800)); // 2048 bytes for Chapters.
138 else {
139 w->seek_data.seekhead = 0x80000000;
140 CHECK(mk_writeSeekHead(w, &w->seekhead_ptr));
141 w->seek_data.seekhead = 0;
144 if ((c = mk_createContext(w, w->root, 0x1549a966)) == NULL) // SegmentInfo
145 return -1;
146 w->seek_data.segmentinfo = w->root->d_cur - w->segment_ptr;
147 CHECK(mk_writeStr(c, 0x4d80, PACKAGE_STRING)); // MuxingApp
148 CHECK(mk_writeStr(c, 0x5741, writingApp)); // WritingApp
149 CHECK(mk_writeUInt(c, 0x2ad7b1, w->timescale)); // TimecodeScale
150 CHECK(mk_writeFloat(c, 0x4489, 0)); // Duration
151 w->duration_ptr = c->d_cur - 4;
152 CHECK(mk_closeContext(c, &w->duration_ptr));
154 w->seek_data.tracks = w->root->d_cur - w->segment_ptr;
156 if (w->tracks) {
157 CHECK(mk_closeContext(w->tracks, 0));
160 CHECK(mk_flushContextData(w->root));
162 w->wrote_header = 1;
163 w->def_duration = w->tracks_arr[0]->default_duration;
164 return 0;
167 static int mk_closeCluster(mk_Writer *w) {
168 if (w->cluster.context == NULL)
169 return 0;
170 w->cluster.count++;
171 CHECK(mk_closeContext(w->cluster.context, 0));
172 w->cluster.context = NULL;
173 CHECK(mk_flushContextData(w->root));
174 return 0;
177 int mk_flushFrame(mk_Writer *w, mk_Track *track) {
178 mk_Context *c, *tp;
179 int64_t delta, ref = 0;
180 unsigned fsize, bgsize;
181 uint8_t flags, c_delta_flags[2];
182 int i;
183 char *laced = NULL;
184 uint64_t length = 0;
186 if (!track->in_frame)
187 return 0;
189 delta = track->frame.timecode/w->timescale - w->cluster.tc_scaled;
190 if (delta > 32767ll || delta < -32768ll)
191 CHECK(mk_closeCluster(w));
193 if (w->cluster.context == NULL) {
194 w->cluster.tc_scaled = track->frame.timecode / w->timescale;
195 w->cluster.context = mk_createContext(w, w->root, 0x1f43b675); // Cluster
196 if (w->cluster.context == NULL)
197 return -1;
199 w->cluster.pointer = w->f_pos - w->segment_ptr;
201 CHECK(mk_writeUInt(w->cluster.context, 0xe7, w->cluster.tc_scaled)); // Cluster Timecode
203 delta = 0;
204 w->cluster.block_count = 0;
207 fsize = track->frame.data ? track->frame.data->d_cur : 0;
208 bgsize = fsize + 4 + mk_ebmlSizeSize(fsize + 4) + 1;
209 if (!track->frame.keyframe) {
210 ref = track->prev_frame_tc_scaled - w->cluster.tc_scaled - delta;
211 bgsize += 1 + 1 + mk_ebmlSIntSize(ref);
214 CHECK(mk_writeID(w->cluster.context, 0xa0)); // BlockGroup
215 CHECK(mk_writeSize(w->cluster.context, bgsize));
216 CHECK(mk_writeID(w->cluster.context, 0xa1)); // Block
218 switch (track->frame.lacing) {
219 case MK_LACING_XIPH:
220 laced = mk_laceXiph(track->frame.lacing_sizes, track->frame.lacing_num_frames, &length);
221 break;
222 case MK_LACING_EBML:
223 length += mk_ebmlSizeSize(track->frame.lacing_sizes[0]) + 1;
224 for (i = 1; i < track->frame.lacing_num_frames; i++)
225 length += mk_ebmlSizeSize(track->frame.lacing_sizes[i] << 1);
226 break;
227 case MK_LACING_FIXED:
229 laced = calloc(1, sizeof(char));
230 laced[0] = track->frame.lacing_num_frames;
231 ++length;
233 break;
236 CHECK(mk_writeSize(w->cluster.context, fsize + 4 + length));
237 CHECK(mk_writeSize(w->cluster.context, track->track_id)); // track number
239 w->cluster.block_count++;
241 c_delta_flags[0] = delta >> 8;
242 c_delta_flags[1] = delta;
243 CHECK(mk_appendContextData(w->cluster.context, c_delta_flags, 2));
245 flags = ( track->frame.keyframe << 8 ) | track->frame.lacing;
246 CHECK(mk_appendContextData(w->cluster.context, &flags, 1));
247 if (track->frame.lacing) {
248 if (track->frame.lacing == MK_LACING_EBML) {
249 CHECK(mk_appendContextData(w->cluster.context, &track->frame.lacing_num_frames, 1));
250 CHECK(mk_writeSize(w->cluster.context, track->frame.lacing_sizes[0]));
251 for (i = 1; i < track->frame.lacing_num_frames; i++)
253 CHECK(mk_writeSSize(w->cluster.context, track->frame.lacing_sizes[i] - track->frame.lacing_sizes[i-1]));
255 } else if (length > 0 && laced != NULL) {
256 CHECK(mk_appendContextData(w->cluster.context, laced, length));
257 free(laced);
258 laced = NULL;
262 if (track->frame.data) {
263 CHECK(mk_appendContextData(w->cluster.context, track->frame.data->data, track->frame.data->d_cur));
264 track->frame.data->d_cur = 0;
266 if (!track->frame.keyframe)
267 CHECK(mk_writeSInt(w->cluster.context, 0xfb, ref)); // ReferenceBlock
269 if (track->frame.keyframe && (track->track_type & MK_TRACK_VIDEO) && (track->prev_cue_pos + 3*CLSIZE) >= w->f_pos) {
270 if ((c = mk_createContext(w, w->cues, 0xbb)) == NULL) // CuePoint
271 return -1;
272 CHECK(mk_writeUInt(c, 0xb3, track->frame.timecode)); // CueTime
274 if ((tp = mk_createContext(w, c, 0xb7)) == NULL) // CueTrackPositions
275 return -1;
276 CHECK(mk_writeUInt(tp, 0xf7, track->track_id)); // CueTrack
277 CHECK(mk_writeUInt(tp, 0xf1, w->cluster.pointer)); // CueClusterPosition
278 // CHECK(mk_writeUInt(c, 0x5378, w->cluster.block_count)); // CueBlockNumber
279 CHECK(mk_closeContext(tp, 0));
280 CHECK(mk_closeContext(c, 0));
283 track->in_frame = 0;
284 track->prev_frame_tc_scaled = w->cluster.tc_scaled + delta;
286 if (w->cluster.context->d_cur > CLSIZE)
287 CHECK(mk_closeCluster(w));
289 return 0;
292 int mk_startFrame(mk_Writer *w, mk_Track *track) {
293 if (mk_flushFrame(w, track) < 0)
294 return -1;
296 track->in_frame = 1;
297 track->frame.keyframe = 0;
298 track->frame.lacing = MK_LACING_NONE;
299 track->frame.lacing_num_frames = 0;
300 track->frame.lacing_sizes = NULL;
302 return 0;
305 int mk_setFrameFlags(mk_Writer *w, mk_Track *track, int64_t timestamp, unsigned keyframe) {
306 if (!track->in_frame)
307 return -1;
309 track->frame.timecode = timestamp;
310 track->frame.keyframe = keyframe != 0;
312 if (track->max_frame_tc < timestamp)
313 track->max_frame_tc = timestamp;
315 return 0;
318 int mk_setFrameLacing(mk_Writer *w, mk_Track *track, uint8_t lacing, uint8_t num_frames, uint32_t sizes[]) {
319 if (!track->in_frame)
320 return -1;
321 track->frame.lacing_sizes = calloc(num_frames, sizeof(uint32_t));
323 track->frame.lacing = lacing;
324 track->frame.lacing_num_frames = num_frames;
325 memcpy(track->frame.lacing_sizes, sizes, num_frames);
327 return 0;
330 int mk_addFrameData(mk_Writer *w, mk_Track *track, const void *data, unsigned size) {
331 if (!track->in_frame)
332 return -1;
334 if (track->frame.data == NULL)
335 if ((track->frame.data = mk_createContext(w, NULL, 0)) == NULL)
336 return -1;
338 return mk_appendContextData(track->frame.data, data, size);
341 int mk_writeSeek(mk_Write *w, mk_Context *c, unsigned seek_id, uint64_t seek_pos) {
342 mk_Context *s;
343 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
344 return -1;
345 CHECK(mk_writeUInt(s, 0x53ab, seek_id)); // SeekID
346 CHECK(mk_writeUInt(s, 0x53ac, seek_pos)); // SeekPosition
347 CHECK(mk_closeContext(s, 0));
349 return 0;
352 /* The offset of the SeekHead is returned in *pointer. */
353 int mk_writeSeekHead(mk_Writer *w, int64_t *pointer) {
354 mk_Context *c, *s;
355 int64_t seekhead_ptr;
357 if ((c = mk_createContext(w, w->root, 0x114d9b74)) == NULL) // SeekHead
358 return -1;
359 if (pointer != NULL)
360 seekhead_ptr = w->f_pos;
361 if (w->seek_data.seekhead)
362 CHECK(mk_writeSeek(w, c, 0x114d9b74, w->seek_data.seekhead));
363 if (w->seek_data.segmentinfo)
364 CHECK(mk_writeSeek(w, c, 0x1549a966, w->seek_data.segmentinfo));
365 if (w->seek_data.tracks)
366 CHECK(mk_writeSeek(w, c, 0x1654ae6b, w->seek_data.tracks));
367 if (w->seek_data.cues)
368 CHECK(mk_writeSeek(w, c, 0x1c53bb6b, w->seek_data.cues));
369 if (w->seek_data.attachments)
370 CHECK(mk_writeSeek(w, c, 0x1941a469, w->seek_data.attachments));
371 if (w->seek_data.chapters)
372 CHECK(mk_writeSeek(w, c, 0x1043a770, w->seek_data.chapters));
373 if (w->seek_data.tags)
374 CHECK(mk_writeSeek(w, c, 0x1254c367, w->seek_data.tags));
375 CHECK(mk_closeContext(c, 0));
377 if (pointer != NULL)
378 *pointer = seekhead_ptr;
380 return 0;
383 int mk_close(mk_Writer *w) {
384 int i, ret = 0;
385 mk_Track *tk;
386 int64_t max_frame_tc = w->tracks_arr[0]->max_frame_tc;
387 uint64_t segment_size = 0;
388 unsigned char c_size[8];
390 for (i = w->num_tracks - 1; i >= 0; i--)
392 tk = w->tracks_arr[i];
393 w->tracks_arr[i] = NULL;
394 --w->num_tracks;
395 if (mk_flushFrame(w, tk) < 0)
396 ret = -1;
397 free(tk);
398 tk = NULL;
401 if (mk_closeCluster(w) < 0)
402 ret = -1;
405 w->seek_data.cues = w->f_pos - w->segment_ptr;
406 if (mk_closeContext(w->cues, 0) < 0)
407 ret = -1;
408 if (mk_flushContextData(w->root) < 0)
409 ret = -1;
411 if (w->chapters != NULL)
413 if (w->vlc_compat) {
414 if (mk_seekFile(w, w->segment_ptr + 0x103) < 0)
415 ret = -1;
417 w->seek_data.chapters = w->f_pos - w->segment_ptr;
418 mk_writeChapters(w);
419 if (w->vlc_compat) {
420 if (mk_flushContextData(w->root) < 0)
421 ret = -1;
422 if (mk_writeVoid(w->root, (0x800 - (w->f_pos - w->segment_ptr))) < 0)
423 ret = -1;
425 if (mk_flushContextData(w->root) < 0)
426 ret = -1;
429 if (w->wrote_header) {
430 if (w->vlc_compat) {
431 if (mk_seekFile(w, w->segment_ptr) < 0)
432 ret = -1;
435 if (mk_writeSeekHead(w, &w->seek_data.seekhead) < 0)
436 ret = -1;
437 w->seek_data.seekhead -= w->segment_ptr;
439 if (w->vlc_compat)
441 if (mk_flushContextData(w->root) < 0)
442 ret = -1;
443 if (mk_writeVoid(w->root, (256 - (w->f_pos - w->segment_ptr))) < 0)
444 ret = -1;
447 if (mk_flushContextData(w->root) < 0)
448 ret = -1;
450 if (!w->vlc_compat)
452 int i = w->seek_data.segmentinfo;
453 w->seek_data.segmentinfo = 0;
454 w->seek_data.tracks = 0;
455 w->seek_data.cues = 0;
456 w->seek_data.chapters = 0;
457 w->seek_data.attachments = 0;
458 w->seek_data.tags = 0;
459 if (mk_seekFile(w, w->segment_ptr) < 0)
460 ret = -1;
461 if (mk_writeSeekHead(w, NULL) < 0 ||
462 mk_flushContextData(w->root) < 0)
463 ret = -1;
464 if (((i + w->segment_ptr) - w->f_pos - 2) > 1)
465 if (mk_writeVoid(w->root, (i + w->segment_ptr) - w->f_pos - 2) < 0 ||
466 mk_flushContextData(w->root) < 0)
467 ret = -1;
470 if (mk_seekFile(w, w->duration_ptr) < 0)
471 ret = -1;
472 if (mk_writeFloatRaw(w->root, (float)((double)(max_frame_tc+w->def_duration) / w->timescale)) < 0 ||
473 mk_flushContextData(w->root) < 0)
474 ret = -1;
475 if (mk_seekFile(w, w->segment_ptr - 8) < 0)
476 ret = -1;
477 segment_size = w->f_eof - w->segment_ptr;
478 for (i = 7; i > 0; --i)
479 c_size[i] = segment_size >> (8 * (7-i));
480 c_size[i] = 0x01;
481 if (mk_appendContextData(w->root, &c_size, 8) < 0 ||
482 mk_flushContextData(w->root) < 0)
483 ret = -1;
486 if (mk_closeContext(w->root, 0) < 0)
487 ret = -1;
488 mk_destroyContexts(w);
489 fclose(w->fp);
490 free(w->tracks_arr);
491 free(w);
493 return ret;