mkvmuxerutil.cc 15.2 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 "mkvmuxer/mkvmuxerutil.h"
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
#include "common/webmids.h"
#include "mkvmuxer/mkvmuxer.h"
#include "mkvmuxer/mkvwriter.h"
26

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

32 33
namespace mkvmuxer {

34 35 36 37 38
namespace {

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

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

    block_more_payload_size =
        block_addid_elem_size + block_additional_elem_size;
    block_more_elem_size =
57
        EbmlMasterElementSize(libwebm::kMkvBlockMore, block_more_payload_size) +
58 59 60
        block_more_payload_size;
    block_additions_payload_size = block_more_elem_size;
    block_additions_elem_size =
61
        EbmlMasterElementSize(libwebm::kMkvBlockAdditions,
62 63 64 65
                              block_additions_payload_size) +
        block_additions_payload_size;
  }

66
  uint64_t discard_padding_elem_size = 0;
67 68
  if (frame->discard_padding() != 0) {
    discard_padding_elem_size =
69
        EbmlElementSize(libwebm::kMkvDiscardPadding, frame->discard_padding());
70 71
  }

72
  const uint64_t reference_block_timestamp =
73
      frame->reference_block_timestamp() / timecode_scale;
74
  uint64_t reference_block_elem_size = 0;
75 76
  if (!frame->is_key()) {
    reference_block_elem_size =
77
        EbmlElementSize(libwebm::kMkvReferenceBlock, reference_block_timestamp);
78 79
  }

80 81
  const uint64_t duration = frame->duration() / timecode_scale;
  uint64_t block_duration_elem_size = 0;
82
  if (duration > 0)
83 84
    block_duration_elem_size =
        EbmlElementSize(libwebm::kMkvBlockDuration, duration);
85

86 87 88 89
  const uint64_t block_payload_size = 4 + frame->length();
  const uint64_t block_elem_size =
      EbmlMasterElementSize(libwebm::kMkvBlock, block_payload_size) +
      block_payload_size;
90

91
  const uint64_t block_group_payload_size =
92 93 94
      block_elem_size + block_additions_elem_size + block_duration_elem_size +
      discard_padding_elem_size + reference_block_elem_size;

95
  if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlockGroup,
96 97 98 99
                              block_group_payload_size)) {
    return 0;
  }

100
  if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlock, block_payload_size))
101 102 103 104 105 106 107 108 109 110 111 112
    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;

113
  if (writer->Write(frame->frame(), static_cast<uint32_t>(frame->length())))
114 115 116
    return 0;

  if (frame->additional()) {
117
    if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlockAdditions,
118 119 120 121
                                block_additions_payload_size)) {
      return 0;
    }

122 123
    if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlockMore,
                                block_more_payload_size))
124 125
      return 0;

126
    if (!WriteEbmlElement(writer, libwebm::kMkvBlockAddID, frame->add_id()))
127 128
      return 0;

129 130
    if (!WriteEbmlElement(writer, libwebm::kMkvBlockAdditional,
                          frame->additional(), frame->additional_length())) {
131 132 133 134 135
      return 0;
    }
  }

  if (frame->discard_padding() != 0 &&
136 137
      !WriteEbmlElement(writer, libwebm::kMkvDiscardPadding,
                        frame->discard_padding())) {
138 139 140 141
    return false;
  }

  if (!frame->is_key() &&
142
      !WriteEbmlElement(writer, libwebm::kMkvReferenceBlock,
143 144 145 146
                        reference_block_timestamp)) {
    return false;
  }

147 148
  if (duration > 0 &&
      !WriteEbmlElement(writer, libwebm::kMkvBlockDuration, duration)) {
149 150
    return false;
  }
151 152
  return EbmlMasterElementSize(libwebm::kMkvBlockGroup,
                               block_group_payload_size) +
153 154 155
         block_group_payload_size;
}

156 157 158
uint64_t WriteSimpleBlock(IMkvWriter* writer, const Frame* const frame,
                          int64_t timecode) {
  if (WriteID(writer, libwebm::kMkvSimpleBlock))
159 160
    return 0;

161
  const int32_t size = static_cast<int32_t>(frame->length()) + 4;
162 163 164
  if (WriteUInt(writer, size))
    return 0;

165
  if (WriteUInt(writer, static_cast<uint64_t>(frame->track_number())))
166 167 168 169 170
    return 0;

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

171
  uint64_t flags = 0;
172 173 174 175 176 177
  if (frame->is_key())
    flags |= 0x80;

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

178
  if (writer->Write(frame->frame(), static_cast<uint32_t>(frame->length())))
179 180
    return 0;

181
  return GetUIntSize(libwebm::kMkvSimpleBlock) + GetCodedUIntSize(size) + 4 +
182 183 184
         frame->length();
}

185 186
}  // namespace

187
int32_t GetCodedUIntSize(uint64_t value) {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  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;
}

205
int32_t GetUIntSize(uint64_t value) {
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  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;
}

