mkvmuxer.hpp 51.5 KB
Newer Older
1
//
2
3
4
5
6
7
8
9
10
11
// Copyright (c) 2016, Alliance for Open Media. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.
//

12
13
14
15
16
17
18
19
20
21

#ifndef MKVMUXER_HPP
#define MKVMUXER_HPP

#include "mkvmuxertypes.hpp"

// For a description of the WebM elements see
// http://www.webmproject.org/code/specs/container/.

namespace mkvparser {
22
class IMkvReader;
23
24
25
26
27
28
29
}  // end namespace

namespace mkvmuxer {

class MkvWriter;
class Segment;

30
31
const uint64 kMaxTrackNumber = 126;

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
///////////////////////////////////////////////////////////////
// Interface used by the mkvmuxer to write out the Mkv data.
class IMkvWriter {
 public:
  // Writes out |len| bytes of |buf|. Returns 0 on success.
  virtual int32 Write(const void* buf, uint32 len) = 0;

  // Returns the offset of the output position from the beginning of the
  // output.
  virtual int64 Position() const = 0;

  // Set the current File position. Returns 0 on success.
  virtual int32 Position(int64 position) = 0;

  // Returns true if the writer is seekable.
  virtual bool Seekable() const = 0;

  // Element start notification. Called whenever an element identifier is about
  // to be written to the stream. |element_id| is the element identifier, and
  // |position| is the location in the WebM stream where the first octet of the
  // element identifier will be written.
  // Note: the |MkvId| enumeration in webmids.hpp defines element values.
  virtual void ElementStartNotify(uint64 element_id, int64 position) = 0;

 protected:
  IMkvWriter();
  virtual ~IMkvWriter();

 private:
  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(IMkvWriter);
};

// Writes out the EBML header for a WebM file. This function must be called
// before any other libwebm writing functions are called.
66
67
68
69
bool WriteEbmlHeader(IMkvWriter* writer, uint64 doc_type_version);

// Deprecated. Writes out EBML header with doc_type_version as
// kDefaultDocTypeVersion. Exists for backward compatibility.
70
71
72
bool WriteEbmlHeader(IMkvWriter* writer);

// Copies in Chunk from source to destination between the given byte positions
73
74
bool ChunkedCopy(mkvparser::IMkvReader* source, IMkvWriter* dst, int64 start,
                 int64 size);
75
76
77
78
79
80
81
82

///////////////////////////////////////////////////////////////
// Class to hold data the will be written to a block.
class Frame {
 public:
  Frame();
  ~Frame();

83
84
85
86
  // Sets this frame's contents based on |frame|. Returns true on success. On
  // failure, this frame's existing contents may be lost.
  bool CopyFrom(const Frame& frame);

87
88
89
90
  // Copies |frame| data into |frame_|. Returns true on success.
  bool Init(const uint8* frame, uint64 length);

  // Copies |additional| data into |additional_|. Returns true on success.
91
  bool AddAdditionalData(const uint8* additional, uint64 length, uint64 add_id);
92

93
94
95
96
97
98
99
  // Returns true if the frame has valid parameters.
  bool IsValid() const;

  // Returns true if the frame can be written as a SimpleBlock based on current
  // parameters.
  bool CanBeSimpleBlock() const;

100
101
102
103
104
105
106
107
108
109
110
111
112
  uint64 add_id() const { return add_id_; }
  const uint8* additional() const { return additional_; }
  uint64 additional_length() const { return additional_length_; }
  void set_duration(uint64 duration) { duration_ = duration; }
  uint64 duration() const { return duration_; }
  const uint8* frame() const { return frame_; }
  void set_is_key(bool key) { is_key_ = key; }
  bool is_key() const { return is_key_; }
  uint64 length() const { return length_; }
  void set_track_number(uint64 track_number) { track_number_ = track_number; }
  uint64 track_number() const { return track_number_; }
  void set_timestamp(uint64 timestamp) { timestamp_ = timestamp; }
  uint64 timestamp() const { return timestamp_; }
113
  void set_discard_padding(int64 discard_padding) {
114
115
    discard_padding_ = discard_padding;
  }
116
117
118
119
120
121
  int64 discard_padding() const { return discard_padding_; }
  void set_reference_block_timestamp(int64 reference_block_timestamp);
  int64 reference_block_timestamp() const { return reference_block_timestamp_; }
  bool reference_block_timestamp_set() const {
    return reference_block_timestamp_set_;
  }
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

