summaryrefslogtreecommitdiffstats
path: root/browser/base/content/test/webrtc/head.js
blob: 13526e91b6e3232ea607ffb2a326797858e89d30 (plain)
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
var { PermissionTestUtils } = ChromeUtils.importESModule(
  "resource://testing-common/PermissionTestUtils.sys.mjs"
);

const PREF_PERMISSION_FAKE = "media.navigator.permission.fake";
const PREF_AUDIO_LOOPBACK = "media.audio_loopback_dev";
const PREF_VIDEO_LOOPBACK = "media.video_loopback_dev";
const PREF_FAKE_STREAMS = "media.navigator.streams.fake";
const PREF_FOCUS_SOURCE = "media.getusermedia.window.focus_source.enabled";

const STATE_CAPTURE_ENABLED = Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED;
const STATE_CAPTURE_DISABLED = Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED;

const USING_LEGACY_INDICATOR = Services.prefs.getBoolPref(
  "privacy.webrtc.legacyGlobalIndicator",
  false
);

const ALLOW_SILENCING_NOTIFICATIONS = Services.prefs.getBoolPref(
  "privacy.webrtc.allowSilencingNotifications",
  false
);

const SHOW_GLOBAL_MUTE_TOGGLES = Services.prefs.getBoolPref(
  "privacy.webrtc.globalMuteToggles",
  false
);

const INDICATOR_PATH = USING_LEGACY_INDICATOR
  ? "chrome://browser/content/webrtcLegacyIndicator.xhtml"
  : "chrome://browser/content/webrtcIndicator.xhtml";

const IS_MAC = AppConstants.platform == "macosx";

const SHARE_SCREEN = 1;
const SHARE_WINDOW = 2;

let observerTopics = [
  "getUserMedia:response:allow",
  "getUserMedia:revoke",
  "getUserMedia:response:deny",
  "getUserMedia:request",
  "recording-device-events",
  "recording-window-ended",
];

// Structured hierarchy of subframes. Keys are frame id:s, The children member
// contains nested sub frames if any. The noTest member make a frame be ignored
// for testing if true.
let gObserveSubFrames = {};
// Object of subframes to test. Each element contains the members bc and id, for
// the frames BrowsingContext and id, respectively.
let gSubFramesToTest = [];
let gBrowserContextsToObserve = [];

function whenDelayedStartupFinished(aWindow) {
  return TestUtils.topicObserved(
    "browser-delayed-startup-finished",
    subject => subject == aWindow
  );
}

function promiseIndicatorWindow() {
  let startTime = performance.now();

  // We don't show the legacy indicator window on Mac.
  if (USING_LEGACY_INDICATOR && IS_MAC) {
    return Promise.resolve();
  }

  return new Promise(resolve => {
    Services.obs.addObserver(function obs(win) {
      win.addEventListener(
        "load",
        function () {
          if (win.location.href !== INDICATOR_PATH) {
            info("ignoring a window with this url: " + win.location.href);
            return;
          }

          Services.obs.removeObserver(obs, "domwindowopened");
          executeSoon(() => {
            ChromeUtils.addProfilerMarker("promiseIndicatorWindow", {
              startTime,
              category: "Test",
            });
            resolve(win);
          });
        },
        { once: true }
      );
    }, "domwindowopened");
  });
}

