DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

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 (c68fe15a81fc)

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 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* 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 "AudioContext.h"

#include "blink/PeriodicWave.h"


#include "mozilla/ErrorResult.h"
#include "mozilla/NotNull.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Preferences.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_media.h"

#include "mozilla/dom/AnalyserNode.h"
#include "mozilla/dom/AnalyserNodeBinding.h"
#include "mozilla/dom/AudioBufferSourceNodeBinding.h"
#include "mozilla/dom/AudioBufferSourceNodeBinding.h"
#include "mozilla/dom/AudioContextBinding.h"
#include "mozilla/dom/BaseAudioContextBinding.h"
#include "mozilla/dom/BiquadFilterNodeBinding.h"
#include "mozilla/dom/ChannelMergerNodeBinding.h"
#include "mozilla/dom/ChannelSplitterNodeBinding.h"
#include "mozilla/dom/ChannelSplitterNodeBinding.h"
#include "mozilla/dom/ConvolverNodeBinding.h"
#include "mozilla/dom/DelayNodeBinding.h"
#include "mozilla/dom/DynamicsCompressorNodeBinding.h"
#include "mozilla/dom/DynamicsCompressorNodeBinding.h"
#include "mozilla/dom/GainNodeBinding.h"
#include "mozilla/dom/IIRFilterNodeBinding.h"
#include "mozilla/dom/HTMLMediaElement.h"
#include "mozilla/dom/MediaElementAudioSourceNodeBinding.h"
#include "mozilla/dom/MediaStreamAudioSourceNodeBinding.h"
#include "mozilla/dom/MediaStreamAudioSourceNodeBinding.h"
#include "mozilla/dom/MediaStreamTrackAudioSourceNodeBinding.h"
#include "mozilla/dom/OfflineAudioContextBinding.h"
#include "mozilla/dom/OscillatorNodeBinding.h"
#include "mozilla/dom/PannerNodeBinding.h"
#include "mozilla/dom/PeriodicWaveBinding.h"
#include "mozilla/dom/PeriodicWaveBinding.h"
#include "mozilla/dom/Performance.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/StereoPannerNodeBinding.h"
#include "mozilla/dom/WaveShaperNodeBinding.h"
#include "mozilla/dom/Worklet.h"
#include "mozilla/dom/Worklet.h"

#include "AudioBuffer.h"
#include "AudioBufferSourceNode.h"
#include "AudioChannelService.h"
#include "AudioChannelService.h"
#include "AudioDestinationNode.h"
#include "AudioListener.h"
#include "AudioNodeTrack.h"
#include "AudioStream.h"
#include "AudioWorkletImpl.h"
#include "AudioWorkletImpl.h"
#include "AutoplayPolicy.h"
#include "BiquadFilterNode.h"
#include "ChannelMergerNode.h"
#include "ChannelSplitterNode.h"
#include "ConstantSourceNode.h"
#include "ConstantSourceNode.h"
#include "ConvolverNode.h"
#include "DelayNode.h"
#include "DynamicsCompressorNode.h"
#include "DynamicsCompressorNode.h"
#include "GainNode.h"
#include "IIRFilterNode.h"
#include "js/ArrayBuffer.h"  // JS::StealArrayBufferContents
#include "MediaElementAudioSourceNode.h"
#include "MediaStreamAudioDestinationNode.h"
#include "MediaStreamAudioDestinationNode.h"
#include "MediaStreamAudioSourceNode.h"
#include "MediaTrackGraph.h"
#include "MediaStreamTrackAudioSourceNode.h"
#include "nsContentUtils.h"
#include "nsIScriptError.h"
#include "nsIScriptError.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsPIDOMWindow.h"
#include "nsPrintfCString.h"
#include "nsRFPService.h"
#include "nsRFPService.h"
#include "OscillatorNode.h"
#include "PannerNode.h"
#include "PeriodicWave.h"
#include "ScriptProcessorNode.h"
#include "StereoPannerNode.h"
#include "StereoPannerNode.h"
#include "WaveShaperNode.h"

extern mozilla::LazyLogModule gAutoplayPermissionLog;

#define AUTOPLAY_LOG(msg, ...) \
  MOZ_LOG(gAutoplayPermissionLog, LogLevel::Debug, (msg, ##__VA_ARGS__))


using std::move;

namespace mozilla {
namespace dom {

static dom::AudioContext::AudioContextId gAudioContextId = 1;
// 0 is a special value that MediaTracks use to denote they are not part of a
// AudioContext.
static dom::AudioContext::AudioContextId gAudioContextId = 1;

NS_IMPL_CYCLE_COLLECTION_CLASS(AudioContext)
  // The destination node and AudioContext form a cycle and so the destination

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(AudioContext)
  // The destination node and AudioContext form a cycle and so the destination
  // track will be destroyed.  mWorklet must be shut down before the track
  // is destroyed.  Do this before clearing mWorklet.
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mListener)
  tmp->ShutdownWorklet();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mDestination)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mListener)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mWorklet)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mPromiseGripArray)
    NS_IMPL_CYCLE_COLLECTION_UNLINK(mActiveNodes)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mPendingResumePromises)
  if (tmp->mSuspendCalled || !tmp->mIsStarted) {
    NS_IMPL_CYCLE_COLLECTION_UNLINK(mActiveNodes)
  }
  // mBasicWaveFormCache cannot participate in cycles, ignore it here.
  // mDecodeJobs owns the WebAudioDecodeJob objects whose lifetime is managed
  // explicitly. mAllNodes is an array of weak pointers, ignore it here.
  // mBasicWaveFormCache cannot participate in cycles, ignore it here.

  // Remove weak reference on the global window as the context is not usable