 private:
  // Id of the Additional data.
  uint64 add_id_;

  // Pointer to additional data. Owned by this class.
  uint8* additional_;

  // Length of the additional data.
  uint64 additional_length_;

  // Duration of the frame in nanoseconds.
  uint64 duration_;

  // Pointer to the data. Owned by this class.
  uint8* frame_;

  // Flag telling if the data should set the key flag of a block.
  bool is_key_;

  // Length of the data.
  uint64 length_;

  // Mkv track number the data is associated with.
  uint64 track_number_;

  // Timestamp of the data in nanoseconds.
  uint64 timestamp_;

  // Discard padding for the frame.
  int64 discard_padding_;
153
154
155
156
157
158
159
160

  // Reference block timestamp.
  int64 reference_block_timestamp_;

  // Flag indicating if |reference_block_timestamp_| has been set.
  bool reference_block_timestamp_set_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Frame);
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
};

///////////////////////////////////////////////////////////////
// Class to hold one cue point in a Cues element.
class CuePoint {
 public:
  CuePoint();
  ~CuePoint();

  // Returns the size in bytes for the entire CuePoint element.
  uint64 Size() const;

  // Output the CuePoint element to the writer. Returns true on success.
  bool Write(IMkvWriter* writer) const;

  void set_time(uint64 time) { time_ = time; }
  uint64 time() const { return time_; }
  void set_track(uint64 track) { track_ = track; }
  uint64 track() const { return track_; }
  void set_cluster_pos(uint64 cluster_pos) { cluster_pos_ = cluster_pos; }
  uint64 cluster_pos() const { return cluster_pos_; }
  void set_block_number(uint64 block_number) { block_number_ = block_number; }
  uint64 block_number() const { return block_number_; }
  void set_output_block_number(bool output_block_number) {
    output_block_number_ = output_block_number;
  }
  bool output_block_number() const { return output_block_number_; }

 private:
  // Returns the size in bytes for the payload of the CuePoint element.
  uint64 PayloadSize() const;

  // Absolute timecode according to the segment time base.
  uint64 time_;

  // The Track element associated with the CuePoint.
  uint64 track_;

  // The position of the Cluster containing the Block.
  uint64 cluster_pos_;

  // Number of the Block within the Cluster, starting from 1.
  uint64 block_number_;

  // If true the muxer will write out the block number for the cue if the
  // block number is different than the default of 1. Default is set to true.
  bool output_block_number_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(CuePoint);
};

///////////////////////////////////////////////////////////////
// Cues element.
class Cues {
 public:
  Cues();
  ~Cues();

  // Adds a cue point to the Cues element. Returns true on success.
  bool AddCue(CuePoint* cue);

  // Returns the cue point by index. Returns NULL if there is no cue point
  // match.
  CuePoint* GetCueByIndex(int32 index) const;

  // Returns the total size of the Cues element
  uint64 Size();

  // Output the Cues element to the writer. Returns true on success.
  bool Write(IMkvWriter* writer) const;

  int32 cue_entries_size() const { return cue_entries_size_; }
  void set_output_block_number(bool output_block_number) {
    output_block_number_ = output_block_number;
  }
  bool output_block_number() const { return output_block_number_; }

 private:
  // Number of allocated elements in |cue_entries_|.
  int32 cue_entries_capacity_;

  // Number of CuePoints in |cue_entries_|.
  int32 cue_entries_size_;

  // CuePoint list.
  CuePoint** cue_entries_;

  // If true the muxer will write out the block number for the cue if the
  // block number is different than the default of 1. Default is set to true.
  bool output_block_number_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Cues);
};

///////////////////////////////////////////////////////////////
// ContentEncAESSettings element
class ContentEncAESSettings {
 public:
259
  enum { kCTR = 1 };
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386

  ContentEncAESSettings();
  ~ContentEncAESSettings() {}