async function assertWebRTCIndicatorStatus(expected) {
  let ui = ChromeUtils.import("resource:///modules/webrtcUI.jsm").webrtcUI;
  let expectedState = expected ? "visible" : "hidden";
  let msg = "WebRTC indicator " + expectedState;
  if (!expected && ui.showGlobalIndicator) {
    // It seems the global indicator is not always removed synchronously
    // in some cases.
    await TestUtils.waitForCondition(
      () => !ui.showGlobalIndicator,
      "waiting for the global indicator to be hidden"
    );
  }
  is(ui.showGlobalIndicator, !!expected, msg);

  let expectVideo = false,
    expectAudio = false,
    expectScreen = "";
  if (expected) {
    if (expected.video) {
      expectVideo = true;
    }
    if (expected.audio) {
      expectAudio = true;
    }
    if (expected.screen) {
      expectScreen = expected.screen;
    }
  }
  is(
    Boolean(ui.showCameraIndicator),
    expectVideo,
    "camera global indicator as expected"
  );
  is(
    Boolean(ui.showMicrophoneIndicator),
    expectAudio,
    "microphone global indicator as expected"
  );
  is(
    ui.showScreenSharingIndicator,
    expectScreen,
    "screen global indicator as expected"
  );

  for (let win of Services.wm.getEnumerator("navigator:browser")) {
    let menu = win.document.getElementById("tabSharingMenu");
    is(
      !!menu && !menu.hidden,
      !!expected,
      "WebRTC menu should be " + expectedState
    );
  }

  if (USING_LEGACY_INDICATOR && IS_MAC) {
    return;
  }

  if (!expected) {
    let win = Services.wm.getMostRecentWindow("Browser:WebRTCGlobalIndicator");
    if (win) {
      await new Promise((resolve, reject) => {
        win.addEventListener("unload", function listener(e) {
          if (e.target == win.document) {
            win.removeEventListener("unload", listener);
            executeSoon(resolve);
          }
        });
      });
    }
  }

  let indicator = Services.wm.getEnumerator("Browser:WebRTCGlobalIndicator");
  let hasWindow = indicator.hasMoreElements();
  is(hasWindow, !!expected, "popup " + msg);
  if (hasWindow) {
    let document = indicator.getNext().document;
    let docElt = document.documentElement;

    if (document.readyState != "complete") {
      info("Waiting for the sharing indicator's document to load");
      await new Promise(resolve => {
        document.addEventListener(
          "readystatechange",
          function onReadyStateChange() {
            if (document.readyState != "complete") {
              return;
            }
            document.removeEventListener(
              "readystatechange",
              onReadyStateChange
            );
            executeSoon(resolve);
          }
        );
      });
    }

    if (
      !USING_LEGACY_INDICATOR &&
      expected.screen &&
      expected.screen.startsWith("Window")
    ) {
      // These tests were originally written to express window sharing by
      // having expected.screen start with "Window". This meant that the
      // legacy indicator is expected to have the "sharingscreen" attribute
      // set to true when sharing a window.
      //
      // The new indicator, however, differentiates between screen, window
      // and browser window sharing. If we're using the new indicator, we
      // update the expectations accordingly. This can be removed once we
      // are able to remove the tests for the legacy indicator.
      expected.screen = null;
      expected.window = true;
    }

    if (!USING_LEGACY_INDICATOR && !SHOW_GLOBAL_MUTE_TOGGLES) {
      expected.video = false;
      expected.audio = false;

      let visible = docElt.getAttribute("visible") == "true";

      if (!expected.screen && !expected.window && !expected.browserwindow) {
        ok(!visible, "Indicator should not be visible in this configuation.");
      } else {
        ok(visible, "Indicator should be visible.");
      }
    }

    for (let item of ["video", "audio", "screen", "window", "browserwindow"]) {
      let expectedValue;

      if (USING_LEGACY_INDICATOR) {
        expectedValue = expected && expected[item] ? "true" : "";
      } else {
        expectedValue = expected && expected[item] ? "true" : null;
      }

      is(
        docElt.getAttribute("sharing" + item),
        expectedValue,
        item + " global indicator attribute as expected"
      );
    }

    ok(!indicator.hasMoreElements(), "only one global indicator window");
  }
}

function promiseNotificationShown(notification) {
  let win = notification.browser.ownerGlobal;
  if (win.PopupNotifications.panel.state == "open") {
    return Promise.resolve();
  }
  let panelPromise = BrowserTestUtils.waitForPopupEvent(
    win.PopupNotifications.panel,
    "shown"
  );
  notification.reshow();
  return panelPromise;
}

function ignoreEvent(aSubject, aTopic, aData) {
  // With e10s disabled, our content script receives notifications for the
  // preview displayed in our screen sharing permission prompt; ignore them.
  const kBrowserURL = AppConstants.BROWSER_CHROME_URL;
  const nsIPropertyBag = Ci.nsIPropertyBag;
  if (
    aTopic == "recording-device-events" &&
    aSubject.QueryInterface(nsIPropertyBag).getProperty("requestURL") ==
      kBrowserURL
  ) {
    return true;
  }
  if (aTopic == "recording-window-ended") {
    let win = Services.wm.getOuterWindowWithId(aData).top;
    if (win.document.documentURI == kBrowserURL) {
      return true;
    }
  }
  return false;
}

function expectObserverCalledInProcess(aTopic, aCount = 1) {
  let promises = [];
  for (let count = aCount; count > 0; count--) {
    promises.push(TestUtils.topicObserved(aTopic, ignoreEvent));
  }
  return promises;
}

function expectObserverCalled(
  aTopic,
  aCount = 1,
  browser = gBrowser.selectedBrowser
) {
  if (!gMultiProcessBrowser) {
    return expectObserverCalledInProcess(aTopic, aCount);
  }

  let browsingContext = Element.isInstance(browser)
    ? browser.browsingContext
    : browser;

  return BrowserTestUtils.contentTopicObserved(browsingContext, aTopic, aCount);
}

// This is a special version of expectObserverCalled that should only
// be used when expecting a notification upon closing a window. It uses
// the per-process message manager instead of actors to send the
// notifications.
function expectObserverCalledOnClose(
  aTopic,
  aCount = 1,
  browser = gBrowser.selectedBrowser
) {
  if (!gMultiProcessBrowser) {
    return expectObserverCalledInProcess(aTopic, aCount);
  }

  let browsingContext = Element.isInstance(browser)
    ? browser.browsingContext
    : browser;

  return new Promise(resolve => {
    BrowserTestUtils.sendAsyncMessage(
      browsingContext,
      "BrowserTestUtils:ObserveTopic",
      {
        topic: aTopic,
        count: 1,
        filterFunctionSource: ((subject, topic, data) => {
          Services.cpmm.sendAsyncMessage("WebRTCTest:ObserverCalled", {
            topic,
          });
          return true;
        }).toSource(),
      }
    );

    function observerCalled(message) {
      if (message.data.topic == aTopic) {
        Services.ppmm.removeMessageListener(
          "WebRTCTest:ObserverCalled",
          observerCalled
        );
        resolve();
      }
    }
    Services.ppmm.addMessageListener(
      "WebRTCTest:ObserverCalled",
      observerCalled
    );
  });
}