223
int32_t GetIntSize(int64_t value) {
224 225
  // Doubling the requested value ensures positive values with their high bit
  // set are written with 0-padding to avoid flipping the signedness.
226
  const uint64_t v = (value < 0) ? value ^ -1LL : value;
227 228 229
  return GetUIntSize(2 * v);
}

230
uint64_t EbmlMasterElementSize(uint64_t type, uint64_t value) {
231
  // Size of EBML ID
232
  int32_t ebml_size = GetUIntSize(type);
233 234 235 236 237 238 239

  // Datasize
  ebml_size += GetCodedUIntSize(value);

  return ebml_size;
}

240
uint64_t EbmlElementSize(uint64_t type, int64_t value) {
241
  // Size of EBML ID
242
  int32_t ebml_size = GetUIntSize(type);
243 244 245 246 247 248 249 250

  // Datasize
  ebml_size += GetIntSize(value);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
251 252
}

253
uint64_t EbmlElementSize(uint64_t type, uint64_t value) {
254
  // Size of EBML ID
255
  int32_t ebml_size = GetUIntSize(type);
256 257 258 259 260 261 262 263 264 265

  // Datasize
  ebml_size += GetUIntSize(value);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

266
uint64_t EbmlElementSize(uint64_t type, float /* value */) {
267
  // Size of EBML ID
268
  uint64_t ebml_size = GetUIntSize(type);
269 270 271 272 273 274 275 276 277 278

  // Datasize
  ebml_size += sizeof(float);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

279
uint64_t EbmlElementSize(uint64_t type, const char* value) {
280 281 282 283
  if (!value)
    return 0;

  // Size of EBML ID
284
  uint64_t ebml_size = GetUIntSize(type);
285 286 287 288 289 290 291 292 293 294

  // Datasize
  ebml_size += strlen(value);

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

295
uint64_t EbmlElementSize(uint64_t type, const uint8_t* value, uint64_t size) {
296 297 298 299
  if (!value)
    return 0;

  // Size of EBML ID
300
  uint64_t ebml_size = GetUIntSize(type);
301 302 303 304 305 306 307 308 309 310

  // Datasize
  ebml_size += size;

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

  return ebml_size;
}

311
uint64_t EbmlDateElementSize(uint64_t type) {
312
  // Size of EBML ID
313
  uint64_t ebml_size = GetUIntSize(type);
314 315 316 317 318 319 320 321 322 323

  // Datasize
  ebml_size += kDateElementSize;

  // Size of Datasize
  ebml_size++;

  return ebml_size;
}

324
int32_t SerializeInt(IMkvWriter* writer, int64_t value, int32_t size) {
325 326 327
  if (!writer || size < 1 || size > 8)
    return -1;

328 329 330
  for (int32_t i = 1; i <= size; ++i) {
    const int32_t byte_count = size - i;
    const int32_t bit_count = byte_count * 8;
331

332 333
    const int64_t bb = value >> bit_count;
    const uint8_t b = static_cast<uint8_t>(bb);
334

335
    const int32_t status = writer->Write(&b, 1);
336 337 338 339 340 341 342 343

    if (status < 0)
      return status;
  }

  return 0;
}

344
int32_t SerializeFloat(IMkvWriter* writer, float f) {
345 346 347
  if (!writer)
    return -1;

348
  assert(sizeof(uint32_t) == sizeof(float));
349 350 351
  // This union is merely used to avoid a reinterpret_cast from float& to
  // uint32& which will result in violation of strict aliasing.
  union U32 {
352
    uint32_t u32;
353 354 355 356
    float f;
  } value;
  value.f = f;

357 358 359
  for (int32_t i = 1; i <= 4; ++i) {
    const int32_t byte_count = 4 - i;
    const int32_t bit_count = byte_count * 8;
360

361
    const uint8_t byte = static_cast<uint8_t>(value.u32 >> bit_count);
362

363
    const int32_t status = writer->Write(&byte, 1);
364 365 366 367 368 369 370 371

    if (status < 0)
      return status;
  }

  return 0;
}

372
int32_t WriteUInt(IMkvWriter* writer, uint64_t value) {
373 374 375
  if (!writer)
    return -1;

376
  int32_t size = GetCodedUIntSize(value);
377 378 379 380

  return WriteUIntSize(writer, value, size);
}

381
int32_t WriteUIntSize(IMkvWriter* writer, uint64_t value, int32_t size) {
382 383 384 385
  if (!writer || size < 0 || size > 8)
    return -1;

  if (size > 0) {
386
    const uint64_t bit = 1LL << (size * 7);
387 388 389 390 391 392 393

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

    value |= bit;
  } else {
    size = 1;
394
    int64_t bit;
395 396 397

    for (;;) {
      bit = 1LL << (size * 7);
398
      const uint64_t max = bit - 2;
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

      if (value <= max)
        break;

      ++size;
    }

    if (size > 8)
      return false;

    value |= bit;
  }

  return SerializeInt(writer, value, size);
}

415
int32_t WriteID(IMkvWriter* writer, uint64_t type) {
416 417 418 419 420
  if (!writer)
    return -1;

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

421
  const int32_t size = GetUIntSize(type);
422 423 424 425

  return SerializeInt(writer, type, size);
}

426
bool WriteEbmlMasterElement(IMkvWriter* writer, uint64_t type, uint64_t size) {
427 428 429 430 431 432 433 434 435 436 437 438
  if (!writer)
    return false;

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

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

  return true;
}

439
bool WriteEbmlElement(IMkvWriter* writer, uint64_t type, uint64_t value) {
440 441 442 443 444 445
  if (!writer)
    return false;

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

446
  const uint64_t size = GetUIntSize(value);
447 448 449
  if (WriteUInt(writer, size))
    return false;

450
  if (SerializeInt(writer, value, static_cast<int32_t>(size)))
451 452 453 454 455
    return false;

  return true;
}

456
bool WriteEbmlElement(IMkvWriter* writer, uint64_t type, int64_t value) {
457 458 459 460 461 462
  if (!writer)
    return false;

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

463
  const uint64_t size = GetIntSize(value);
464 465 466
  if (WriteUInt(writer, size))
    return false;

467
  if (SerializeInt(writer, value, static_cast<int32_t>(size)))
468 469 470 471 472
    return false;

  return true;
}

473
bool WriteEbmlElement(IMkvWriter* writer, uint64_t type, float value) {
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
  if (!writer)
    return false;

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

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

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

  return true;
}

489
bool WriteEbmlElement(IMkvWriter* writer, uint64_t type, const char* value) {
490 491 492 493 494 495
  if (!writer || !value)
    return false;

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

496
  const uint64_t length = strlen(value);
497 498 499
  if (WriteUInt(writer, length))
    return false;

500
  if (writer->Write(value, static_cast<const uint32_t>(length)))
501 502 503 504 505
    return false;

  return true;
}

506 507
bool WriteEbmlElement(IMkvWriter* writer, uint64_t type, const uint8_t* value,
                      uint64_t size) {
508 509 510 511 512 513 514 515 516
  if (!writer || !value || size < 1)
    return false;

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

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

517
  if (writer->Write(value, static_cast<uint32_t>(size)))
518 519 520 521 522
    return false;

  return true;
}

523
bool WriteEbmlDateElement(IMkvWriter* writer, uint64_t type, int64_t value) {
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  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;
}

539 540
uint64_t WriteFrame(IMkvWriter* writer, const Frame* const frame,
                    Cluster* cluster) {
541 542
  if (!writer || !frame || !frame->IsValid() || !cluster ||
      !cluster->timecode_scale())
543 544
    return 0;

545 546 547 548
  //  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.
549
  const int64_t relative_timecode = cluster->GetRelativeTimecode(
550 551
      frame->timestamp() / cluster->timecode_scale());
  if (relative_timecode < 0 || relative_timecode > kMaxBlockTimecode)
552 553
    return 0;

554 555 556 557
  return frame->CanBeSimpleBlock() ?
             WriteSimpleBlock(writer, frame, relative_timecode) :
             WriteBlock(writer, frame, relative_timecode,
                        cluster->timecode_scale());
558 559
}

560
uint64_t WriteVoidElement(IMkvWriter* writer, uint64_t size) {
561 562 563 564
  if (!writer)
    return false;

  // Subtract one for the void ID and the coded size.
565 566 567 568
  uint64_t void_entry_size = size - 1 - GetCodedUIntSize(size - 1);
  uint64_t void_size =
      EbmlMasterElementSize(libwebm::kMkvVoid, void_entry_size) +
      void_entry_size;
569 570 571 572

  if (void_size != size)
    return 0;

573
  const int64_t payload_position = writer->Position();
574 575 576
  if (payload_position < 0)
    return 0;

577
  if (WriteID(writer, libwebm::kMkvVoid))
578 579 580 581 582
    return 0;

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

583 584
  const uint8_t value = 0;
  for (int32_t i = 0; i < static_cast<int32_t>(void_entry_size); ++i) {
585 586 587 588
    if (writer->Write(&value, 1))
      return 0;
  }

589
  const int64_t stop_position = writer->Position();
590
  if (stop_position < 0 ||
591
      stop_position - payload_position != static_cast<int64_t>(void_size))
592 593 594 595 596
    return 0;

  return void_size;
}

597 598
void GetVersion(int32_t* major, int32_t* minor, int32_t* build,
                int32_t* revision) {
599 600 601 602 603 604
  *major = 0;
  *minor = 2;
  *build = 1;
  *revision = 0;
}

605 606
uint64_t MakeUID(unsigned int* seed) {
  uint64_t uid = 0;
607 608 609 610 611 612 613 614

#ifdef __MINGW32__
  srand(*seed);
#endif

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

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

    uid |= n;
  }

  return uid;
}
639 640

}  // namespace mkvmuxer