  // Returns the size in bytes for the ContentEncAESSettings element.
  uint64 Size() const;

  // Writes out the ContentEncAESSettings element to |writer|. Returns true on
  // success.
  bool Write(IMkvWriter* writer) const;

  uint64 cipher_mode() const { return cipher_mode_; }

 private:
  // Returns the size in bytes for the payload of the ContentEncAESSettings
  // element.
  uint64 PayloadSize() const;

  // Sub elements
  uint64 cipher_mode_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(ContentEncAESSettings);
};

///////////////////////////////////////////////////////////////
// ContentEncoding element
// Elements used to describe if the track data has been encrypted or
// compressed with zlib or header stripping.
// Currently only whole frames can be encrypted with AES. This dictates that
// ContentEncodingOrder will be 0, ContentEncodingScope will be 1,
// ContentEncodingType will be 1, and ContentEncAlgo will be 5.
class ContentEncoding {
 public:
  ContentEncoding();
  ~ContentEncoding();

  // Sets the content encryption id. Copies |length| bytes from |id| to
  // |enc_key_id_|. Returns true on success.
  bool SetEncryptionID(const uint8* id, uint64 length);

  // Returns the size in bytes for the ContentEncoding element.
  uint64 Size() const;

  // Writes out the ContentEncoding element to |writer|. Returns true on
  // success.
  bool Write(IMkvWriter* writer) const;

  uint64 enc_algo() const { return enc_algo_; }
  uint64 encoding_order() const { return encoding_order_; }
  uint64 encoding_scope() const { return encoding_scope_; }
  uint64 encoding_type() const { return encoding_type_; }
  ContentEncAESSettings* enc_aes_settings() { return &enc_aes_settings_; }

 private:
  // Returns the size in bytes for the encoding elements.
  uint64 EncodingSize(uint64 compresion_size, uint64 encryption_size) const;

  // Returns the size in bytes for the encryption elements.
  uint64 EncryptionSize() const;

  // Track element names
  uint64 enc_algo_;
  uint8* enc_key_id_;
  uint64 encoding_order_;
  uint64 encoding_scope_;
  uint64 encoding_type_;

  // ContentEncAESSettings element.
  ContentEncAESSettings enc_aes_settings_;

  // Size of the ContentEncKeyID data in bytes.
  uint64 enc_key_id_length_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(ContentEncoding);
};

///////////////////////////////////////////////////////////////
// Track element.
class Track {
 public:
  // The |seed| parameter is used to synthesize a UID for the track.
  explicit Track(unsigned int* seed);
  virtual ~Track();

  // Adds a ContentEncoding element to the Track. Returns true on success.
  virtual bool AddContentEncoding();

  // Returns the ContentEncoding by index. Returns NULL if there is no
  // ContentEncoding match.
  ContentEncoding* GetContentEncodingByIndex(uint32 index) const;

  // Returns the size in bytes for the payload of the Track element.
  virtual uint64 PayloadSize() const;

  // Returns the size in bytes of the Track element.
  virtual uint64 Size() const;

  // Output the Track element to the writer. Returns true on success.
  virtual bool Write(IMkvWriter* writer) const;

  // Sets the CodecPrivate element of the Track element. Copies |length|
  // bytes from |codec_private| to |codec_private_|. Returns true on success.
  bool SetCodecPrivate(const uint8* codec_private, uint64 length);

  void set_codec_id(const char* codec_id);
  const char* codec_id() const { return codec_id_; }
  const uint8* codec_private() const { return codec_private_; }
  void set_language(const char* language);
  const char* language() const { return language_; }
  void set_max_block_additional_id(uint64 max_block_additional_id) {
    max_block_additional_id_ = max_block_additional_id;
  }
  uint64 max_block_additional_id() const { return max_block_additional_id_; }
  void set_name(const char* name);
  const char* name() const { return name_; }
  void set_number(uint64 number) { number_ = number; }
  uint64 number() const { return number_; }
  void set_type(uint64 type) { type_ = type; }
  uint64 type() const { return type_; }
  void set_uid(uint64 uid) { uid_ = uid; }
  uint64 uid() const { return uid_; }
  void set_codec_delay(uint64 codec_delay) { codec_delay_ = codec_delay; }
  uint64 codec_delay() const { return codec_delay_; }
  void set_seek_pre_roll(uint64 seek_pre_roll) {
    seek_pre_roll_ = seek_pre_roll;
  }
  uint64 seek_pre_roll() const { return seek_pre_roll_; }
387
388
389
390
  void set_default_duration(uint64 default_duration) {
    default_duration_ = default_duration;
  }
  uint64 default_duration() const { return default_duration_; }
391
392
393
394
395
396
397