function promiseMessage(
  aMessage,
  aAction,
  aCount = 1,
  browser = gBrowser.selectedBrowser
) {
  let startTime = performance.now();
  let promise = ContentTask.spawn(
    browser,
    [aMessage, aCount],
    async function ([expectedMessage, expectedCount]) {
      return new Promise(resolve => {
        function listenForMessage({ data }) {
          if (
            (!expectedMessage || data == expectedMessage) &&
            --expectedCount == 0
          ) {
            content.removeEventListener("message", listenForMessage);
            resolve(data);
          }
        }
        content.addEventListener("message", listenForMessage);
      });
    }
  );
  if (aAction) {
    aAction();
  }
  return promise.then(data => {
    ChromeUtils.addProfilerMarker(
      "promiseMessage",
      { startTime, category: "Test" },
      data
    );
    return data;
  });
}

function promisePopupNotificationShown(aName, aAction, aWindow = window) {
  let startTime = performance.now();
  return new Promise(resolve => {
    aWindow.PopupNotifications.panel.addEventListener(
      "popupshown",
      function () {
        ok(
          !!aWindow.PopupNotifications.getNotification(aName),
          aName + " notification shown"
        );
        ok(aWindow.PopupNotifications.isPanelOpen, "notification panel open");
        ok(
          !!aWindow.PopupNotifications.panel.firstElementChild,
          "notification panel populated"
        );

        executeSoon(() => {
          ChromeUtils.addProfilerMarker(
            "promisePopupNotificationShown",
            { startTime, category: "Test" },
            aName
          );
          resolve();
        });
      },
      { once: true }
    );

    if (aAction) {
      aAction();
    }
  });
}

async function promisePopupNotification(aName) {
  return TestUtils.waitForCondition(
    () => PopupNotifications.getNotification(aName),
    aName + " notification appeared"
  );
}

async function promiseNoPopupNotification(aName) {
  return TestUtils.waitForCondition(
    () => !PopupNotifications.getNotification(aName),
    aName + " notification removed"
  );
}

const kActionAlways = 1;
const kActionDeny = 2;
const kActionNever = 3;

async function activateSecondaryAction(aAction) {
  let notification = PopupNotifications.panel.firstElementChild;
  switch (aAction) {
    case kActionNever:
      if (notification.notification.secondaryActions.length > 1) {
        // "Always Block" is the first (and only) item in the menupopup.
        await Promise.all([
          BrowserTestUtils.waitForEvent(notification.menupopup, "popupshown"),
          notification.menubutton.click(),
        ]);
        notification.menupopup.querySelector("menuitem").click();
        return;
      }
      if (!notification.checkbox.checked) {
        notification.checkbox.click();
      }
    // fallthrough
    case kActionDeny:
      notification.secondaryButton.click();
      break;
    case kActionAlways:
      if (!notification.checkbox.checked) {
        notification.checkbox.click();
      }
      notification.button.click();
      break;
  }
}

