DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (e67641c2e4cc)

VCS Links

Line Code
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 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
/* 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 "DOMMediaStream.h"

#include "AudioCaptureStream.h"
#include "AudioChannelAgent.h"
#include "AudioStreamTrack.h"
#include "Layers.h"
#include "MediaStreamGraph.h"
#include "MediaStreamGraphImpl.h"
#include "MediaStreamListener.h"
#include "VideoStreamTrack.h"
#include "mozilla/dom/AudioNode.h"
#include "mozilla/dom/AudioTrack.h"
#include "mozilla/dom/AudioTrackList.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/HTMLCanvasElement.h"
#include "mozilla/dom/LocalMediaStreamBinding.h"
#include "mozilla/dom/MediaStreamBinding.h"
#include "mozilla/dom/MediaStreamTrackEvent.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/VideoTrack.h"
#include "mozilla/dom/VideoTrackList.h"
#include "mozilla/media/MediaUtils.h"
#include "nsContentUtils.h"
#include "nsIScriptError.h"
#include "nsIUUIDGenerator.h"
#include "nsPIDOMWindow.h"
#include "nsProxyRelease.h"
#include "nsRFPService.h"
#include "nsServiceManagerUtils.h"

// GetCurrentTime is defined in winbase.h as zero argument macro forwarding to
// GetTickCount() and conflicts with NS_DECL_NSIDOMMEDIASTREAM, containing
// currentTime getter.
#ifdef GetCurrentTime
#undef GetCurrentTime
#endif

#ifdef LOG
#undef LOG
#endif

// GetCurrentTime is defined in winbase.h as zero argument macro forwarding to
// GetTickCount() and conflicts with MediaStream::GetCurrentTime.
#ifdef GetCurrentTime
#undef GetCurrentTime
#endif

using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::layers;
using namespace mozilla::media;

static LazyLogModule gMediaStreamLog("MediaStream");
#define LOG(type, msg) MOZ_LOG(gMediaStreamLog, type, msg)

const TrackID TRACK_VIDEO_PRIMARY = 1;

static bool ContainsLiveTracks(
    nsTArray<RefPtr<DOMMediaStream::TrackPort>>& aTracks) {
  for (auto& port : aTracks) {
    if (port->GetTrack()->ReadyState() == MediaStreamTrackState::Live) {
      return true;
    }
  }

  return false;
}

DOMMediaStream::TrackPort::TrackPort(MediaInputPort* aInputPort,
                                     MediaStreamTrack* aTrack,
                                     const InputPortOwnership aOwnership)
    : mInputPort(aInputPort), mTrack(aTrack), mOwnership(aOwnership) {
  MOZ_ASSERT(mInputPort);
  MOZ_ASSERT(mTrack);

  MOZ_COUNT_CTOR(TrackPort);
}

DOMMediaStream::TrackPort::~TrackPort() {
  MOZ_COUNT_DTOR(TrackPort);

  if (mOwnership == InputPortOwnership::OWNED) {
    DestroyInputPort();
  }
}

void DOMMediaStream::TrackPort::DestroyInputPort() {
  if (mInputPort) {
    mInputPort->Destroy();
    mInputPort = nullptr;
  }
}

MediaStream* DOMMediaStream::TrackPort::GetSource() const {
  return mInputPort ? mInputPort->GetSource() : nullptr;
}

TrackID DOMMediaStream::TrackPort::GetSourceTrackId() const {
  return mInputPort ? mInputPort->GetSourceTrackId() : TRACK_INVALID;
}

already_AddRefed<Pledge<bool>> DOMMediaStream::TrackPort::BlockSourceTrackId(
    TrackID aTrackId, BlockingMode aBlockingMode) {
  if (mInputPort) {
    return mInputPort->BlockSourceTrackId(aTrackId, aBlockingMode);
  }
  auto rejected = MakeRefPtr<Pledge<bool>>();
  rejected->Reject(NS_ERROR_FAILURE);
  return rejected.forget();
}

NS_IMPL_CYCLE_COLLECTION(DOMMediaStream::TrackPort, mTrack)
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(DOMMediaStream::TrackPort, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(DOMMediaStream::TrackPort, Release)

NS_IMPL_CYCLE_COLLECTING_ADDREF(MediaStreamTrackSourceGetter)
NS_IMPL_CYCLE_COLLECTING_RELEASE(MediaStreamTrackSourceGetter)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MediaStreamTrackSourceGetter)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_0(MediaStreamTrackSourceGetter)

/**
 * Listener registered on the Owned stream to detect added and ended owned
 * tracks for keeping the list of MediaStreamTracks in sync with the tracks
 * added and ended directly at the source.
 */
class DOMMediaStream::OwnedStreamListener : public MediaStreamListener {
 public:
  explicit OwnedStreamListener(DOMMediaStream* aStream) : mStream(aStream) {}

  void Forget() { mStream = nullptr; }

  void DoNotifyTrackCreated(MediaStreamGraph* aGraph, TrackID aTrackID,
                            MediaSegment::Type aType, MediaStream* aInputStream,
                            TrackID aInputTrackID) {
    MOZ_ASSERT(NS_IsMainThread());

    if (!mStream) {
      return;
    }

    MediaStreamTrack* track =
        mStream->FindOwnedDOMTrack(aInputStream, aInputTrackID, aTrackID);

    if (track) {
      LOG(LogLevel::Debug, ("DOMMediaStream %p Track %d from owned stream %p "
                            "bound to MediaStreamTrack %p.",
                            mStream, aTrackID, aInputStream, track));
      return;
    }

    // Track had not been created on main thread before, create it now.
    NS_WARNING_ASSERTION(
        !mStream->mTracks.IsEmpty(),
        "A new track was detected on the input stream; creating a "
        "corresponding "
        "MediaStreamTrack. Initial tracks should be added manually to "
        "immediately and synchronously be available to JS.");
    RefPtr<MediaStreamTrackSource> source;
    if (mStream->mTrackSourceGetter) {
      source = mStream->mTrackSourceGetter->GetMediaStreamTrackSource(aTrackID);
    }
    if (!source) {
      NS_ASSERTION(false,
                   "Dynamic track created without an explicit TrackSource");
      nsPIDOMWindowInner* window = mStream->GetParentObject();
      nsIDocument* doc = window ? window->GetExtantDoc() : nullptr;
      nsIPrincipal* principal = doc ? doc->NodePrincipal() : nullptr;
      source = new BasicTrackSource(principal);
    }

    RefPtr<MediaStreamTrack> newTrack =
        mStream->CreateDOMTrack(aTrackID, aType, source);
    aGraph->AbstractMainThread()->Dispatch(
        NewRunnableMethod<RefPtr<MediaStreamTrack>>(
            "DOMMediaStream::AddTrackInternal", mStream,
            &DOMMediaStream::AddTrackInternal, newTrack));
  }