NS_IMPL_CYCLE_COLLECTION_UNLINK_END_INHERITED(DOMEventTargetHelper)
  // without mDestination.
  tmp->DisconnectFromWindow();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END_INHERITED(DOMEventTargetHelper)

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(AudioContext,
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mListener)
                                                  DOMEventTargetHelper)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDestination)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mListener)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWorklet)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPromiseGripArray)
    NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mActiveNodes)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPendingResumePromises)
  if (tmp->mSuspendCalled || !tmp->mIsStarted) {
    NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mActiveNodes)
  }
  // mDecodeJobs owns the WebAudioDecodeJob objects whose lifetime is managed
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  // explicitly. mAllNodes is an array of weak pointers, ignore it here.
  // mBasicWaveFormCache cannot participate in cycles, ignore it here.
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_ADDREF_INHERITED(AudioContext, DOMEventTargetHelper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AudioContext)
NS_IMPL_RELEASE_INHERITED(AudioContext, DOMEventTargetHelper)

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AudioContext)
  NS_INTERFACE_MAP_ENTRY(nsIMemoryReporter)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
  if (aIsOffline || aSampleRate != 0.0) {

static float GetSampleRateForAudioContext(bool aIsOffline, float aSampleRate) {
  if (aIsOffline || aSampleRate != 0.0) {
    return aSampleRate;
  } else {
      return 44100.f;
    return static_cast<float>(CubebUtils::PreferredSampleRate());
  }
}

AudioContext::AudioContext(nsPIDOMWindowInner* aWindow, bool aIsOffline,

                           uint32_t aNumberOfChannels, uint32_t aLength,
                           float aSampleRate)
    : DOMEventTargetHelper(aWindow),
      mId(gAudioContextId++),
      mSampleRate(GetSampleRateForAudioContext(aIsOffline, aSampleRate)),
      mId(gAudioContextId++),
      mAudioContextState(AudioContextState::Suspended),
      mNumberOfChannels(aNumberOfChannels),
      mIsOffline(aIsOffline),
      mIsStarted(!aIsOffline),
      mIsShutDown(false),
      mIsStarted(!aIsOffline),
      mCloseCalled(false),
      // Realtime contexts start with suspended tracks until an
      // AudioCallbackDriver is running.
      mSuspendCalled(!aIsOffline),
      mIsDisconnecting(false),
      mWasAllowedToStart(true),
      mSuspendedByContent(false),
      mWasEverAllowedToStart(false),
      mWasEverAllowedToStart(false),
      mWasEverBlockedToStart(false),
      mWouldBeAllowedToStart(true) {
  bool mute = aWindow->AddAudioContext(this);

  // Note: AudioDestinationNode needs an AudioContext that must already be
  // Note: AudioDestinationNode needs an AudioContext that must already be
  // bound to the window.
  const bool allowedToStart = AutoplayPolicy::IsAllowedToPlay(*this);
  mDestination = new AudioDestinationNode(this, aIsOffline, allowedToStart,
                                          aNumberOfChannels, aLength);
  // If an AudioContext is not allowed to start, we would postpone its state
  // AudioContext.resume() or AudioScheduledSourceNode.start().
  // transition from `suspended` to `running` until sites explicitly call
  // AudioContext.resume() or AudioScheduledSourceNode.start().
  if (!allowedToStart) {
    MOZ_ASSERT(!mIsOffline);
    AUTOPLAY_LOG("AudioContext %p is not allowed to start", this);
  }
    ReportBlocked();
  } else if (!mIsOffline) {
    ResumeInternal(AudioContextOperationFlags::SendStateChange);
  }

  if (mute) {
  // The context can't be muted until it has a destination.
  if (mute) {
    Mute();
  }

  UpdateAutoplayAssumptionStatus();

  FFTBlock::MainThreadInit();
void AudioContext::StartBlockedAudioContextIfAllowed() {
}

void AudioContext::StartBlockedAudioContextIfAllowed() {
  MOZ_ASSERT(NS_IsMainThread());
  MaybeUpdateAutoplayTelemetry();
    return;
  // Only try to start AudioContext when AudioContext was not allowed to start.
  if (mWasAllowedToStart) {
    return;
  }

  AUTOPLAY_LOG("Trying to start AudioContext %p, IsAllowedToPlay=%d", this,
  const bool isAllowedToPlay = AutoplayPolicy::IsAllowedToPlay(*this);
  AUTOPLAY_LOG("Trying to start AudioContext %p, IsAllowedToPlay=%d", this,
               isAllowedToPlay);

  // Only start the AudioContext if this resume() call was initiated by content,
  // blocked because of the auto-play policy.
  // not if it was a result of the AudioContext starting after having been
  // blocked because of the auto-play policy.
  if (isAllowedToPlay && !mSuspendedByContent) {
    ResumeInternal(AudioContextOperationFlags::SendStateChange);
  } else {
    ReportBlocked();
  }
}
  if (!mIsOffline) {

nsresult AudioContext::Init() {
  if (!mIsOffline) {
    nsresult rv = mDestination->CreateAudioChannelAgent();
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
  }
    }
  }

  return NS_OK;
}
void AudioContext::DisconnectFromWindow() {

void AudioContext::DisconnectFromWindow() {
  nsPIDOMWindowInner* window = GetOwner();
  if (window) {
    window->RemoveAudioContext(this);
}
  }
}

AudioContext::~AudioContext() {
  DisconnectFromWindow();
}
  UnregisterWeakMemoryReporter(this);
}

JSObject* AudioContext::WrapObject(JSContext* aCx,
                                   JS::Handle<JSObject*> aGivenProto) {
    return OfflineAudioContext_Binding::Wrap(aCx, this, aGivenProto);
  if (mIsOffline) {
    return OfflineAudioContext_Binding::Wrap(aCx, this, aGivenProto);
  }
  } else {
    return AudioContext_Binding::Wrap(aCx, this, aGivenProto);
  }
}

    const GlobalObject& aGlobal, const AudioContextOptions& aOptions,
/* static */
already_AddRefed<AudioContext> AudioContext::Constructor(
    const GlobalObject& aGlobal, const AudioContextOptions& aOptions,
    ErrorResult& aRv) {
  nsCOMPtr<nsPIDOMWindowInner> window =
    aRv.Throw(NS_ERROR_FAILURE);
      do_QueryInterface(aGlobal.GetAsSupports());
  if (!window) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }

  if (aOptions.mSampleRate > 0 &&
  float sampleRate = MediaTrackGraph::REQUEST_DEFAULT_SAMPLE_RATE;
  if (aOptions.mSampleRate > 0 &&
      (aOptions.mSampleRate - WebAudioUtils::MinSampleRate < 0.0 ||
       WebAudioUtils::MaxSampleRate - aOptions.mSampleRate < 0.0)) {
    aRv.ThrowNotSupportedError(nsPrintfCString(
        WebAudioUtils::MinSampleRate, WebAudioUtils::MaxSampleRate));
        "Sample rate %g is not in the range [%u, %u]", aOptions.mSampleRate,
        WebAudioUtils::MinSampleRate, WebAudioUtils::MaxSampleRate));
    return nullptr;
  }
  sampleRate = aOptions.mSampleRate;
  RefPtr<AudioContext> object =

  RefPtr<AudioContext> object =
      new AudioContext(window, false, 2, 0, sampleRate);
  aRv = object->Init();
  if (NS_WARN_IF(aRv.Failed())) {

    return nullptr;
  }

  RegisterWeakMemoryReporter(object);


  return object.forget();
}

/* static */
already_AddRefed<AudioContext> AudioContext::Constructor(
    const GlobalObject& aGlobal, const OfflineAudioContextOptions& aOptions,
                     aOptions.mSampleRate, aRv);
    ErrorResult& aRv) {
  return Constructor(aGlobal, aOptions.mNumberOfChannels, aOptions.mLength,
                     aOptions.mSampleRate, aRv);
}

    const GlobalObject& aGlobal, uint32_t aNumberOfChannels, uint32_t aLength,
