Replace all calls to fseek() with mk_seekFile().
[libmkv.git] / src / matroska.c
blob48be7c67affb1f886c6e99221259694f2356aa9c
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_cur = 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 = malloc(sizeof(*w));
82 if (w == NULL)
83 return NULL;
85 memset(w, 0, sizeof(*w));
87 w->root = mk_createContext(w, NULL, 0);
88 if (w->root == NULL) {
89 free(w);
90 return NULL;
93 if ((w->cues = mk_createContext(w, w->root, 0x1c53bb6b)) == NULL) // Cues
95 mk_destroyContexts(w);
96 free(w);
97 return NULL;
100 w->fp = fopen(filename, "wb");
101 if (w->fp == NULL) {
102 mk_destroyContexts(w);
103 free(w);
104 return NULL;
107 w->timescale = timescale;
108 w->vlc_compat = vlc_compat;
110 return w;
113 int mk_writeHeader(mk_Writer *w, const char *writingApp) {
114 mk_Context *c;
116 if (w->wrote_header)
117 return -1;
119 if ((c = mk_createContext(w, w->root, 0x1a45dfa3)) == NULL) // EBML
120 return -1;
121 CHECK(mk_writeUInt(c, 0x4286, 1)); // EBMLVersion
122 CHECK(mk_writeUInt(c, 0x42f7, 1)); // EBMLReadVersion
123 CHECK(mk_writeUInt(c, 0x42f2, 4)); // EBMLMaxIDLength
124 CHECK(mk_writeUInt(c, 0x42f3, 8)); // EBMLMaxSizeLength
125 CHECK(mk_writeStr(c, 0x4282, "matroska")); // DocType
126 CHECK(mk_writeUInt(c, 0x4287, 1)); // DocTypeVersion
127 CHECK(mk_writeUInt(c, 0x4285, 1)); // DocTypeReadversion
128 CHECK(mk_closeContext(c, 0));
130 if ((c = mk_createContext(w, w->root, 0x18538067)) == NULL) // Segment
131 return -1;
132 CHECK(mk_flushContextID(c));
133 w->segment_ptr = c->d_cur;
134 CHECK(mk_closeContext(c, &w->segment_ptr));
136 if (w->vlc_compat)
138 CHECK(mk_writeVoid(w->root, 0x100)); // 256 bytes should be enough room for our Seek entries.
139 CHECK(mk_writeVoid(w->root, 0x800)); // 2048 bytes for Chapters.
140 CHECK(mk_writeVoid(w->root, 0x1000)); // 4096 bytes for Cues.
141 } else
143 w->seek_data.seekhead = 0x80000000;
144 CHECK(mk_writeSeek(w, &w->seekhead_ptr));
145 w->seek_data.seekhead = 0;
148 if ((c = mk_createContext(w, w->root, 0x1549a966)) == NULL) // SegmentInfo
149 return -1;
150 w->seek_data.segmentinfo = w->root->d_cur - w->segment_ptr;
151 CHECK(mk_writeStr(c, 0x4d80, PACKAGE_STRING)); // MuxingApp
152 CHECK(mk_writeStr(c, 0x5741, writingApp)); // WritingApp
153 CHECK(mk_writeUInt(c, 0x2ad7b1, w->timescale)); // TimecodeScale
154 CHECK(mk_writeFloat(c, 0x4489, 0)); // Duration
155 w->duration_ptr = c->d_cur - 4;
156 CHECK(mk_closeContext(c, &w->duration_ptr));
158 w->seek_data.tracks = w->root->d_cur - w->segment_ptr;
160 if (w->tracks) {
161 CHECK(mk_closeContext(w->tracks, 0));
164 CHECK(mk_flushContextData(w->root));
166 w->wrote_header = 1;
167 w->def_duration = w->tracks_arr[0]->default_duration;
168 return 0;
171 static int mk_closeCluster(mk_Writer *w) {
172 if (w->cluster.context == NULL)
173 return 0;
174 w->cluster.count++;
175 CHECK(mk_closeContext(w->cluster.context, 0));
176 w->cluster.context = NULL;
177 CHECK(mk_flushContextData(w->root));
178 return 0;
181 int mk_flushFrame(mk_Writer *w, mk_Track *track) {
182 mk_Context *c;
183 int64_t delta, ref = 0;
184 unsigned fsize, bgsize;
185 uint8_t flags, c_delta_flags[2];
186 int i;
187 char *laced = NULL;
188 uint64_t length = 0;
190 if (!track->in_frame)
191 return 0;
193 delta = track->frame.timecode/w->timescale - w->cluster.tc_scaled;
194 if (delta > 32767ll || delta < -32768ll)
195 CHECK(mk_closeCluster(w));
197 if (w->cluster.context == NULL) {
198 w->cluster.tc_scaled = track->frame.timecode / w->timescale;
199 w->cluster.context = mk_createContext(w, w->root, 0x1f43b675); // Cluster
200 if (w->cluster.context == NULL)
201 return -1;
203 w->cluster.pointer = ftell(w->fp) - w->segment_ptr;
205 CHECK(mk_writeUInt(w->cluster.context, 0xe7, w->cluster.tc_scaled)); // Cluster Timecode
207 delta = 0;
208 w->cluster.block_count = 0;
210 if ((w->cluster.count % 15) == 0) {
211 for(i = 0; i < w->num_tracks; i++)
212 w->tracks_arr[i]->cue_flag = 1;
216 fsize = track->frame.data ? track->frame.data->d_cur : 0;
217 bgsize = fsize + 4 + mk_ebmlSizeSize(fsize + 4) + 1;
218 if (!track->frame.keyframe) {
219 ref = track->prev_frame_tc_scaled - w->cluster.tc_scaled - delta;
220 bgsize += 1 + 1 + mk_ebmlSIntSize(ref);
223 CHECK(mk_writeID(w->cluster.context, 0xa0)); // BlockGroup
224 CHECK(mk_writeSize(w->cluster.context, bgsize));
225 CHECK(mk_writeID(w->cluster.context, 0xa1)); // Block
227 switch (track->frame.lacing) {
228 case MK_LACING_XIPH:
229 laced = mk_laceXiph(track->frame.lacing_sizes, track->frame.lacing_num_frames, &length);
230 break;
231 case MK_LACING_EBML:
232 length += mk_ebmlSizeSize(track->frame.lacing_sizes[0]) + 1;
233 for (i = 1; i < track->frame.lacing_num_frames; i++)
234 length += mk_ebmlSizeSize(track->frame.lacing_sizes[i] << 1);
235 break;
236 case MK_LACING_FIXED:
238 laced = calloc(1, sizeof(char));
239 laced[0] = track->frame.lacing_num_frames;
240 ++length;
242 break;
245 CHECK(mk_writeSize(w->cluster.context, fsize + 4 + length));
246 CHECK(mk_writeSize(w->cluster.context, track->track_id)); // track number
248 w->cluster.block_count++;
250 c_delta_flags[0] = delta >> 8;
251 c_delta_flags[1] = delta;
252 CHECK(mk_appendContextData(w->cluster.context, c_delta_flags, 2));
254 flags = ( track->frame.keyframe << 8 ) | track->frame.lacing;
255 CHECK(mk_appendContextData(w->cluster.context, &flags, 1));
256 if (track->frame.lacing) {
257 if (track->frame.lacing == MK_LACING_EBML) {
258 CHECK(mk_appendContextData(w->cluster.context, &track->frame.lacing_num_frames, 1));
259 CHECK(mk_writeSize(w->cluster.context, track->frame.lacing_sizes[0]));
260 for (i = 1; i < track->frame.lacing_num_frames; i++)
262 CHECK(mk_writeSSize(w->cluster.context, track->frame.lacing_sizes[i] - track->frame.lacing_sizes[i-1]));
264 } else if (length > 0 && laced != NULL) {
265 CHECK(mk_appendContextData(w->cluster.context, laced, length));
266 free(laced);
267 laced = NULL;
271 if (track->frame.data) {
272 CHECK(mk_appendContextData(w->cluster.context, track->frame.data->data, track->frame.data->d_cur));
273 track->frame.data->d_cur = 0;
275 if (!track->frame.keyframe)
276 CHECK(mk_writeSInt(w->cluster.context, 0xfb, ref)); // ReferenceBlock
278 if (track->cue_flag && track->frame.keyframe) {
279 if (w->cue_point.timecode != track->frame.timecode) {
280 if (w->cue_point.context != NULL) {
281 CHECK(mk_closeContext(w->cue_point.context, 0));
282 w->cue_point.context = NULL;
285 if (w->cue_point.context == NULL) {
286 if ((w->cue_point.context = mk_createContext(w, w->cues, 0xbb)) == NULL) // CuePoint
287 return -1;
288 CHECK(mk_writeUInt(w->cue_point.context, 0xb3, track->frame.timecode)); // CueTime
289 w->cue_point.timecode = track->frame.timecode;
292 if ((c = mk_createContext(w, w->cue_point.context, 0xb7)) == NULL) // CueTrackPositions
293 return -1;
294 CHECK(mk_writeUInt(c, 0xf7, track->track_id)); // CueTrack
295 CHECK(mk_writeUInt(c, 0xf1, w->cluster.pointer)); // CueClusterPosition
296 CHECK(mk_writeUInt(c, 0x5378, w->cluster.block_count)); // CueBlockNumber
297 CHECK(mk_closeContext(c, 0));
298 track->cue_flag = 0;
301 track->in_frame = 0;
302 track->prev_frame_tc_scaled = w->cluster.tc_scaled + delta;
304 if (w->cluster.context->d_cur > CLSIZE)
305 CHECK(mk_closeCluster(w));
307 return 0;
310 int mk_startFrame(mk_Writer *w, mk_Track *track) {
311 if (mk_flushFrame(w, track) < 0)
312 return -1;
314 track->in_frame = 1;
315 track->frame.keyframe = 0;
316 track->frame.lacing = MK_LACING_NONE;
317 track->frame.lacing_num_frames = 0;
318 track->frame.lacing_sizes = NULL;
320 return 0;
323 int mk_setFrameFlags(mk_Writer *w, mk_Track *track, int64_t timestamp, unsigned keyframe) {
324 if (!track->in_frame)
325 return -1;
327 track->frame.timecode = timestamp;
328 track->frame.keyframe = keyframe != 0;
330 if (track->max_frame_tc < timestamp)
331 track->max_frame_tc = timestamp;
333 return 0;
336 int mk_setFrameLacing(mk_Writer *w, mk_Track *track, uint8_t lacing, uint8_t num_frames, uint32_t sizes[]) {
337 if (!track->in_frame)
338 return -1;
339 track->frame.lacing_sizes = calloc(num_frames, sizeof(uint32_t));
341 track->frame.lacing = lacing;
342 track->frame.lacing_num_frames = num_frames;
343 memcpy(track->frame.lacing_sizes, sizes, num_frames);
345 return 0;
348 int mk_addFrameData(mk_Writer *w, mk_Track *track, const void *data, unsigned size) {
349 if (!track->in_frame)
350 return -1;
352 if (track->frame.data == NULL)
353 if ((track->frame.data = mk_createContext(w, NULL, 0)) == NULL)
354 return -1;
356 return mk_appendContextData(track->frame.data, data, size);
359 /* The offset of the SeekHead is returned in *pointer. */
360 int mk_writeSeek(mk_Writer *w, int64_t *pointer) {
361 mk_Context *c, *s;
362 int64_t seekhead_ptr;
364 if ((c = mk_createContext(w, w->root, 0x114d9b74)) == NULL) // SeekHead
365 return -1;
366 if (pointer != NULL)
367 seekhead_ptr = ftell(w->fp);
368 if (w->seek_data.seekhead) {
369 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
370 return -1;
371 CHECK(mk_writeUInt(s, 0x53ab, 0x114d9b74)); // SeekID
372 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.seekhead)); // SeekPosition
373 CHECK(mk_closeContext(s, 0));
375 if (w->seek_data.segmentinfo) {
376 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
377 return -1;
378 CHECK(mk_writeUInt(s, 0x53ab, 0x1549a966)); // SeekID
379 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.segmentinfo)); // SeekPosition
380 CHECK(mk_closeContext(s, 0));
382 if (w->seek_data.tracks) {
383 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
384 return -1;
385 CHECK(mk_writeUInt(s, 0x53ab, 0x1654ae6b)); // SeekID
386 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.tracks)); // SeekPosition
387 CHECK(mk_closeContext(s, 0));
389 if (w->seek_data.cues) {
390 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
391 return -1;
392 CHECK(mk_writeUInt(s, 0x53ab, 0x1c53bb6b)); // SeekID
393 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.cues)); // SeekPosition
394 CHECK(mk_closeContext(s, 0));
396 if (w->seek_data.attachments) {
397 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
398 return -1;
399 CHECK(mk_writeUInt(s, 0x53ab, 0x1941a469)); // SeekID
400 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.attachments)); // SeekPosition
401 CHECK(mk_closeContext(s, 0));
403 if (w->seek_data.chapters) {
404 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
405 return -1;
406 CHECK(mk_writeUInt(s, 0x53ab, 0x1043a770)); // SeekID
407 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.chapters)); // SeekPosition
408 CHECK(mk_closeContext(s, 0));
410 if (w->seek_data.tags) {
411 if ((s = mk_createContext(w, c, 0x4dbb)) == NULL) // Seek
412 return -1;
413 CHECK(mk_writeUInt(s, 0x53ab, 0x1254c367)); // SeekID
414 CHECK(mk_writeUInt(s, 0x53ac, w->seek_data.tags)); // SeekPosition
415 CHECK(mk_closeContext(s, 0));
417 CHECK(mk_closeContext(c, 0));
419 if (pointer != NULL)
420 *pointer = seekhead_ptr;
422 return 0;
425 int mk_close(mk_Writer *w) {
426 int i, ret = 0;
427 mk_Track *tk;
428 int64_t max_frame_tc = w->tracks_arr[0]->max_frame_tc;
430 for (i = w->num_tracks - 1; i >= 0; i--)
432 tk = w->tracks_arr[i];
433 w->tracks_arr[i] = NULL;
434 if (mk_flushFrame(w, tk) < 0)
435 ret = -1;
436 free(tk);
437 tk = NULL;
440 if (mk_closeCluster(w) < 0)
441 ret = -1;
443 if (w->chapters != NULL)
445 if (w->vlc_compat) {
446 if (mk_seekFile(w, w->segment_ptr + 0x103) < 0)
447 ret = -1;
449 w->seek_data.chapters = ftell(w->fp) - w->segment_ptr;
450 mk_writeChapters(w);
451 if (w->vlc_compat) {
452 if (mk_flushContextData(w->root) < 0)
453 ret = -1;
454 if (mk_writeVoid(w->root, (0x800 - (ftell(w->fp) - w->segment_ptr))) < 0)
455 ret = -1;
457 if (mk_flushContextData(w->root) < 0)
458 ret = -1;
461 w->seek_data.cues = ftell(w->fp) - w->segment_ptr;
462 if (w->cue_point.context != NULL)
463 if (mk_closeContext(w->cue_point.context, 0) < 0)
464 ret = -1;
465 // if (w->vlc_compat) {
466 // if (mk_seekFile(w, w->segment_ptr + 259 + 2051) < 0)
467 // ret = -1;
468 // }
469 if (mk_closeContext(w->cues, 0) < 0)
470 ret = -1;
471 if (w->vlc_compat) {
472 if (mk_flushContextData(w->root) < 0)
473 ret = -1;
474 if (mk_writeVoid(w->root, (0x1000 - (ftell(w->fp) - w->segment_ptr))) < 0)
475 ret = -1;
477 if (mk_flushContextData(w->root) < 0)
478 ret = -1;
480 if (w->wrote_header) {
481 if (w->vlc_compat) {
482 if (mk_seekFile(w, w->segment_ptr) < 0)
483 ret = -1;
486 if (mk_writeSeek(w, &w->seek_data.seekhead) < 0)
487 ret = -1;
488 w->seek_data.seekhead -= w->segment_ptr;
490 if (w->vlc_compat)
492 if (mk_flushContextData(w->root) < 0)
493 ret = -1;
494 if (mk_writeVoid(w->root, (256 - (ftell(w->fp) - w->segment_ptr))) < 0)
495 ret = -1;
498 if (mk_flushContextData(w->root) < 0)
499 ret = -1;
501 if (!w->vlc_compat)
503 int i = w->seek_data.segmentinfo;
504 w->seek_data.segmentinfo = 0;
505 w->seek_data.tracks = 0;
506 w->seek_data.cues = 0;
507 w->seek_data.chapters = 0;
508 w->seek_data.attachments = 0;
509 w->seek_data.tags = 0;
510 if (mk_seekFile(w, w->segment_ptr) < 0)
511 ret = -1;
512 if (mk_writeSeek(w, NULL) < 0 ||
513 mk_flushContextData(w->root) < 0)
514 ret = -1;
515 if (((i + w->segment_ptr) - ftell(w->fp) - 2) > 1)
516 if (mk_writeVoid(w->root, (i + w->segment_ptr) - ftell(w->fp) - 2) < 0 ||
517 mk_flushContextData(w->root) < 0)
518 ret = -1;
521 if (mk_seekFile(w, w->duration_ptr) < 0)
522 ret = -1;
523 if (mk_writeFloatRaw(w->root, (float)((double)(max_frame_tc+w->def_duration) / w->timescale)) < 0 ||
524 mk_flushContextData(w->root) < 0)
525 ret = -1;
528 if (mk_closeContext(w->root, 0) < 1)
529 ret = -1;
530 mk_destroyContexts(w);
531 fclose(w->fp);
532 free(w->tracks_arr);
533 free(w);
535 return ret;