  void DoNotifyTrackEnded(MediaStreamGraph* aGraph, MediaStream* aInputStream,
                          TrackID aInputTrackID, TrackID aTrackID) {
    MOZ_ASSERT(NS_IsMainThread());

    if (!mStream) {
      return;
    }

    RefPtr<MediaStreamTrack> track =
        mStream->FindOwnedDOMTrack(aInputStream, aInputTrackID, aTrackID);
    NS_ASSERTION(track,
                 "Owned MediaStreamTracks must be known by the DOMMediaStream");
    if (track) {
      LOG(LogLevel::Debug, ("DOMMediaStream %p MediaStreamTrack %p ended at "
                            "the source. Marking it ended.",
                            mStream, track.get()));
      aGraph->AbstractMainThread()->Dispatch(
          NewRunnableMethod("dom::MediaStreamTrack::OverrideEnded", track,
                            &MediaStreamTrack::OverrideEnded));
    }
  }

  void NotifyQueuedTrackChanges(MediaStreamGraph* aGraph, TrackID aID,
                                StreamTime aTrackOffset,
                                TrackEventCommand aTrackEvents,
                                const MediaSegment& aQueuedMedia,
                                MediaStream* aInputStream,
                                TrackID aInputTrackID) override {
    if (aTrackEvents & TrackEventCommand::TRACK_EVENT_CREATED) {
      aGraph->DispatchToMainThreadAfterStreamStateUpdate(
          NewRunnableMethod<MediaStreamGraph*, TrackID, MediaSegment::Type,
                            RefPtr<MediaStream>, TrackID>(
              "DOMMediaStream::OwnedStreamListener::DoNotifyTrackCreated", this,
              &OwnedStreamListener::DoNotifyTrackCreated, aGraph, aID,
              aQueuedMedia.GetType(), aInputStream, aInputTrackID));
    } else if (aTrackEvents & TrackEventCommand::TRACK_EVENT_ENDED) {
      aGraph->DispatchToMainThreadAfterStreamStateUpdate(
          NewRunnableMethod<MediaStreamGraph*, RefPtr<MediaStream>, TrackID,
                            TrackID>(
              "DOMMediaStream::OwnedStreamListener::DoNotifyTrackEnded", this,
              &OwnedStreamListener::DoNotifyTrackEnded, aGraph, aInputStream,
              aInputTrackID, aID));
    }
  }

 private:
  // These fields may only be accessed on the main thread
  DOMMediaStream* mStream;
};

/**
 * Listener registered on the Playback stream to detect when tracks end and when
 * all new tracks this iteration have been created - for when several tracks are
 * queued by the source and committed all at once.
 */
class DOMMediaStream::PlaybackStreamListener : public MediaStreamListener {
 public:
  explicit PlaybackStreamListener(DOMMediaStream* aStream) : mStream(aStream) {}

  void Forget() {
    MOZ_ASSERT(NS_IsMainThread());
    mStream = nullptr;
  }

  void DoNotifyFinishedTrackCreation() {
    MOZ_ASSERT(NS_IsMainThread());

    if (!mStream) {
      return;
    }

    // The owned stream listener adds its tracks after another main thread
    // dispatch. We have to do the same to notify of created tracks to stay
    // in sync. (Or NotifyTracksCreated is called before tracks are added).
    MOZ_ASSERT(mStream->GetPlaybackStream());
    mStream->GetPlaybackStream()->Graph()->AbstractMainThread()->Dispatch(
        NewRunnableMethod("DOMMediaStream::NotifyTracksCreated", mStream,
                          &DOMMediaStream::NotifyTracksCreated));
  }

  void DoNotifyFinished() {
    MOZ_ASSERT(NS_IsMainThread());

    if (!mStream) {
      return;
    }

    mStream->GetPlaybackStream()->Graph()->AbstractMainThread()->Dispatch(
        NewRunnableMethod("DOMMediaStream::NotifyFinished", mStream,
                          &DOMMediaStream::NotifyFinished));
  }

  // The methods below are called on the MediaStreamGraph thread.

  void NotifyFinishedTrackCreation(MediaStreamGraph* aGraph) override {
    aGraph->DispatchToMainThreadAfterStreamStateUpdate(NewRunnableMethod(
        "DOMMediaStream::PlaybackStreamListener::DoNotifyFinishedTrackCreation",
        this, &PlaybackStreamListener::DoNotifyFinishedTrackCreation));
  }

  void NotifyEvent(MediaStreamGraph* aGraph,
                   MediaStreamGraphEvent event) override {
    if (event == MediaStreamGraphEvent::EVENT_FINISHED) {
      aGraph->DispatchToMainThreadAfterStreamStateUpdate(NewRunnableMethod(
          "DOMMediaStream::PlaybackStreamListener::DoNotifyFinished", this,
          &PlaybackStreamListener::DoNotifyFinished));
    }
  }

 private:
  // These fields may only be accessed on the main thread
  DOMMediaStream* mStream;
};

class DOMMediaStream::PlaybackTrackListener : public MediaStreamTrackConsumer {
 public:
  explicit PlaybackTrackListener(DOMMediaStream* aStream) : mStream(aStream) {}

  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(PlaybackTrackListener)
  NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(PlaybackTrackListener)

  void NotifyEnded(MediaStreamTrack* aTrack) override {
    if (!mStream) {
      MOZ_ASSERT(false);
      return;
    }

    if (!aTrack) {
      MOZ_ASSERT(false);
      return;
    }

    MOZ_ASSERT(mStream->HasTrack(*aTrack));
    mStream->NotifyTrackRemoved(aTrack);
  }

 protected:
  virtual ~PlaybackTrackListener() {}

  RefPtr<DOMMediaStream> mStream;
};

NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(DOMMediaStream::PlaybackTrackListener,
                                     AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(DOMMediaStream::PlaybackTrackListener,
                                       Release)
NS_IMPL_CYCLE_COLLECTION(DOMMediaStream::PlaybackTrackListener, mStream)

NS_IMPL_CYCLE_COLLECTION_CLASS(DOMMediaStream)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(DOMMediaStream,
                                                DOMEventTargetHelper)
  tmp->Destroy();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOwnedTracks)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTracks)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mConsumersToKeepAlive)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTrackSourceGetter)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mPlaybackTrackListener)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mPrincipal)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mVideoPrincipal)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(DOMMediaStream,
                                                  DOMEventTargetHelper)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOwnedTracks)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTracks)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mConsumersToKeepAlive)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTrackSourceGetter)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPlaybackTrackListener)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPrincipal)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mVideoPrincipal)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_ADDREF_INHERITED(DOMMediaStream, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(DOMMediaStream, DOMEventTargetHelper)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DOMMediaStream)
  NS_INTERFACE_MAP_ENTRY(DOMMediaStream)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)

NS_IMPL_ADDREF_INHERITED(DOMLocalMediaStream, DOMMediaStream)
NS_IMPL_RELEASE_INHERITED(DOMLocalMediaStream, DOMMediaStream)

NS_INTERFACE_MAP_BEGIN(DOMLocalMediaStream)
  NS_INTERFACE_MAP_ENTRY(DOMLocalMediaStream)
NS_INTERFACE_MAP_END_INHERITING(DOMMediaStream)

NS_IMPL_CYCLE_COLLECTION_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream,
                                   mStreamNode)

NS_IMPL_ADDREF_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream)
NS_IMPL_RELEASE_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DOMAudioNodeMediaStream)
NS_INTERFACE_MAP_END_INHERITING(DOMMediaStream)