async function getMediaCaptureState() {
  let startTime = performance.now();

  function gatherBrowsingContexts(aBrowsingContext) {
    let list = [aBrowsingContext];

    let children = aBrowsingContext.children;
    for (let child of children) {
      list.push(...gatherBrowsingContexts(child));
    }

    return list;
  }

  function combine(x, y) {
    if (
      x == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED ||
      y == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED
    ) {
      return Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED;
    }
    if (
      x == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED ||
      y == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED
    ) {
      return Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED;
    }
    return Ci.nsIMediaManagerService.STATE_NOCAPTURE;
  }

  let video = Ci.nsIMediaManagerService.STATE_NOCAPTURE;
  let audio = Ci.nsIMediaManagerService.STATE_NOCAPTURE;
  let screen = Ci.nsIMediaManagerService.STATE_NOCAPTURE;
  let window = Ci.nsIMediaManagerService.STATE_NOCAPTURE;
  let browser = Ci.nsIMediaManagerService.STATE_NOCAPTURE;

  for (let bc of gatherBrowsingContexts(
    gBrowser.selectedBrowser.browsingContext
  )) {
    let state = await SpecialPowers.spawn(bc, [], async function () {
      let mediaManagerService = Cc[
        "@mozilla.org/mediaManagerService;1"
      ].getService(Ci.nsIMediaManagerService);

      let hasCamera = {};
      let hasMicrophone = {};
      let hasScreenShare = {};
      let hasWindowShare = {};
      let hasBrowserShare = {};
      let devices = {};
      mediaManagerService.mediaCaptureWindowState(
        content,
        hasCamera,
        hasMicrophone,
        hasScreenShare,
        hasWindowShare,
        hasBrowserShare,
        devices,
        false
      );

      return {
        video: hasCamera.value,
        audio: hasMicrophone.value,
        screen: hasScreenShare.value,
        window: hasWindowShare.value,
        browser: hasBrowserShare.value,
      };
    });

    video = combine(state.video, video);
    audio = combine(state.audio, audio);
    screen = combine(state.screen, screen);
    window = combine(state.window, window);
    browser = combine(state.browser, browser);
  }

  let result = {};

  if (video != Ci.nsIMediaManagerService.STATE_NOCAPTURE) {
    result.video = true;
  }
  if (audio != Ci.nsIMediaManagerService.STATE_NOCAPTURE) {
    result.audio = true;
  }

  if (screen != Ci.nsIMediaManagerService.STATE_NOCAPTURE) {
    result.screen = "Screen";
  } else if (window != Ci.nsIMediaManagerService.STATE_NOCAPTURE) {
    result.screen = "Window";
  } else if (browser != Ci.nsIMediaManagerService.STATE_NOCAPTURE) {
    result.screen = "Browser";
  }

  ChromeUtils.addProfilerMarker("getMediaCaptureState", {
    startTime,
    category: "Test",
  });
  return result;
}

async function stopSharing(
  aType = "camera",
  aShouldKeepSharing = false,
  aFrameBC,
  aWindow = window
) {
  let promiseRecordingEvent = expectObserverCalled(
    "recording-device-events",
    1,
    aFrameBC
  );
  let observerPromise1 = expectObserverCalled(
    "getUserMedia:revoke",
    1,
    aFrameBC
  );

  // If we are stopping screen sharing and expect to still have another stream,
  // "recording-window-ended" won't be fired.
  let observerPromise2 = null;
  if (!aShouldKeepSharing) {
    observerPromise2 = expectObserverCalled(
      "recording-window-ended",
      1,
      aFrameBC
    );
  }

  await revokePermission(aType, aShouldKeepSharing, aFrameBC, aWindow);
  await promiseRecordingEvent;
  await observerPromise1;
  await observerPromise2;

  if (!aShouldKeepSharing) {
    await checkNotSharing();
  }
}

async function revokePermission(
  aType = "camera",
  aShouldKeepSharing = false,
  aFrameBC,
  aWindow = window
) {
  aWindow.gPermissionPanel._identityPermissionBox.click();
  let popup = aWindow.gPermissionPanel._permissionPopup;
  // If the popup gets hidden before being shown, by stray focus/activate
  // events, don't bother failing the test. It's enough to know that we
  // started showing the popup.
  let hiddenEvent = BrowserTestUtils.waitForEvent(popup, "popuphidden");
  let shownEvent = BrowserTestUtils.waitForEvent(popup, "popupshown");
  await Promise.race([hiddenEvent, shownEvent]);
  let doc = aWindow.document;
  let permissions = doc.getElementById("permission-popup-permission-list");
  let cancelButton = permissions.querySelector(
    ".permission-popup-permission-icon." +
      aType +
      "-icon ~ " +
      ".permission-popup-permission-remove-button"
  );

  cancelButton.click();
  popup.hidePopup();

  if (!aShouldKeepSharing) {
    await checkNotSharing();
  }
}

function getBrowsingContextForFrame(aBrowsingContext, aFrameId) {
  if (!aFrameId) {
    return aBrowsingContext;
  }

  return SpecialPowers.spawn(aBrowsingContext, [aFrameId], frameId => {
    return content.document.getElementById(frameId).browsingContext;
  });
}

async function getBrowsingContextsAndFrameIdsForSubFrames(
  aBrowsingContext,
  aSubFrames
) {
  let pendingBrowserSubFrames = [
    { bc: aBrowsingContext, subFrames: aSubFrames },
  ];
  let browsingContextsAndFrames = [];
  while (pendingBrowserSubFrames.length) {
    let { bc, subFrames } = pendingBrowserSubFrames.shift();
    for (let id of Object.keys(subFrames)) {
      let subBc = await getBrowsingContextForFrame(bc, id);
      if (subFrames[id].children) {
        pendingBrowserSubFrames.push({
          bc: subBc,
          subFrames: subFrames[id].children,
        });
      }
      if (subFrames[id].noTest) {
        continue;
      }
      let observeBC = subFrames[id].observe ? subBc : undefined;
      browsingContextsAndFrames.push({ bc: subBc, id, observeBC });
    }
  }
  return browsingContextsAndFrames;
}