/* static */
already_AddRefed<AudioContext> AudioContext::Constructor(
    const GlobalObject& aGlobal, uint32_t aNumberOfChannels, uint32_t aLength,
    float aSampleRate, ErrorResult& aRv) {
      do_QueryInterface(aGlobal.GetAsSupports());
  if (!window) {
  nsCOMPtr<nsPIDOMWindowInner> window =
    aRv.Throw(NS_ERROR_FAILURE);
      do_QueryInterface(aGlobal.GetAsSupports());
  if (!window) {
    aRv.Throw(NS_ERROR_FAILURE);
    return nullptr;
  }
      aNumberOfChannels > WebAudioUtils::MaxChannelCount) {

  if (aNumberOfChannels == 0 ||
      aNumberOfChannels > WebAudioUtils::MaxChannelCount) {
    aRv.ThrowNotSupportedError(
        nsPrintfCString("%u is not a valid channel count", aNumberOfChannels));

    return nullptr;
  }

  if (aLength == 0) {
    aRv.ThrowNotSupportedError("Length must be nonzero");

    return nullptr;
  }

  if (aSampleRate < WebAudioUtils::MinSampleRate ||
      aSampleRate > WebAudioUtils::MaxSampleRate) {
        "Sample rate %g is not in the range [%u, %u]", aSampleRate,
    // The DOM binding protects us against infinity and NaN
    aRv.ThrowNotSupportedError(nsPrintfCString(
        "Sample rate %g is not in the range [%u, %u]", aSampleRate,
        WebAudioUtils::MinSampleRate, WebAudioUtils::MaxSampleRate));
    return nullptr;
  }

  RefPtr<AudioContext> object =
  RegisterWeakMemoryReporter(object);
      new AudioContext(window, true, aNumberOfChannels, aLength, aSampleRate);

  RegisterWeakMemoryReporter(object);

  return object.forget();
already_AddRefed<AudioBufferSourceNode> AudioContext::CreateBufferSource() {
}

already_AddRefed<AudioBufferSourceNode> AudioContext::CreateBufferSource() {
  return AudioBufferSourceNode::Create(nullptr, *this,
                                       AudioBufferSourceOptions());
already_AddRefed<ConstantSourceNode> AudioContext::CreateConstantSource() {
}

already_AddRefed<ConstantSourceNode> AudioContext::CreateConstantSource() {
  RefPtr<ConstantSourceNode> constantSourceNode = new ConstantSourceNode(this);
  return constantSourceNode.forget();
}

already_AddRefed<AudioBuffer> AudioContext::CreateBuffer(
    ErrorResult& aRv) {
    uint32_t aNumberOfChannels, uint32_t aLength, float aSampleRate,
    ErrorResult& aRv) {
  if (!aNumberOfChannels) {
    aRv.ThrowNotSupportedError("Number of channels must be nonzero");
    return nullptr;

  }

  return AudioBuffer::Create(GetOwner(), aNumberOfChannels, aLength,
                             aSampleRate, aRv);
}
namespace {

namespace {

bool IsValidBufferSize(uint32_t aBufferSize) {
  switch (aBufferSize) {
    case 256:
    case 0:  // let the implementation choose the buffer size
    case 256:
    case 512:
    case 1024:
    case 2048:
    case 4096:
    case 8192:
    case 16384:
      return false;
      return true;
    default:
      return false;
  }
}


}  // namespace

already_AddRefed<MediaStreamAudioDestinationNode>
AudioContext::CreateMediaStreamDestination(ErrorResult& aRv) {
}
  return MediaStreamAudioDestinationNode::Create(*this, AudioNodeOptions(),
                                                 aRv);
}

already_AddRefed<ScriptProcessorNode> AudioContext::CreateScriptProcessor(
  if (aNumberOfInputChannels == 0 && aNumberOfOutputChannels == 0) {
    uint32_t aBufferSize, uint32_t aNumberOfInputChannels,
    uint32_t aNumberOfOutputChannels, ErrorResult& aRv) {
  if (aNumberOfInputChannels == 0 && aNumberOfOutputChannels == 0) {
    aRv.ThrowIndexSizeError(
        "At least one of numberOfInputChannels and numberOfOutputChannels must "
        "be nonzero");
  }
    return nullptr;
  }

  if (aNumberOfInputChannels > WebAudioUtils::MaxChannelCount) {
    aRv.ThrowIndexSizeError(nsPrintfCString(
    return nullptr;
        "%u is not a valid number of input channels", aNumberOfInputChannels));
    return nullptr;
  }

  if (aNumberOfOutputChannels > WebAudioUtils::MaxChannelCount) {
        nsPrintfCString("%u is not a valid number of output channels",
    aRv.ThrowIndexSizeError(
        nsPrintfCString("%u is not a valid number of output channels",
  }
                        aNumberOfOutputChannels));
    return nullptr;
  }

  if (!IsValidBufferSize(aBufferSize)) {
    return nullptr;
    aRv.ThrowIndexSizeError(
        nsPrintfCString("%u is not a valid bufferSize", aBufferSize));
    return nullptr;
  }

  return scriptProcessor.forget();
  RefPtr<ScriptProcessorNode> scriptProcessor = new ScriptProcessorNode(
      this, aBufferSize, aNumberOfInputChannels, aNumberOfOutputChannels);
  return scriptProcessor.forget();
}

}
already_AddRefed<AnalyserNode> AudioContext::CreateAnalyser(ErrorResult& aRv) {
  return AnalyserNode::Create(*this, AnalyserOptions(), aRv);
}

already_AddRefed<StereoPannerNode> AudioContext::CreateStereoPanner(
}
    ErrorResult& aRv) {
  return StereoPannerNode::Create(*this, StereoPannerOptions(), aRv);
}

already_AddRefed<MediaElementAudioSourceNode>
AudioContext::CreateMediaElementSource(HTMLMediaElement& aMediaElement,
                                       ErrorResult& aRv) {
  MediaElementAudioSourceOptions options;
  options.mMediaElement = aMediaElement;
}

  return MediaElementAudioSourceNode::Create(*this, options, aRv);
}

already_AddRefed<MediaStreamAudioSourceNode>
  MediaStreamAudioSourceOptions options;
AudioContext::CreateMediaStreamSource(DOMMediaStream& aMediaStream,
                                      ErrorResult& aRv) {
  MediaStreamAudioSourceOptions options;
  options.mMediaStream = aMediaStream;

  return MediaStreamAudioSourceNode::Create(*this, options, aRv);
}