  uint64 codec_private_length() const { return codec_private_length_; }
  uint32 content_encoding_entries_size() const {
    return content_encoding_entries_size_;
  }

 private:
398
  // Track element names.
399
400
401
402
403
404
405
406
407
408
  char* codec_id_;
  uint8* codec_private_;
  char* language_;
  uint64 max_block_additional_id_;
  char* name_;
  uint64 number_;
  uint64 type_;
  uint64 uid_;
  uint64 codec_delay_;
  uint64 seek_pre_roll_;
409
  uint64 default_duration_;
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429

  // Size of the CodecPrivate data in bytes.
  uint64 codec_private_length_;

  // ContentEncoding element list.
  ContentEncoding** content_encoding_entries_;

  // Number of ContentEncoding elements added.
  uint32 content_encoding_entries_size_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Track);
};

///////////////////////////////////////////////////////////////
// Track that has video specific elements.
class VideoTrack : public Track {
 public:
  // Supported modes for stereo 3D.
  enum StereoMode {
    kMono = 0,
430
431
432
    kSideBySideLeftIsFirst = 1,
    kTopBottomRightIsFirst = 2,
    kTopBottomLeftIsFirst = 3,
433
434
435
    kSideBySideRightIsFirst = 11
  };

436
  enum AlphaMode { kNoAlpha = 0, kAlpha = 1 };
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

  // The |seed| parameter is used to synthesize a UID for the track.
  explicit VideoTrack(unsigned int* seed);
  virtual ~VideoTrack();

  // Returns the size in bytes for the payload of the Track element plus the
  // video specific elements.
  virtual uint64 PayloadSize() const;

  // Output the VideoTrack element to the writer. Returns true on success.
  virtual bool Write(IMkvWriter* writer) const;

  // Sets the video's stereo mode. Returns true on success.
  bool SetStereoMode(uint64 stereo_mode);

  // Sets the video's alpha mode. Returns true on success.
  bool SetAlphaMode(uint64 alpha_mode);

  void set_display_height(uint64 height) { display_height_ = height; }
  uint64 display_height() const { return display_height_; }
  void set_display_width(uint64 width) { display_width_ = width; }
  uint64 display_width() const { return display_width_; }
459
460
461
462
463
464
465
466
467
468

  void set_crop_left(uint64 crop_left) { crop_left_ = crop_left; }
  uint64 crop_left() const { return crop_left_; }
  void set_crop_right(uint64 crop_right) { crop_right_ = crop_right; }
  uint64 crop_right() const { return crop_right_; }
  void set_crop_top(uint64 crop_top) { crop_top_ = crop_top; }
  uint64 crop_top() const { return crop_top_; }
  void set_crop_bottom(uint64 crop_bottom) { crop_bottom_ = crop_bottom; }
  uint64 crop_bottom() const { return crop_bottom_; }

469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
  void set_frame_rate(double frame_rate) { frame_rate_ = frame_rate; }
  double frame_rate() const { return frame_rate_; }
  void set_height(uint64 height) { height_ = height; }
  uint64 height() const { return height_; }
  uint64 stereo_mode() { return stereo_mode_; }
  uint64 alpha_mode() { return alpha_mode_; }
  void set_width(uint64 width) { width_ = width; }
  uint64 width() const { return width_; }

 private:
  // Returns the size in bytes of the Video element.
  uint64 VideoPayloadSize() const;

  // Video track element names.
  uint64 display_height_;
  uint64 display_width_;
485
486
487
488
  uint64 crop_left_;
  uint64 crop_right_;
  uint64 crop_top_;
  uint64 crop_bottom_;
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
  double frame_rate_;
  uint64 height_;
  uint64 stereo_mode_;
  uint64 alpha_mode_;
  uint64 width_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(VideoTrack);
};