async function promiseRequestDevice(
  aRequestAudio,
  aRequestVideo,
  aFrameId,
  aType,
  aBrowsingContext,
  aBadDevice = false
) {
  info("requesting devices");
  let bc =
    aBrowsingContext ??
    (await getBrowsingContextForFrame(gBrowser.selectedBrowser, aFrameId));
  return SpecialPowers.spawn(
    bc,
    [{ aRequestAudio, aRequestVideo, aType, aBadDevice }],
    async function (args) {
      let global = content.wrappedJSObject;
      global.requestDevice(
        args.aRequestAudio,
        args.aRequestVideo,
        args.aType,
        args.aBadDevice
      );
    }
  );
}

async function promiseRequestAudioOutput(options) {
  info("requesting audio output");
  const bc = gBrowser.selectedBrowser;
  return SpecialPowers.spawn(bc, [options], async function (opts) {
    const global = content.wrappedJSObject;
    global.requestAudioOutput(Cu.cloneInto(opts, content));
  });
}

async function stopTracks(
  aKind,
  aAlreadyStopped,
  aLastTracks,
  aFrameId,
  aBrowsingContext,
  aBrowsingContextToObserve
) {
  // If the observers are listening to other frames, listen for a notification
  // on the right subframe.
  let frameBC =
    aBrowsingContext ??
    (await getBrowsingContextForFrame(
      gBrowser.selectedBrowser.browsingContext,
      aFrameId
    ));

  let observerPromises = [];
  if (!aAlreadyStopped) {
    observerPromises.push(
      expectObserverCalled(
        "recording-device-events",
        1,
        aBrowsingContextToObserve
      )
    );
  }
  if (aLastTracks) {
    observerPromises.push(
      expectObserverCalled(
        "recording-window-ended",
        1,
        aBrowsingContextToObserve
      )
    );
  }

  info(`Stopping all ${aKind} tracks`);
  await SpecialPowers.spawn(frameBC, [aKind], async function (kind) {
    content.wrappedJSObject.stopTracks(kind);
  });

  await Promise.all(observerPromises);
}

async function closeStream(
  aAlreadyClosed,
  aFrameId,
  aDontFlushObserverVerification,
  aBrowsingContext,
  aBrowsingContextToObserve
) {
  // Check that spurious notifications that occur while closing the
  // stream are handled separately. Tests that use skipObserverVerification
  // should pass true for aDontFlushObserverVerification.
  if (!aDontFlushObserverVerification) {
    await disableObserverVerification();
    await enableObserverVerification();
  }

  // If the observers are listening to other frames, listen for a notification
  // on the right subframe.
  let frameBC =
    aBrowsingContext ??
    (await getBrowsingContextForFrame(
      gBrowser.selectedBrowser.browsingContext,
      aFrameId
    ));

  let observerPromises = [];
  if (!aAlreadyClosed) {
    observerPromises.push(
      expectObserverCalled(
        "recording-device-events",
        1,
        aBrowsingContextToObserve
      )
    );
    observerPromises.push(
      expectObserverCalled(
        "recording-window-ended",
        1,
        aBrowsingContextToObserve
      )
    );
  }

  info("closing the stream");
  await SpecialPowers.spawn(frameBC, [], async function () {
    content.wrappedJSObject.closeStream();
  });

  await Promise.all(observerPromises);

  await assertWebRTCIndicatorStatus(null);
}

async function reloadAsUser() {
  info("reloading as a user");

  const reloadButton = document.getElementById("reload-button");
  await TestUtils.waitForCondition(() => !reloadButton.disabled);
  // Disable observers as the page is being reloaded which can destroy
  // the actors listening to the notifications.
  await disableObserverVerification();

  let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
  reloadButton.click();
  await loadedPromise;

  await enableObserverVerification();
}

async function reloadFromContent() {
  info("reloading from content");

  // Disable observers as the page is being reloaded which can destroy
  // the actors listening to the notifications.
  await disableObserverVerification();

  let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
  await ContentTask.spawn(gBrowser.selectedBrowser, null, () =>
    content.location.reload()
  );

  await loadedPromise;

  await enableObserverVerification();
}

async function reloadAndAssertClosedStreams() {
  await reloadFromContent();
  await checkNotSharing();
}

/**
 * @param {("microphone"|"camera"|"screen")[]} aExpectedTypes
 * @param {Window} [aWindow]
 */