already_AddRefed<MediaStreamTrackAudioSourceNode>
AudioContext::CreateMediaStreamTrackSource(MediaStreamTrack& aMediaStreamTrack,
  options.mMediaStreamTrack = aMediaStreamTrack;
                                           ErrorResult& aRv) {
  MediaStreamTrackAudioSourceOptions options;
  options.mMediaStreamTrack = aMediaStreamTrack;

  return MediaStreamTrackAudioSourceNode::Create(*this, options, aRv);
}
already_AddRefed<GainNode> AudioContext::CreateGain(ErrorResult& aRv) {

already_AddRefed<GainNode> AudioContext::CreateGain(ErrorResult& aRv) {
  return GainNode::Create(*this, GainOptions(), aRv);
}

    ErrorResult& aRv) {
already_AddRefed<WaveShaperNode> AudioContext::CreateWaveShaper(
    ErrorResult& aRv) {
  return WaveShaperNode::Create(*this, WaveShaperOptions(), aRv);
}

                                                      ErrorResult& aRv) {
already_AddRefed<DelayNode> AudioContext::CreateDelay(double aMaxDelayTime,
                                                      ErrorResult& aRv) {
  DelayOptions options;
  options.mMaxDelayTime = aMaxDelayTime;
  return DelayNode::Create(*this, options, aRv);

}

already_AddRefed<PannerNode> AudioContext::CreatePanner(ErrorResult& aRv) {
  return PannerNode::Create(*this, PannerOptions(), aRv);
}

already_AddRefed<ConvolverNode> AudioContext::CreateConvolver(
    ErrorResult& aRv) {

  return ConvolverNode::Create(nullptr, *this, ConvolverOptions(), aRv);
}

already_AddRefed<ChannelSplitterNode> AudioContext::CreateChannelSplitter(
    uint32_t aNumberOfOutputs, ErrorResult& aRv) {
  ChannelSplitterOptions options;
  options.mNumberOfOutputs = aNumberOfOutputs;
  return ChannelSplitterNode::Create(*this, options, aRv);
already_AddRefed<ChannelMergerNode> AudioContext::CreateChannelMerger(
}

already_AddRefed<ChannelMergerNode> AudioContext::CreateChannelMerger(
    uint32_t aNumberOfInputs, ErrorResult& aRv) {
  ChannelMergerOptions options;
  options.mNumberOfInputs = aNumberOfInputs;
  return ChannelMergerNode::Create(*this, options, aRv);
}
already_AddRefed<DynamicsCompressorNode> AudioContext::CreateDynamicsCompressor(

already_AddRefed<DynamicsCompressorNode> AudioContext::CreateDynamicsCompressor(
    ErrorResult& aRv) {
  return DynamicsCompressorNode::Create(*this, DynamicsCompressorOptions(),
                                        aRv);

}

already_AddRefed<BiquadFilterNode> AudioContext::CreateBiquadFilter(
    ErrorResult& aRv) {
  return BiquadFilterNode::Create(*this, BiquadFilterOptions(), aRv);

}

already_AddRefed<IIRFilterNode> AudioContext::CreateIIRFilter(
    const Sequence<double>& aFeedforward, const Sequence<double>& aFeedback,
    mozilla::ErrorResult& aRv) {
  options.mFeedforward = aFeedforward;
  IIRFilterOptions options;
  options.mFeedforward = aFeedforward;
  options.mFeedback = aFeedback;
  return IIRFilterNode::Create(*this, options, aRv);
}
already_AddRefed<OscillatorNode> AudioContext::CreateOscillator(

already_AddRefed<OscillatorNode> AudioContext::CreateOscillator(
    ErrorResult& aRv) {
  return OscillatorNode::Create(*this, OscillatorOptions(), aRv);
already_AddRefed<PeriodicWave> AudioContext::CreatePeriodicWave(
}

already_AddRefed<PeriodicWave> AudioContext::CreatePeriodicWave(
    const Float32Array& aRealData, const Float32Array& aImagData,
    const PeriodicWaveConstraints& aConstraints, ErrorResult& aRv) {
  aImagData.ComputeState();
  aRealData.ComputeState();
  aImagData.ComputeState();

    return nullptr;
  if (aRealData.Length() != aImagData.Length()) {
    aRv.ThrowIndexSizeError("\"real\" and \"imag\" must be the same length");
    return nullptr;
  }

    return nullptr;
  if (aRealData.Length() == 0) {
    aRv.ThrowIndexSizeError("\"real\" and \"imag\" are both empty arrays");
    return nullptr;
  }

      aConstraints.mDisableNormalization, aRv);
  RefPtr<PeriodicWave> periodicWave = new PeriodicWave(
      this, aRealData.Data(), aImagData.Data(), aImagData.Length(),
      aConstraints.mDisableNormalization, aRv);
  if (aRv.Failed()) {
    return nullptr;
}
  }
  return periodicWave.forget();
}

AudioListener* AudioContext::Listener() {
  if (!mListener) {
  }
    mListener = new AudioListener(this);
  }
  return mListener;
}

  // When reduceFingerprinting is enabled, return a latency figure that is
double AudioContext::OutputLatency() {
  // When reduceFingerprinting is enabled, return a latency figure that is
  // fixed, but plausible for the platform.
  double latency_s = 0.0;
  if (StaticPrefs::privacy_resistFingerprinting()) {
    latency_s = 512. / mSampleRate;
#ifdef XP_MACOSX
    latency_s = 512. / mSampleRate;
#elif MOZ_WIDGET_ANDROID
    latency_s = 0.020;
#elif XP_WIN
#else  // Catchall for other OSes, including Linux.
    latency_s = 0.04;
#else  // Catchall for other OSes, including Linux.
    latency_s = 0.025;
#endif
  } else {
  }
    return Graph()->AudioOutputLatency();
  }
  return latency_s;
}

  if (!Destination()) {
void AudioContext::GetOutputTimestamp(AudioTimestamp& aTimeStamp) {
  if (!Destination()) {
    aTimeStamp.mContextTime.Construct(0.0);
    aTimeStamp.mPerformanceTime.Construct(0.0);
    return;

  }

  // The currentTime currently being output is the currentTime minus the audio
  // output latency. The resolution of CurrentTime() is already reduced.
  aTimeStamp.mContextTime.Construct(
  nsPIDOMWindowInner* parent = GetParentObject();
      std::max(0.0, CurrentTime() - OutputLatency()));
  nsPIDOMWindowInner* parent = GetParentObject();
  Performance* perf = parent ? parent->GetPerformance() : nullptr;
  if (perf) {
    // perf->Now() already has reduced resolution here, no need to do it again.
    aTimeStamp.mPerformanceTime.Construct(
        std::max(0., perf->Now() - (OutputLatency() * 1000.)));
  } else {
}
    aTimeStamp.mPerformanceTime.Construct(0.0);
  }
}

Worklet* AudioContext::GetAudioWorklet(ErrorResult& aRv) {
  }
  if (!mWorklet) {
    mWorklet = AudioWorkletImpl::CreateWorklet(this, aRv);
  }

  return mWorklet;
  return mAudioContextState == AudioContextState::Running;
}
bool AudioContext::IsRunning() const {
  return mAudioContextState == AudioContextState::Running;
}

already_AddRefed<Promise> AudioContext::DecodeAudioData(
    const ArrayBuffer& aBuffer,
    const Optional<OwningNonNull<DecodeSuccessCallback>>& aSuccessCallback,
    const Optional<OwningNonNull<DecodeErrorCallback>>& aFailureCallback,
  RefPtr<Promise> promise;
    ErrorResult& aRv) {
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  RefPtr<Promise> promise;
  AutoJSAPI jsapi;
  jsapi.Init();
  // CheckedUnwrapStatic is OK, since we know we have an ArrayBuffer.
  JSContext* cx = jsapi.cx();

  // CheckedUnwrapStatic is OK, since we know we have an ArrayBuffer.
  JS::Rooted<JSObject*> obj(cx, js::CheckedUnwrapStatic(aBuffer.Obj()));
  if (!obj) {
  }
    aRv.ThrowSecurityError("Can't get audio data from cross-origin object");
    return nullptr;
  }

  JSAutoRealm ar(cx, obj);
  if (aRv.Failed()) {

  promise = Promise::Create(parentObject, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }


  aBuffer.ComputeState();

  if (!aBuffer.Data()) {
    // Throw if the buffer is detached
  }
    aRv.ThrowTypeError("Buffer argument can't be a detached buffer");
    return nullptr;
  }

  // Detach the array buffer
  uint8_t* data = static_cast<uint8_t*>(JS::StealArrayBufferContents(cx, obj));
  size_t length = aBuffer.Length();

  uint8_t* data = static_cast<uint8_t*>(JS::StealArrayBufferContents(cx, obj));

  // Sniff the content of the media.
  // Failed type sniffing will be handled by AsyncDecodeWebAudio.
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr, data, length, contentType);
  nsAutoCString contentType;
  NS_SniffContent(NS_DATA_SNIFFER_CATEGORY, nullptr, data, length, contentType);

  RefPtr<DecodeErrorCallback> failureCallback;
    failureCallback = &aFailureCallback.Value();
  RefPtr<DecodeSuccessCallback> successCallback;
  if (aFailureCallback.WasPassed()) {
    failureCallback = &aFailureCallback.Value();
  }
  if (aSuccessCallback.WasPassed()) {
  UniquePtr<WebAudioDecodeJob> job(
    successCallback = &aSuccessCallback.Value();
  }
  UniquePtr<WebAudioDecodeJob> job(
      new WebAudioDecodeJob(this, promise, successCallback, failureCallback));
  AsyncDecodeWebAudio(contentType.get(), data, length, *job);

  // Transfer the ownership to mDecodeJobs
  mDecodeJobs.AppendElement(move(job));

  return promise.forget();
}
  // Since UniquePtr doesn't provide an operator== which allows you to compare