DOMMediaStream::DOMMediaStream(nsPIDOMWindowInner* aWindow,
                               MediaStreamTrackSourceGetter* aTrackSourceGetter)
    : mLogicalStreamStartTime(0),
      mWindow(aWindow),
      mInputStream(nullptr),
      mOwnedStream(nullptr),
      mPlaybackStream(nullptr),
      mTracksPendingRemoval(0),
      mTrackSourceGetter(aTrackSourceGetter),
      mPlaybackTrackListener(MakeAndAddRef<PlaybackTrackListener>(this)),
      mTracksCreated(false),
      mNotifiedOfMediaStreamGraphShutdown(false),
      mActive(false),
      mSetInactiveOnFinish(false) {
  nsresult rv;
  nsCOMPtr<nsIUUIDGenerator> uuidgen =
      do_GetService("@mozilla.org/uuid-generator;1", &rv);

  if (NS_SUCCEEDED(rv) && uuidgen) {
    nsID uuid;
    memset(&uuid, 0, sizeof(uuid));
    rv = uuidgen->GenerateUUIDInPlace(&uuid);
    if (NS_SUCCEEDED(rv)) {
      char buffer[NSID_LENGTH];
      uuid.ToProvidedString(buffer);
      mID = NS_ConvertASCIItoUTF16(buffer);
    }
  }
}

DOMMediaStream::~DOMMediaStream() { Destroy(); }

void DOMMediaStream::Destroy() {
  LOG(LogLevel::Debug, ("DOMMediaStream %p Being destroyed.", this));
  if (mOwnedListener) {
    mOwnedListener->Forget();
    mOwnedListener = nullptr;
  }
  if (mPlaybackListener) {
    mPlaybackListener->Forget();
    mPlaybackListener = nullptr;
  }
  for (const RefPtr<TrackPort>& info : mTracks) {
    // We must remove ourselves from each track's principal change observer list
    // before we die. CC may have cleared info->mTrack so guard against it.
    MediaStreamTrack* track = info->GetTrack();
    if (track) {
      track->RemovePrincipalChangeObserver(this);
      if (!track->Ended()) {
        track->RemoveConsumer(mPlaybackTrackListener);
      }
    }
  }
  if (mPlaybackPort) {
    mPlaybackPort->Destroy();
    mPlaybackPort = nullptr;
  }
  if (mOwnedPort) {
    mOwnedPort->Destroy();
    mOwnedPort = nullptr;
  }
  if (mPlaybackStream) {
    mPlaybackStream->UnregisterUser();
    mPlaybackStream = nullptr;
  }
  if (mOwnedStream) {
    mOwnedStream->UnregisterUser();
    mOwnedStream = nullptr;
  }
  if (mInputStream) {
    mInputStream->UnregisterUser();
    mInputStream = nullptr;
  }
  mRunOnTracksAvailable.Clear();
  mTrackListeners.Clear();
}

JSObject* DOMMediaStream::WrapObject(JSContext* aCx,
                                     JS::Handle<JSObject*> aGivenProto) {
  return dom::MediaStreamBinding::Wrap(aCx, this, aGivenProto);
}

/* static */ already_AddRefed<DOMMediaStream> DOMMediaStream::Constructor(
    const GlobalObject& aGlobal, ErrorResult& aRv) {
  Sequence<OwningNonNull<MediaStreamTrack>> emptyTrackSeq;
  return Constructor(aGlobal, emptyTrackSeq, aRv);
}

/* static */ already_AddRefed<DOMMediaStream> DOMMediaStream::Constructor(
    const GlobalObject& aGlobal, const DOMMediaStream& aStream,
    ErrorResult& aRv) {
  nsTArray<RefPtr<MediaStreamTrack>> tracks;
  aStream.GetTracks(tracks);

  Sequence<OwningNonNull<MediaStreamTrack>> nonNullTrackSeq;
  if (!nonNullTrackSeq.SetLength(tracks.Length(), fallible)) {
    MOZ_ASSERT(false);
    aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
    return nullptr;
  }

  for (size_t i = 0; i < tracks.Length(); ++i) {
    nonNullTrackSeq[i] = tracks[i];
  }

  return Constructor(aGlobal, nonNullTrackSeq, aRv);
}

/* static */ already_AddRefed<DOMMediaStream> DOMMediaStream::Constructor(
    const GlobalObject& aGlobal,
    const Sequence<OwningNonNull<MediaStreamTrack>>& aTracks,
    ErrorResult& aRv) {
  nsCOMPtr<nsPIDOMWindowInner> ownerWindow =
      do_QueryInterface(aGlobal.GetAsSupports());
  if (!ownerWindow) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  // Streams created from JS cannot have dynamically created tracks.
  MediaStreamTrackSourceGetter* getter = nullptr;
  RefPtr<DOMMediaStream> newStream = new DOMMediaStream(ownerWindow, getter);

  for (MediaStreamTrack& track : aTracks) {
    if (!newStream->GetPlaybackStream()) {
      MOZ_RELEASE_ASSERT(track.Graph());
      newStream->InitPlaybackStreamCommon(track.Graph());
    }
    newStream->AddTrack(track);
  }

  if (!newStream->GetPlaybackStream()) {
    MOZ_ASSERT(aTracks.IsEmpty());
    MediaStreamGraph* graph = MediaStreamGraph::GetInstance(
        MediaStreamGraph::SYSTEM_THREAD_DRIVER, ownerWindow);
    newStream->InitPlaybackStreamCommon(graph);
  }

  return newStream.forget();
}

double DOMMediaStream::CurrentTime() {
  if (!mPlaybackStream) {
    return 0.0;
  }
  // The value of a MediaStream's CurrentTime will always advance forward; it
  // will never reset (even if one rewinds a video.) Therefore we can use a
  // single Random Seed initialized at the same time as the object.
  return nsRFPService::ReduceTimePrecisionAsSecs(
      mPlaybackStream->StreamTimeToSeconds(mPlaybackStream->GetCurrentTime() -
                                           mLogicalStreamStartTime),
      GetRandomTimelineSeed());
}