function checkDeviceSelectors(aExpectedTypes, aWindow = window) {
  for (const type of aExpectedTypes) {
    if (!["microphone", "camera", "screen", "speaker"].includes(type)) {
      throw new Error(`Bad device type name ${type}`);
    }
  }
  let document = aWindow.document;

  let expectedDescribedBy = "webRTC-shareDevices-notification-description";
  for (let type of ["Camera", "Microphone", "Speaker"]) {
    let selector = document.getElementById(`webRTC-select${type}`);
    if (!aExpectedTypes.includes(type.toLowerCase())) {
      ok(selector.hidden, `${type} selector hidden`);
      continue;
    }
    ok(!selector.hidden, `${type} selector visible`);
    let selectorList = document.getElementById(`webRTC-select${type}-menulist`);
    let label = document.getElementById(
      `webRTC-select${type}-single-device-label`
    );
    // If there's only 1 device listed, then we should show the label
    // instead of the menulist.
    if (selectorList.itemCount == 1) {
      ok(selectorList.hidden, `${type} selector list should be hidden.`);
      ok(!label.hidden, `${type} selector label should not be hidden.`);
      is(
        label.value,
        selectorList.selectedItem.getAttribute("label"),
        `${type} label should be showing the lone device label.`
      );
      expectedDescribedBy += ` webRTC-select${type}-icon webRTC-select${type}-single-device-label`;
    } else {
      ok(!selectorList.hidden, `${type} selector list should not be hidden.`);
      ok(label.hidden, `${type} selector label should be hidden.`);
    }
  }
  let ariaDescribedby =
    aWindow.PopupNotifications.panel.getAttribute("aria-describedby");
  is(ariaDescribedby, expectedDescribedBy, "aria-describedby");

  let screenSelector = document.getElementById("webRTC-selectWindowOrScreen");
  if (aExpectedTypes.includes("screen")) {
    ok(!screenSelector.hidden, "screen selector visible");
  } else {
    ok(screenSelector.hidden, "screen selector hidden");
  }
}

/**
 * Tests the siteIdentity icons, the permission panel and the global indicator
 * UI state.
 * @param {Object} aExpected - Expected state for the current tab.
 * @param {window} [aWin] - Top level chrome window to test state of.
 * @param {Object} [aExpectedGlobal] - Expected state for all tabs.
 * @param {Object} [aExpectedPerm] - Expected permission states keyed by device
 * type.
 */
async function checkSharingUI(
  aExpected,
  aWin = window,
  aExpectedGlobal = null,
  aExpectedPerm = null
) {
  function isPaused(streamState) {
    if (typeof streamState == "string") {
      return streamState.includes("Paused");
    }
    return streamState == STATE_CAPTURE_DISABLED;
  }

  let doc = aWin.document;
  // First check the icon above the control center (i) icon.
  let permissionBox = doc.getElementById("identity-permission-box");
  let webrtcSharingIcon = doc.getElementById("webrtc-sharing-icon");
  ok(webrtcSharingIcon.hasAttribute("sharing"), "sharing attribute is set");
  let sharing = webrtcSharingIcon.getAttribute("sharing");
  if (aExpected.screen) {
    is(sharing, "screen", "showing screen icon in the identity block");
  } else if (aExpected.video == STATE_CAPTURE_ENABLED) {
    is(sharing, "camera", "showing camera icon in the identity block");
  } else if (aExpected.audio == STATE_CAPTURE_ENABLED) {
    is(sharing, "microphone", "showing mic icon in the identity block");
  } else if (aExpected.video) {
    is(sharing, "camera", "showing camera icon in the identity block");
  } else if (aExpected.audio) {
    is(sharing, "microphone", "showing mic icon in the identity block");
  }

  let allStreamsPaused = Object.values(aExpected).every(isPaused);
  is(
    webrtcSharingIcon.hasAttribute("paused"),
    allStreamsPaused,
    "sharing icon(s) should be in paused state when paused"
  );

  // Then check the sharing indicators inside the permission popup.
  permissionBox.click();
  let popup = aWin.gPermissionPanel._permissionPopup;
  // If the popup gets hidden before being shown, by stray focus/activate
  // events, don't bother failing the test. It's enough to know that we
  // started showing the popup.
  let hiddenEvent = BrowserTestUtils.waitForEvent(popup, "popuphidden");
  let shownEvent = BrowserTestUtils.waitForEvent(popup, "popupshown");
  await Promise.race([hiddenEvent, shownEvent]);
  let permissions = doc.getElementById("permission-popup-permission-list");
  for (let id of ["microphone", "camera", "screen"]) {
    let convertId = idToConvert => {
      if (idToConvert == "camera") {
        return "video";
      }
      if (idToConvert == "microphone") {
        return "audio";
      }
      return idToConvert;
    };
    let expected = aExpected[convertId(id)];

    // Extract the expected permission for the device type.
    // Defaults to temporary allow.
    let { state, scope } = aExpectedPerm?.[convertId(id)] || {};
    if (state == null) {
      state = SitePermissions.ALLOW;
    }
    if (scope == null) {
      scope = SitePermissions.SCOPE_TEMPORARY;
    }

    is(
      !!aWin.gPermissionPanel._sharingState.webRTC[id],
      !!expected,
      "sharing state for " + id + " as expected"
    );
    let item = permissions.querySelectorAll(
      ".permission-popup-permission-item-" + id
    );
    let stateLabel = item?.[0]?.querySelector(
      ".permission-popup-permission-state-label"
    );
    let icon = permissions.querySelectorAll(
      ".permission-popup-permission-icon." + id + "-icon"
    );
    if (expected) {
      is(item.length, 1, "should show " + id + " item in permission panel");
      is(
        stateLabel?.textContent,
        SitePermissions.getCurrentStateLabel(state, id, scope),
        "should show correct item label for " + id
      );
      is(icon.length, 1, "should show " + id + " icon in permission panel");
      is(
        icon[0].classList.contains("in-use"),
        expected && !isPaused(expected),
        "icon should have the in-use class, unless paused"
      );
    } else if (!icon.length && !item.length && !stateLabel) {
      ok(true, "should not show " + id + " item in the permission panel");
      ok(true, "should not show " + id + " icon in the permission panel");
      ok(
        true,
        "should not show " + id + " state label in the permission panel"
      );
    } else {
      // This will happen if there are persistent permissions set.
      ok(
        !icon[0].classList.contains("in-use"),
        "if shown, the " + id + " icon should not have the in-use class"
      );
      is(item.length, 1, "should not show more than 1 " + id + " item");
      is(icon.length, 1, "should not show more than 1 " + id + " icon");
    }
  }
  aWin.gPermissionPanel._permissionPopup.hidePopup();
  await TestUtils.waitForCondition(
    () => permissionPopupHidden(aWin),
    "identity popup should be hidden"
  );

  // Check the global indicators.
  await assertWebRTCIndicatorStatus(aExpectedGlobal || aExpected);
}