void AudioContext::RemoveFromDecodeQueue(WebAudioDecodeJob* aDecodeJob) {
  // Since UniquePtr doesn't provide an operator== which allows you to compare
  // against raw pointers, we need to iterate manually.
  for (uint32_t i = 0; i < mDecodeJobs.Length(); ++i) {
    if (mDecodeJobs[i].get() == aDecodeJob) {
      mDecodeJobs.RemoveElementAt(i);
  }
      break;
    }
  }
}

void AudioContext::RegisterActiveNode(AudioNode* aNode) {
  if (!mCloseCalled) {
    mActiveNodes.PutEntry(aNode);
  }

}

void AudioContext::UnregisterActiveNode(AudioNode* aNode) {
  mActiveNodes.RemoveEntry(aNode);
}
uint32_t AudioContext::MaxChannelCount() const {

uint32_t AudioContext::MaxChannelCount() const {
  if (StaticPrefs::privacy_resistFingerprinting()) {
    return 2;
  }
      WebAudioUtils::MaxChannelCount,
  return std::min<uint32_t>(
      WebAudioUtils::MaxChannelCount,
      mIsOffline ? mNumberOfChannels : CubebUtils::MaxNumberOfChannels());
}

uint32_t AudioContext::ActiveNodeCount() const { return mActiveNodes.Count(); }
  return Destination()->Track()->Graph();

MediaTrackGraph* AudioContext::Graph() const {
  return Destination()->Track()->Graph();
}

    return Destination()->Track();
AudioNodeTrack* AudioContext::DestinationTrack() const {
  if (Destination()) {
    return Destination()->Track();
  }
  return nullptr;
void AudioContext::ShutdownWorklet() {
}

void AudioContext::ShutdownWorklet() {
  if (mWorklet) {
    mWorklet->Impl()->NotifyWorkletFinished();
  }

}

double AudioContext::CurrentTime() {
  mozilla::MediaTrack* track = Destination()->Track();

  double rawTime = track->TrackTimeToSeconds(track->GetCurrentTime());
  // Precision Reduction is smaller than this interval, the jittered time

  // CurrentTime increments in intervals of 128/sampleRate. If the Timer
  // Precision Reduction is smaller than this interval, the jittered time
  // can always be reversed to the raw step of the interval. In that case
  // we can simply return the un-reduced time; and avoid breaking tests.
    return rawTime;
  // We have to convert each variable into a common magnitude, we choose ms.
  if ((128 / mSampleRate) * 1000.0 > nsRFPService::TimerResolution() / 1000.0) {
    return rawTime;
  }

  // will never reset (even if one rewinds a video.) Therefore we can use a
  MOZ_ASSERT(GetParentObject()->AsGlobal());
  // The value of a MediaTrack'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(
      GetParentObject()->AsGlobal()->CrossOriginIsolated());
      rawTime, GetRandomTimelineSeed(),
      /* aIsSystemPrincipal */ false,
      GetParentObject()->AsGlobal()->CrossOriginIsolated());
}

nsISerialEventTarget* AudioContext::GetMainThread() const {
  if (nsPIDOMWindowInner* window = GetParentObject()) {

    return window->AsGlobal()->EventTargetFor(TaskCategory::Other);
  }

  return GetCurrentThreadSerialEventTarget();
}
  mIsDisconnecting = true;

void AudioContext::DisconnectFromOwner() {
  mIsDisconnecting = true;
  OnWindowDestroy();
  DOMEventTargetHelper::DisconnectFromOwner();
void AudioContext::Shutdown() {
}

void AudioContext::OnWindowDestroy() {
  // Avoid resend the Telemetry data.
  if (!mIsShutDown) {
    MaybeUpdateAutoplayTelemetryWhenShutdown();
  }
  CloseInternal(nullptr, AudioContextOperationFlags::None);
  mIsShutDown = true;

  CloseInternal(nullptr, AudioContextOperationFlags::None);

  // We don't want to touch promises if the global is going away soon.
      p->MaybeRejectWithInvalidStateError("Navigated away from page");
  if (!mIsDisconnecting) {
    for (auto p : mPromiseGripArray) {
      p->MaybeRejectWithInvalidStateError("Navigated away from page");
    }


    mPromiseGripArray.Clear();

    for (const auto& p : mPendingResumePromises) {
      p->MaybeRejectWithInvalidStateError("Navigated away from page");
    }
  }
    mPendingResumePromises.Clear();
  }

  // On process shutdown, the MTG thread shuts down before the destination
  // PBrowser::Destroy() message before xpcom shutdown begins.
  // track is destroyed, but AudioWorklet needs to release objects on the MTG
  // thread.  AudioContext::Shutdown() is invoked on processing the
  // PBrowser::Destroy() message before xpcom shutdown begins.
  ShutdownWorklet();

    mDestination->OfflineShutdown();
  if (mDestination) {
    // We can destroy the MediaTrackGraph at this point.
    // Although there may be other clients using the graph, this graph is used
    // only for clients in the same window and this window is going away.
    // This will also interrupt any worklet script still running on the graph
class OnStateChangeTask final : public Runnable {
    // thread.
    Graph()->ForceShutDown();
    // AudioDestinationNodes on rendering offline contexts have a
    // self-reference which needs removal.
    if (mIsOffline) {
  NS_IMETHODIMP
      mDestination->OfflineShutdown();
    }
  }
}

      return NS_ERROR_FAILURE;
/* This runnable allows to fire the "statechange" event */
class OnStateChangeTask final : public Runnable {
 public:
  explicit OnStateChangeTask(AudioContext* aAudioContext)
      return NS_ERROR_FAILURE;
      : Runnable("dom::OnStateChangeTask"), mAudioContext(aAudioContext) {}

  NS_IMETHODIMP
  Run() override {
    nsPIDOMWindowInner* parent = mAudioContext->GetParentObject();
        NS_LITERAL_STRING("statechange"), CanBubble::eNo, Cancelable::eNo);
    if (!parent) {
      return NS_ERROR_FAILURE;
    }

    Document* doc = parent->GetExtantDoc();
};
    if (!doc) {
      return NS_ERROR_FAILURE;
    }

    return nsContentUtils::DispatchTrustedEvent(
  // It can happen that this runnable took a long time to reach the main thread,
        doc, static_cast<DOMEventTargetHelper*>(mAudioContext),
        NS_LITERAL_STRING("statechange"), CanBubble::eNo, Cancelable::eNo);
  }

 private:
  } else {
  RefPtr<AudioContext> mAudioContext;
};