///////////////////////////////////////////////////////////////
// Track that has audio specific elements.
class AudioTrack : public Track {
 public:
  // The |seed| parameter is used to synthesize a UID for the track.
  explicit AudioTrack(unsigned int* seed);
  virtual ~AudioTrack();

  // Returns the size in bytes for the payload of the Track element plus the
  // audio specific elements.
  virtual uint64 PayloadSize() const;

  // Output the AudioTrack element to the writer. Returns true on success.
  virtual bool Write(IMkvWriter* writer) const;

  void set_bit_depth(uint64 bit_depth) { bit_depth_ = bit_depth; }
  uint64 bit_depth() const { return bit_depth_; }
  void set_channels(uint64 channels) { channels_ = channels; }
  uint64 channels() const { return channels_; }
  void set_sample_rate(double sample_rate) { sample_rate_ = sample_rate; }
  double sample_rate() const { return sample_rate_; }

 private:
  // Audio track element names.
  uint64 bit_depth_;
  uint64 channels_;
  double sample_rate_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(AudioTrack);
};

///////////////////////////////////////////////////////////////
// Tracks element
class Tracks {
 public:
  // Audio and video type defined by the Matroska specs.
534
  enum { kVideo = 0x1, kAudio = 0x2 };
535

536
537
  static const char kOpusCodecId[];
  static const char kVorbisCodecId[];
Adrian Grange's avatar
Adrian Grange committed
538
  static const char kAOMCodecId[];
539
  static const char kAV1CodecId[];
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590

  Tracks();
  ~Tracks();

  // Adds a Track element to the Tracks object. |track| will be owned and
  // deleted by the Tracks object. Returns true on success. |number| is the
  // number to use for the track. |number| must be >= 0. If |number| == 0
  // then the muxer will decide on the track number.
  bool AddTrack(Track* track, int32 number);

  // Returns the track by index. Returns NULL if there is no track match.
  const Track* GetTrackByIndex(uint32 idx) const;

  // Search the Tracks and return the track that matches |tn|. Returns NULL
  // if there is no track match.
  Track* GetTrackByNumber(uint64 track_number) const;

  // Returns true if the track number is an audio track.
  bool TrackIsAudio(uint64 track_number) const;

  // Returns true if the track number is a video track.
  bool TrackIsVideo(uint64 track_number) const;

  // Output the Tracks element to the writer. Returns true on success.
  bool Write(IMkvWriter* writer) const;

  uint32 track_entries_size() const { return track_entries_size_; }

 private:
  // Track element list.
  Track** track_entries_;

  // Number of Track elements added.
  uint32 track_entries_size_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Tracks);
};

///////////////////////////////////////////////////////////////
// Chapter element
//
class Chapter {
 public:
  // Set the identifier for this chapter.  (This corresponds to the
  // Cue Identifier line in WebVTT.)
  // TODO(matthewjheaney): the actual serialization of this item in
  // MKV is pending.
  bool set_id(const char* id);

  // Converts the nanosecond start and stop times of this chapter to
  // their corresponding timecode values, and stores them that way.
591
  void set_time(const Segment& segment, uint64 start_time_ns,
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
                uint64 end_time_ns);

  // Sets the uid for this chapter. Primarily used to enable
  // deterministic output from the muxer.
  void set_uid(const uint64 uid) { uid_ = uid; }

  // Add a title string to this chapter, per the semantics described
  // here:
  //  http://www.matroska.org/technical/specs/index.html
  //
  // The title ("chapter string") is a UTF-8 string.
  //
  // The language has ISO 639-2 representation, described here:
  //  http://www.loc.gov/standards/iso639-2/englangn.html
  //  http://www.loc.gov/standards/iso639-2/php/English_list.php
  // If you specify NULL as the language value, this implies
  // English ("eng").
  //
  // The country value corresponds to the codes listed here:
  //  http://www.iana.org/domains/root/db/
  //
  // The function returns false if the string could not be allocated.
614
  bool add_string(const char* title, const char* language, const char* country);
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742

