1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 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 153 154 155 156 157 158 159 160 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 259 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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 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 534 535 536 537 538 539 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 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 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 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 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 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 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "MoofParser.h"
#include <limits>
#include "Box.h"
#include "MP4Interval.h"
#include "MediaDataDemuxer.h"
#include "SinfParser.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/HelperMacros.h"
#include "mozilla/Logging.h"
#include "mozilla/Try.h"
#define LOG_ERROR(name, arg, ...) \
MOZ_LOG( \
gMediaDemuxerLog, mozilla::LogLevel::Error, \
(MOZ_STRINGIFY(name) "(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
#define LOG_WARN(name, arg, ...) \
MOZ_LOG( \
gMediaDemuxerLog, mozilla::LogLevel::Warning, \
(MOZ_STRINGIFY(name) "(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
#define LOG_DEBUG(name, arg, ...) \
MOZ_LOG( \
gMediaDemuxerLog, mozilla::LogLevel::Debug, \
(MOZ_STRINGIFY(name) "(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
namespace mozilla {
using TimeUnit = media::TimeUnit;
const uint32_t kKeyIdSize = 16;
bool MoofParser::RebuildFragmentedIndex(const MediaByteRangeSet& aByteRanges) {
BoxContext context(mSource, aByteRanges);
return RebuildFragmentedIndex(context);
}
bool MoofParser::RebuildFragmentedIndex(const MediaByteRangeSet& aByteRanges,
bool* aCanEvict) {
MOZ_ASSERT(aCanEvict);
if (*aCanEvict && mMoofs.Length() > 1) {
MOZ_ASSERT(mMoofs.Length() == mMediaRanges.Length());
mMoofs.RemoveElementsAt(0, mMoofs.Length() - 1);
mMediaRanges.RemoveElementsAt(0, mMediaRanges.Length() - 1);
*aCanEvict = true;
} else {
*aCanEvict = false;
}
return RebuildFragmentedIndex(aByteRanges);
}
bool MoofParser::RebuildFragmentedIndex(BoxContext& aContext) {
LOG_DEBUG(
Moof,
"Starting, mTrackParseMode=%s, track#=%" PRIu32
" (ignore if multitrack).",
mTrackParseMode.is<ParseAllTracks>() ? "multitrack" : "single track",
mTrackParseMode.is<ParseAllTracks>() ? 0
: mTrackParseMode.as<uint32_t>());
bool foundValidMoof = false;
for (Box box(&aContext, mOffset); box.IsAvailable();
mOffset = box.NextOffset(), box = box.Next()) {
if (box.IsType("moov") && mInitRange.IsEmpty()) {
mInitRange = MediaByteRange(0, box.Range().mEnd);
ParseMoov(box);
} else if (box.IsType("moof")) {
Moof moof(box, mTrackParseMode, mTrex, mMvhd, mMdhd, mEdts, mSinf,
mIsAudio, &mLastDecodeTime, mTracksEndCts);
if (!moof.IsValid()) {
continue; // Skip to next box.
}
if (!mMoofs.IsEmpty()) {
// Stitch time ranges together in the case of a (hopefully small) time
// range gap between moofs.
mMoofs.LastElement().FixRounding(moof);
}
mMediaRanges.AppendElement(moof.mRange);
mMoofs.AppendElement(std::move(moof));
foundValidMoof = true;
} else if (box.IsType("mdat") && !Moofs().IsEmpty()) {
// Check if we have all our data from last moof.
Moof& moof = Moofs().LastElement();
media::Interval<int64_t> datarange(moof.mMdatRange.mStart,
moof.mMdatRange.mEnd, 0);
media::Interval<int64_t> mdat(box.Range().mStart, box.Range().mEnd, 0);
if (datarange.Intersects(mdat)) {
mMediaRanges.LastElement() =
mMediaRanges.LastElement().Span(box.Range());
}
}
}
MOZ_ASSERT(mTrackParseMode.is<ParseAllTracks>() ||
mTrex.mTrackId == mTrackParseMode.as<uint32_t>(),
"If not parsing all tracks, mTrex should have the same track id "
"as the track being parsed.");
LOG_DEBUG(Moof, "Done, foundValidMoof=%s.",
foundValidMoof ? "true" : "false");
return foundValidMoof;
}
MediaByteRange MoofParser::FirstCompleteMediaHeader() {
if (Moofs().IsEmpty()) {
return MediaByteRange();
}
return Moofs()[0].mRange;
}
MediaByteRange MoofParser::FirstCompleteMediaSegment() {
for (uint32_t i = 0; i < mMediaRanges.Length(); i++) {
if (mMediaRanges[i].Contains(Moofs()[i].mMdatRange)) {
return mMediaRanges[i];
}
}
return MediaByteRange();
}
const CencSampleEncryptionInfoEntry* MoofParser::GetSampleEncryptionEntry(
size_t aMoof, size_t aSample) const {
if (aMoof >= mMoofs.Length()) {
return nullptr;
}
return mMoofs[aMoof].GetSampleEncryptionEntry(
aSample, &mTrackSampleToGroupEntries, &mTrackSampleEncryptionInfoEntries);
}
DDLoggedTypeDeclNameAndBase(BlockingStream, ByteStream);
class BlockingStream : public ByteStream,
public DecoderDoctorLifeLogger<BlockingStream> {
public:
explicit BlockingStream(ByteStream* aStream) : mStream(aStream) {
DDLINKCHILD("stream", aStream);
}
nsresult ReadAt(int64_t offset, void* data, size_t size,
size_t* bytes_read) override {
return mStream->ReadAt(offset, data, size, bytes_read);
}
nsresult CachedReadAt(int64_t offset, void* data, size_t size,
size_t* bytes_read) override {
return mStream->ReadAt(offset, data, size, bytes_read);
}
virtual bool Length(int64_t* size) override { return mStream->Length(size); }
private:
RefPtr<ByteStream> mStream;
};
nsresult MoofParser::BlockingReadNextMoof() {
LOG_DEBUG(Moof, "Starting.");
int64_t length = std::numeric_limits<int64_t>::max();
mSource->Length(&length);
RefPtr<BlockingStream> stream = new BlockingStream(mSource);
MediaByteRangeSet byteRanges(MediaByteRange(0, length));
BoxContext context(stream, byteRanges);
Box box(&context, mOffset);
for (; box.IsAvailable(); box = box.Next()) {
if (box.IsType("moof")) {
MediaByteRangeSet parseByteRanges(
MediaByteRange(mOffset, box.Range().mEnd));
BoxContext parseContext(stream, parseByteRanges);
if (RebuildFragmentedIndex(parseContext)) {
LOG_DEBUG(Moof, "Succeeded on RebuildFragmentedIndex, returning NS_OK");
return NS_OK;
}
}
}
nsresult rv = box.Offset() == length ? NS_ERROR_DOM_MEDIA_END_OF_STREAM
: box.InitStatus();
LOG_DEBUG(Moof, "Couldn't read next moof, returning %s",
GetStaticErrorName(rv));
return rv;
}
void MoofParser::ScanForMetadata(mozilla::MediaByteRange& aMoov) {
LOG_DEBUG(Moof, "Starting.");
int64_t length = std::numeric_limits<int64_t>::max();
mSource->Length(&length);
MediaByteRangeSet byteRanges;
byteRanges += MediaByteRange(0, length);
RefPtr<BlockingStream> stream = new BlockingStream(mSource);
BoxContext context(stream, byteRanges);
for (Box box(&context, mOffset); box.IsAvailable(); box = box.Next()) {
if (box.IsType("moov")) {
aMoov = box.Range();
break;
}
}
mInitRange = aMoov;
LOG_DEBUG(Moof,
"Done, mInitRange.mStart=%" PRIi64 ", mInitRange.mEnd=%" PRIi64,
mInitRange.mStart, mInitRange.mEnd);
}
already_AddRefed<mozilla::MediaByteBuffer> MoofParser::Metadata() {
LOG_DEBUG(Moof, "Starting.");
MediaByteRange moov;
ScanForMetadata(moov);
CheckedInt<MediaByteBuffer::size_type> moovLength = moov.Length();
if (!moovLength.isValid() || !moovLength.value()) {
// No moov, or cannot be used as array size.
LOG_WARN(Moof,
"Did not get usable moov length while trying to parse Metadata.");
return nullptr;
}
RefPtr<MediaByteBuffer> metadata = new MediaByteBuffer();
if (!metadata->SetLength(moovLength.value(), fallible)) {
LOG_ERROR(Moof, "OOM");
return nullptr;
}
RefPtr<BlockingStream> stream = new BlockingStream(mSource);
size_t read;
nsresult rv = stream->ReadAt(moov.mStart, metadata->Elements(),
moovLength.value(), &read);
if (NS_FAILED(rv) || read != moovLength.value()) {
LOG_WARN(Moof, "Failed to read moov while trying to parse Metadata.");
return nullptr;
}
LOG_DEBUG(Moof, "Done, found metadata.");
return metadata.forget();
}
MP4Interval<TimeUnit> MoofParser::GetCompositionRange(
const MediaByteRangeSet& aByteRanges) {
LOG_DEBUG(Moof, "Starting.");
MP4Interval<TimeUnit> compositionRange;
BoxContext context(mSource, aByteRanges);
for (size_t i = 0; i < mMoofs.Length(); i++) {
Moof& moof = mMoofs[i];
Box box(&context, moof.mRange.mStart);
if (box.IsAvailable()) {
compositionRange = compositionRange.Extents(moof.mTimeRange);
}
}
LOG_DEBUG(Moof,
"Done, compositionRange.start=%" PRIi64
", compositionRange.end=%" PRIi64 ".",
compositionRange.start.ToMicroseconds(),
compositionRange.end.ToMicroseconds());
return compositionRange;
}
bool MoofParser::ReachedEnd() {
int64_t length;
return mSource->Length(&length) && mOffset == length;
}
void MoofParser::ParseMoov(Box& aBox) {
LOG_DEBUG(Moof, "Starting.");
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("mvhd")) {
mMvhd = Mvhd(box);
} else if (box.IsType("trak")) {
ParseTrak(box);
} else if (box.IsType("mvex")) {
ParseMvex(box);
}
}
LOG_DEBUG(Moof, "Done.");
}
void MoofParser::ParseTrak(Box& aBox) {
LOG_DEBUG(Trak, "Starting.");
Tkhd tkhd;
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("tkhd")) {
tkhd = Tkhd(box);
} else if (box.IsType("mdia")) {
if (mTrackParseMode.is<ParseAllTracks>() ||
tkhd.mTrackId == mTrackParseMode.as<uint32_t>()) {
ParseMdia(box);
}
} else if (box.IsType("edts") &&
(mTrackParseMode.is<ParseAllTracks>() ||
tkhd.mTrackId == mTrackParseMode.as<uint32_t>())) {
mEdts = Edts(box);
}
}
LOG_DEBUG(Trak, "Done.");
}
void MoofParser::ParseMdia(Box& aBox) {
LOG_DEBUG(Mdia, "Starting.");
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("mdhd")) {
mMdhd = Mdhd(box);
} else if (box.IsType("minf")) {
ParseMinf(box);
}
}
LOG_DEBUG(Mdia, "Done.");
}
void MoofParser::ParseMvex(Box& aBox) {
LOG_DEBUG(Mvex, "Starting.");
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("trex")) {
Trex trex = Trex(box);
if (mTrackParseMode.is<ParseAllTracks>() ||
trex.mTrackId == mTrackParseMode.as<uint32_t>()) {
mTrex = trex;
}
}
}
LOG_DEBUG(Mvex, "Done.");
}
void MoofParser::ParseMinf(Box& aBox) {
LOG_DEBUG(Minf, "Starting.");
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("stbl")) {
ParseStbl(box);
}
}
LOG_DEBUG(Minf, "Done.");
}
void MoofParser::ParseStbl(Box& aBox) {
LOG_DEBUG(Stbl, "Starting.");
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("stsd")) {
ParseStsd(box);
} else if (box.IsType("sgpd")) {
Sgpd sgpd(box);
if (sgpd.IsValid() && sgpd.mGroupingType == "seig") {
mTrackSampleEncryptionInfoEntries.Clear();
if (!mTrackSampleEncryptionInfoEntries.AppendElements(
sgpd.mEntries, mozilla::fallible)) {
LOG_ERROR(Stbl, "OOM");
return;
}
}
} else if (box.IsType("sbgp")) {
Sbgp sbgp(box);
if (sbgp.IsValid() && sbgp.mGroupingType == "seig") {
mTrackSampleToGroupEntries.Clear();
if (!mTrackSampleToGroupEntries.AppendElements(sbgp.mEntries,
mozilla::fallible)) {
LOG_ERROR(Stbl, "OOM");
return;
}
}
}
}
LOG_DEBUG(Stbl, "Done.");
}
void MoofParser::ParseStsd(Box& aBox) {
LOG_DEBUG(Stsd, "Starting.");
if (mTrackParseMode.is<ParseAllTracks>()) {
// It is not a sane operation to try and map sample description boxes from
// multiple tracks onto the parser, which is modeled around storing metadata
// for a single track.
LOG_DEBUG(Stsd, "Early return due to multitrack parser.");
return;
}
MOZ_ASSERT(
mSampleDescriptions.IsEmpty(),
"Shouldn't have any sample descriptions yet when starting to parse stsd");
uint32_t numberEncryptedEntries = 0;
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
SampleDescriptionEntry sampleDescriptionEntry{false};
if (box.IsType("encv") || box.IsType("enca")) {
ParseEncrypted(box);
sampleDescriptionEntry.mIsEncryptedEntry = true;
numberEncryptedEntries++;
}
if (!mSampleDescriptions.AppendElement(sampleDescriptionEntry,
mozilla::fallible)) {
LOG_ERROR(Stsd, "OOM");
return;
}
}
if (mSampleDescriptions.IsEmpty()) {
LOG_WARN(Stsd,
"No sample description entries found while parsing Stsd! This "
"shouldn't happen, as the spec requires one for each track!");
}
if (numberEncryptedEntries > 1) {
LOG_WARN(Stsd,
"More than one encrypted sample description entry found while "
"parsing track! We don't expect this, and it will likely break "
"during fragment look up!");
}
LOG_DEBUG(Stsd,
"Done, numberEncryptedEntries=%" PRIu32
", mSampleDescriptions.Length=%zu",
numberEncryptedEntries, mSampleDescriptions.Length());
}
void MoofParser::ParseEncrypted(Box& aBox) {
LOG_DEBUG(Moof, "Starting.");
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
// Some MP4 files have been found to have multiple sinf boxes in the same
// enc* box. This does not match spec anyway, so just choose the first
// one that parses properly.
if (box.IsType("sinf")) {
mSinf = Sinf(box);
if (mSinf.IsValid()) {
break;
}
}
}
LOG_DEBUG(Moof, "Done.");
}
class CtsComparator {
public:
bool Equals(Sample* const aA, Sample* const aB) const {
return aA->mCompositionRange.start == aB->mCompositionRange.start;
}
bool LessThan(Sample* const aA, Sample* const aB) const {
return aA->mCompositionRange.start < aB->mCompositionRange.start;
}
};
Moof::Moof(Box& aBox, const TrackParseMode& aTrackParseMode, Trex& aTrex,
const Mvhd& aMvhd, const Mdhd& aMdhd, const Edts& aEdts,
const Sinf& aSinf, const bool aIsAudio, uint64_t* aDecodeTime,
nsTArray<TrackEndCts>& aTracksEndCts)
: mRange(aBox.Range()),
mTfhd(aTrex),
// Do not reporting discontuities less than 35ms
mMaxRoundingError(TimeUnit::FromSeconds(0.035)) {
LOG_DEBUG(
Moof,
"Starting, aTrackParseMode=%s, track#=%" PRIu32
" (ignore if multitrack).",
aTrackParseMode.is<ParseAllTracks>() ? "multitrack" : "single track",
aTrackParseMode.is<ParseAllTracks>() ? 0
: aTrackParseMode.as<uint32_t>());
MOZ_ASSERT(aTrackParseMode.is<ParseAllTracks>() ||
aTrex.mTrackId == aTrackParseMode.as<uint32_t>(),
"If not parsing all tracks, aTrex should have the same track id "
"as the track being parsed.");
nsTArray<Box> psshBoxes;
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("traf")) {
ParseTraf(box, aTrackParseMode, aTrex, aMvhd, aMdhd, aEdts, aSinf,
aIsAudio, aDecodeTime);
}
if (box.IsType("pssh")) {
psshBoxes.AppendElement(box);
}
}
// The EME spec requires that PSSH boxes which are contiguous in the
// file are dispatched to the media element in a single "encrypted" event.
// So append contiguous boxes here.
for (size_t i = 0; i < psshBoxes.Length(); ++i) {
Box box = psshBoxes[i];
if (i == 0 || box.Offset() != psshBoxes[i - 1].NextOffset()) {
mPsshes.AppendElement();
}
nsTArray<uint8_t>& pssh = mPsshes.LastElement();
pssh.AppendElements(std::move(box.ReadCompleteBox()));
}
if (IsValid()) {
if (mIndex.Length()) {
// Ensure the samples are contiguous with no gaps.
nsTArray<Sample*> ctsOrder;
for (auto& sample : mIndex) {
ctsOrder.AppendElement(&sample);
}
ctsOrder.Sort(CtsComparator());
for (size_t i = 1; i < ctsOrder.Length(); i++) {
ctsOrder[i - 1]->mCompositionRange.end =
ctsOrder[i]->mCompositionRange.start;
}
// Ensure that there are no gaps between the first sample in this
// Moof and the preceeding Moof.
if (!ctsOrder.IsEmpty()) {
bool found = false;
// Track ID of the track we're parsing.
const uint32_t trackId = aTrex.mTrackId;
// Find the previous CTS end time of Moof preceeding the Moofs we just
// parsed, for the track we're parsing.
for (auto& prevCts : aTracksEndCts) {
if (prevCts.mTrackId == trackId) {
// We ensure there are no gaps in samples' CTS between the last
// sample in a Moof, and the first sample in the next Moof, if
// they're within these many Microseconds of each other.
const TimeUnit CROSS_MOOF_CTS_MERGE_THRESHOLD =
TimeUnit::FromMicroseconds(1);
// We have previously parsed a Moof for this track. Smooth the gap
// between samples for this track across the Moof bounary.
if (ctsOrder[0]->mCompositionRange.start > prevCts.mCtsEndTime &&
ctsOrder[0]->mCompositionRange.start - prevCts.mCtsEndTime <=
CROSS_MOOF_CTS_MERGE_THRESHOLD) {
ctsOrder[0]->mCompositionRange.start = prevCts.mCtsEndTime;
}
prevCts.mCtsEndTime = ctsOrder.LastElement()->mCompositionRange.end;
found = true;
break;
}
}
if (!found) {
// We've not parsed a Moof for this track yet. Save its CTS end
// time for the next Moof we parse.
aTracksEndCts.AppendElement(TrackEndCts(
trackId, ctsOrder.LastElement()->mCompositionRange.end));
}
}
// In MP4, the duration of a sample is defined as the delta between two
// decode timestamps. The operation above has updated the duration of each
// sample as a Sample's duration is mCompositionRange.end -
// mCompositionRange.start MSE's TrackBuffersManager expects dts that
// increased by the sample's duration, so we rewrite the dts accordingly.
TimeUnit presentationDuration =
ctsOrder.LastElement()->mCompositionRange.end -
ctsOrder[0]->mCompositionRange.start;
auto decodeOffset = aMdhd.ToTimeUnit(static_cast<int64_t>(*aDecodeTime) -
aEdts.mMediaStart);
auto offsetOffset = aMvhd.ToTimeUnit(aEdts.mEmptyOffset);
TimeUnit endDecodeTime =
(decodeOffset.isOk() && offsetOffset.isOk())
? decodeOffset.unwrap() + offsetOffset.unwrap()
: TimeUnit::Zero(aMvhd.mTimescale);
TimeUnit decodeDuration = endDecodeTime - mIndex[0].mDecodeTime;
double adjust = 0.;
if (!presentationDuration.IsZero()) {
double num = decodeDuration.ToSeconds();
double denom = presentationDuration.ToSeconds();
if (denom != 0.) {
adjust = num / denom;
}
}
TimeUnit dtsOffset = mIndex[0].mDecodeTime;
TimeUnit compositionDuration(0, aMvhd.mTimescale);
// Adjust the dts, ensuring that the new adjusted dts will never be
// greater than decodeTime (the next moof's decode start time).
for (auto& sample : mIndex) {
sample.mDecodeTime = dtsOffset + compositionDuration.MultDouble(adjust);
compositionDuration += sample.mCompositionRange.Length();
}
mTimeRange =
MP4Interval<TimeUnit>(ctsOrder[0]->mCompositionRange.start,
ctsOrder.LastElement()->mCompositionRange.end);
}
// No need to retrieve auxiliary encryption data if we have a senc box: we
// won't use it in SampleIterator::GetNext()
if (!mSencValid) {
ProcessCencAuxInfo(aSinf.mDefaultEncryptionType);
}
}
LOG_DEBUG(Moof, "Done.");
}
bool Moof::GetAuxInfo(AtomType aType,
FallibleTArray<MediaByteRange>* aByteRanges) {
LOG_DEBUG(Moof, "Starting.");
aByteRanges->Clear();
Saiz* saiz = nullptr;
for (int i = 0;; i++) {
if (i == mSaizs.Length()) {
LOG_DEBUG(Moof, "Could not find saiz matching aType. Returning false.");
return false;
}
if (mSaizs[i].mAuxInfoType == aType) {
saiz = &mSaizs[i];
break;
}
}
Saio* saio = nullptr;
for (int i = 0;; i++) {
if (i == mSaios.Length()) {
LOG_DEBUG(Moof, "Could not find saio matching aType. Returning false.");
return false;
}
if (mSaios[i].mAuxInfoType == aType) {
saio = &mSaios[i];
break;
}
}
if (saio->mOffsets.Length() == 1) {
if (!aByteRanges->SetCapacity(saiz->mSampleInfoSize.Length(),
mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return false;
}
uint64_t offset = mTfhd.mBaseDataOffset + saio->mOffsets[0];
for (size_t i = 0; i < saiz->mSampleInfoSize.Length(); i++) {
if (!aByteRanges->AppendElement(
MediaByteRange(offset, offset + saiz->mSampleInfoSize[i]),
mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return false;
}
offset += saiz->mSampleInfoSize[i];
}
LOG_DEBUG(
Moof,
"Saio has 1 entry. aByteRanges populated accordingly. Returning true.");
return true;
}
if (saio->mOffsets.Length() == saiz->mSampleInfoSize.Length()) {
if (!aByteRanges->SetCapacity(saiz->mSampleInfoSize.Length(),
mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return false;
}
for (size_t i = 0; i < saio->mOffsets.Length(); i++) {
uint64_t offset = mRange.mStart + saio->mOffsets[i];
if (!aByteRanges->AppendElement(
MediaByteRange(offset, offset + saiz->mSampleInfoSize[i]),
mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return false;
}
}
LOG_DEBUG(
Moof,
"Saio and saiz have same number of entries. aByteRanges populated "
"accordingly. Returning true.");
return true;
}
LOG_DEBUG(Moof,
"Moof::GetAuxInfo could not find any Aux info, returning false.");
return false;
}
bool Moof::ProcessCencAuxInfo(AtomType aScheme) {
LOG_DEBUG(Moof, "Starting.");
FallibleTArray<MediaByteRange> cencRanges;
if (!GetAuxInfo(aScheme, &cencRanges) ||
cencRanges.Length() != mIndex.Length()) {
LOG_DEBUG(Moof, "Couldn't find cenc aux info.");
return false;
}
for (int i = 0; i < cencRanges.Length(); i++) {
mIndex[i].mCencRange = cencRanges[i];
}
LOG_DEBUG(Moof, "Found cenc aux info and stored on index.");
return true;
}
const CencSampleEncryptionInfoEntry* Moof::GetSampleEncryptionEntry(
size_t aSample,
const FallibleTArray<SampleToGroupEntry>* aTrackSampleToGroupEntries,
const FallibleTArray<CencSampleEncryptionInfoEntry>*
aTrackSampleEncryptionInfoEntries) const {
const SampleToGroupEntry* sampleToGroupEntry = nullptr;
// Default to using the sample to group entries for the fragment, otherwise
// fall back to the sample to group entries for the track.
const FallibleTArray<SampleToGroupEntry>* sampleToGroupEntries =
mFragmentSampleToGroupEntries.Length() != 0
? &mFragmentSampleToGroupEntries
: aTrackSampleToGroupEntries;
if (!sampleToGroupEntries) {
return nullptr;
}
uint32_t seen = 0;
for (const SampleToGroupEntry& entry : *sampleToGroupEntries) {
if (seen + entry.mSampleCount > aSample) {
sampleToGroupEntry = &entry;
break;
}
seen += entry.mSampleCount;
}
// ISO-14496-12 Section 8.9.2.3 and 8.9.4 : group description index
// (1) ranges from 1 to the number of sample group entries in the track
// level SampleGroupDescription Box, or (2) takes the value 0 to
// indicate that this sample is a member of no group, in this case, the
// sample is associated with the default values specified in
// TrackEncryption Box, or (3) starts at 0x10001, i.e. the index value
// 1, with the value 1 in the top 16 bits, to reference fragment-local
// SampleGroupDescription Box.
// According to the spec, ISO-14496-12, the sum of the sample counts in this
// box should be equal to the total number of samples, and, if less, the
// reader should behave as if an extra SampleToGroupEntry existed, with
// groupDescriptionIndex 0.
if (!sampleToGroupEntry || sampleToGroupEntry->mGroupDescriptionIndex == 0) {
return nullptr;
}
const FallibleTArray<CencSampleEncryptionInfoEntry>* entries =
aTrackSampleEncryptionInfoEntries;
uint32_t groupIndex = sampleToGroupEntry->mGroupDescriptionIndex;
// If the first bit is set to a one, then we should use the sample group
// descriptions from the fragment.
if (groupIndex > SampleToGroupEntry::kFragmentGroupDescriptionIndexBase) {
groupIndex -= SampleToGroupEntry::kFragmentGroupDescriptionIndexBase;
entries = &mFragmentSampleEncryptionInfoEntries;
}
if (!entries) {
return nullptr;
}
// The group_index is one based.
return groupIndex > entries->Length() ? nullptr
: &entries->ElementAt(groupIndex - 1);
}
void Moof::ParseTraf(Box& aBox, const TrackParseMode& aTrackParseMode,
Trex& aTrex, const Mvhd& aMvhd, const Mdhd& aMdhd,
const Edts& aEdts, const Sinf& aSinf, const bool aIsAudio,
uint64_t* aDecodeTime) {
LOG_DEBUG(
Traf,
"Starting, aTrackParseMode=%s, track#=%" PRIu32
" (ignore if multitrack).",
aTrackParseMode.is<ParseAllTracks>() ? "multitrack" : "single track",
aTrackParseMode.is<ParseAllTracks>() ? 0
: aTrackParseMode.as<uint32_t>());
MOZ_ASSERT(aDecodeTime);
MOZ_ASSERT(aTrackParseMode.is<ParseAllTracks>() ||
aTrex.mTrackId == aTrackParseMode.as<uint32_t>(),
"If not parsing all tracks, aTrex should have the same track id "
"as the track being parsed.");
Tfdt tfdt;
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("tfhd")) {
mTfhd = Tfhd(box, aTrex);
} else if (aTrackParseMode.is<ParseAllTracks>() ||
mTfhd.mTrackId == aTrackParseMode.as<uint32_t>()) {
if (box.IsType("tfdt")) {
tfdt = Tfdt(box);
} else if (box.IsType("sgpd")) {
Sgpd sgpd(box);
if (sgpd.IsValid() && sgpd.mGroupingType == "seig") {
mFragmentSampleEncryptionInfoEntries.Clear();
if (!mFragmentSampleEncryptionInfoEntries.AppendElements(
sgpd.mEntries, mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return;
}
}
} else if (box.IsType("sbgp")) {
Sbgp sbgp(box);
if (sbgp.IsValid() && sbgp.mGroupingType == "seig") {
mFragmentSampleToGroupEntries.Clear();
if (!mFragmentSampleToGroupEntries.AppendElements(
sbgp.mEntries, mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return;
}
}
} else if (box.IsType("saiz")) {
if (!mSaizs.AppendElement(Saiz(box, aSinf.mDefaultEncryptionType),
mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return;
}
} else if (box.IsType("saio")) {
if (!mSaios.AppendElement(Saio(box, aSinf.mDefaultEncryptionType),
mozilla::fallible)) {
LOG_ERROR(Moof, "OOM");
return;
}
}
}
}
if (aTrackParseMode.is<uint32_t>() &&
mTfhd.mTrackId != aTrackParseMode.as<uint32_t>()) {
LOG_DEBUG(Traf,
"Early return as not multitrack parser and track id didn't match "
"mTfhd.mTrackId=%" PRIu32,
mTfhd.mTrackId);
return;
}
// Second pass: search for trun boxes and senc boxes.
uint64_t decodeTime =
tfdt.IsValid() ? tfdt.mBaseMediaDecodeTime : *aDecodeTime;
Box sencBox;
for (Box box = aBox.FirstChild(); box.IsAvailable(); box = box.Next()) {
if (box.IsType("trun")) {
if (ParseTrun(box, aMvhd, aMdhd, aEdts, aIsAudio, &decodeTime).isOk()) {
mValid = true;
} else {
LOG_WARN(Moof, "ParseTrun failed");
mValid = false;
return;
}
} else if (box.IsType("senc")) {
LOG_DEBUG(Moof, "Found senc box");
sencBox = box;
}
}
// senc box found: parse it.
// We need to parse senc boxes in another pass because we need potential sgpd
// and sbgp boxes to have been parsed, as they might override the IV size and
// as such the size of senc entries.
// trun box shall have been parsed as well, so mIndex has been filled.
if (sencBox.IsAvailable()) {
if (ParseSenc(sencBox, aSinf).isErr()) [[unlikely]] {
LOG_WARN(Moof, "ParseSenc failed");
}
}
*aDecodeTime = decodeTime;
LOG_DEBUG(Traf, "Done, setting aDecodeTime=%." PRIu64 ".", decodeTime);
}
void Moof::FixRounding(const Moof& aMoof) {
TimeUnit gap = aMoof.mTimeRange.start - mTimeRange.end;
if (gap.IsPositive() && gap <= mMaxRoundingError) {
mTimeRange.end = aMoof.mTimeRange.start;
}
}
Result<Ok, nsresult> Moof::ParseSenc(Box& aBox, const Sinf& aSinf) {
// If we already had a senc box, ignore following ones
// Not sure how likely this could be in real life
if (mSencValid) [[unlikely]] {
LOG_WARN(Moof, "Already found a valid senc box, ignoring new one");
return Ok();
}
BoxReader reader(aBox);
const uint8_t version = MOZ_TRY(reader->ReadU8());
const uint32_t flags = MOZ_TRY(reader->ReadU24());
const uint32_t sampleCount = MOZ_TRY(reader->ReadU32());
// ISO/IEC 23001-7 ยง7.2:
// "sample_count is the number of protected samples in the containing track or
// track fragment. This value SHALL be either zero (0) or the total number of
// samples in the track or track fragment."
if (sampleCount == 0) {
LOG_DEBUG(Moof, "senc box has 0 sample_count");
// Though having sample_count = 0 seems to be compliant, return without
// error but don't set mSencValid to true in case there is another senc box
// or saio/saiz auxiliary data
return Ok();
}
if (sampleCount != mIndex.Length()) {
LOG_ERROR(Moof, "Invalid sample count in senc box: expecting %zu, got %d\n",
mIndex.Length(), sampleCount);
return Err(NS_ERROR_FAILURE);
}
if (version == 0) {
for (size_t i = 0; i < sampleCount; ++i) {
Sample& sample = mIndex[i];
const CencSampleEncryptionInfoEntry* sampleInfo =
GetSampleEncryptionEntry(i);
uint8_t ivSize = sampleInfo ? sampleInfo->mIVSize : aSinf.mDefaultIVSize;
if (!reader->ReadArray(sample.mIV, ivSize)) {
return Err(MediaResult::Logged(
NS_ERROR_DOM_MEDIA_DEMUXER_ERR,
RESULT_DETAIL("sample InitializationVector error"),
gMediaDemuxerLog));
}
// Clear arrays, to be safe, in the (unlikely and invalid) case we started
// to parse a previous senc box but it failed halfway.
sample.mPlainSizes.Clear();
sample.mEncryptedSizes.Clear();
const bool useSubSampleEncryption = flags & 0x02;
if (useSubSampleEncryption) {
uint16_t subsampleCount = MOZ_TRY(reader->ReadU16());
for (uint16_t i = 0; i < subsampleCount; ++i) {
uint16_t bytesOfClearData = MOZ_TRY(reader->ReadU16());
uint32_t bytesOfProtectedData = MOZ_TRY(reader->ReadU32());
sample.mPlainSizes.AppendElement(bytesOfClearData);
sample.mEncryptedSizes.AppendElement(bytesOfProtectedData);
}
} else {
// No UseSubSampleEncryption flag means the entire sample is encrypted.
sample.mPlainSizes.AppendElement(0);
sample.mEncryptedSizes.AppendElement(sample.mByteRange.Length());
}
}
} else if (version == 1) {
// TODO
LOG_ERROR(Senc, "version %d not supported yet", version);
return Err(NS_ERROR_FAILURE);
} else if (version == 2) {
// TODO
LOG_ERROR(Senc, "version %d not supported yet", version);
return Err(NS_ERROR_FAILURE);
} else {
LOG_ERROR(Senc, "Unknown version %d", version);
return Err(NS_ERROR_FAILURE);
}
mSencValid = true;
return Ok();
}
Result<Ok, nsresult> Moof::ParseTrun(Box& aBox, const Mvhd& aMvhd,
const Mdhd& aMdhd, const Edts& aEdts,
const bool aIsAudio,
uint64_t* aDecodeTime) {
LOG_DEBUG(Trun, "Starting.");
if (!mTfhd.IsValid() || !aMvhd.IsValid() || !aMdhd.IsValid() ||
!aEdts.IsValid()) {
LOG_WARN(
Moof, "Invalid dependencies: mTfhd(%d) aMvhd(%d) aMdhd(%d) aEdts(%d)",
mTfhd.IsValid(), aMvhd.IsValid(), aMdhd.IsValid(), !aEdts.IsValid());
return Err(NS_ERROR_FAILURE);
}
BoxReader reader(aBox);
if (!reader->CanReadType<uint32_t>()) {
LOG_WARN(Moof, "Incomplete Box (missing flags)");
return Err(NS_ERROR_FAILURE);
}
uint32_t flags = MOZ_TRY(reader->ReadU32());
if (!reader->CanReadType<uint32_t>()) {
LOG_WARN(Moof, "Incomplete Box (missing sampleCount)");
return Err(NS_ERROR_FAILURE);
}
uint32_t sampleCount = MOZ_TRY(reader->ReadU32());
if (sampleCount == 0) {
LOG_DEBUG(Trun, "Trun with no samples, returning.");
return Ok();
}
uint64_t offset = mTfhd.mBaseDataOffset;
if (flags & 0x01) {
offset += MOZ_TRY(reader->ReadU32());
}
uint32_t firstSampleFlags = mTfhd.mDefaultSampleFlags;
if (flags & 0x04) {
firstSampleFlags = MOZ_TRY(reader->ReadU32());
}
nsTArray<MP4Interval<TimeUnit>> timeRanges;
uint64_t decodeTime = *aDecodeTime;
if (!mIndex.SetCapacity(mIndex.Length() + sampleCount, fallible)) {
LOG_ERROR(Moof, "Out of Memory");
return Err(NS_ERROR_FAILURE);
}
for (size_t i = 0; i < sampleCount; i++) {
uint32_t sampleDuration = mTfhd.mDefaultSampleDuration;
if (flags & 0x100) {
sampleDuration = MOZ_TRY(reader->ReadU32());
}
uint32_t sampleSize = mTfhd.mDefaultSampleSize;
if (flags & 0x200) {
sampleSize = MOZ_TRY(reader->ReadU32());
}
uint32_t sampleFlags = i ? mTfhd.mDefaultSampleFlags : firstSampleFlags;
if (flags & 0x400) {
sampleFlags = MOZ_TRY(reader->ReadU32());
}
int32_t ctsOffset = 0;
if (flags & 0x800) {
ctsOffset = MOZ_TRY(reader->Read32());
}
if (sampleSize) {
Sample sample;
sample.mByteRange = MediaByteRange(offset, offset + sampleSize);
offset += sampleSize;
TimeUnit decodeOffset =
MOZ_TRY(aMdhd.ToTimeUnit((int64_t)decodeTime - aEdts.mMediaStart));
TimeUnit emptyOffset = MOZ_TRY(aMvhd.ToTimeUnit(aEdts.mEmptyOffset));
sample.mDecodeTime = decodeOffset + emptyOffset;
TimeUnit startCts = MOZ_TRY(aMdhd.ToTimeUnit(
(int64_t)decodeTime + ctsOffset - aEdts.mMediaStart));
TimeUnit endCts =
MOZ_TRY(aMdhd.ToTimeUnit((int64_t)decodeTime + ctsOffset +
sampleDuration - aEdts.mMediaStart));
sample.mCompositionRange =
MP4Interval<TimeUnit>(startCts + emptyOffset, endCts + emptyOffset);
// Sometimes audio streams don't properly mark their samples as keyframes,
// because every audio sample is a keyframe.
sample.mSync = !(sampleFlags & 0x1010000) || aIsAudio;
MOZ_ALWAYS_TRUE(mIndex.AppendElement(sample, fallible));
mMdatRange = mMdatRange.Span(sample.mByteRange);
}
decodeTime += sampleDuration;
}
TimeUnit roundTime = MOZ_TRY(aMdhd.ToTimeUnit(sampleCount));
mMaxRoundingError = roundTime + mMaxRoundingError;
*aDecodeTime = decodeTime;
LOG_DEBUG(Trun, "Done.");
return Ok();
}
Tkhd::Tkhd(Box& aBox) : mTrackId(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Tkhd, "Parse failed");
}
}
Result<Ok, nsresult> Tkhd::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
uint8_t version = flags >> 24;
if (version == 0) {
uint32_t creationTime = MOZ_TRY(reader->ReadU32());
uint32_t modificationTime = MOZ_TRY(reader->ReadU32());
mTrackId = MOZ_TRY(reader->ReadU32());
[[maybe_unused]] uint32_t reserved = MOZ_TRY(reader->ReadU32());
uint32_t duration = MOZ_TRY(reader->ReadU32());
NS_ASSERTION(!reserved, "reserved should be 0");
mCreationTime = creationTime;
mModificationTime = modificationTime;
mDuration = duration;
} else if (version == 1) {
mCreationTime = MOZ_TRY(reader->ReadU64());
mModificationTime = MOZ_TRY(reader->ReadU64());
mTrackId = MOZ_TRY(reader->ReadU32());
[[maybe_unused]] uint32_t reserved = MOZ_TRY(reader->ReadU32());
NS_ASSERTION(!reserved, "reserved should be 0");
mDuration = MOZ_TRY(reader->ReadU64());
}
return Ok();
}
Mvhd::Mvhd(Box& aBox)
: mCreationTime(0), mModificationTime(0), mTimescale(0), mDuration(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Mvhd, "Parse failed");
}
}
Result<Ok, nsresult> Mvhd::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
uint8_t version = flags >> 24;
if (version == 0) {
uint32_t creationTime = MOZ_TRY(reader->ReadU32());
uint32_t modificationTime = MOZ_TRY(reader->ReadU32());
mTimescale = MOZ_TRY(reader->ReadU32());
uint32_t duration = MOZ_TRY(reader->ReadU32());
mCreationTime = creationTime;
mModificationTime = modificationTime;
mDuration = duration;
} else if (version == 1) {
mCreationTime = MOZ_TRY(reader->ReadU64());
mModificationTime = MOZ_TRY(reader->ReadU64());
mTimescale = MOZ_TRY(reader->ReadU32());
mDuration = MOZ_TRY(reader->ReadU64());
} else {
return Err(NS_ERROR_FAILURE);
}
return Ok();
}
Mdhd::Mdhd(Box& aBox) : Mvhd(aBox) {}
Trex::Trex(Box& aBox)
: mFlags(0),
mTrackId(0),
mDefaultSampleDescriptionIndex(0),
mDefaultSampleDuration(0),
mDefaultSampleSize(0),
mDefaultSampleFlags(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Trex, "Parse failed");
}
}
Result<Ok, nsresult> Trex::Parse(Box& aBox) {
BoxReader reader(aBox);
mFlags = MOZ_TRY(reader->ReadU32());
mTrackId = MOZ_TRY(reader->ReadU32());
mDefaultSampleDescriptionIndex = MOZ_TRY(reader->ReadU32());
mDefaultSampleDuration = MOZ_TRY(reader->ReadU32());
mDefaultSampleSize = MOZ_TRY(reader->ReadU32());
mDefaultSampleFlags = MOZ_TRY(reader->ReadU32());
return Ok();
}
Tfhd::Tfhd(Box& aBox, Trex& aTrex) : Trex(aTrex), mBaseDataOffset(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Tfhd, "Parse failed");
}
}
Result<Ok, nsresult> Tfhd::Parse(Box& aBox) {
MOZ_ASSERT(aBox.IsType("tfhd"));
MOZ_ASSERT(aBox.Parent()->IsType("traf"));
MOZ_ASSERT(aBox.Parent()->Parent()->IsType("moof"));
BoxReader reader(aBox);
mFlags = MOZ_TRY(reader->ReadU32());
mTrackId = MOZ_TRY(reader->ReadU32());
mBaseDataOffset = aBox.Parent()->Parent()->Offset();
if (mFlags & 0x01) {
mBaseDataOffset = MOZ_TRY(reader->ReadU64());
}
if (mFlags & 0x02) {
mDefaultSampleDescriptionIndex = MOZ_TRY(reader->ReadU32());
}
if (mFlags & 0x08) {
mDefaultSampleDuration = MOZ_TRY(reader->ReadU32());
}
if (mFlags & 0x10) {
mDefaultSampleSize = MOZ_TRY(reader->ReadU32());
}
if (mFlags & 0x20) {
mDefaultSampleFlags = MOZ_TRY(reader->ReadU32());
}
return Ok();
}
Tfdt::Tfdt(Box& aBox) : mBaseMediaDecodeTime(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Tfdt, "Parse failed");
}
}
Result<Ok, nsresult> Tfdt::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
uint8_t version = flags >> 24;
if (version == 0) {
mBaseMediaDecodeTime = MOZ_TRY(reader->ReadU32());
} else if (version == 1) {
mBaseMediaDecodeTime = MOZ_TRY(reader->ReadU64());
}
return Ok();
}
Edts::Edts(Box& aBox) : mMediaStart(0), mEmptyOffset(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Edts, "Parse failed");
}
}
Result<Ok, nsresult> Edts::Parse(Box& aBox) {
Box child = aBox.FirstChild();
if (!child.IsType("elst")) {
return Err(NS_ERROR_FAILURE);
}
BoxReader reader(child);
uint32_t flags = MOZ_TRY(reader->ReadU32());
uint8_t version = flags >> 24;
bool emptyEntry = false;
uint32_t entryCount = MOZ_TRY(reader->ReadU32());
for (uint32_t i = 0; i < entryCount; i++) {
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
segment_duration = MOZ_TRY(reader->ReadU64());
media_time = MOZ_TRY(reader->Read64());
} else {
segment_duration = MOZ_TRY(reader->ReadU32());
media_time = MOZ_TRY(reader->Read32());
}
if (media_time == -1 && i) {
LOG_WARN(Edts, "Multiple empty edit, not handled");
} else if (media_time == -1) {
if (segment_duration > std::numeric_limits<int64_t>::max()) {
NS_WARNING("Segment duration higher than int64_t max.");
mEmptyOffset = std::numeric_limits<int64_t>::max();
} else {
mEmptyOffset = static_cast<int64_t>(segment_duration);
}
emptyEntry = true;
} else if (i > 1 || (i > 0 && !emptyEntry)) {
LOG_WARN(Edts,
"More than one edit entry, not handled. A/V sync will be wrong");
break;
} else {
mMediaStart = media_time;
}
MOZ_TRY(reader->ReadU32()); // media_rate_integer and media_rate_fraction
}
return Ok();
}
Saiz::Saiz(Box& aBox, AtomType aDefaultType)
: mAuxInfoType(aDefaultType), mAuxInfoTypeParameter(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Saiz, "Parse failed");
}
}
Result<Ok, nsresult> Saiz::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
if (flags & 1) {
mAuxInfoType = MOZ_TRY(reader->ReadU32());
mAuxInfoTypeParameter = MOZ_TRY(reader->ReadU32());
}
uint8_t defaultSampleInfoSize = MOZ_TRY(reader->ReadU8());
uint32_t count = MOZ_TRY(reader->ReadU32());
if (defaultSampleInfoSize) {
if (!mSampleInfoSize.SetLength(count, fallible)) {
LOG_ERROR(Saiz, "OOM");
return Err(NS_ERROR_FAILURE);
}
memset(mSampleInfoSize.Elements(), defaultSampleInfoSize,
mSampleInfoSize.Length());
} else {
if (!reader->ReadArray(mSampleInfoSize, count)) {
LOG_WARN(Saiz, "Incomplete Box (OOM or missing count:%u)", count);
return Err(NS_ERROR_FAILURE);
}
}
return Ok();
}
Saio::Saio(Box& aBox, AtomType aDefaultType)
: mAuxInfoType(aDefaultType), mAuxInfoTypeParameter(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Saio, "Parse failed");
}
}
Result<Ok, nsresult> Saio::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
uint8_t version = flags >> 24;
if (flags & 1) {
mAuxInfoType = MOZ_TRY(reader->ReadU32());
mAuxInfoTypeParameter = MOZ_TRY(reader->ReadU32());
}
size_t count = MOZ_TRY(reader->ReadU32());
if (!mOffsets.SetCapacity(count, fallible)) {
LOG_ERROR(Saiz, "OOM");
return Err(NS_ERROR_FAILURE);
}
if (version == 0) {
for (size_t i = 0; i < count; i++) {
uint32_t offset = MOZ_TRY(reader->ReadU32());
MOZ_ALWAYS_TRUE(mOffsets.AppendElement(offset, fallible));
}
} else {
for (size_t i = 0; i < count; i++) {
uint64_t offset = MOZ_TRY(reader->ReadU64());
MOZ_ALWAYS_TRUE(mOffsets.AppendElement(offset, fallible));
}
}
return Ok();
}
Sbgp::Sbgp(Box& aBox) : mGroupingTypeParam(0) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Sbgp, "Parse failed");
}
}
Result<Ok, nsresult> Sbgp::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
const uint8_t version = flags >> 24;
mGroupingType = MOZ_TRY(reader->ReadU32());
if (version == 1) {
mGroupingTypeParam = MOZ_TRY(reader->ReadU32());
}
uint32_t count = MOZ_TRY(reader->ReadU32());
for (uint32_t i = 0; i < count; i++) {
uint32_t sampleCount = MOZ_TRY(reader->ReadU32());
uint32_t groupDescriptionIndex = MOZ_TRY(reader->ReadU32());
SampleToGroupEntry entry(sampleCount, groupDescriptionIndex);
if (!mEntries.AppendElement(entry, mozilla::fallible)) {
LOG_ERROR(Sbgp, "OOM");
return Err(NS_ERROR_FAILURE);
}
}
return Ok();
}
Sgpd::Sgpd(Box& aBox) {
mValid = Parse(aBox).isOk();
if (!mValid) {
LOG_WARN(Sgpd, "Parse failed");
}
}
Result<Ok, nsresult> Sgpd::Parse(Box& aBox) {
BoxReader reader(aBox);
uint32_t flags = MOZ_TRY(reader->ReadU32());
const uint8_t version = flags >> 24;
mGroupingType = MOZ_TRY(reader->ReadU32());
const uint32_t entrySize = sizeof(uint32_t) + kKeyIdSize;
uint32_t defaultLength = 0;
if (version == 1) {
defaultLength = MOZ_TRY(reader->ReadU32());
if (defaultLength < entrySize && defaultLength != 0) {
return Err(NS_ERROR_FAILURE);
}
}
uint32_t count = MOZ_TRY(reader->ReadU32());
for (uint32_t i = 0; i < count; ++i) {
if (version == 1 && defaultLength == 0) {
uint32_t descriptionLength = MOZ_TRY(reader->ReadU32());
if (descriptionLength < entrySize) {
return Err(NS_ERROR_FAILURE);
}
}
CencSampleEncryptionInfoEntry entry;
bool valid = entry.Init(reader).isOk();
if (!valid) {
return Err(NS_ERROR_FAILURE);
}
if (!mEntries.AppendElement(entry, mozilla::fallible)) {
LOG_ERROR(Sgpd, "OOM");
return Err(NS_ERROR_FAILURE);
}
}
return Ok();
}
Result<Ok, nsresult> CencSampleEncryptionInfoEntry::Init(BoxReader& aReader) {
// Skip a reserved byte.
MOZ_TRY(aReader->ReadU8());
uint8_t pattern = MOZ_TRY(aReader->ReadU8());
mCryptByteBlock = pattern >> 4;
mSkipByteBlock = pattern & 0x0f;
uint8_t isEncrypted = MOZ_TRY(aReader->ReadU8());
mIsEncrypted = isEncrypted != 0;
mIVSize = MOZ_TRY(aReader->ReadU8());
// Read the key id.
if (!mKeyId.SetLength(kKeyIdSize, fallible)) {
LOG_ERROR(CencSampleEncryptionInfoEntry, "OOM");
return Err(NS_ERROR_FAILURE);
}
for (uint32_t i = 0; i < kKeyIdSize; ++i) {
mKeyId.ElementAt(i) = MOZ_TRY(aReader->ReadU8());
}
if (mIsEncrypted) {
if (mIVSize != 8 && mIVSize != 16) {
return Err(NS_ERROR_FAILURE);
}
} else if (mIVSize != 0) {
// Protected content with 0 sized IV indicates a constant IV is present.
// This is used for the cbcs scheme.
uint8_t constantIVSize = MOZ_TRY(aReader->ReadU8());
if (constantIVSize != 8 && constantIVSize != 16) {
LOG_WARN(CencSampleEncryptionInfoEntry,
"Unexpected constantIVSize: %" PRIu8, constantIVSize);
return Err(NS_ERROR_FAILURE);
}
if (!mConsantIV.SetLength(constantIVSize, mozilla::fallible)) {
LOG_ERROR(CencSampleEncryptionInfoEntry, "OOM");
return Err(NS_ERROR_FAILURE);
}
for (uint32_t i = 0; i < constantIVSize; ++i) {
mConsantIV.ElementAt(i) = MOZ_TRY(aReader->ReadU8());
}
}
return Ok();
}
} // namespace mozilla
#undef LOG_DEBUG
#undef LOG_WARN
#undef LOG_ERROR
|