void AudioContext::Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) {
  MOZ_ASSERT(NS_IsMainThread());
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  // It can happen that this runnable took a long time to reach the main thread,
  MOZ_ASSERT(NS_IsMainThread());
  // and the global is not valid anymore.
  if (parentObject) {
    parentObject->AbstractMainThreadFor(TaskCategory::Other)
        ->Dispatch(move(aRunnable));
  } else {
    RefPtr<nsIRunnable> runnable(aRunnable);
    runnable = nullptr;
    return;
  }
}

void AudioContext::OnStateChanged(void* aPromise, AudioContextState aNewState) {
  // suspended at the same time, for example if a page was being
  MOZ_ASSERT(NS_IsMainThread());

  if (mAudioContextState == AudioContextState::Closed) {
    fprintf(stderr,
            "Invalid transition: mAudioContextState: %d -> aNewState %d\n",
  }
            static_cast<int>(mAudioContextState), static_cast<int>(aNewState));
    MOZ_ASSERT(false);
  }

  if (aPromise) {
    Promise* promise = reinterpret_cast<Promise*>(aPromise);
    // It is possible for the promise to have been removed from
    // mPromiseGripArray if the cycle collector has severed our connections. DO
         aNewState == AudioContextState::Running) ||
    // NOT dereference the promise pointer in that case since it may point to
    // already freed memory.
    if (mPromiseGripArray.Contains(promise)) {
      promise->MaybeResolveWithUndefined();
      DebugOnly<bool> rv = mPromiseGripArray.RemoveElement(promise);
        (mAudioContextState == AudioContextState::Suspended &&
      MOZ_ASSERT(rv, "Promise wasn't in the grip array?");
    }
  }

  // Resolve all pending promises once the audio context has been allowed to
            static_cast<int>(mAudioContextState), static_cast<int>(aNewState));
  // start.
  if (aNewState == AudioContextState::Running) {
    for (const auto& p : mPendingResumePromises) {
      p->MaybeResolveWithUndefined();
#  endif    // XP_MACOSX
    }
#endif      // WIN32
    mPendingResumePromises.Clear();
  }

  if (mAudioContextState != aNewState) {
    RefPtr<OnStateChangeTask> task = new OnStateChangeTask(this);
    Dispatch(task.forget());
  }

    // already freed memory.
  mAudioContextState = aNewState;
}

nsTArray<RefPtr<mozilla::MediaTrack>> AudioContext::GetAllTracks() const {
  nsTArray<RefPtr<mozilla::MediaTrack>> tracks;
    }
  for (auto iter = mAllNodes.ConstIter(); !iter.Done(); iter.Next()) {
    AudioNode* node = iter.Get()->GetKey();
    mozilla::MediaTrack* t = node->GetTrack();
    if (t) {
      tracks.AppendElement(t);
  if (aNewState == AudioContextState::Running) {
    }
    // Add the tracks of AudioParam.
    const nsTArray<RefPtr<AudioParam>>& audioParams = node->GetAudioParams();
    if (!audioParams.IsEmpty()) {
      for (auto& param : audioParams) {
  }
        t = param->GetTrack();
        if (t && !tracks.Contains(t)) {
          tracks.AppendElement(t);
        }
      }
  }
    }
  }
  return tracks;

}

already_AddRefed<Promise> AudioContext::Suspend(ErrorResult& aRv) {
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  RefPtr<Promise> promise;
    mozilla::MediaTrack* t = node->GetTrack();
  promise = Promise::Create(parentObject, aRv);
  if (aRv.Failed()) {
    return nullptr;
    }
  }
  if (mIsOffline) {
    // XXXbz This is not reachable, since we don't implement this
    // method on OfflineAudioContext at all!
    promise->MaybeRejectWithNotSupportedError(
        t = param->GetTrack();
        "Can't suspend OfflineAudioContext yet");
    return promise.forget();
  }

  if (mAudioContextState == AudioContextState::Closed || mCloseCalled) {
    }
    promise->MaybeRejectWithInvalidStateError(
        "Can't suspend if the control thread state is \"closed\"");
    return promise.forget();
  }

already_AddRefed<Promise> AudioContext::Suspend(ErrorResult& aRv) {
  mSuspendedByContent = true;
  mPromiseGripArray.AppendElement(promise);
  SuspendInternal(promise, AudioContextOperationFlags::SendStateChange);
  return promise.forget();
}
    return nullptr;

void AudioContext::SuspendFromChrome() {
  if (mIsOffline || mIsShutDown) {
    return;
  }
    promise->MaybeRejectWithNotSupportedError(
  SuspendInternal(nullptr, AudioContextOperationFlags::None);
}

void AudioContext::SuspendInternal(void* aPromise,
                                   AudioContextOperationFlags aFlags) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(!mIsOffline);
  Destination()->Suspend();
        "Can't suspend if the control thread state is \"closed\"");

  nsTArray<RefPtr<mozilla::MediaTrack>> tracks;
  // If mSuspendCalled is true then we already suspended all our tracks,
  // so don't suspend them again (since suspend(); suspend(); resume(); should
  // cancel both suspends). But we still need to do ApplyAudioContextOperation
  mPromiseGripArray.AppendElement(promise);
  SuspendInternal(promise, AudioContextOperationFlags::SendStateChange);
  // to ensure our new promise is resolved.
  if (!mSuspendCalled) {
    tracks = GetAllTracks();
  }
  auto promise = Graph()->ApplyAudioContextOperation(
  if (mIsOffline || mIsShutDown) {
      DestinationTrack(), move(tracks), AudioContextOperation::Suspend);
  if ((aFlags & AudioContextOperationFlags::SendStateChange)) {
    promise->Then(
        GetMainThread(), "AudioContext::OnStateChanged",
        [self = RefPtr<AudioContext>(this),

         aPromise](AudioContextState aNewState) {
          self->OnStateChanged(aPromise, aNewState);
        },
        [] { MOZ_CRASH("Unexpected rejection"); });
  }

  mSuspendCalled = true;
}
  // If mSuspendCalled is true then we already suspended all our tracks,

void AudioContext::ResumeFromChrome() {
  if (mIsOffline || mIsShutDown) {
    return;
    tracks = GetAllTracks();
  }
  ResumeInternal(AudioContextOperationFlags::None);
}

already_AddRefed<Promise> AudioContext::Resume(ErrorResult& aRv) {
    promise->Then(
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  RefPtr<Promise> promise;
  promise = Promise::Create(parentObject, aRv);
  if (aRv.Failed()) {
    return nullptr;
        },
  }

  if (mIsOffline) {
    promise->MaybeRejectWithNotSupportedError(
        "Can't resume OfflineAudioContext");
}
    return promise.forget();
  }

  if (mAudioContextState == AudioContextState::Closed || mCloseCalled) {
    promise->MaybeRejectWithInvalidStateError(
    return;
        "Can't resume if the control thread state is \"closed\"");
    return promise.forget();
  }

  mSuspendedByContent = false;
already_AddRefed<Promise> AudioContext::Resume(ErrorResult& aRv) {
  mPendingResumePromises.AppendElement(promise);

  const bool isAllowedToPlay = AutoplayPolicy::IsAllowedToPlay(*this);
  AUTOPLAY_LOG("Trying to resume AudioContext %p, IsAllowedToPlay=%d", this,
    return nullptr;
               isAllowedToPlay);
  if (isAllowedToPlay) {
    ResumeInternal(AudioContextOperationFlags::SendStateChange);
  } else {
    ReportBlocked();
        "Can't resume OfflineAudioContext");
  }

  MaybeUpdateAutoplayTelemetry();

  return promise.forget();
    promise->MaybeRejectWithInvalidStateError(
}

