1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2005 x264 project
6 * Authors: Mike Matsnev
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
22 *****************************************************************************/
28 #define RESERVED_SEEKHEAD 0x100
29 /* 256 bytes should be enough room for our Seek entries. */
30 #define RESERVED_CHAPTERS 0x800
31 /* 2048 bytes, hopefully enough for Chapters. */
33 int mk_seekFile(mk_Writer
*w
, uint64_t pos
)
35 if (fseek(w
->fp
, pos
, SEEK_SET
))
46 char *mk_laceXiph(uint64_t *sizes
, uint8_t num_frames
,
47 uint64_t *output_size
)
51 uint64_t alloc_size
= num_frames
* 6; /* Complete guess. It gets realloc'd
52 * below if we need more space, though.
54 char *laced
= calloc(alloc_size
, sizeof(*laced
));
58 laced
[offset
++] = num_frames
;
59 for (i
= 0; i
< num_frames
; i
++) {
60 for (j
= sizes
[i
]; j
>= 255; j
-= 255) {
61 laced
[offset
++] = 255;
62 if (offset
+ 1 >= alloc_size
) {
63 int avg_sz
= offset
/ (i
- 1); /* Compute approximate average bytes/frame */
64 alloc_size
+= avg_sz
* (num_frames
- i
);
65 /* Sum average so far and number of frames left
68 if ((laced
= realloc(laced
, alloc_size
)) == NULL
)
75 if (output_size
!= NULL
)
76 *output_size
= offset
;
81 mk_Writer
*mk_createWriter(const char *filename
, int64_t timescale
,
84 mk_Writer
*w
= calloc(1, sizeof(*w
));
88 w
->root
= mk_createContext(w
, NULL
, 0);
89 if (w
->root
== NULL
) {
95 if ((w
->cues
= mk_createContext(w
, w
->root
, MATROSKA_ID_CUES
)) == NULL
)
97 mk_destroyContexts(w
);
102 /* Clusters SeekHead */
103 if ((w
->cluster
.seekhead
= mk_createContext(w
, w
->root
, MATROSKA_ID_SEEKHEAD
)) == NULL
)
105 mk_destroyContexts(w
);
110 w
->fp
= fopen(filename
, "wb");
112 mk_destroyContexts(w
);
117 w
->timescale
= timescale
;
118 w
->vlc_compat
= vlc_compat
;
123 int mk_writeHeader(mk_Writer
*w
, const char *writingApp
)
131 md5_starts(&w
->segment_md5
); /* Initalize MD5 */
133 CHECK(mk_writeEbmlHeader(w
, "matroska", MATROSKA_VERSION
, MATROSKA_VERSION
));
136 if ((c
= mk_createContext(w
, w
->root
, MATROSKA_ID_SEGMENT
)) == NULL
)
138 CHECK(mk_flushContextID(c
));
139 w
->segment_ptr
= c
->d_cur
;
140 CHECK(mk_closeContext(c
, &w
->segment_ptr
));
143 CHECK(mk_writeVoid(w
->root
, RESERVED_SEEKHEAD
)); /* Reserved space for SeekHead */
144 CHECK(mk_writeVoid(w
->root
, RESERVED_CHAPTERS
)); /* Reserved space for Chapters */
146 w
->seek_data
.seekhead
= 0x80000000;
147 CHECK(mk_writeSeekHead(w
, &w
->seekhead_ptr
));
148 w
->seek_data
.seekhead
= 0;
151 if ((c
= mk_createContext(w
, w
->root
, MATROSKA_ID_INFO
)) == NULL
) /* SegmentInfo */
153 w
->seek_data
.segmentinfo
= w
->root
->d_cur
- w
->segment_ptr
;
154 CHECK(mk_writeVoid(c
, 16)); /* Reserve space for a SegmentUID, to be written it later. */
155 CHECK(mk_writeStr(c
, MATROSKA_ID_MUXINGAPP
, PACKAGE_STRING
)); /* MuxingApp */
156 CHECK(mk_writeStr(c
, MATROSKA_ID_WRITINGAPP
, writingApp
)); /* WritingApp */
157 CHECK(mk_writeUInt(c
, MATROSKA_ID_TIMECODESCALE
, w
->timescale
)); /* TimecodeScale */
158 CHECK(mk_writeFloat(c
, MATROSKA_ID_DURATION
, 0)); /* Duration */
159 w
->duration_ptr
= c
->d_cur
- 4;
160 CHECK(mk_closeContext(c
, &offset
));
161 w
->duration_ptr
+= offset
;
162 w
->segmentuid_ptr
= offset
;
164 w
->seek_data
.tracks
= w
->root
->d_cur
- w
->segment_ptr
;
167 CHECK(mk_closeContext(w
->tracks
, 0));
169 CHECK(mk_flushContextData(w
->root
));
172 w
->def_duration
= w
->tracks_arr
[0]->default_duration
;
176 static int mk_closeCluster(mk_Writer
*w
)
178 if (w
->cluster
.context
== NULL
)
181 CHECK(mk_closeContext(w
->cluster
.context
, 0));
182 w
->cluster
.context
= NULL
;
183 CHECK(mk_flushContextData(w
->root
));
188 int mk_flushFrame(mk_Writer
*w
, mk_Track
*track
)
191 int64_t delta
, ref
= 0;
192 unsigned fsize
, bgsize
;
193 uint8_t flags
, c_delta
[2];
198 if (!track
->in_frame
)
201 delta
= track
->frame
.timecode
/ w
->timescale
- w
->cluster
.tc_scaled
;
202 /* If switch rapidly back-and-forth between tracks with drastically different timecodes
203 * this causes a new cluster to be written each time a switch is made. This causes
204 * unnecessary overhead.
207 if (delta
> 20000ll || delta
< -20000ll)
208 CHECK(mk_closeCluster(w
));
210 if (w
->cluster
.context
== NULL
) {
211 w
->cluster
.tc_scaled
= track
->frame
.timecode
/ w
->timescale
;
213 w
->cluster
.context
= mk_createContext(w
, w
->root
, MATROSKA_ID_CLUSTER
);
214 if (w
->cluster
.context
== NULL
)
217 w
->cluster
.pointer
= w
->f_pos
- w
->segment_ptr
;
219 /* Cluster SeekEntry */
220 CHECK(mk_writeSeek(w
, w
->cluster
.seekhead
, MATROSKA_ID_CLUSTER
,
221 w
->cluster
.pointer
));
223 /* Cluster Timecode */
224 CHECK(mk_writeUInt(w
->cluster
.context
, MATROSKA_ID_CLUSTERTIMECODE
, w
->cluster
.tc_scaled
));
227 w
->cluster
.block_count
= 0;
230 /* Calculate the encoded lacing sizes. */
231 switch (track
->frame
.lacing
) {
233 laced
= mk_laceXiph(track
->frame
.lacing_sizes
,
234 track
->frame
.lacing_num_frames
, &length
);
239 /* Add one below for the frame count. */
240 length
+= mk_ebmlSizeSize(track
->frame
.lacing_sizes
[0]) + 1;
241 for (i
= 1; i
< track
->frame
.lacing_num_frames
; i
++) {
242 u_size
= llabs(track
->frame
.lacing_sizes
[i
] -
243 track
->frame
.lacing_sizes
[i
- 1]);
244 /* Shift by one so we get the right size for a signed number. */
245 length
+= mk_ebmlSizeSize((u_size
) << 1);
249 case MK_LACING_FIXED
:
251 laced
= calloc(1, sizeof(*laced
));
252 laced
[0] = track
->frame
.lacing_num_frames
;
260 fsize
= track
->frame
.data
? track
->frame
.data
->d_cur
: 0;
261 bgsize
= fsize
+ 4 + mk_ebmlSizeSize(fsize
+ 4 + length
) + 1 + length
;
262 if (!track
->frame
.keyframe
) {
263 ref
= track
->prev_frame_tc_scaled
- w
->cluster
.tc_scaled
- delta
;
264 bgsize
+= 1 + 1 + mk_ebmlSIntSize(ref
);
266 if (track
->frame
.duration
> 0) /* BlockDuration */
268 bgsize
+= 1 + 1 + mk_ebmlUIntSize(track
->frame
.duration
);
271 CHECK(mk_writeID(w
->cluster
.context
, MATROSKA_ID_BLOCKGROUP
)); /* BlockGroup */
272 CHECK(mk_writeSize(w
->cluster
.context
, bgsize
));
273 CHECK(mk_writeID(w
->cluster
.context
, MATROSKA_ID_BLOCK
)); /* Block */
274 CHECK(mk_writeSize(w
->cluster
.context
, fsize
+ 4 + length
)); /* BlockSize */
275 CHECK(mk_writeSize(w
->cluster
.context
, track
->track_id
)); /* track number */
277 w
->cluster
.block_count
++;
279 c_delta
[0] = delta
>> 8;
281 /* Timecode relative to Cluster. */
282 CHECK(mk_appendContextData(w
->cluster
.context
, c_delta
, 2));
284 /* flags = ( track->frame.keyframe << 8 ) | track->frame.lacing; */
285 flags
= track
->frame
.lacing
<< 1; /* Flags: Bit 5-6 describe what type of lacing to use. */
286 CHECK(mk_appendContextData(w
->cluster
.context
, &flags
, 1));
287 if (track
->frame
.lacing
) {
288 if (track
->frame
.lacing
== MK_LACING_EBML
) {
289 /* Number of frames in lace - 1 */
290 CHECK(mk_appendContextData(w
->cluster
.context
, &track
->frame
.lacing_num_frames
, 1));
291 /* Size of 1st frame. */
292 CHECK(mk_writeSize(w
->cluster
.context
, track
->frame
.lacing_sizes
[0]));
293 for (i
= 1; i
< track
->frame
.lacing_num_frames
; i
++) {
294 /* Size difference between previous size and this size. */
295 CHECK(mk_writeSSize(w
->cluster
.context
, track
->frame
.lacing_sizes
[i
] - track
->frame
.lacing_sizes
[i
- 1]));
297 } else if (length
> 0 && laced
!= NULL
) {
298 CHECK(mk_appendContextData(w
->cluster
.context
, laced
, length
));
304 if (track
->frame
.data
) {
305 CHECK(mk_appendContextData(w
->cluster
.context
, track
->frame
.data
->data
,
306 track
->frame
.data
->d_cur
));
307 track
->frame
.data
->d_cur
= 0;
309 if (!track
->frame
.keyframe
) /* ReferenceBlock */
310 CHECK(mk_writeSInt(w
->cluster
.context
, MATROSKA_ID_REFERENCEBLOCK
, ref
));
312 if (track
->frame
.duration
> 0) /* BlockDuration */
313 CHECK(mk_writeUInt(w
->cluster
.context
, 0x9b, track
->frame
.duration
));
315 /* This may get a little out of hand, but it seems sane enough for now. */
316 if (track
->frame
.keyframe
&& (track
->track_type
== MK_TRACK_VIDEO
)) {
317 /* if (track->frame.keyframe && (track->track_type & MK_TRACK_VIDEO) && ((track->prev_cue_pos + 3*CLSIZE) <= w->f_pos || track->frame.timecode == 0)) { */
319 if ((c
= mk_createContext(w
, w
->cues
, MATROSKA_ID_CUEPOINT
)) == NULL
)
322 CHECK(mk_writeUInt(c
, MATROSKA_ID_CUETIME
, (track
->frame
.timecode
/ w
->timescale
)));
324 /* CueTrackPositions */
325 if ((tp
= mk_createContext(w
, c
, MATROSKA_ID_CUETRACKPOSITIONS
)) == NULL
)
328 CHECK(mk_writeUInt(tp
, MATROSKA_ID_CUETRACK
, track
->track_id
));
329 /* CueClusterPosition */
330 CHECK(mk_writeUInt(tp
, MATROSKA_ID_CUECLUSTERPOSITION
, w
->cluster
.pointer
));
332 /* CHECK(mk_writeUInt(c, MATROSKA_ID_CUEBLOCKNUMBER, w->cluster.block_count)); */
333 CHECK(mk_closeContext(tp
, 0));
334 CHECK(mk_closeContext(c
, 0));
335 track
->prev_cue_pos
= w
->f_pos
;
339 track
->prev_frame_tc_scaled
= w
->cluster
.tc_scaled
+ delta
;
341 /* Write a new Cluster ~ every 5MB */
342 if (w
->cluster
.context
->d_cur
> 5 * CLSIZE
)
343 CHECK(mk_closeCluster(w
));
348 int mk_startFrame(mk_Writer
*w
, mk_Track
*track
)
350 if (mk_flushFrame(w
, track
) < 0)
354 track
->frame
.keyframe
= 0;
355 track
->frame
.lacing
= MK_LACING_NONE
;
356 track
->frame
.lacing_num_frames
= 0;
357 track
->frame
.lacing_sizes
= NULL
;
362 int mk_setFrameFlags(mk_Writer
*w
, mk_Track
*track
, int64_t timestamp
,
363 unsigned keyframe
, uint64_t duration
)
365 if (!track
->in_frame
)
368 track
->frame
.timecode
= timestamp
;
369 track
->frame
.keyframe
= keyframe
!= 0;
371 if (track
->max_frame_tc
< timestamp
)
372 track
->max_frame_tc
= timestamp
;
375 track
->frame
.duration
= duration
;
380 int mk_setFrameLacing(mk_Writer
*w
, mk_Track
*track
,
381 mk_LacingType lacing
, uint8_t num_frames
,
384 if (!track
->in_frame
)
386 track
->frame
.lacing_sizes
= calloc(num_frames
, sizeof(*sizes
));
388 track
->frame
.lacing
= lacing
;
389 track
->frame
.lacing_num_frames
= num_frames
;
390 memcpy(track
->frame
.lacing_sizes
, sizes
,
391 num_frames
* sizeof(*sizes
));
396 int mk_addFrameData(mk_Writer
*w
, mk_Track
*track
, const void *data
,
399 if (!track
->in_frame
)
402 if (track
->frame
.data
== NULL
) {
403 if ((track
->frame
.data
= mk_createContext(w
, NULL
, 0)) == NULL
)
407 md5_update(&w
->segment_md5
, (unsigned char *) data
, size
);
409 return mk_appendContextData(track
->frame
.data
, data
, size
);
412 int mk_writeSeek(mk_Writer
*w
, mk_Context
*c
, unsigned seek_id
,
417 if ((s
= mk_createContext(w
, c
, MATROSKA_ID_SEEKENTRY
)) == NULL
) /* Seek */
419 CHECK(mk_writeUInt(s
, MATROSKA_ID_SEEKID
, seek_id
)); /* SeekID */
420 CHECK(mk_writeUInt(s
, MATROSKA_ID_SEEKPOSITION
, seek_pos
)); /* SeekPosition */
421 CHECK(mk_closeContext(s
, 0));
426 /* The offset of the SeekHead is returned in pointer. */
427 int mk_writeSeekHead(mk_Writer
*w
, int64_t *pointer
)
430 int64_t seekhead_ptr
;
433 if ((c
= mk_createContext(w
, w
->root
, MATROSKA_ID_SEEKHEAD
)) == NULL
)
436 seekhead_ptr
= w
->f_pos
;
437 if (w
->seek_data
.seekhead
)
438 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_SEEKHEAD
, w
->seek_data
.seekhead
));
439 if (w
->seek_data
.segmentinfo
)
440 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_INFO
, w
->seek_data
.segmentinfo
));
441 if (w
->seek_data
.tracks
)
442 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_TRACKS
, w
->seek_data
.tracks
));
443 if (w
->seek_data
.cues
)
444 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_CUES
, w
->seek_data
.cues
));
445 if (w
->seek_data
.attachments
)
446 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_ATTACHMENTS
, w
->seek_data
.attachments
));
447 if (w
->seek_data
.chapters
)
448 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_CHAPTERS
, w
->seek_data
.chapters
));
449 if (w
->seek_data
.tags
)
450 CHECK(mk_writeSeek(w
, c
, MATROSKA_ID_TAGS
, w
->seek_data
.tags
));
451 CHECK(mk_closeContext(c
, 0));
454 *pointer
= seekhead_ptr
;
459 int mk_close(mk_Writer
*w
)
463 int64_t max_frame_tc
= w
->tracks_arr
[0]->max_frame_tc
;
464 uint64_t segment_size
= 0;
465 unsigned char c_size
[8];
466 unsigned char segment_uid
[16];
468 md5_finish(&w
->segment_md5
, segment_uid
);
470 for (i
= w
->num_tracks
- 1; i
>= 0; i
--) {
471 tk
= w
->tracks_arr
[i
];
472 w
->tracks_arr
[i
] = NULL
;
474 if (mk_flushFrame(w
, tk
) < 0)
480 if (mk_closeCluster(w
) < 0)
483 w
->seek_data
.cues
= w
->f_pos
- w
->segment_ptr
;
484 if (mk_closeContext(w
->cues
, 0) < 0)
486 if (mk_flushContextData(w
->root
) < 0)
489 if (w
->cluster
.seekhead
) {
490 w
->seek_data
.seekhead
= w
->f_pos
- w
->segment_ptr
;
491 if (mk_closeContext(w
->cluster
.seekhead
, 0) < 0)
493 if (mk_flushContextData(w
->root
) < 0)
497 if (w
->chapters
!= NULL
) {
499 if (mk_flushContextData(w
->root
) < 0)
501 if (mk_seekFile(w
, w
->segment_ptr
+ RESERVED_SEEKHEAD
+ 3) < 0)
504 w
->seek_data
.chapters
= w
->f_pos
- w
->segment_ptr
;
506 if (mk_flushContextData(w
->root
) < 0)
509 if (mk_writeVoid(w
->root
, (RESERVED_CHAPTERS
- (w
->f_pos
- w
->segment_ptr
- RESERVED_SEEKHEAD
- 3))) < 0)
511 if (mk_flushContextData(w
->root
) < 0)
516 if (w
->tags
!= NULL
) {
517 w
->seek_data
.tags
= w
->f_pos
- w
->segment_ptr
;
519 if (mk_flushContextData(w
->root
) < 0)
523 if (w
->wrote_header
) {
525 if (mk_seekFile(w
, w
->segment_ptr
) < 0)
529 if (mk_writeSeekHead(w
, &w
->seek_data
.seekhead
) < 0)
531 w
->seek_data
.seekhead
-= w
->segment_ptr
;
534 if (mk_flushContextData(w
->root
) < 0)
536 if (mk_writeVoid(w
->root
, (RESERVED_SEEKHEAD
- (w
->f_pos
- w
->segment_ptr
))) < 0)
540 if (mk_flushContextData(w
->root
) < 0)
543 if (!w
->vlc_compat
) {
544 int i
= w
->seek_data
.segmentinfo
;
545 w
->seek_data
.segmentinfo
= 0;
546 w
->seek_data
.tracks
= 0;
547 w
->seek_data
.cues
= 0;
548 w
->seek_data
.chapters
= 0;
549 w
->seek_data
.attachments
= 0;
550 w
->seek_data
.tags
= 0;
551 if (mk_seekFile(w
, w
->segment_ptr
) < 0)
553 if (mk_writeSeekHead(w
, NULL
) < 0 || mk_flushContextData(w
->root
) < 0)
555 // The conditional below is easier to understand, but incorrect
556 // because f_pos is unsigned and causes the lhs to be evaluated
557 // as an unsigned quantity.
558 // if (((i + w->segment_ptr) - w->f_pos - 2) > 1)
559 if ((i
+ w
->segment_ptr
) > (w
->f_pos
+ 3))
560 if (mk_writeVoid(w
->root
, (i
+ w
->segment_ptr
) - w
->f_pos
- 2) < 0
561 || mk_flushContextData(w
->root
) < 0)
565 if (mk_seekFile(w
, w
->duration_ptr
) < 0)
567 if (mk_writeFloatRaw(w
->root
,
568 (float) ((double) (max_frame_tc
+ w
->def_duration
) /
570 || mk_flushContextData(w
->root
) < 0)
572 if (mk_seekFile(w
, w
->segment_ptr
- 8) < 0)
574 segment_size
= w
->f_eof
- w
->segment_ptr
;
575 for (i
= 7; i
> 0; --i
)
576 c_size
[i
] = segment_size
>> (8 * (7 - i
));
578 if (mk_appendContextData(w
->root
, &c_size
, 8) < 0 ||
579 mk_flushContextData(w
->root
) < 0)
581 if (mk_seekFile(w
, w
->segmentuid_ptr
) < 0)
583 if (mk_writeBin(w
->root
, MATROSKA_ID_SEGMENTUID
, segment_uid
,
584 sizeof(segment_uid
)) < 0 ||
585 mk_flushContextData(w
->root
) < 0)
589 if (mk_closeContext(w
->root
, 0) < 0)
591 mk_destroyContexts(w
);