 private:
  friend class Chapters;

  // For storage of chapter titles that differ by language.
  class Display {
   public:
    // Establish representation invariant for new Display object.
    void Init();

    // Reclaim resources, in anticipation of destruction.
    void Clear();

    // Copies the title to the |title_| member.  Returns false on
    // error.
    bool set_title(const char* title);

    // Copies the language to the |language_| member.  Returns false
    // on error.
    bool set_language(const char* language);

    // Copies the country to the |country_| member.  Returns false on
    // error.
    bool set_country(const char* country);

    // If |writer| is non-NULL, serialize the Display sub-element of
    // the Atom into the stream.  Returns the Display element size on
    // success, 0 if error.
    uint64 WriteDisplay(IMkvWriter* writer) const;

   private:
    char* title_;
    char* language_;
    char* country_;
  };

  Chapter();
  ~Chapter();

  // Establish the representation invariant for a newly-created
  // Chapter object.  The |seed| parameter is used to create the UID
  // for this chapter atom.
  void Init(unsigned int* seed);

  // Copies this Chapter object to a different one.  This is used when
  // expanding a plain array of Chapter objects (see Chapters).
  void ShallowCopy(Chapter* dst) const;

  // Reclaim resources used by this Chapter object, pending its
  // destruction.
  void Clear();

  // If there is no storage remaining on the |displays_| array for a
  // new display object, creates a new, longer array and copies the
  // existing Display objects to the new array.  Returns false if the
  // array cannot be expanded.
  bool ExpandDisplaysArray();

  // If |writer| is non-NULL, serialize the Atom sub-element into the
  // stream.  Returns the total size of the element on success, 0 if
  // error.
  uint64 WriteAtom(IMkvWriter* writer) const;

  // The string identifier for this chapter (corresponds to WebVTT cue
  // identifier).
  char* id_;

  // Start timecode of the chapter.
  uint64 start_timecode_;

  // Stop timecode of the chapter.
  uint64 end_timecode_;

  // The binary identifier for this chapter.
  uint64 uid_;

  // The Atom element can contain multiple Display sub-elements, as
  // the same logical title can be rendered in different languages.
  Display* displays_;

  // The physical length (total size) of the |displays_| array.
  int displays_size_;

  // The logical length (number of active elements) on the |displays_|
  // array.
  int displays_count_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Chapter);
};

///////////////////////////////////////////////////////////////
// Chapters element
//
class Chapters {
 public:
  Chapters();
  ~Chapters();

  Chapter* AddChapter(unsigned int* seed);

  // Returns the number of chapters that have been added.
  int Count() const;

  // Output the Chapters element to the writer. Returns true on success.
  bool Write(IMkvWriter* writer) const;

 private:
  // Expands the chapters_ array if there is not enough space to contain
  // another chapter object.  Returns true on success.
  bool ExpandChaptersArray();

  // If |writer| is non-NULL, serialize the Edition sub-element of the
  // Chapters element into the stream.  Returns the Edition element
  // size on success, 0 if error.
  uint64 WriteEdition(IMkvWriter* writer) const;

  // Total length of the chapters_ array.
  int chapters_size_;

  // Number of active chapters on the chapters_ array.
  int chapters_count_;

  // Array for storage of chapter objects.
  Chapter* chapters_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Chapters);
};

743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
///////////////////////////////////////////////////////////////
// Tag element
//
class Tag {
 public:
  bool add_simple_tag(const char* tag_name, const char* tag_string);

 private:
  // Tags calls Clear and the destructor of Tag
  friend class Tags;

  // For storage of simple tags
  class SimpleTag {
   public:
    // Establish representation invariant for new SimpleTag object.
    void Init();

    // Reclaim resources, in anticipation of destruction.
    void Clear();

    // Copies the title to the |tag_name_| member.  Returns false on
    // error.
    bool set_tag_name(const char* tag_name);

    // Copies the language to the |tag_string_| member.  Returns false
    // on error.
    bool set_tag_string(const char* tag_string);

    // If |writer| is non-NULL, serialize the SimpleTag sub-element of
    // the Atom into the stream.  Returns the SimpleTag element size on
    // success, 0 if error.
    uint64 Write(IMkvWriter* writer) const;

