mkvmuxerutil.cpp 14.6 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

9
#include "mkvmuxerutil.hpp"
10 11 12 13 14 15 16 17 18 19 20 21 22

#ifdef __ANDROID__
#include <fcntl.h>
#endif

#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <new>

23 24 25 26 27 28 29
#include "mkvwriter.hpp"
#include "webmids.hpp"

#ifdef _MSC_VER
// Disable MSVC warnings that suggest making code non-portable.
#pragma warning(disable : 4996)
#endif
30

31 32
namespace mkvmuxer {

33 34 35 36 37
namespace {

// Date elements are always 8 octets in size.
const int kDateElementSize = 8;

38 39 40 41 42 43 44 45
uint64 WriteBlock(IMkvWriter* writer, const Frame* const frame, int64 timecode,
                  uint64 timecode_scale) {
  uint64 block_additional_elem_size = 0;
  uint64 block_addid_elem_size = 0;
  uint64 block_more_payload_size = 0;
  uint64 block_more_elem_size = 0;
  uint64 block_additions_payload_size = 0;
  uint64 block_additions_elem_size = 0;
46
  if (frame->additional()) {
47 48 49
    block_additional_elem_size = EbmlElementSize(
        kMkvBlockAdditional, frame->additional(), frame->additional_length());
    block_addid_elem_size = EbmlElementSize(kMkvBlockAddID, frame->add_id());
50 51 52 53

    block_more_payload_size =
        block_addid_elem_size + block_additional_elem_size;
    block_more_elem_size =
54
        EbmlMasterElementSize(kMkvBlockMore, block_more_payload_size) +
55 56 57
        block_more_payload_size;
    block_additions_payload_size = block_more_elem_size;
    block_additions_elem_size =
58
        EbmlMasterElementSize(kMkvBlockAdditions,
59 60 61 62
                              block_additions_payload_size) +
        block_additions_payload_size;
  }

63
  uint64 discard_padding_elem_size = 0;
64 65
  if (frame->discard_padding() != 0) {
    discard_padding_elem_size =
66
        EbmlElementSize(kMkvDiscardPadding, frame->discard_padding());
67 68
  }

69
  const uint64 reference_block_timestamp =
70
      frame->reference_block_timestamp() / timecode_scale;
71
  uint64 reference_block_elem_size = 0;
72 73
  if (!frame->is_key()) {
    reference_block_elem_size =
74
        EbmlElementSize(kMkvReferenceBlock, reference_block_timestamp);
75 76
  }

77 78
  const uint64 duration = frame->duration() / timecode_scale;
  uint64 block_duration_elem_size = 0;
79
  if (duration > 0)
80
    block_duration_elem_size = EbmlElementSize(kMkvBlockDuration, duration);
81

82 83 84
  const uint64 block_payload_size = 4 + frame->length();
  const uint64 block_elem_size =
      EbmlMasterElementSize(kMkvBlock, block_payload_size) + block_payload_size;
85

86
  const uint64 block_group_payload_size =
87 88 89
      block_elem_size + block_additions_elem_size + block_duration_elem_size +
      discard_padding_elem_size + reference_block_elem_size;

90
  if (!WriteEbmlMasterElement(writer, kMkvBlockGroup,
91 92 93 94
                              block_group_payload_size)) {
    return 0;
  }

95
  if (!WriteEbmlMasterElement(writer, kMkvBlock, block_payload_size))
96 97 98 99 100 101 102 103 104 105 106 107
    return 0;

  if (WriteUInt(writer, frame->track_number()))
    return 0;

  if (SerializeInt(writer, timecode, 2))
    return 0;

  // For a Block, flags is always 0.
  if (SerializeInt(writer, 0, 1))
    return 0;

108
  if (writer->Write(frame->frame(), static_cast<uint32>(frame->length())))
109 110 111
    return 0;

  if (frame->additional()) {
112
    if (!WriteEbmlMasterElement(writer, kMkvBlockAdditions,
113 114 115 116
                                block_additions_payload_size)) {
      return 0;
    }

117
    if (!WriteEbmlMasterElement(writer, kMkvBlockMore, block_more_payload_size))
118 119
      return 0;

120
    if (!WriteEbmlElement(writer, kMkvBlockAddID, frame->add_id()))
121 122
      return 0;

123 124
    if (!WriteEbmlElement(writer, kMkvBlockAdditional, frame->additional(),
                          frame->additional_length())) {
125 126 127 128 129
      return 0;
    }
  }

  if (frame->discard_padding() != 0 &&
130
      !WriteEbmlElement(writer, kMkvDiscardPadding, frame->discard_padding())) {
131 132 133 134
    return false;
  }

  if (!frame->is_key() &&
135
      !WriteEbmlElement(writer, kMkvReferenceBlock,
136 137 138 139
                        reference_block_timestamp)) {
    return false;
  }

140
  if (duration > 0 && !WriteEbmlElement(writer, kMkvBlockDuration, duration)) {
141 142
    return false;
  }
143
  return EbmlMasterElementSize(kMkvBlockGroup, block_group_payload_size) +
144 145 146
         block_group_payload_size;
}

147 148 149
uint64 WriteSimpleBlock(IMkvWriter* writer, const Frame* const frame,
                        int64 timecode) {
  if (WriteID(writer, kMkvSimpleBlock))
150 151
    return 0;

152
  const int32 size = static_cast<int32>(frame->length()) + 4;
153 154 155
  if (WriteUInt(writer, size))
    return 0;

156
  if (WriteUInt(writer, static_cast<uint64>(frame->track_number())))
157 158 159 160 161
    return 0;

  if (SerializeInt(writer, timecode, 2))
    return 0;

162
  uint64 flags = 0;
163 164 165 166 167 168
  if (frame->is_key())
    flags |= 0x80;

  if (SerializeInt(writer, flags, 1))
    return 0;

169
  if (writer->Write(frame->frame(), static_cast<uint32>(frame->length())))
170 171
    return 0;

172
  return GetUIntSize(kMkvSimpleBlock) + GetCodedUIntSize(size) + 4 +
173 174 175
         frame->length();
}

176 177
}  // namespace

178
int32 GetCodedUIntSize(uint64 value) {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  if (value < 0x000000000000007FULL)
    return 1;
  else if (value < 0x0000000000003FFFULL)
    return 2;
  else if (value < 0x00000000001FFFFFULL)
    return 3;
  else if (value < 0x000000000FFFFFFFULL)
    return 4;
  else if (value < 0x00000007FFFFFFFFULL)
    return 5;
  else if (value < 0x000003FFFFFFFFFFULL)
    return 6;
  else if (value < 0x0001FFFFFFFFFFFFULL)
    return 7;
  return 8;
}

196
int32 GetUIntSize(uint64 value) {
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  if (value < 0x0000000000000100ULL)
    return 1;
  else if (value < 0x0000000000010000ULL)
    return 2;
  else if (value < 0x0000000001000000ULL)
    return 3;
  else if (value < 0x0000000100000000ULL)
    return 4;
  else if (value < 0x0000010000000000ULL)
    return 5;
  else if (value < 0x0001000000000000ULL)
    return 6;
  else if (value < 0x0100000000000000ULL)
    return 7;
  return 8;
}

214
int32 GetIntSize(int64 value) {
215 216
  // Doubling the requested value ensures positive values with their high bit
  // set are written with 0-padding to avoid flipping the signedness.
217
  const uint64 v = (value < 0) ? value ^ -1LL : value;
218 219 220
  return GetUIntSize(2 * v);
}

221
uint64 EbmlMasterElementSize(uint64 type, uint64 value) {
222
  // Size of EBML ID
223
  int32 ebml_size = GetUIntSize(type);
224 225 226 227 228 229 230

  // Datasize
  ebml_size += GetCodedUIntSize(value);

  return ebml_size;
}

231
uint64 EbmlElementSize(uint64 type, int64 value) {
232
  // Size of EBML ID
233
  int32 ebml_size = GetUIntSize(type);
234 235 236 237 238 239 240 241

  // Datasize
  ebml_size += GetIntSize(value);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
242 243
}

244
uint64 EbmlElementSize(uint64 type, uint64 value) {
245
  // Size of EBML ID
246
  int32 ebml_size = GetUIntSize(type);
247 248 249 250 251 252 253 254 255 256

  // Datasize
  ebml_size += GetUIntSize(value);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

257
uint64 EbmlElementSize(uint64 type, float /* value */) {
258
  // Size of EBML ID
259
  uint64 ebml_size = GetUIntSize(type);
260 261 262 263 264 265 266 267 268 269

  // Datasize
  ebml_size += sizeof(float);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

270
uint64 EbmlElementSize(uint64 type, const char* value) {
271 272 273 274
  if (!value)
    return 0;

  // Size of EBML ID
275
  uint64 ebml_size = GetUIntSize(type);
276 277 278 279 280 281 282 283 284 285

  // Datasize
  ebml_size += strlen(value);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

286
uint64 EbmlElementSize(uint64 type, const uint8* value, uint64 size) {
287 288 289 290
  if (!value)
    return 0;

  // Size of EBML ID
291
  uint64 ebml_size = GetUIntSize(type);
292 293 294 295 296 297 298 299 300 301

  // Datasize
  ebml_size += size;

  // Size of Datasize
  ebml_size += GetCodedUIntSize(size);

  return ebml_size;
}

302
uint64 EbmlDateElementSize(uint64 type) {
303
  // Size of EBML ID
304
  uint64 ebml_size = GetUIntSize(type);
305 306 307 308 309 310 311 312 313 314

  // Datasize
  ebml_size += kDateElementSize;

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

315
int32 SerializeInt(IMkvWriter* writer, int64 value, int32 size) {
316 317 318
  if (!writer || size < 1 || size > 8)
    return -1;

319 320 321
  for (int32 i = 1; i <= size; ++i) {
    const int32 byte_count = size - i;
    const int32 bit_count = byte_count * 8;
322

323 324
    const int64 bb = value >> bit_count;
    const uint8 b = static_cast<uint8>(bb);
325

326
    const int32 status = writer->Write(&b, 1);
327 328 329 330 331 332 333 334

    if (status < 0)
      return status;
  }

  return 0;
}

335
int32 SerializeFloat(IMkvWriter* writer, float f) {
336 337 338
  if (!writer)
    return -1;

339
  assert(sizeof(uint32) == sizeof(float));
340 341 342
  // This union is merely used to avoid a reinterpret_cast from float& to
  // uint32& which will result in violation of strict aliasing.
  union U32 {
343
    uint32 u32;
344 345 346 347
    float f;
  } value;
  value.f = f;

348 349 350
  for (int32 i = 1; i <= 4; ++i) {
    const int32 byte_count = 4 - i;
    const int32 bit_count = byte_count * 8;
351

352
    const uint8 byte = static_cast<uint8>(value.u32 >> bit_count);
353

354
    const int32 status = writer->Write(&byte, 1);
355 356 357 358 359 360 361 362

    if (status < 0)
      return status;
  }

  return 0;
}

363
int32 WriteUInt(IMkvWriter* writer, uint64 value) {
364 365 366
  if (!writer)
    return -1;

367
  int32 size = GetCodedUIntSize(value);
368 369 370 371

  return WriteUIntSize(writer, value, size);
}

372
int32 WriteUIntSize(IMkvWriter* writer, uint64 value, int32 size) {
373 374 375 376
  if (!writer || size < 0 || size > 8)
    return -1;

  if (size > 0) {
377
    const uint64 bit = 1LL << (size * 7);
378 379 380 381 382 383 384

    if (value > (bit - 2))
      return -1;

    value |= bit;
  } else {
    size = 1;
385
    int64 bit;
386 387 388

    for (;;) {
      bit = 1LL << (size * 7);
389
      const uint64 max = bit - 2;
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

      if (value <= max)
        break;

      ++size;
    }

    if (size > 8)
      return false;

    value |= bit;
  }

  return SerializeInt(writer, value, size);
}

406
int32 WriteID(IMkvWriter* writer, uint64 type) {
407 408 409 410 411
  if (!writer)
    return -1;

  writer->ElementStartNotify(type, writer->Position());

412
  const int32 size = GetUIntSize(type);
413 414 415 416

  return SerializeInt(writer, type, size);
}

417
bool WriteEbmlMasterElement(IMkvWriter* writer, uint64 type, uint64 size) {
418 419 420 421 422 423 424 425 426 427 428 429
  if (!writer)
    return false;

  if (WriteID(writer, type))
    return false;

  if (WriteUInt(writer, size))
    return false;

  return true;
}

430
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, uint64 value) {
431 432 433 434 435 436
  if (!writer)
    return false;

  if (WriteID(writer, type))
    return false;

437
  const uint64 size = GetUIntSize(value);
438 439 440
  if (WriteUInt(writer, size))
    return false;

441
  if (SerializeInt(writer, value, static_cast<int32>(size)))
442 443 444 445 446
    return false;

  return true;
}

447
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, int64 value) {
448 449 450 451 452 453
  if (!writer)
    return false;

  if (WriteID(writer, type))
    return 0;

454
  const uint64 size = GetIntSize(value);
455 456 457
  if (WriteUInt(writer, size))
    return false;

458
  if (SerializeInt(writer, value, static_cast<int32>(size)))
459 460 461 462 463
    return false;

  return true;
}

464
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, float value) {
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  if (!writer)
    return false;

  if (WriteID(writer, type))
    return false;

  if (WriteUInt(writer, 4))
    return false;

  if (SerializeFloat(writer, value))
    return false;

  return true;
}

480
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, const char* value) {
481 482 483 484 485 486
  if (!writer || !value)
    return false;

  if (WriteID(writer, type))
    return false;

487
  const uint64 length = strlen(value);
488 489 490
  if (WriteUInt(writer, length))
    return false;

491
  if (writer->Write(value, static_cast<const uint32>(length)))
492 493 494 495 496
    return false;

  return true;
}

497 498
bool WriteEbmlElement(IMkvWriter* writer, uint64 type, const uint8* value,
                      uint64 size) {
499 500 501 502 503 504 505 506 507
  if (!writer || !value || size < 1)
    return false;

  if (WriteID(writer, type))
    return false;

  if (WriteUInt(writer, size))
    return false;

508
  if (writer->Write(value, static_cast<uint32>(size)))
509 510 511 512 513
    return false;

  return true;
}

514
bool WriteEbmlDateElement(IMkvWriter* writer, uint64 type, int64 value) {
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  if (!writer)
    return false;

  if (WriteID(writer, type))
    return false;

  if (WriteUInt(writer, kDateElementSize))
    return false;

  if (SerializeInt(writer, value, kDateElementSize))
    return false;

  return true;
}

530 531
uint64 WriteFrame(IMkvWriter* writer, const Frame* const frame,
                  Cluster* cluster) {
532 533
  if (!writer || !frame || !frame->IsValid() || !cluster ||
      !cluster->timecode_scale())
534 535
    return 0;

536 537 538 539
  //  Technically the timecode for a block can be less than the
  //  timecode for the cluster itself (remember that block timecode
  //  is a signed, 16-bit integer).  However, as a simplification we
  //  only permit non-negative cluster-relative timecodes for blocks.
540
  const int64 relative_timecode = cluster->GetRelativeTimecode(
541 542
      frame->timestamp() / cluster->timecode_scale());
  if (relative_timecode < 0 || relative_timecode > kMaxBlockTimecode)
543 544
    return 0;

545 546 547 548
  return frame->CanBeSimpleBlock() ?
             WriteSimpleBlock(writer, frame, relative_timecode) :
             WriteBlock(writer, frame, relative_timecode,
                        cluster->timecode_scale());
549 550
}

551
uint64 WriteVoidElement(IMkvWriter* writer, uint64 size) {
552 553 554 555
  if (!writer)
    return false;

  // Subtract one for the void ID and the coded size.
556 557 558
  uint64 void_entry_size = size - 1 - GetCodedUIntSize(size - 1);
  uint64 void_size =
      EbmlMasterElementSize(kMkvVoid, void_entry_size) + void_entry_size;
559 560 561 562

  if (void_size != size)
    return 0;

563
  const int64 payload_position = writer->Position();
564 565 566
  if (payload_position < 0)
    return 0;

567
  if (WriteID(writer, kMkvVoid))
568 569 570 571 572
    return 0;

  if (WriteUInt(writer, void_entry_size))
    return 0;

573 574
  const uint8 value = 0;
  for (int32 i = 0; i < static_cast<int32>(void_entry_size); ++i) {
575 576 577 578
    if (writer->Write(&value, 1))
      return 0;
  }

579
  const int64 stop_position = writer->Position();
580
  if (stop_position < 0 ||
581
      stop_position - payload_position != static_cast<int64>(void_size))
582 583 584 585 586
    return 0;

  return void_size;
}

587
void GetVersion(int32* major, int32* minor, int32* build, int32* revision) {
588 589 590 591 592 593
  *major = 0;
  *minor = 2;
  *build = 1;
  *revision = 0;
}

594 595 596 597
}  // namespace mkvmuxer

mkvmuxer::uint64 mkvmuxer::MakeUID(unsigned int* seed) {
  uint64 uid = 0;
598 599 600 601 602 603 604 605

#ifdef __MINGW32__
  srand(*seed);
#endif

  for (int i = 0; i < 7; ++i) {  // avoid problems with 8-byte values
    uid <<= 8;

606
// TODO(fgalligan): Move random number generation to platform specific code.
607 608
#ifdef _MSC_VER
    (void)seed;
609
    const int32 nn = rand();
610
#elif __ANDROID__
611
    int32 temp_num = 1;
612 613
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd != -1) {
614
      read(fd, &temp_num, sizeof(int32));
615 616
      close(fd);
    }
617
    const int32 nn = temp_num;
618
#elif defined __MINGW32__
619
    const int32 nn = rand();
620
#else
621
    const int32 nn = rand_r(seed);
622
#endif
623
    const int32 n = 0xFF & (nn >> 4);  // throw away low-order bits
624 625 626 627 628 629

    uid |= n;
  }

  return uid;
}