already_AddRefed<Promise> DOMMediaStream::CountUnderlyingStreams(
    const GlobalObject& aGlobal, ErrorResult& aRv) {
  nsCOMPtr<nsPIDOMWindowInner> window =
      do_QueryInterface(aGlobal.GetAsSupports());
  if (!window) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> go = do_QueryInterface(aGlobal.GetAsSupports());
  if (!go) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  RefPtr<Promise> p = Promise::Create(go, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  MediaStreamGraph* graph = MediaStreamGraph::GetInstanceIfExists(window);
  if (!graph) {
    p->MaybeResolve(0);
    return p.forget();
  }

  auto* graphImpl = static_cast<MediaStreamGraphImpl*>(graph);

  class Counter : public ControlMessage {
   public:
    Counter(MediaStreamGraphImpl* aGraph, const RefPtr<Promise>& aPromise)
        : ControlMessage(nullptr),
          mGraph(aGraph),
          mPromise(MakeAndAddRef<nsMainThreadPtrHolder<Promise>>(
              "DOMMediaStream::Counter::mPromise", aPromise)) {
      MOZ_ASSERT(NS_IsMainThread());
    }

    void Run() override {
      nsMainThreadPtrHandle<Promise>& promise = mPromise;
      uint32_t streams =
          mGraph->mStreams.Length() + mGraph->mSuspendedStreams.Length();
      mGraph->DispatchToMainThreadAfterStreamStateUpdate(
          NewRunnableFrom([promise, streams]() mutable {
            promise->MaybeResolve(streams);
            return NS_OK;
          }));
    }

   private:
    // mGraph owns this Counter instance and decides its lifetime.
    MediaStreamGraphImpl* mGraph;
    nsMainThreadPtrHandle<Promise> mPromise;
  };
  graphImpl->AppendMessage(MakeUnique<Counter>(graphImpl, p));

  return p.forget();
}

void DOMMediaStream::GetId(nsAString& aID) const { aID = mID; }

void DOMMediaStream::GetAudioTracks(
    nsTArray<RefPtr<AudioStreamTrack>>& aTracks) const {
  for (const RefPtr<TrackPort>& info : mTracks) {
    AudioStreamTrack* t = info->GetTrack()->AsAudioStreamTrack();
    if (t) {
      aTracks.AppendElement(t);
    }
  }
}

void DOMMediaStream::GetVideoTracks(
    nsTArray<RefPtr<VideoStreamTrack>>& aTracks) const {
  for (const RefPtr<TrackPort>& info : mTracks) {
    VideoStreamTrack* t = info->GetTrack()->AsVideoStreamTrack();
    if (t) {
      aTracks.AppendElement(t);
    }
  }
}

void DOMMediaStream::GetTracks(
    nsTArray<RefPtr<MediaStreamTrack>>& aTracks) const {
  for (const RefPtr<TrackPort>& info : mTracks) {
    aTracks.AppendElement(info->GetTrack());
  }
}

void DOMMediaStream::AddTrack(MediaStreamTrack& aTrack) {
  MOZ_RELEASE_ASSERT(mPlaybackStream);

  RefPtr<ProcessedMediaStream> dest = mPlaybackStream->AsProcessedStream();
  MOZ_ASSERT(dest);
  if (!dest) {
    return;
  }

  LOG(LogLevel::Info,
      ("DOMMediaStream %p Adding track %p (from stream %p with ID %d)", this,
       &aTrack, aTrack.mOwningStream.get(), aTrack.mTrackID));

  if (mPlaybackStream->Graph() != aTrack.Graph()) {
    NS_ASSERTION(false,
                 "Cannot combine tracks from different MediaStreamGraphs");
    LOG(LogLevel::Error, ("DOMMediaStream %p Own MSG %p != aTrack's MSG %p",
                          this, mPlaybackStream->Graph(), aTrack.Graph()));

    nsAutoString trackId;
    aTrack.GetId(trackId);
    const char16_t* params[] = {trackId.get()};
    nsCOMPtr<nsPIDOMWindowInner> pWindow = GetParentObject();
    nsIDocument* document = pWindow ? pWindow->GetExtantDoc() : nullptr;
    nsContentUtils::ReportToConsole(nsIScriptError::errorFlag,
                                    NS_LITERAL_CSTRING("Media"), document,
                                    nsContentUtils::eDOM_PROPERTIES,
                                    "MediaStreamAddTrackDifferentAudioChannel",
                                    params, ArrayLength(params));
    return;
  }

  if (HasTrack(aTrack)) {
    LOG(LogLevel::Debug,
        ("DOMMediaStream %p already contains track %p", this, &aTrack));
    return;
  }

  // Hook up the underlying track with our underlying playback stream.
  RefPtr<MediaInputPort> inputPort = GetPlaybackStream()->AllocateInputPort(
      aTrack.GetOwnedStream(), aTrack.mTrackID);
  RefPtr<TrackPort> trackPort =
      new TrackPort(inputPort, &aTrack, TrackPort::InputPortOwnership::OWNED);
  mTracks.AppendElement(trackPort.forget());
  NotifyTrackAdded(&aTrack);

  LOG(LogLevel::Debug, ("DOMMediaStream %p Added track %p", this, &aTrack));
}

void DOMMediaStream::RemoveTrack(MediaStreamTrack& aTrack) {
  LOG(LogLevel::Info,
      ("DOMMediaStream %p Removing track %p (from stream %p with ID %d)", this,
       &aTrack, aTrack.mOwningStream.get(), aTrack.mTrackID));

  RefPtr<TrackPort> toRemove = FindPlaybackTrackPort(aTrack);
  if (!toRemove) {
    LOG(LogLevel::Debug,
        ("DOMMediaStream %p does not contain track %p", this, &aTrack));
    return;
  }

  DebugOnly<bool> removed = mTracks.RemoveElement(toRemove);
  NS_ASSERTION(removed,
               "If there's a track port we should be able to remove it");

  // If the track comes from a TRACK_ANY input port (i.e., mOwnedPort), we need
  // to block it in the port. Doing this for a locked track is still OK as it
  // will first block the track, then destroy the port. Both cause the track to
  // end.
  // If the track has already ended, it's input port might be gone, so in those
  // cases blocking the underlying track should be avoided.
  if (!aTrack.Ended()) {
    BlockPlaybackTrack(toRemove);
    NotifyTrackRemoved(&aTrack);
  }

  LOG(LogLevel::Debug, ("DOMMediaStream %p Removed track %p", this, &aTrack));
}

class ClonedStreamSourceGetter : public MediaStreamTrackSourceGetter {
 public:
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(ClonedStreamSourceGetter,
                                           MediaStreamTrackSourceGetter)

  explicit ClonedStreamSourceGetter(DOMMediaStream* aStream)
      : mStream(aStream) {}

  already_AddRefed<MediaStreamTrackSource> GetMediaStreamTrackSource(
      TrackID aInputTrackID) override {
    MediaStreamTrack* sourceTrack =
        mStream->FindOwnedDOMTrack(mStream->GetOwnedStream(), aInputTrackID);
    MOZ_RELEASE_ASSERT(sourceTrack);

    return do_AddRef(&sourceTrack->GetSource());
  }

 protected:
  virtual ~ClonedStreamSourceGetter() {}

  RefPtr<DOMMediaStream> mStream;
};

NS_IMPL_ADDREF_INHERITED(ClonedStreamSourceGetter, MediaStreamTrackSourceGetter)
NS_IMPL_RELEASE_INHERITED(ClonedStreamSourceGetter,
                          MediaStreamTrackSourceGetter)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ClonedStreamSourceGetter)
NS_INTERFACE_MAP_END_INHERITING(MediaStreamTrackSourceGetter)
NS_IMPL_CYCLE_COLLECTION_INHERITED(ClonedStreamSourceGetter,
                                   MediaStreamTrackSourceGetter, mStream)

already_AddRefed<DOMMediaStream> DOMMediaStream::Clone() {
  return CloneInternal(TrackForwardingOption::CURRENT);
}