void AudioContext::ResumeInternal(AudioContextOperationFlags aFlags) {
  MOZ_ASSERT(!mIsOffline);
  AUTOPLAY_LOG("Allow to resume AudioContext %p", this);

  mWasAllowedToStart = true;

  Destination()->Resume();

  nsTArray<RefPtr<mozilla::MediaTrack>> tracks;
  AUTOPLAY_LOG("Trying to resume AudioContext %p, IsAllowedToPlay=%d", this,
  // If mSuspendCalled is false then we already resumed all our tracks,
  // so don't resume them again (since suspend(); resume(); resume(); should
  // be OK). But we still need to do ApplyAudioContextOperation
  // to ensure our new promise is resolved.
  if (mSuspendCalled) {
    ReportBlocked();
    tracks = GetAllTracks();
  }
  MaybeUpdateAutoplayTelemetry();
  auto promise = Graph()->ApplyAudioContextOperation(
      DestinationTrack(), move(tracks), AudioContextOperation::Resume);
  if (aFlags & AudioContextOperationFlags::SendStateChange) {
    promise->Then(
        GetMainThread(), "AudioContext::OnStateChanged",
void AudioContext::ResumeInternal(AudioContextOperationFlags aFlags) {
        [self = RefPtr<AudioContext>(this)](AudioContextState aNewState) {
          self->OnStateChanged(nullptr, aNewState);
        },
        [] {});  // Promise may be rejected after graph shutdown.
  }
  Destination()->Resume();
  mSuspendCalled = false;
}

void AudioContext::UpdateAutoplayAssumptionStatus() {
  if (AutoplayPolicyTelemetryUtils::WouldBeAllowedToPlayIfAutoplayDisabled(
  // be OK). But we still need to do ApplyAudioContextOperation
          *this)) {
    mWasEverAllowedToStart |= true;
    mWouldBeAllowedToStart = true;
  } else {
    mWasEverBlockedToStart |= true;
  auto promise = Graph()->ApplyAudioContextOperation(
    mWouldBeAllowedToStart = false;
  }
}

void AudioContext::MaybeUpdateAutoplayTelemetry() {
        [self = RefPtr<AudioContext>(this)](AudioContextState aNewState) {
  // Exclude offline AudioContext because it's always allowed to start.
  if (mIsOffline) {
    return;
  }

  mSuspendCalled = false;
  if (AutoplayPolicyTelemetryUtils::WouldBeAllowedToPlayIfAutoplayDisabled(
          *this) &&
      !mWouldBeAllowedToStart) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_WEB_AUDIO_AUTOPLAY::AllowedAfterBlocked);
          *this)) {
  }
  UpdateAutoplayAssumptionStatus();
}

void AudioContext::MaybeUpdateAutoplayTelemetryWhenShutdown() {
  }
  // Exclude offline AudioContext because it's always allowed to start.
  if (mIsOffline) {
    return;
  }

  if (mIsOffline) {
  if (mWasEverAllowedToStart && !mWasEverBlockedToStart) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_WEB_AUDIO_AUTOPLAY::NeverBlocked);
  } else if (!mWasEverAllowedToStart && mWasEverBlockedToStart) {
    AccumulateCategorical(
          *this) &&
        mozilla::Telemetry::LABELS_WEB_AUDIO_AUTOPLAY::NeverAllowed);
  }
}