   private:
    char* tag_name_;
    char* tag_string_;
  };

  Tag();
  ~Tag();

  // Copies this Tag object to a different one.  This is used when
  // expanding a plain array of Tag objects (see Tags).
  void ShallowCopy(Tag* dst) const;

  // Reclaim resources used by this Tag object, pending its
  // destruction.
  void Clear();

  // If there is no storage remaining on the |simple_tags_| array for a
  // new display object, creates a new, longer array and copies the
  // existing SimpleTag objects to the new array.  Returns false if the
  // array cannot be expanded.
  bool ExpandSimpleTagsArray();

  // If |writer| is non-NULL, serialize the Tag sub-element into the
  // stream.  Returns the total size of the element on success, 0 if
  // error.
  uint64 Write(IMkvWriter* writer) const;

  // The Atom element can contain multiple SimpleTag sub-elements
  SimpleTag* simple_tags_;

  // The physical length (total size) of the |simple_tags_| array.
  int simple_tags_size_;

  // The logical length (number of active elements) on the |simple_tags_|
  // array.
  int simple_tags_count_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Tag);
};

///////////////////////////////////////////////////////////////
// Tags element
//
class Tags {
 public:
  Tags();
  ~Tags();

  Tag* AddTag();

  // Returns the number of tags that have been added.
  int Count() const;

  // Output the Tags element to the writer. Returns true on success.
  bool Write(IMkvWriter* writer) const;

 private:
  // Expands the tags_ array if there is not enough space to contain
  // another tag object.  Returns true on success.
  bool ExpandTagsArray();

  // Total length of the tags_ array.
  int tags_size_;

  // Number of active tags on the tags_ array.
  int tags_count_;

  // Array for storage of tag objects.
  Tag* tags_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Tags);
};

849
850
851
852
853
854
855
856
857
///////////////////////////////////////////////////////////////
// Cluster element
//
// Notes:
//  |Init| must be called before any other method in this class.
class Cluster {
 public:
  // |timecode| is the absolute timecode of the cluster. |cues_pos| is the
  // position for the cluster within the segment that should be written in
858
859
860
861
  // the cues element. |timecode_scale| is the timecode scale of the segment.
  Cluster(uint64 timecode, int64 cues_pos, uint64 timecode_scale);
  ~Cluster();

862
863
  bool Init(IMkvWriter* ptr_writer);

864
865
866
867
  // Adds a frame to be output in the file. The frame is written out through
  // |writer_| if successful. Returns true on success.
  bool AddFrame(const Frame* frame);

868
869
870
  // Adds a frame to be output in the file. The frame is written out through
  // |writer_| if successful. Returns true on success.
  // Inputs:
871
  //   data: Pointer to the data
872
873
874
875
876
877
  //   length: Length of the data
  //   track_number: Track to add the data to. Value returned by Add track
  //                 functions.  The range of allowed values is [1, 126].
  //   timecode:     Absolute (not relative to cluster) timestamp of the
  //                 frame, expressed in timecode units.
  //   is_key:       Flag telling whether or not this frame is a key frame.
878
  bool AddFrame(const uint8* data, uint64 length, uint64 track_number,
879
880
881
882
883
884
                uint64 timecode,  // timecode units (absolute)
                bool is_key);

  // Adds a frame to be output in the file. The frame is written out through
  // |writer_| if successful. Returns true on success.
  // Inputs:
885
  //   data: Pointer to the data
886
887
888
889
890
891
892
893
894
  //   length: Length of the data
  //   additional: Pointer to the additional data
  //   additional_length: Length of the additional data
  //   add_id: Value of BlockAddID element
  //   track_number: Track to add the data to. Value returned by Add track
  //                 functions.  The range of allowed values is [1, 126].
  //   abs_timecode: Absolute (not relative to cluster) timestamp of the
  //                 frame, expressed in timecode units.
  //   is_key:       Flag telling whether or not this frame is a key frame.
895
  bool AddFrameWithAdditional(const uint8* data, uint64 length,
896
897
898
                              const uint8* additional, uint64 additional_length,
                              uint64 add_id, uint64 track_number,
                              uint64 abs_timecode, bool is_key);
899
900
901
902