async function checkNotSharing() {
  Assert.deepEqual(
    await getMediaCaptureState(),
    {},
    "expected nothing to be shared"
  );

  ok(
    !document.getElementById("webrtc-sharing-icon").hasAttribute("sharing"),
    "no sharing indicator on the control center icon"
  );

  await assertWebRTCIndicatorStatus(null);
}

async function checkNotSharingWithinGracePeriod() {
  Assert.deepEqual(
    await getMediaCaptureState(),
    {},
    "expected nothing to be shared"
  );

  ok(
    document.getElementById("webrtc-sharing-icon").hasAttribute("sharing"),
    "has sharing indicator on the control center icon"
  );
  ok(
    document.getElementById("webrtc-sharing-icon").hasAttribute("paused"),
    "sharing indicator is paused"
  );

  await assertWebRTCIndicatorStatus(null);
}

async function promiseReloadFrame(aFrameId, aBrowsingContext) {
  let loadedPromise = BrowserTestUtils.browserLoaded(
    gBrowser.selectedBrowser,
    true,
    arg => {
      return true;
    }
  );
  let bc =
    aBrowsingContext ??
    (await getBrowsingContextForFrame(
      gBrowser.selectedBrowser.browsingContext,
      aFrameId
    ));
  await SpecialPowers.spawn(bc, [], async function () {
    content.location.reload();
  });
  return loadedPromise;
}

function promiseChangeLocationFrame(aFrameId, aNewLocation) {
  return SpecialPowers.spawn(
    gBrowser.selectedBrowser.browsingContext,
    [{ aFrameId, aNewLocation }],
    async function (args) {
      let frame = content.wrappedJSObject.document.getElementById(
        args.aFrameId
      );
      return new Promise(resolve => {
        function listener() {
          frame.removeEventListener("load", listener, true);
          resolve();
        }
        frame.addEventListener("load", listener, true);

        content.wrappedJSObject.document.getElementById(
          args.aFrameId
        ).contentWindow.location = args.aNewLocation;
      });
    }
  );
}

async function openNewTestTab(leaf = "get_user_media.html") {
  let rootDir = getRootDirectory(gTestPath);
  rootDir = rootDir.replace(
    "chrome://mochitests/content/",
    "https://example.com/"
  );
  let absoluteURI = rootDir + leaf;

  let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, absoluteURI);
  return tab.linkedBrowser;
}

// Enabling observer verification adds listeners for all of the webrtc
// observer topics. If any notifications occur for those topics that
// were not explicitly requested, a failure will occur.
async function enableObserverVerification(browser = gBrowser.selectedBrowser) {
  // Skip these checks in single process mode as it isn't worth implementing it.
  if (!gMultiProcessBrowser) {
    return;
  }

  gBrowserContextsToObserve = [browser.browsingContext];

  // A list of subframe indicies to also add observers to. This only
  // supports one nested level.
  if (gObserveSubFrames) {
    let bcsAndFrameIds = await getBrowsingContextsAndFrameIdsForSubFrames(
      browser,
      gObserveSubFrames
    );
    for (let { observeBC } of bcsAndFrameIds) {
      if (observeBC) {
        gBrowserContextsToObserve.push(observeBC);
      }
    }
  }

  for (let bc of gBrowserContextsToObserve) {
    await BrowserTestUtils.startObservingTopics(bc, observerTopics);
  }
}

async function disableObserverVerification() {
  if (!gMultiProcessBrowser) {
    return;
  }

  for (let bc of gBrowserContextsToObserve) {
    await BrowserTestUtils.stopObservingTopics(bc, observerTopics).catch(
      reason => {
        ok(false, "Failed " + reason);
      }
    );
  }
}

function permissionPopupHidden(win = window) {
  let popup = win.gPermissionPanel._permissionPopup;
  return !popup || popup.state == "closed";
}