void AudioContext::ReportBlocked() {
  UpdateAutoplayAssumptionStatus();
  ReportToConsole(nsIScriptError::warningFlag,
                  "BlockAutoplayWebAudioStartError");
  mWasAllowedToStart = false;

  if (!StaticPrefs::media_autoplay_block_event_enabled()) {
  if (mIsOffline) {
    return;
  }

  RefPtr<AudioContext> self = this;
  RefPtr<nsIRunnable> r =
    AccumulateCategorical(
      NS_NewRunnableFunction("AudioContext::AutoplayBlocked", [self]() {
        nsPIDOMWindowInner* parent = self->GetParentObject();
        if (!parent) {
          return;
        }

        Document* doc = parent->GetExtantDoc();
        if (!doc) {
          return;
        }
  ReportToConsole(nsIScriptError::warningFlag,

        AUTOPLAY_LOG("Dispatch `blocked` event for AudioContext %p",
                     self.get());
        nsContentUtils::DispatchTrustedEvent(
    return;
            doc, static_cast<DOMEventTargetHelper*>(self),
            NS_LITERAL_STRING("blocked"), CanBubble::eNo, Cancelable::eNo);
      });
  Dispatch(r.forget());
}
      NS_NewRunnableFunction("AudioContext::AutoplayBlocked", [self]() {

already_AddRefed<Promise> AudioContext::Close(ErrorResult& aRv) {
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());
  RefPtr<Promise> promise;
  promise = Promise::Create(parentObject, aRv);

  if (aRv.Failed()) {
    return nullptr;
  }

  if (mIsOffline) {

    // XXXbz This is not reachable, since we don't implement this
    // method on OfflineAudioContext at all!
    promise->MaybeRejectWithNotSupportedError(
        "Can't close OfflineAudioContext yet");
    return promise.forget();
  }
            NS_LITERAL_STRING("blocked"), CanBubble::eNo, Cancelable::eNo);

  if (mAudioContextState == AudioContextState::Closed) {
    promise->MaybeRejectWithInvalidStateError(
        "Can't close an AudioContext twice");
    return promise.forget();
already_AddRefed<Promise> AudioContext::Close(ErrorResult& aRv) {
  }

  mPromiseGripArray.AppendElement(promise);

  CloseInternal(promise, AudioContextOperationFlags::SendStateChange);


  return promise.forget();
}

void AudioContext::OfflineClose() {
  CloseInternal(nullptr, AudioContextOperationFlags::None);
}

  }
void AudioContext::CloseInternal(void* aPromise,
                                 AudioContextOperationFlags aFlags) {
  // This can be called when freeing a document, and the tracks are dead at
  // this point, so we need extra null-checks.
  AudioNodeTrack* ds = DestinationTrack();
    return promise.forget();
  if (ds && !mIsOffline) {
    Destination()->DestroyAudioChannelAgent();

    nsTArray<RefPtr<mozilla::MediaTrack>> tracks;
    // If mSuspendCalled or mCloseCalled are true then we already suspended
  CloseInternal(promise, AudioContextOperationFlags::SendStateChange);
    // all our tracks, so don't suspend them again. But we still need to do
    // ApplyAudioContextOperation to ensure our new promise is resolved.
    if (!mSuspendCalled && !mCloseCalled) {
      tracks = GetAllTracks();
    }
    auto promise = Graph()->ApplyAudioContextOperation(
        ds, move(tracks), AudioContextOperation::Close);
}
    if ((aFlags & AudioContextOperationFlags::SendStateChange)) {
      promise->Then(
          GetMainThread(), "AudioContext::OnStateChanged",
          [self = RefPtr<AudioContext>(this),
           aPromise](AudioContextState aNewState) {
  // this point, so we need extra null-checks.
            self->OnStateChanged(aPromise, aNewState);
          },
          [] {});  // Promise may be rejected after graph shutdown.
    }
  }
    nsTArray<mozilla::MediaTrack*> tracks;
  mCloseCalled = true;
  // Release references to active nodes.
  // Active AudioNodes don't unregister in destructors, at which point the
  // Node is already unregistered.
  mActiveNodes.Clear();
      tracks = GetAllTracks();
}

void AudioContext::RegisterNode(AudioNode* aNode) {
  MOZ_ASSERT(!mAllNodes.Contains(aNode));
  mAllNodes.PutEntry(aNode);
}

          GetMainThread(), "AudioContext::OnStateChanged",
void AudioContext::UnregisterNode(AudioNode* aNode) {
  MOZ_ASSERT(mAllNodes.Contains(aNode));
  mAllNodes.RemoveEntry(aNode);
}

          [] { MOZ_CRASH("Unexpected rejection"); });
already_AddRefed<Promise> AudioContext::StartRendering(ErrorResult& aRv) {
  nsCOMPtr<nsIGlobalObject> parentObject = do_QueryInterface(GetParentObject());

  MOZ_ASSERT(mIsOffline, "This should only be called on OfflineAudioContext");
  // Active AudioNodes don't unregister in destructors, at which point the
  if (mIsStarted) {
    aRv.ThrowInvalidStateError("Rendering already started");
    return nullptr;
  }

void AudioContext::RegisterNode(AudioNode* aNode) {
  mIsStarted = true;
  RefPtr<Promise> promise = Promise::Create(parentObject, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }
void AudioContext::UnregisterNode(AudioNode* aNode) {
  mDestination->StartRendering(promise);

  OnStateChanged(nullptr, AudioContextState::Running);

  return promise.forget();

}

unsigned long AudioContext::Length() {
  MOZ_ASSERT(mIsOffline);
  return mDestination->Length();
  if (mIsStarted) {
}

void AudioContext::Mute() const {
  MOZ_ASSERT(!mIsOffline);
  if (mDestination) {
  mIsStarted = true;
    mDestination->Mute();
  }
}

  }
void AudioContext::Unmute() const {
  MOZ_ASSERT(!mIsOffline);
  if (mDestination) {
    mDestination->Unmute();
  return promise.forget();
  }
}

void AudioContext::SetParamMapForWorkletName(
  MOZ_ASSERT(mIsOffline);
    const nsAString& aName, AudioParamDescriptorMap* aParamMap) {
  MOZ_ASSERT(!mWorkletParamDescriptors.GetValue(aName));
  Unused << mWorkletParamDescriptors.Put(aName, move(*aParamMap), fallible);
}

  MOZ_ASSERT(!mIsOffline);
size_t AudioContext::SizeOfIncludingThis(
    mozilla::MallocSizeOf aMallocSizeOf) const {
  // AudioNodes are tracked separately because we do not want the AudioContext
  // to track all of the AudioNodes it creates, so we wouldn't be able to
  // traverse them from here.


  size_t amount = aMallocSizeOf(this);
  if (mListener) {
    amount += mListener->SizeOfIncludingThis(aMallocSizeOf);
  }
  }
  amount += mDecodeJobs.ShallowSizeOfExcludingThis(aMallocSizeOf);
  for (uint32_t i = 0; i < mDecodeJobs.Length(); ++i) {
    amount += mDecodeJobs[i]->SizeOfIncludingThis(aMallocSizeOf);
  }
  amount += mActiveNodes.ShallowSizeOfExcludingThis(aMallocSizeOf);
  MOZ_ASSERT(!mWorkletParamDescriptors.GetValue(aName));
  return amount;
}

NS_IMETHODIMP
AudioContext::CollectReports(nsIHandleReportCallback* aHandleReport,
                             nsISupports* aData, bool aAnonymize) {
size_t AudioContext::SizeOfIncludingThis(
  const nsLiteralCString nodeDescription(
      "Memory used by AudioNode DOM objects (Web Audio).");
  for (auto iter = mAllNodes.ConstIter(); !iter.Done(); iter.Next()) {
    AudioNode* node = iter.Get()->GetKey();
    int64_t amount = node->SizeOfIncludingThis(MallocSizeOf);

    nsPrintfCString domNodePath("explicit/webaudio/audio-node/%s/dom-nodes",
                                node->NodeType());
    aHandleReport->Callback(EmptyCString(), domNodePath, KIND_HEAP, UNITS_BYTES,
                            amount, nodeDescription, aData);
  amount += mDecodeJobs.ShallowSizeOfExcludingThis(aMallocSizeOf);
  }

  int64_t amount = SizeOfIncludingThis(MallocSizeOf);
  MOZ_COLLECT_REPORT("explicit/webaudio/audiocontext", KIND_HEAP, UNITS_BYTES,
                     amount,
  return amount;
                     "Memory used by AudioContext objects (Web Audio).");

  return NS_OK;
}

                             nsISupports* aData, bool aAnonymize) {
BasicWaveFormCache* AudioContext::GetBasicWaveFormCache() {
  MOZ_ASSERT(NS_IsMainThread());
  if (!mBasicWaveFormCache) {
    mBasicWaveFormCache = new BasicWaveFormCache(SampleRate());
  }
    int64_t amount = node->SizeOfIncludingThis(MallocSizeOf);
  return mBasicWaveFormCache;
}

void AudioContext::ReportToConsole(uint32_t aErrorFlags,
                                   const char* aMsg) const {
  }
  MOZ_ASSERT(aMsg);
  Document* doc =
      GetParentObject() ? GetParentObject()->GetExtantDoc() : nullptr;
  nsContentUtils::ReportToConsole(aErrorFlags, NS_LITERAL_CSTRING("Media"), doc,
                                  nsContentUtils::eDOM_PROPERTIES, aMsg);
                     "Memory used by AudioContext objects (Web Audio).");
}

BasicWaveFormCache::BasicWaveFormCache(uint32_t aSampleRate)
    : mSampleRate(aSampleRate) {
  MOZ_ASSERT(NS_IsMainThread());
}
BasicWaveFormCache::~BasicWaveFormCache() = default;
  if (!mBasicWaveFormCache) {

WebCore::PeriodicWave* BasicWaveFormCache::GetBasicWaveForm(
    OscillatorType aType) {
  return mBasicWaveFormCache;
  MOZ_ASSERT(!NS_IsMainThread());
  if (aType == OscillatorType::Sawtooth) {
    if (!mSawtooth) {
      mSawtooth = WebCore::PeriodicWave::createSawtooth(mSampleRate);
    }
  MOZ_ASSERT(aMsg);
    return mSawtooth;
  }
  if (aType == OscillatorType::Square) {
    if (!mSquare) {
      mSquare = WebCore::PeriodicWave::createSquare(mSampleRate);
}
    }
    return mSquare;
  }
  if (aType == OscillatorType::Triangle) {
    if (!mTriangle) {
      mTriangle = WebCore::PeriodicWave::createTriangle(mSampleRate);
    }
    return mTriangle;

  }
  MOZ_ASSERT(false, "Not reached");
  return nullptr;
}
    if (!mSawtooth) {

}  // namespace dom
}  // namespace mozilla
  if (aType == OscillatorType::Square) {
  }
  return nullptr;
}  // namespace mozilla