  // Adds a frame to be output in the file. The frame is written out through
  // |writer_| if successful. Returns true on success.
  // Inputs:
903
  //   data: Pointer to the data.
904
905
906
907
908
909
910
  //   length: Length of the data.
  //   discard_padding: DiscardPadding element value.
  //   track_number: Track to add the data to. Value returned by Add track
  //                 functions.  The range of allowed values is [1, 126].
  //   abs_timecode: Absolute (not relative to cluster) timestamp of the
  //                 frame, expressed in timecode units.
  //   is_key:       Flag telling whether or not this frame is a key frame.
911
  bool AddFrameWithDiscardPadding(const uint8* data, uint64 length,
912
913
                                  int64 discard_padding, uint64 track_number,
                                  uint64 abs_timecode, bool is_key);
914
915
916
917

  // Writes a frame of metadata to the output medium; returns true on
  // success.
  // Inputs:
918
  //   data: Pointer to the data
919
920
921
922
923
924
925
926
927
928
  //   length: Length of the data
  //   track_number: Track to add the data to. Value returned by Add track
  //                 functions.  The range of allowed values is [1, 126].
  //   timecode:     Absolute (not relative to cluster) timestamp of the
  //                 metadata frame, expressed in timecode units.
  //   duration:     Duration of metadata frame, in timecode units.
  //
  // The metadata frame is written as a block group, with a duration
  // sub-element but no reference time sub-elements (indicating that
  // it is considered a keyframe, per Matroska semantics).
929
  bool AddMetadata(const uint8* data, uint64 length, uint64 track_number,
930
                   uint64 timecode, uint64 duration);
931
932
933
934
935
936
937
938
939
940
941

  // Increments the size of the cluster's data in bytes.
  void AddPayloadSize(uint64 size);

  // Closes the cluster so no more data can be written to it. Will update the
  // cluster's size if |writer_| is seekable. Returns true on success.
  bool Finalize();

  // Returns the size in bytes for the entire Cluster element.
  uint64 Size() const;

942
943
944
945
  // Given |abs_timecode|, calculates timecode relative to most recent timecode.
  // Returns -1 on failure, or a relative timecode.
  int64 GetRelativeTimecode(int64 abs_timecode) const;

946
947
948
949
950
  int64 size_position() const { return size_position_; }
  int32 blocks_added() const { return blocks_added_; }
  uint64 payload_size() const { return payload_size_; }
  int64 position_for_cues() const { return position_for_cues_; }
  uint64 timecode() const { return timecode_; }
951
  uint64 timecode_scale() const { return timecode_scale_; }
952
953
954

 private:
  // Utility method that confirms that blocks can still be added, and that the
955
  // cluster header has been written. Used by |DoWriteFrame*|. Returns true
956
  // when successful.
957
  bool PreWriteBlock();
958

959
  // Utility method used by the |DoWriteFrame*| methods that handles the book
960
961
962
  // keeping required after each block is written.
  void PostWriteBlock(uint64 element_size);

963
964
  // Does some verification and calls WriteFrame.
  bool DoWriteFrame(const Frame* const frame);
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989

  // Outputs the Cluster header to |writer_|. Returns true on success.
  bool WriteClusterHeader();

  // Number of blocks added to the cluster.
  int32 blocks_added_;

  // Flag telling if the cluster has been closed.
  bool finalized_;

  // Flag telling if the cluster's header has been written.
  bool header_written_;

  // The size of the cluster elements in bytes.
  uint64 payload_size_;

  // The file position used for cue points.
  const int64 position_for_cues_;

  // The file position of the cluster's size element.
  int64 size_position_;

  // The absolute timecode of the cluster.
  const uint64 timecode_;

990
991
992
  // The timecode scale of the Segment containing the cluster.
  const uint64 timecode_scale_;

993
994
995
996
997
998
999
1000
  // Pointer to the writer object. Not owned by this class.
  IMkvWriter* writer_;

  LIBWEBM_DISALLOW_COPY_AND_ASSIGN(Cluster);
};

///////////////////////////////////////////////////////////////
// SeekHead element