already_AddRefed<DOMMediaStream> DOMMediaStream::CloneInternal(
    TrackForwardingOption aForwarding) {
  RefPtr<DOMMediaStream> newStream =
      new DOMMediaStream(GetParentObject(), new ClonedStreamSourceGetter(this));

  LOG(LogLevel::Info,
      ("DOMMediaStream %p created clone %p, forwarding %s tracks", this,
       newStream.get(),
       aForwarding == TrackForwardingOption::ALL ? "all" : "current"));

  MOZ_RELEASE_ASSERT(mPlaybackStream);
  MOZ_RELEASE_ASSERT(mPlaybackStream->Graph());
  MediaStreamGraph* graph = mPlaybackStream->Graph();

  // We initiate the owned and playback streams first, since we need to create
  // all existing DOM tracks before we add the generic input port from
  // mInputStream to mOwnedStream (see AllocateInputPort wrt. destination
  // TrackID as to why).
  newStream->InitOwnedStreamCommon(graph);
  newStream->InitPlaybackStreamCommon(graph);

  // Set up existing DOM tracks.
  TrackID allocatedTrackID = 1;
  for (const RefPtr<TrackPort>& info : mTracks) {
    MediaStreamTrack& track = *info->GetTrack();

    LOG(LogLevel::Debug,
        ("DOMMediaStream %p forwarding external track %p to clone %p", this,
         &track, newStream.get()));
    RefPtr<MediaStreamTrack> trackClone =
        newStream->CloneDOMTrack(track, allocatedTrackID++);
  }

  if (aForwarding == TrackForwardingOption::ALL) {
    // Set up an input port from our input stream to the new DOM stream's owned
    // stream, to allow for dynamically added tracks at the source to appear in
    // the clone. The clone may treat mInputStream as its own mInputStream but
    // ownership remains with us.
    newStream->mInputStream = mInputStream;
    if (mInputStream) {
      // We have already set up track-locked input ports for all existing DOM
      // tracks, so now we need to block those in the generic input port to
      // avoid ending up with double instances of them.
      nsTArray<TrackID> tracksToBlock;
      for (const RefPtr<TrackPort>& info : mOwnedTracks) {
        tracksToBlock.AppendElement(info->GetTrack()->mTrackID);
      }

      newStream->mInputStream->RegisterUser();
      newStream->mOwnedPort = newStream->mOwnedStream->AllocateInputPort(
          mInputStream, TRACK_ANY, TRACK_ANY, 0, 0, &tracksToBlock);
    }
  }

  return newStream.forget();
}

bool DOMMediaStream::Active() const { return mActive; }

MediaStreamTrack* DOMMediaStream::GetTrackById(const nsAString& aId) const {
  for (const RefPtr<TrackPort>& info : mTracks) {
    nsString id;
    info->GetTrack()->GetId(id);
    if (id == aId) {
      return info->GetTrack();
    }
  }
  return nullptr;
}

MediaStreamTrack* DOMMediaStream::GetOwnedTrackById(const nsAString& aId) {
  for (const RefPtr<TrackPort>& info : mOwnedTracks) {
    nsString id;
    info->GetTrack()->GetId(id);
    if (id == aId) {
      return info->GetTrack();
    }
  }
  return nullptr;
}

bool DOMMediaStream::HasTrack(const MediaStreamTrack& aTrack) const {
  return !!FindPlaybackTrackPort(aTrack);
}

bool DOMMediaStream::OwnsTrack(const MediaStreamTrack& aTrack) const {
  return !!FindOwnedTrackPort(aTrack);
}

bool DOMMediaStream::IsFinished() const {
  return !mPlaybackStream || mPlaybackStream->IsFinished();
}

TrackRate DOMMediaStream::GraphRate() {
  if (mPlaybackStream) {
    return mPlaybackStream->GraphRate();
  }
  if (mOwnedStream) {
    return mOwnedStream->GraphRate();
  }
  if (mInputStream) {
    return mInputStream->GraphRate();
  }

  MOZ_ASSERT(false, "Not hooked up to a graph");
  return 0;
}

void DOMMediaStream::SetInactiveOnFinish() { mSetInactiveOnFinish = true; }

void DOMMediaStream::InitSourceStream(MediaStreamGraph* aGraph) {
  InitInputStreamCommon(aGraph->CreateSourceStream(), aGraph);
  InitOwnedStreamCommon(aGraph);
  InitPlaybackStreamCommon(aGraph);
}

void DOMMediaStream::InitTrackUnionStream(MediaStreamGraph* aGraph) {
  InitInputStreamCommon(aGraph->CreateTrackUnionStream(), aGraph);
  InitOwnedStreamCommon(aGraph);
  InitPlaybackStreamCommon(aGraph);
}

void DOMMediaStream::InitAudioCaptureStream(nsIPrincipal* aPrincipal,
                                            MediaStreamGraph* aGraph) {
  const TrackID AUDIO_TRACK = 1;

  RefPtr<BasicTrackSource> audioCaptureSource =
      new BasicTrackSource(aPrincipal, MediaSourceEnum::AudioCapture);

  AudioCaptureStream* audioCaptureStream = static_cast<AudioCaptureStream*>(
      aGraph->CreateAudioCaptureStream(AUDIO_TRACK));
  InitInputStreamCommon(audioCaptureStream, aGraph);
  InitOwnedStreamCommon(aGraph);
  InitPlaybackStreamCommon(aGraph);
  RefPtr<MediaStreamTrack> track =
      CreateDOMTrack(AUDIO_TRACK, MediaSegment::AUDIO, audioCaptureSource);
  AddTrackInternal(track);

  audioCaptureStream->Start();
}

void DOMMediaStream::InitInputStreamCommon(MediaStream* aStream,
                                           MediaStreamGraph* aGraph) {
  MOZ_ASSERT(!mOwnedStream,
             "Input stream must be initialized before owned stream");

  mInputStream = aStream;
  mInputStream->RegisterUser();
}

void DOMMediaStream::InitOwnedStreamCommon(MediaStreamGraph* aGraph) {
  MOZ_ASSERT(!mPlaybackStream,
             "Owned stream must be initialized before playback stream");

  mOwnedStream = aGraph->CreateTrackUnionStream();
  mOwnedStream->QueueSetAutofinish(true);
  mOwnedStream->RegisterUser();
  if (mInputStream) {
    mOwnedPort = mOwnedStream->AllocateInputPort(mInputStream);
  }

  // Setup track listeners
  mOwnedListener = new OwnedStreamListener(this);
  mOwnedStream->AddListener(mOwnedListener);
}

void DOMMediaStream::InitPlaybackStreamCommon(MediaStreamGraph* aGraph) {
  mPlaybackStream = aGraph->CreateTrackUnionStream();
  mPlaybackStream->QueueSetAutofinish(true);
  mPlaybackStream->RegisterUser();
  if (mOwnedStream) {
    mPlaybackPort = mPlaybackStream->AllocateInputPort(mOwnedStream);
  }

  mPlaybackListener = new PlaybackStreamListener(this);
  mPlaybackStream->AddListener(mPlaybackListener);

  LOG(LogLevel::Debug, ("DOMMediaStream %p Initiated with mInputStream=%p, "
                        "mOwnedStream=%p, mPlaybackStream=%p",
                        this, mInputStream, mOwnedStream, mPlaybackStream));
}