async function runTests(tests, options = {}) {
  let browser = await openNewTestTab(options.relativeURI);

  is(
    PopupNotifications._currentNotifications.length,
    0,
    "should start the test without any prior popup notification"
  );
  ok(
    permissionPopupHidden(),
    "should start the test with the permission panel hidden"
  );

  // Set prefs so that permissions prompts are shown and loopback devices
  // are not used. To test the chrome we want prompts to be shown, and
  // these tests are flakey when using loopback devices (though it would
  // be desirable to make them work with loopback in future). See bug 1643711.
  let prefs = [
    [PREF_PERMISSION_FAKE, true],
    [PREF_AUDIO_LOOPBACK, ""],
    [PREF_VIDEO_LOOPBACK, ""],
    [PREF_FAKE_STREAMS, true],
    [PREF_FOCUS_SOURCE, false],
  ];
  await SpecialPowers.pushPrefEnv({ set: prefs });

  // When the frames are in different processes, add observers to each frame,
  // to ensure that the notifications don't get sent in the wrong process.
  gObserveSubFrames = SpecialPowers.useRemoteSubframes ? options.subFrames : {};

  for (let testCase of tests) {
    let startTime = performance.now();
    info(testCase.desc);
    if (
      !testCase.skipObserverVerification &&
      !options.skipObserverVerification
    ) {
      await enableObserverVerification();
    }
    await testCase.run(browser, options.subFrames);
    if (
      !testCase.skipObserverVerification &&
      !options.skipObserverVerification
    ) {
      await disableObserverVerification();
    }
    if (options.cleanup) {
      await options.cleanup();
    }
    ChromeUtils.addProfilerMarker(
      "browser-test",
      { startTime, category: "Test" },
      testCase.desc
    );
  }

  // Some tests destroy the original tab and leave a new one in its place.
  BrowserTestUtils.removeTab(gBrowser.selectedTab);
}

/**
 * Given a browser from a tab in this window, chooses to share
 * some combination of camera, mic or screen.
 *
 * @param {<xul:browser} browser - The browser to share devices with.
 * @param {boolean} camera - True to share a camera device.
 * @param {boolean} mic - True to share a microphone device.
 * @param {Number} [screenOrWin] - One of either SHARE_WINDOW or SHARE_SCREEN
 *   to share a window or screen. Defaults to neither.
 * @param {boolean} remember - True to persist the permission to the
 *   SitePermissions database as SitePermissions.SCOPE_PERSISTENT. Note that
 *   callers are responsible for clearing this persistent permission.
 * @return {Promise}
 * @resolves {undefined} - Once the sharing is complete.
 */
async function shareDevices(
  browser,
  camera,
  mic,
  screenOrWin = 0,
  remember = false
) {
  if (camera || mic) {
    let promise = promisePopupNotificationShown(
      "webRTC-shareDevices",
      null,
      window
    );

    await promiseRequestDevice(mic, camera, null, null, browser);
    await promise;

    const expectedDeviceSelectorTypes = [
      camera && "camera",
      mic && "microphone",
    ].filter(x => x);
    checkDeviceSelectors(expectedDeviceSelectorTypes);
    let observerPromise1 = expectObserverCalled("getUserMedia:response:allow");
    let observerPromise2 = expectObserverCalled("recording-device-events");

    let rememberCheck = PopupNotifications.panel.querySelector(
      ".popup-notification-checkbox"
    );
    rememberCheck.checked = remember;

    promise = promiseMessage("ok", () => {
      PopupNotifications.panel.firstElementChild.button.click();
    });

    await observerPromise1;
    await observerPromise2;
    await promise;
  }

  if (screenOrWin) {
    let promise = promisePopupNotificationShown(
      "webRTC-shareDevices",
      null,
      window
    );

    await promiseRequestDevice(false, true, null, "screen", browser);
    await promise;

    checkDeviceSelectors(["screen"], window);

    let document = window.document;

    let menulist = document.getElementById("webRTC-selectWindow-menulist");
    let displayMediaSource;

    if (screenOrWin == SHARE_SCREEN) {
      displayMediaSource = "screen";
    } else if (screenOrWin == SHARE_WINDOW) {
      displayMediaSource = "window";
    } else {
      throw new Error("Got an invalid argument to shareDevices.");
    }

    let menuitem = null;
    for (let i = 0; i < menulist.itemCount; ++i) {
      let current = menulist.getItemAtIndex(i);
      if (current.mediaSource == displayMediaSource) {
        menuitem = current;
        break;
      }
    }

    Assert.ok(menuitem, "Should have found an appropriate display menuitem");
    menuitem.doCommand();

    let notification = window.PopupNotifications.panel.firstElementChild;

    let observerPromise1 = expectObserverCalled("getUserMedia:response:allow");
    let observerPromise2 = expectObserverCalled("recording-device-events");
    await promiseMessage(
      "ok",
      () => {
        notification.button.click();
      },
      1,
      browser
    );
    await observerPromise1;
    await observerPromise2;
  }
}