already_AddRefed<DOMMediaStream> DOMMediaStream::CreateSourceStreamAsInput(
    nsPIDOMWindowInner* aWindow, MediaStreamGraph* aGraph,
    MediaStreamTrackSourceGetter* aTrackSourceGetter) {
  RefPtr<DOMMediaStream> stream =
      new DOMMediaStream(aWindow, aTrackSourceGetter);
  stream->InitSourceStream(aGraph);
  return stream.forget();
}

already_AddRefed<DOMMediaStream> DOMMediaStream::CreateTrackUnionStreamAsInput(
    nsPIDOMWindowInner* aWindow, MediaStreamGraph* aGraph,
    MediaStreamTrackSourceGetter* aTrackSourceGetter) {
  RefPtr<DOMMediaStream> stream =
      new DOMMediaStream(aWindow, aTrackSourceGetter);
  stream->InitTrackUnionStream(aGraph);
  return stream.forget();
}

already_AddRefed<DOMMediaStream>
DOMMediaStream::CreateAudioCaptureStreamAsInput(nsPIDOMWindowInner* aWindow,
                                                nsIPrincipal* aPrincipal,
                                                MediaStreamGraph* aGraph) {
  // Audio capture doesn't create tracks dynamically
  MediaStreamTrackSourceGetter* getter = nullptr;
  RefPtr<DOMMediaStream> stream = new DOMMediaStream(aWindow, getter);
  stream->InitAudioCaptureStream(aPrincipal, aGraph);
  return stream.forget();
}

void DOMMediaStream::PrincipalChanged(MediaStreamTrack* aTrack) {
  MOZ_ASSERT(aTrack);
  NS_ASSERTION(HasTrack(*aTrack), "Principal changed for an unknown track");
  LOG(LogLevel::Info,
      ("DOMMediaStream %p Principal changed for track %p", this, aTrack));
  RecomputePrincipal();
}

void DOMMediaStream::RecomputePrincipal() {
  nsCOMPtr<nsIPrincipal> previousPrincipal = mPrincipal.forget();
  nsCOMPtr<nsIPrincipal> previousVideoPrincipal = mVideoPrincipal.forget();

  if (mTracksPendingRemoval > 0) {
    LOG(LogLevel::Info, ("DOMMediaStream %p RecomputePrincipal() Cannot "
                         "recompute stream principal with tracks pending "
                         "removal.",
                         this));
    return;
  }

  LOG(LogLevel::Debug, ("DOMMediaStream %p Recomputing principal. "
                        "Old principal was %p.",
                        this, previousPrincipal.get()));

  // mPrincipal is recomputed based on all current tracks, and tracks that have
  // not ended in our playback stream.
  for (const RefPtr<TrackPort>& info : mTracks) {
    if (info->GetTrack()->Ended()) {
      continue;
    }
    LOG(LogLevel::Debug,
        ("DOMMediaStream %p Taking live track %p with "
         "principal %p into account.",
         this, info->GetTrack(), info->GetTrack()->GetPrincipal()));
    nsContentUtils::CombineResourcePrincipals(&mPrincipal,
                                              info->GetTrack()->GetPrincipal());
    if (info->GetTrack()->AsVideoStreamTrack()) {
      nsContentUtils::CombineResourcePrincipals(
          &mVideoPrincipal, info->GetTrack()->GetPrincipal());
    }
  }

  LOG(LogLevel::Debug,
      ("DOMMediaStream %p new principal is %p.", this, mPrincipal.get()));

  if (previousPrincipal != mPrincipal ||
      previousVideoPrincipal != mVideoPrincipal) {
    NotifyPrincipalChanged();
  }
}

void DOMMediaStream::NotifyPrincipalChanged() {
  if (!mPrincipal) {
    // When all tracks are removed, mPrincipal will change to nullptr.
    LOG(LogLevel::Info,
        ("DOMMediaStream %p Principal changed to nothing.", this));
  } else {
    LOG(LogLevel::Info, ("DOMMediaStream %p Principal changed. Now: "
                         "null=%d, codebase=%d, expanded=%d, system=%d",
                         this, mPrincipal->GetIsNullPrincipal(),
                         mPrincipal->GetIsCodebasePrincipal(),
                         mPrincipal->GetIsExpandedPrincipal(),
                         mPrincipal->GetIsSystemPrincipal()));
  }

  for (uint32_t i = 0; i < mPrincipalChangeObservers.Length(); ++i) {
    mPrincipalChangeObservers[i]->PrincipalChanged(this);
  }
}

bool DOMMediaStream::AddPrincipalChangeObserver(
    PrincipalChangeObserver<DOMMediaStream>* aObserver) {
  return mPrincipalChangeObservers.AppendElement(aObserver) != nullptr;
}

bool DOMMediaStream::RemovePrincipalChangeObserver(
    PrincipalChangeObserver<DOMMediaStream>* aObserver) {
  return mPrincipalChangeObservers.RemoveElement(aObserver);
}

void DOMMediaStream::AddTrackInternal(MediaStreamTrack* aTrack) {
  MOZ_ASSERT(aTrack->mOwningStream == this);
  MOZ_ASSERT(FindOwnedDOMTrack(aTrack->GetInputStream(), aTrack->mInputTrackID,
                               aTrack->mTrackID));
  MOZ_ASSERT(!FindPlaybackDOMTrack(aTrack->GetOwnedStream(), aTrack->mTrackID));

  LOG(LogLevel::Debug,
      ("DOMMediaStream %p Adding owned track %p", this, aTrack));

  mTracks.AppendElement(new TrackPort(mPlaybackPort, aTrack,
                                      TrackPort::InputPortOwnership::EXTERNAL));

  NotifyTrackAdded(aTrack);

  DispatchTrackEvent(NS_LITERAL_STRING("addtrack"), aTrack);
}

already_AddRefed<MediaStreamTrack> DOMMediaStream::CreateDOMTrack(
    TrackID aTrackID, MediaSegment::Type aType, MediaStreamTrackSource* aSource,
    const MediaTrackConstraints& aConstraints) {
  MOZ_RELEASE_ASSERT(mInputStream);
  MOZ_RELEASE_ASSERT(mOwnedStream);

  MOZ_ASSERT(FindOwnedDOMTrack(GetInputStream(), aTrackID) == nullptr);

  RefPtr<MediaStreamTrack> track;
  switch (aType) {
    case MediaSegment::AUDIO:
      track =
          new AudioStreamTrack(this, aTrackID, aTrackID, aSource, aConstraints);
      break;
    case MediaSegment::VIDEO:
      track =
          new VideoStreamTrack(this, aTrackID, aTrackID, aSource, aConstraints);
      break;
    default:
      MOZ_CRASH("Unhandled track type");
  }

  LOG(LogLevel::Debug, ("DOMMediaStream %p Created new track %p with ID %u",
                        this, track.get(), aTrackID));

  mOwnedTracks.AppendElement(new TrackPort(
      mOwnedPort, track, TrackPort::InputPortOwnership::EXTERNAL));

  return track.forget();
}

already_AddRefed<MediaStreamTrack> DOMMediaStream::CloneDOMTrack(
    MediaStreamTrack& aTrack, TrackID aCloneTrackID) {
  MOZ_RELEASE_ASSERT(mOwnedStream);
  MOZ_RELEASE_ASSERT(mPlaybackStream);
  MOZ_RELEASE_ASSERT(IsTrackIDExplicit(aCloneTrackID));

  TrackID inputTrackID = aTrack.mInputTrackID;
  MediaStream* inputStream = aTrack.GetInputStream();

  RefPtr<MediaStreamTrack> newTrack = aTrack.CloneInternal(this, aCloneTrackID);

  newTrack->mOriginalTrack =
      aTrack.mOriginalTrack ? aTrack.mOriginalTrack.get() : &aTrack;

  LOG(LogLevel::Debug,
      ("DOMMediaStream %p Created new track %p cloned from stream %p track %d",
       this, newTrack.get(), inputStream, inputTrackID));

  RefPtr<MediaInputPort> inputPort =
      mOwnedStream->AllocateInputPort(inputStream, inputTrackID, aCloneTrackID);

  mOwnedTracks.AppendElement(
      new TrackPort(inputPort, newTrack, TrackPort::InputPortOwnership::OWNED));

  mTracks.AppendElement(new TrackPort(mPlaybackPort, newTrack,
                                      TrackPort::InputPortOwnership::EXTERNAL));

  NotifyTrackAdded(newTrack);

  newTrack->SetEnabled(aTrack.Enabled());
  newTrack->SetMuted(aTrack.Muted());
  newTrack->SetReadyState(aTrack.ReadyState());

  if (aTrack.Ended()) {
    // For extra suspenders, make sure that we don't forward data by mistake
    // to the clone when the original has already ended.
    // We only block END_EXISTING to allow any pending clones to end.
    RefPtr<Pledge<bool, nsresult>> blockingPledge =
        inputPort->BlockSourceTrackId(inputTrackID, BlockingMode::END_EXISTING);
    Unused << blockingPledge;
  }

  return newTrack.forget();
}

static DOMMediaStream::TrackPort* FindTrackPortAmongTracks(
    const MediaStreamTrack& aTrack,
    const nsTArray<RefPtr<DOMMediaStream::TrackPort>>& aTracks) {
  for (const RefPtr<DOMMediaStream::TrackPort>& info : aTracks) {
    if (info->GetTrack() == &aTrack) {
      return info;
    }
  }
  return nullptr;
}

MediaStreamTrack* DOMMediaStream::FindOwnedDOMTrack(MediaStream* aInputStream,
                                                    TrackID aInputTrackID,
                                                    TrackID aTrackID) const {
  MOZ_RELEASE_ASSERT(mOwnedStream);

  for (const RefPtr<TrackPort>& info : mOwnedTracks) {
    if (info->GetInputPort() &&
        info->GetInputPort()->GetSource() == aInputStream &&
        info->GetTrack()->mInputTrackID == aInputTrackID &&
        (aTrackID == TRACK_ANY || info->GetTrack()->mTrackID == aTrackID)) {
      // This track is owned externally but in our playback stream.
      return info->GetTrack();
    }
  }
  return nullptr;
}

DOMMediaStream::TrackPort* DOMMediaStream::FindOwnedTrackPort(
    const MediaStreamTrack& aTrack) const {
  return FindTrackPortAmongTracks(aTrack, mOwnedTracks);
}

MediaStreamTrack* DOMMediaStream::FindPlaybackDOMTrack(
    MediaStream* aInputStream, TrackID aInputTrackID) const {
  if (!mPlaybackStream) {
    // One would think we can assert mPlaybackStream here, but track clones have
    // a dummy DOMMediaStream that doesn't have a playback stream, so we can't.
    return nullptr;
  }

  for (const RefPtr<TrackPort>& info : mTracks) {
    if (info->GetInputPort() == mPlaybackPort && aInputStream == mOwnedStream &&
        info->GetTrack()->mInputTrackID == aInputTrackID) {
      // This track is in our owned and playback streams.
      return info->GetTrack();
    }
    if (info->GetInputPort() &&
        info->GetInputPort()->GetSource() == aInputStream &&
        info->GetSourceTrackId() == aInputTrackID) {
      // This track is owned externally but in our playback stream.
      MOZ_ASSERT(IsTrackIDExplicit(aInputTrackID));
      return info->GetTrack();
    }
  }
  return nullptr;
}

DOMMediaStream::TrackPort* DOMMediaStream::FindPlaybackTrackPort(
    const MediaStreamTrack& aTrack) const {
  return FindTrackPortAmongTracks(aTrack, mTracks);
}

void DOMMediaStream::OnTracksAvailable(OnTracksAvailableCallback* aRunnable) {
  if (mNotifiedOfMediaStreamGraphShutdown) {
    // No more tracks will ever be added, so just delete the callback now.
    delete aRunnable;
    return;
  }
  mRunOnTracksAvailable.AppendElement(aRunnable);
  CheckTracksAvailable();
}

void DOMMediaStream::NotifyTracksCreated() {
  mTracksCreated = true;
  CheckTracksAvailable();
}

void DOMMediaStream::NotifyFinished() {
  if (!mSetInactiveOnFinish) {
    return;
  }

  if (!mActive) {
    // This can happen if the stream never became active.
    return;
  }

  MOZ_ASSERT(!ContainsLiveTracks(mTracks));
  mActive = false;
  NotifyInactive();
}

void DOMMediaStream::NotifyActive() {
  LOG(LogLevel::Info, ("DOMMediaStream %p NotifyActive(). ", this));

  MOZ_ASSERT(mActive);
  for (int32_t i = mTrackListeners.Length() - 1; i >= 0; --i) {
    mTrackListeners[i]->NotifyActive();
  }
}

void DOMMediaStream::NotifyInactive() {
  LOG(LogLevel::Info, ("DOMMediaStream %p NotifyInactive(). ", this));

  MOZ_ASSERT(!mActive);
  for (int32_t i = mTrackListeners.Length() - 1; i >= 0; --i) {
    mTrackListeners[i]->NotifyInactive();
  }
}

void DOMMediaStream::CheckTracksAvailable() {
  if (!mTracksCreated) {
    return;
  }
  nsTArray<nsAutoPtr<OnTracksAvailableCallback>> callbacks;
  callbacks.SwapElements(mRunOnTracksAvailable);

  for (uint32_t i = 0; i < callbacks.Length(); ++i) {
    callbacks[i]->NotifyTracksAvailable(this);
  }
}

void DOMMediaStream::RegisterTrackListener(TrackListener* aListener) {
  MOZ_ASSERT(NS_IsMainThread());

  if (mNotifiedOfMediaStreamGraphShutdown) {
    // No more tracks will ever be added, so just do nothing.
    return;
  }
  mTrackListeners.AppendElement(aListener);
}

void DOMMediaStream::UnregisterTrackListener(TrackListener* aListener) {
  MOZ_ASSERT(NS_IsMainThread());
  mTrackListeners.RemoveElement(aListener);
}

void DOMMediaStream::NotifyTrackAdded(const RefPtr<MediaStreamTrack>& aTrack) {
  MOZ_ASSERT(NS_IsMainThread());

  if (mTracksPendingRemoval > 0) {
    // If there are tracks pending removal we may not degrade the current
    // principals until those tracks have been confirmed removed from the
    // playback stream. Instead combine with the new track and the (potentially)
    // degraded principal will be calculated when it's safe.
    nsContentUtils::CombineResourcePrincipals(&mPrincipal,
                                              aTrack->GetPrincipal());
    LOG(LogLevel::Debug, ("DOMMediaStream %p saw a track get added. Combining "
                          "its principal %p into our while waiting for pending "
                          "tracks to be removed. New principal is %p.",
                          this, aTrack->GetPrincipal(), mPrincipal.get()));
    if (aTrack->AsVideoStreamTrack()) {
      nsContentUtils::CombineResourcePrincipals(&mVideoPrincipal,
                                                aTrack->GetPrincipal());
    }
  } else {
    LOG(LogLevel::Debug, ("DOMMediaStream %p saw a track get added. "
                          "Recomputing principal.",
                          this));
    RecomputePrincipal();
  }

  aTrack->AddPrincipalChangeObserver(this);
  aTrack->AddConsumer(mPlaybackTrackListener);

  for (int32_t i = mTrackListeners.Length() - 1; i >= 0; --i) {
    mTrackListeners[i]->NotifyTrackAdded(aTrack);
  }

  if (mActive) {
    return;
  }

  // Check if we became active.
  if (ContainsLiveTracks(mTracks)) {
    mActive = true;
    NotifyActive();
  }
}

void DOMMediaStream::NotifyTrackRemoved(
    const RefPtr<MediaStreamTrack>& aTrack) {
  MOZ_ASSERT(NS_IsMainThread());

  aTrack->RemoveConsumer(mPlaybackTrackListener);
  aTrack->RemovePrincipalChangeObserver(this);

  for (int32_t i = mTrackListeners.Length() - 1; i >= 0; --i) {
    mTrackListeners[i]->NotifyTrackRemoved(aTrack);
  }

  // Don't call RecomputePrincipal here as the track may still exist in the
  // playback stream in the MediaStreamGraph. It will instead be called when the
  // track has been confirmed removed by the graph. See BlockPlaybackTrack().

  if (!mActive) {
    NS_ASSERTION(false, "Shouldn't remove a live track if already inactive");
    return;
  }

  if (mSetInactiveOnFinish) {
    // For compatibility with mozCaptureStream we in some cases do not go
    // inactive until the playback stream finishes.
    return;
  }

  // Check if we became inactive.
  if (!ContainsLiveTracks(mTracks)) {
    mActive = false;
    NotifyInactive();
  }
}

nsresult DOMMediaStream::DispatchTrackEvent(
    const nsAString& aName, const RefPtr<MediaStreamTrack>& aTrack) {
  MediaStreamTrackEventInit init;
  init.mTrack = aTrack;

  RefPtr<MediaStreamTrackEvent> event =
      MediaStreamTrackEvent::Constructor(this, aName, init);

  return DispatchTrustedEvent(event);
}

void DOMMediaStream::BlockPlaybackTrack(TrackPort* aTrack) {
  MOZ_ASSERT(aTrack);
  ++mTracksPendingRemoval;
  RefPtr<Pledge<bool>> p = aTrack->BlockSourceTrackId(
      aTrack->GetTrack()->mTrackID, BlockingMode::CREATION);
  RefPtr<DOMMediaStream> self = this;
  p->Then([self](const bool& aIgnore) { self->NotifyPlaybackTrackBlocked(); },
          [](const nsresult& aIgnore) {
            NS_ERROR("Could not remove track from MSG");
          });
}

void DOMMediaStream::NotifyPlaybackTrackBlocked() {
  MOZ_ASSERT(mTracksPendingRemoval > 0,
             "A track reported finished blocking more times than we asked for");
  if (--mTracksPendingRemoval == 0) {
    // The MediaStreamGraph has reported a track was blocked and we are not
    // waiting for any further tracks to get blocked. It is now safe to
    // recompute the principal based on our main thread track set state.
    LOG(LogLevel::Debug, ("DOMMediaStream %p saw all tracks pending removal "
                          "finish. Recomputing principal.",
                          this));
    RecomputePrincipal();
  }
}

DOMLocalMediaStream::~DOMLocalMediaStream() {
  if (mInputStream) {
    // Make sure Listeners of this stream know it's going away
    StopImpl();
  }
}

JSObject* DOMLocalMediaStream::WrapObject(JSContext* aCx,
                                          JS::Handle<JSObject*> aGivenProto) {
  return dom::LocalMediaStreamBinding::Wrap(aCx, this, aGivenProto);
}

void DOMLocalMediaStream::Stop() {
  LOG(LogLevel::Debug, ("DOMMediaStream %p Stop()", this));
  nsCOMPtr<nsPIDOMWindowInner> pWindow = GetParentObject();
  nsIDocument* document = pWindow ? pWindow->GetExtantDoc() : nullptr;
  nsContentUtils::ReportToConsole(
      nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Media"), document,
      nsContentUtils::eDOM_PROPERTIES, "MediaStreamStopDeprecatedWarning");

  StopImpl();
}

void DOMLocalMediaStream::StopImpl() {
  if (mInputStream && mInputStream->AsSourceStream()) {
    mInputStream->AsSourceStream()->EndAllTrackAndFinish();
  }
}

already_AddRefed<DOMLocalMediaStream>
DOMLocalMediaStream::CreateSourceStreamAsInput(
    nsPIDOMWindowInner* aWindow, MediaStreamGraph* aGraph,
    MediaStreamTrackSourceGetter* aTrackSourceGetter) {
  RefPtr<DOMLocalMediaStream> stream =
      new DOMLocalMediaStream(aWindow, aTrackSourceGetter);
  stream->InitSourceStream(aGraph);
  return stream.forget();
}

already_AddRefed<DOMLocalMediaStream>
DOMLocalMediaStream::CreateTrackUnionStreamAsInput(
    nsPIDOMWindowInner* aWindow, MediaStreamGraph* aGraph,
    MediaStreamTrackSourceGetter* aTrackSourceGetter) {
  RefPtr<DOMLocalMediaStream> stream =
      new DOMLocalMediaStream(aWindow, aTrackSourceGetter);
  stream->InitTrackUnionStream(aGraph);
  return stream.forget();
}

DOMAudioNodeMediaStream::DOMAudioNodeMediaStream(nsPIDOMWindowInner* aWindow,
                                                 AudioNode* aNode)
    : DOMMediaStream(aWindow, nullptr), mStreamNode(aNode) {}

DOMAudioNodeMediaStream::~DOMAudioNodeMediaStream() {}

already_AddRefed<DOMAudioNodeMediaStream>
DOMAudioNodeMediaStream::CreateTrackUnionStreamAsInput(
    nsPIDOMWindowInner* aWindow, AudioNode* aNode, MediaStreamGraph* aGraph) {
  RefPtr<DOMAudioNodeMediaStream> stream =
      new DOMAudioNodeMediaStream(aWindow, aNode);
  stream->InitTrackUnionStream(aGraph);
  return stream.forget();
}