-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
webrtc_getdisplaymedia_browsertest.cc
1606 lines (1364 loc) · 62.7 KB
/
webrtc_getdisplaymedia_browsertest.cc
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <tuple>
#include <vector>
#include "base/base_switches.h"
#include "base/files/file_util.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/apps/platform_apps/app_browsertest_util.h"
#include "chrome/browser/media/webrtc/webrtc_browsertest_base.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/infobars/content/content_infobar_manager.h"
#include "components/infobars/core/confirm_infobar_delegate.h"
#include "components/infobars/core/infobar.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/url_formatter/elide_url.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "media/base/media_switches.h"
#include "net/base/filename_util.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/features.h"
#include "ui/base/l10n/l10n_util.h"
#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#include "chrome/browser/media/webrtc/system_media_capture_permissions_mac.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/chromeos/policy/dlp/dlp_content_manager_test_helper.h"
#include "chrome/browser/chromeos/policy/dlp/dlp_content_restriction_set.h"
#endif
namespace {
using base::test::FeatureRef;
static const char kMainHtmlPage[] = "/webrtc/webrtc_getdisplaymedia_test.html";
static const char kMainHtmlFileName[] = "webrtc_getdisplaymedia_test.html";
static const char kSameOriginRenamedTitle[] = "Renamed Same Origin Tab";
static const char kMainHtmlTitle[] = "WebRTC Automated Test";
// The captured tab is identified by its title.
static const char kCapturedTabTitle[] = "totally-unique-captured-page-title";
static const char kCapturedPageMain[] = "/webrtc/captured_page_main.html";
static const std::u16string kShareThisTabInsteadMessage =
u"Share this tab instead";
enum class DisplaySurfaceType { kTab, kWindow, kScreen };
enum class GetDisplayMediaVariant : int {
kStandard = 0,
kPreferCurrentTab = 1
};
struct TestConfigForPicker {
TestConfigForPicker(bool should_prefer_current_tab,
bool accept_this_tab_capture)
: should_prefer_current_tab(should_prefer_current_tab),
accept_this_tab_capture(accept_this_tab_capture) {}
explicit TestConfigForPicker(std::tuple<bool, bool> input_tuple)
: TestConfigForPicker(std::get<0>(input_tuple),
std::get<1>(input_tuple)) {}
// If true, specify {preferCurrentTab: true}.
// Otherwise, either don't specify it, or set it to false.
bool should_prefer_current_tab;
// |accept_this_tab_capture| is only applicable if
// |should_prefer_current_tab| is set to true. Then, setting
// |accept_this_tab_capture| to true accepts the current tab, and
// |accept_this_tab_capture| set to false implies dismissing the media picker.
bool accept_this_tab_capture;
};
struct TestConfigForFakeUI {
bool should_prefer_current_tab;
const char* display_surface;
};
struct TestConfigForSelectAllScreens {
const char* display_surface;
bool enable_select_all_screens;
};
struct TestConfigForHiDpi {
bool enable_hidpi;
int constraint_width;
int constraint_height;
};
constexpr char kAppWindowTitle[] = "AppWindow Display Capture Test";
constexpr char kEmbeddedTestServerOrigin[] = "http://127.0.0.1";
constexpr char kOtherOrigin[] = "https://other-origin.com";
std::string DisplaySurfaceTypeAsString(
DisplaySurfaceType display_surface_type) {
switch (display_surface_type) {
case DisplaySurfaceType::kTab:
return "browser";
case DisplaySurfaceType::kWindow:
return "window";
case DisplaySurfaceType::kScreen:
return "screen";
}
NOTREACHED();
return "error";
}
void RunGetDisplayMedia(content::WebContents* tab,
const std::string& constraints,
bool is_fake_ui,
bool expect_success,
bool is_tab_capture,
const std::string& expected_error = "",
bool with_user_gesture = true) {
DCHECK(!expect_success || expected_error.empty());
const content::ToRenderFrameHost& adapter = tab->GetPrimaryMainFrame();
const std::string script = base::StringPrintf(
"runGetDisplayMedia(%s, \"top-level-document\", \"%s\");",
constraints.c_str(), expected_error.c_str());
std::string result;
if (with_user_gesture) {
EXPECT_TRUE(
content::ExecuteScriptAndExtractString(adapter, script, &result));
} else {
EXPECT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString(
adapter, script, &result));
}
#if BUILDFLAG(IS_MAC)
if (!is_fake_ui && !is_tab_capture &&
system_media_permissions::CheckSystemScreenCapturePermission() !=
system_media_permissions::SystemPermission::kAllowed) {
expect_success = false;
}
#endif
EXPECT_EQ(result, expect_success ? "capture-success"
: expected_error.empty() ? "capture-failure"
: "expected-error");
}
void StopAllTracks(content::WebContents* tab) {
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "stopAllTracks();", &result));
EXPECT_EQ(result, "stopped");
}
void UpdateWebContentsTitle(content::WebContents* contents,
const std::u16string& title) {
content::NavigationEntry* entry =
contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(entry);
contents->UpdateTitleForEntry(entry, title);
}
GURL GetFileURL(const char* filename) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::FilePath path;
base::PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("webrtc").AppendASCII(filename);
CHECK(base::PathExists(path));
return net::FilePathToFileURL(path);
}
infobars::ContentInfoBarManager* GetInfoBarManager(
content::WebContents* web_contents) {
return infobars::ContentInfoBarManager::FromWebContents(web_contents);
}
ConfirmInfoBarDelegate* GetDelegate(content::WebContents* web_contents) {
return static_cast<ConfirmInfoBarDelegate*>(
GetInfoBarManager(web_contents)->infobar_at(0)->delegate());
}
bool HasSecondaryButton(content::WebContents* web_contents) {
return GetDelegate(web_contents)->GetButtons() &
ConfirmInfoBarDelegate::InfoBarButton::BUTTON_CANCEL;
}
std::u16string GetSecondaryButtonLabel(content::WebContents* web_contents) {
DCHECK(HasSecondaryButton(web_contents)); // Test error otherwise.
return GetDelegate(web_contents)
->GetButtonLabel(ConfirmInfoBarDelegate::InfoBarButton::BUTTON_CANCEL);
}
} // namespace
// Base class for top level tests for getDisplayMedia().
class WebRtcScreenCaptureBrowserTest : public WebRtcTestBase {
public:
~WebRtcScreenCaptureBrowserTest() override = default;
enum class SelectAllScreens { kUndefined = 0, kTrue = 1, kFalse = 2 };
void SetUpInProcessBrowserTestFixture() override {
DetectErrorsInJavaScript();
}
virtual bool PreferCurrentTab() const = 0;
std::string GetConstraints(bool video,
bool audio,
SelectAllScreens select_all_screens) const {
std::string select_all_screens_property =
(select_all_screens == SelectAllScreens::kUndefined)
? ""
: base::StringPrintf(
"autoSelectAllScreens: %s",
(select_all_screens == SelectAllScreens::kFalse) ? "false"
: "true");
return base::StringPrintf(
"{video: %s, audio: %s, preferCurrentTab: %s, %s}",
video ? "true" : "false", audio ? "true" : "false",
PreferCurrentTab() ? "true" : "false",
select_all_screens_property.c_str());
}
};
// Top level test for getDisplayMedia().
// Pops picker UI and shares by default.
class WebRtcScreenCaptureBrowserTestWithPicker
: public WebRtcScreenCaptureBrowserTest,
public testing::WithParamInterface<std::tuple<bool, bool>> {
public:
WebRtcScreenCaptureBrowserTestWithPicker() : test_config_(GetParam()) {}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
if (test_config_.should_prefer_current_tab) {
command_line->AppendSwitch(test_config_.accept_this_tab_capture
? switches::kThisTabCaptureAutoAccept
: switches::kThisTabCaptureAutoReject);
} else {
#if BUILDFLAG(IS_CHROMEOS_ASH)
command_line->AppendSwitchASCII(switches::kAutoSelectDesktopCaptureSource,
"Display");
#else
command_line->AppendSwitchASCII(switches::kAutoSelectDesktopCaptureSource,
"Entire screen");
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
}
}
bool PreferCurrentTab() const override {
return test_config_.should_prefer_current_tab;
}
const TestConfigForPicker test_config_;
};
INSTANTIATE_TEST_SUITE_P(All,
WebRtcScreenCaptureBrowserTestWithPicker,
testing::Combine(
/*should_prefer_current_tab=*/testing::Bool(),
/*accept_this_tab_capture=*/testing::Bool()));
// TODO(1170479): Real desktop capture is flaky on below platforms.
#if BUILDFLAG(IS_WIN)
#define MAYBE_ScreenCaptureVideo DISABLED_ScreenCaptureVideo
#else
#define MAYBE_ScreenCaptureVideo ScreenCaptureVideo
#endif // BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(WebRtcScreenCaptureBrowserTestWithPicker,
MAYBE_ScreenCaptureVideo) {
if (!test_config_.should_prefer_current_tab &&
!test_config_.accept_this_tab_capture) {
GTEST_SKIP();
}
ASSERT_TRUE(embedded_test_server()->Start());
content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
RunGetDisplayMedia(tab,
GetConstraints(
/*video=*/true, /*audio=*/false,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/false,
/*expect_success=*/test_config_.accept_this_tab_capture,
/*is_tab_capture=*/PreferCurrentTab());
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
IN_PROC_BROWSER_TEST_P(WebRtcScreenCaptureBrowserTestWithPicker,
ScreenCaptureVideoWithDlp) {
if (!test_config_.should_prefer_current_tab &&
!test_config_.accept_this_tab_capture) {
GTEST_SKIP();
}
ASSERT_TRUE(embedded_test_server()->Start());
policy::DlpContentManagerTestHelper helper;
content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
RunGetDisplayMedia(tab,
GetConstraints(
/*video=*/true, /*audio=*/false,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/false,
/*expect_success=*/test_config_.accept_this_tab_capture,
/*is_tab_capture=*/PreferCurrentTab());
if (!test_config_.accept_this_tab_capture) {
// This test is not relevant for this parameterized test case because it
// does not capture the tab/display surface.
return;
}
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "waitVideoUnmuted();", &result));
EXPECT_EQ(result, "unmuted");
const policy::DlpContentRestrictionSet kScreenShareRestricted(
policy::DlpContentRestriction::kScreenShare,
policy::DlpRulesManager::Level::kBlock);
helper.ChangeConfidentiality(tab, kScreenShareRestricted);
content::WaitForLoadStop(tab);
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "waitVideoMuted();", &result));
EXPECT_EQ(result, "muted");
const policy::DlpContentRestrictionSet kEmptyRestrictionSet;
helper.ChangeConfidentiality(tab, kEmptyRestrictionSet);
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "waitVideoUnmuted();", &result));
EXPECT_EQ(result, "unmuted");
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(1170479): Real desktop capture is flaky on below platforms.
#if BUILDFLAG(IS_WIN)
#define MAYBE_ScreenCaptureVideoAndAudio DISABLED_ScreenCaptureVideoAndAudio
// On linux debug bots, it's flaky as well.
#elif ((BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && \
!defined(NDEBUG))
#define MAYBE_ScreenCaptureVideoAndAudio DISABLED_ScreenCaptureVideoAndAudio
// On linux asan bots, it's flaky as well - msan and other rel bot are fine.
#elif ((BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) && \
defined(ADDRESS_SANITIZER))
#define MAYBE_ScreenCaptureVideoAndAudio DISABLED_ScreenCaptureVideoAndAudio
#else
#define MAYBE_ScreenCaptureVideoAndAudio ScreenCaptureVideoAndAudio
#endif // BUILDFLAG(IS_WIN)
IN_PROC_BROWSER_TEST_P(WebRtcScreenCaptureBrowserTestWithPicker,
MAYBE_ScreenCaptureVideoAndAudio) {
if (!test_config_.should_prefer_current_tab &&
!test_config_.accept_this_tab_capture) {
GTEST_SKIP();
}
ASSERT_TRUE(embedded_test_server()->Start());
content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
RunGetDisplayMedia(tab,
GetConstraints(
/*video=*/true, /*audio=*/true,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/false,
/*expect_success=*/test_config_.accept_this_tab_capture,
/*is_tab_capture=*/PreferCurrentTab());
}
// Top level test for getDisplayMedia().
// Skips picker UI and uses fake device with specified type.
class WebRtcScreenCaptureBrowserTestWithFakeUI
: public WebRtcScreenCaptureBrowserTest,
public testing::WithParamInterface<TestConfigForFakeUI> {
public:
WebRtcScreenCaptureBrowserTestWithFakeUI() : test_config_(GetParam()) {}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
command_line->AppendSwitch(switches::kUseFakeUIForMediaStream);
command_line->RemoveSwitch(switches::kUseFakeDeviceForMediaStream);
command_line->AppendSwitchASCII(
switches::kUseFakeDeviceForMediaStream,
base::StringPrintf("display-media-type=%s",
test_config_.display_surface));
}
bool PreferCurrentTab() const override {
return test_config_.should_prefer_current_tab;
}
protected:
const TestConfigForFakeUI test_config_;
};
IN_PROC_BROWSER_TEST_P(WebRtcScreenCaptureBrowserTestWithFakeUI,
ScreenCaptureVideo) {
ASSERT_TRUE(embedded_test_server()->Start());
content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
RunGetDisplayMedia(tab,
GetConstraints(
/*video=*/true, /*audio=*/false,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/true, /*expect_success=*/true,
/*is_tab_capture=*/PreferCurrentTab());
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "getDisplaySurfaceSetting();", &result));
EXPECT_EQ(result, test_config_.display_surface);
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "getLogicalSurfaceSetting();", &result));
EXPECT_EQ(result, "true");
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "getCursorSetting();", &result));
EXPECT_EQ(result, "never");
}
IN_PROC_BROWSER_TEST_P(WebRtcScreenCaptureBrowserTestWithFakeUI,
ScreenCaptureVideoAndAudio) {
ASSERT_TRUE(embedded_test_server()->Start());
content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
RunGetDisplayMedia(tab,
GetConstraints(
/*video=*/true, /*audio=*/true,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/true, /*expect_success=*/true,
/*is_tab_capture=*/PreferCurrentTab());
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "hasAudioTrack();", &result));
EXPECT_EQ(result, "true");
}
IN_PROC_BROWSER_TEST_P(WebRtcScreenCaptureBrowserTestWithFakeUI,
ScreenCaptureWithConstraints) {
ASSERT_TRUE(embedded_test_server()->Start());
content::WebContents* tab = OpenTestPageInNewTab(kMainHtmlPage);
const int kMaxWidth = 200;
const int kMaxFrameRate = 6;
const std::string constraints = base::StringPrintf(
"{video: {width: {max: %d}, frameRate: {max: %d}}, "
"should_prefer_current_tab: "
"%s}",
kMaxWidth, kMaxFrameRate,
test_config_.should_prefer_current_tab ? "true" : "false");
RunGetDisplayMedia(tab, constraints,
/*is_fake_ui=*/true, /*expect_success=*/true,
/*is_tab_capture=*/PreferCurrentTab());
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "getWidthSetting();", &result));
EXPECT_EQ(result, base::StringPrintf("%d", kMaxWidth));
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab->GetPrimaryMainFrame(), "getFrameRateSetting();", &result));
EXPECT_EQ(result, base::StringPrintf("%d", kMaxFrameRate));
}
INSTANTIATE_TEST_SUITE_P(
All,
WebRtcScreenCaptureBrowserTestWithFakeUI,
testing::Values(TestConfigForFakeUI{/*should_prefer_current_tab=*/false,
/*display_surface=*/"monitor"},
TestConfigForFakeUI{/*should_prefer_current_tab=*/false,
/*display_surface=*/"window"},
TestConfigForFakeUI{/*should_prefer_current_tab=*/false,
/*display_surface=*/"browser"},
TestConfigForFakeUI{/*should_prefer_current_tab=*/true,
/*display_surface=*/"browser"}));
class WebRtcScreenCapturePermissionPolicyBrowserTest
: public WebRtcScreenCaptureBrowserTest,
public testing::WithParamInterface<
std::tuple<GetDisplayMediaVariant, bool>> {
public:
WebRtcScreenCapturePermissionPolicyBrowserTest()
: tested_variant_(std::get<0>(GetParam())),
allowlisted_by_policy_(std::get<1>(GetParam())) {}
~WebRtcScreenCapturePermissionPolicyBrowserTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
command_line->AppendSwitchASCII(
switches::kAutoSelectTabCaptureSourceByTitle, kMainHtmlTitle);
}
bool PreferCurrentTab() const override {
return tested_variant_ == GetDisplayMediaVariant::kPreferCurrentTab;
}
protected:
const GetDisplayMediaVariant tested_variant_;
const bool allowlisted_by_policy_;
};
INSTANTIATE_TEST_SUITE_P(
All,
WebRtcScreenCapturePermissionPolicyBrowserTest,
testing::Combine(testing::Values(GetDisplayMediaVariant::kStandard,
GetDisplayMediaVariant::kPreferCurrentTab),
/*allowlisted_by_policy=*/testing::Bool()));
// Flaky on Win bots http://crbug.com/1264805
#if BUILDFLAG(IS_WIN)
#define MAYBE_ScreenShareFromEmbedded DISABLED_ScreenShareFromEmbedded
#else
#define MAYBE_ScreenShareFromEmbedded ScreenShareFromEmbedded
#endif
IN_PROC_BROWSER_TEST_P(WebRtcScreenCapturePermissionPolicyBrowserTest,
MAYBE_ScreenShareFromEmbedded) {
ASSERT_TRUE(embedded_test_server()->Start());
// The use of selfBrowserSurface is in order to simplify the test by
// using just one tab. It is orthogonal to the test's purpose.
const std::string constraints = base::StringPrintf(
"{video: true, selfBrowserSurface: 'include', preferCurrentTab: %s}",
PreferCurrentTab() ? "true" : "false");
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
OpenTestPageInNewTab(kMainHtmlPage)->GetPrimaryMainFrame(),
base::StringPrintf(
"runGetDisplayMedia(%s, \"%s\");", constraints.c_str(),
allowlisted_by_policy_ ? "allowedFrame" : "disallowedFrame"),
&result));
EXPECT_EQ(result, allowlisted_by_policy_ ? "embedded-capture-success"
: "embedded-capture-failure");
}
// Test class used to test WebRTC with App Windows. Unfortunately, due to
// creating a diamond pattern of inheritance, we can only inherit from one of
// the PlatformAppBrowserTest and WebRtcBrowserTestBase (or it's children).
// We need a lot more heavy lifting on creating the AppWindow than we would get
// from WebRtcBrowserTestBase; so we inherit from PlatformAppBrowserTest to
// minimize the code duplication.
class WebRtcAppWindowCaptureBrowserTestWithPicker
: public extensions::PlatformAppBrowserTest {
public:
WebRtcAppWindowCaptureBrowserTestWithPicker() = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
PlatformAppBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
command_line->AppendSwitchASCII(
switches::kAutoSelectTabCaptureSourceByTitle, kAppWindowTitle);
}
void SetUpOnMainThread() override {
extensions::PlatformAppBrowserTest::SetUpOnMainThread();
ASSERT_TRUE(StartEmbeddedTestServer());
// We will restrict all pages to "Tab Capture" only. This should force App
// Windows to show up in the tabs list, and thus make it selectable.
base::Value::List matchlist;
matchlist.Append("*");
browser()->profile()->GetPrefs()->SetList(
prefs::kTabCaptureAllowedByOrigins, std::move(matchlist));
}
void TearDownOnMainThread() override {
extensions::PlatformAppBrowserTest::TearDownOnMainThread();
browser()->profile()->GetPrefs()->SetList(
prefs::kTabCaptureAllowedByOrigins, base::Value::List());
}
extensions::AppWindow* CreateAppWindowWithTitle(const std::u16string& title) {
extensions::AppWindow* app_window = CreateTestAppWindow("{}");
EXPECT_TRUE(app_window);
UpdateWebContentsTitle(app_window->web_contents(), title);
return app_window;
}
// This is mostly lifted from WebRtcBrowserTestBase, with the exception that
// because we know we're setting the auto-accept switches, we don't need to
// set the PermissionsManager auto accept.
content::WebContents* OpenTestPageInNewTab(const std::string& test_url) {
chrome::AddTabAt(browser(), GURL(url::kAboutBlankURL), -1, true);
GURL url = embedded_test_server()->GetURL(test_url);
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
return browser()->tab_strip_model()->GetActiveWebContents();
}
};
IN_PROC_BROWSER_TEST_F(WebRtcAppWindowCaptureBrowserTestWithPicker,
CaptureAppWindow) {
extensions::AppWindow* app_window =
CreateAppWindowWithTitle(base::UTF8ToUTF16(std::string(kAppWindowTitle)));
content::WebContents* capturing_tab = OpenTestPageInNewTab(kMainHtmlPage);
RunGetDisplayMedia(capturing_tab, "{video: true}", /*is_fake_ui=*/false,
/*expect_success=*/true,
/*is_tab_capture=*/true);
CloseAppWindow(app_window);
}
// Base class for running tests with a SameOrigin policy applied.
class WebRtcSameOriginPolicyBrowserTest
: public WebRtcScreenCaptureBrowserTest {
public:
~WebRtcSameOriginPolicyBrowserTest() override = default;
bool PreferCurrentTab() const override { return false; }
void SetUpCommandLine(base::CommandLine* command_line) override {
WebRtcScreenCaptureBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
command_line->AppendSwitchASCII(
switches::kAutoSelectTabCaptureSourceByTitle, kSameOriginRenamedTitle);
}
void SetUpOnMainThread() override {
WebRtcScreenCaptureBrowserTest::SetUpOnMainThread();
ASSERT_TRUE(embedded_test_server()->Start());
// Restrict all origins to SameOrigin tab capture only.
base::Value::List matchlist;
matchlist.Append("*");
browser()->profile()->GetPrefs()->SetList(
prefs::kSameOriginTabCaptureAllowedByOrigins, std::move(matchlist));
}
void TearDownOnMainThread() override {
WebRtcScreenCaptureBrowserTest::TearDownOnMainThread();
browser()->profile()->GetPrefs()->SetList(
prefs::kSameOriginTabCaptureAllowedByOrigins, base::Value::List());
}
};
IN_PROC_BROWSER_TEST_F(WebRtcSameOriginPolicyBrowserTest,
TerminateOnNavigationAwayFromSameOrigin) {
// Open two pages, one to be captured, and one to do the capturing. Note that
// we open the capturing page second so that is focused to allow the
// getDisplayMedia request to succeed.
content::WebContents* target_tab = OpenTestPageInNewTab(kMainHtmlPage);
content::WebContents* capturing_tab = OpenTestPageInNewTab(kMainHtmlPage);
// Update the target tab to a unique title, so that we can ensure that it is
// the one that gets captured via the autoselection.
UpdateWebContentsTitle(
target_tab, base::UTF8ToUTF16(std::string(kSameOriginRenamedTitle)));
RunGetDisplayMedia(capturing_tab,
GetConstraints(
/*video=*/true, /*audio=*/true,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/false, /*expect_success=*/true,
/*is_tab_capture=*/true);
// Though the target tab should've been focused as a result of starting the
// capture, we don't want to take a dependency on that behavior. Ensure that
// the target tab is focused, so that we can navigate it easily. If it is
// already focused, this will just no-op.
int target_index =
browser()->tab_strip_model()->GetIndexOfWebContents(target_tab);
browser()->tab_strip_model()->ActivateTabAt(
target_index, TabStripUserGestureDetails(
TabStripUserGestureDetails::GestureType::kOther));
ASSERT_EQ(target_tab, browser()->tab_strip_model()->GetActiveWebContents());
// We navigate to a FileURL so that the origin will change, which should
// trigger the capture to end.
ASSERT_TRUE(
ui_test_utils::NavigateToURL(browser(), GetFileURL(kMainHtmlFileName)));
// Verify that the video stream has ended.
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
capturing_tab->GetPrimaryMainFrame(), "waitVideoEnded();", &result));
EXPECT_EQ(result, "ended");
}
IN_PROC_BROWSER_TEST_F(WebRtcSameOriginPolicyBrowserTest,
ContinueCapturingForSameOriginNavigation) {
// Open two pages, one to be captured, and one to do the capturing. Note that
// we open the capturing page second so that is focused to allow the
// getDisplayMedia request to succeed.
content::WebContents* target_tab = OpenTestPageInNewTab(kMainHtmlPage);
content::WebContents* capturing_tab = OpenTestPageInNewTab(kMainHtmlPage);
// Update the target tab to a unique title, so that we can ensure that it is
// the one that gets captured via the autoselection.
UpdateWebContentsTitle(
target_tab, base::UTF8ToUTF16(std::string(kSameOriginRenamedTitle)));
RunGetDisplayMedia(capturing_tab,
GetConstraints(
/*video=*/true, /*audio=*/true,
/*select_all_screens=*/
SelectAllScreens::kUndefined),
/*is_fake_ui=*/false, /*expect_success=*/true,
/*is_tab_capture=*/true);
// Though the target tab should've been focused as a result of starting the
// capture, we don't want to take a dependency on that behavior. Ensure that
// the target tab is focused, so that we can navigate it easily. If it is
// already focused, this will just no-op.
int target_index =
browser()->tab_strip_model()->GetIndexOfWebContents(target_tab);
browser()->tab_strip_model()->ActivateTabAt(
target_index, TabStripUserGestureDetails(
TabStripUserGestureDetails::GestureType::kOther));
ASSERT_EQ(target_tab, browser()->tab_strip_model()->GetActiveWebContents());
// We navigate using the test server so that the origin doesn't change.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(),
embedded_test_server()->GetURL("/webrtc/captured_page_main.html")));
// Verify that the video hasn't been ended.
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
capturing_tab->GetPrimaryMainFrame(),
"returnToTest(video_track.readyState);", &result));
EXPECT_EQ(result, "live");
}
class GetDisplayMediaVideoTrackBrowserTest
: public WebRtcTestBase,
public testing::WithParamInterface<std::tuple<bool, DisplaySurfaceType>> {
public:
GetDisplayMediaVideoTrackBrowserTest()
: region_capture_enabled_(std::get<0>(GetParam())),
display_surface_type_(std::get<1>(GetParam())) {}
~GetDisplayMediaVideoTrackBrowserTest() override = default;
void SetUpInProcessBrowserTestFixture() override {
DetectErrorsInJavaScript();
}
void SetUpOnMainThread() override {
WebRtcTestBase::SetUpOnMainThread();
ASSERT_TRUE(embedded_test_server()->Start());
}
// Unlike SetUp(), this is called from the test body. This allows skipping
// this test for (platform, test-case) combinations which are not supported.
void SetupTest() {
// Fire up the page.
tab_ = OpenTestPageInNewTab(kMainHtmlPage);
// Initiate the capture.
std::string result;
ASSERT_TRUE(content::ExecuteScriptAndExtractString(
tab_->GetPrimaryMainFrame(),
"runGetDisplayMedia({video: true, audio: true}, "
"\"top-level-document\");",
&result));
ASSERT_EQ(result, "capture-success");
}
void SetUpCommandLine(base::CommandLine* command_line) override {
WebRtcTestBase::SetUpCommandLine(command_line);
std::vector<std::string> enabled_blink_features;
std::vector<std::string> disabled_blink_features;
if (region_capture_enabled_) {
enabled_blink_features.push_back("RegionCapture");
} else {
disabled_blink_features.push_back("RegionCapture");
}
if (!enabled_blink_features.empty()) {
command_line->AppendSwitchASCII(
switches::kEnableBlinkFeatures,
base::JoinString(enabled_blink_features, ","));
}
if (!disabled_blink_features.empty()) {
command_line->AppendSwitchASCII(
switches::kDisableBlinkFeatures,
base::JoinString(disabled_blink_features, ","));
}
command_line->AppendSwitch(switches::kUseFakeUIForMediaStream);
command_line->AppendSwitchASCII(
switches::kUseFakeDeviceForMediaStream,
base::StrCat({"display-media-type=",
DisplaySurfaceTypeAsString(display_surface_type_)}));
}
std::string GetVideoTrackType() {
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab_->GetPrimaryMainFrame(), "getVideoTrackType();", &result));
return result;
}
std::string GetVideoCloneTrackType() {
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab_->GetPrimaryMainFrame(), "getVideoCloneTrackType();", &result));
return result;
}
bool HasAudioTrack() {
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab_->GetPrimaryMainFrame(), "hasAudioTrack();", &result));
EXPECT_TRUE(result == "true" || result == "false");
return result == "true";
}
std::string GetAudioTrackType() {
std::string result;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
tab_->GetPrimaryMainFrame(), "getAudioTrackType();", &result));
return result;
}
std::string ExpectedVideoTrackType() const {
switch (display_surface_type_) {
case DisplaySurfaceType::kTab:
return region_capture_enabled_ ? "BrowserCaptureMediaStreamTrack"
: "MediaStreamTrack";
case DisplaySurfaceType::kWindow:
case DisplaySurfaceType::kScreen:
return "MediaStreamTrack";
}
NOTREACHED();
return "Error";
}
protected:
const bool region_capture_enabled_;
const DisplaySurfaceType display_surface_type_;
private:
raw_ptr<content::WebContents, DanglingUntriaged> tab_ = nullptr;
};
INSTANTIATE_TEST_SUITE_P(
_,
GetDisplayMediaVideoTrackBrowserTest,
testing::Combine(/*region_capture_enabled=*/testing::Bool(),
/*display_surface_type=*/
testing::Values(DisplaySurfaceType::kTab,
DisplaySurfaceType::kWindow,
DisplaySurfaceType::kScreen)),
[](const testing::TestParamInfo<
GetDisplayMediaVideoTrackBrowserTest::ParamType>& info) {
return base::StrCat(
{std::get<0>(info.param) ? "RegionCapture" : "",
std::get<1>(info.param) == DisplaySurfaceType::kTab ? "Tab"
: std::get<1>(info.param) == DisplaySurfaceType::kWindow
? "Window"
: "Screen"});
});
// Normally, each of these these would have its own test, but the number of
// combinations and the setup time for browser-tests make this undesirable,
// especially given the simplicity of each of these tests.
// After both (a) Conditional Focus and (b) Region Capture ship, this can
// simpplified to three non-parameterized tests (tab/window/screen).
IN_PROC_BROWSER_TEST_P(GetDisplayMediaVideoTrackBrowserTest, RunCombinedTest) {
SetupTest();
// Test #1: The video track is of the expected type.
EXPECT_EQ(GetVideoTrackType(), ExpectedVideoTrackType());
// Test #2: Video clones are of the same type as the original.
EXPECT_EQ(GetVideoTrackType(), GetVideoCloneTrackType());
// Test #3: Audio tracks are all simply MediaStreamTrack.
if (HasAudioTrack()) {
EXPECT_EQ(GetAudioTrackType(), "MediaStreamTrack");
}
}
// Flaky on Mac, Windows, and ChromeOS bots, https://crbug.com/1371309
// Also some flakes on Linux ASAN/MSAN builds.
#if BUILDFLAG(IS_LINUX) && \
!(defined(MEMORY_SANITIZER) || defined(ADDRESS_SANITIZER))
class GetDisplayMediaHiDpiBrowserTest
: public WebRtcTestBase,
public testing::WithParamInterface<TestConfigForHiDpi> {
public:
GetDisplayMediaHiDpiBrowserTest() : test_config_(GetParam()) {}
// The browser window size must be consistent with the
// INSTANTIATE_TEST_SUITE_P TestConfigForHiDpi configurations below. See the
// comments there for more details.
static constexpr int kBrowserWindowWidth = 800;
static constexpr int kBrowserWindowHeight = 600;
bool enable_hidpi() const { return test_config_.enable_hidpi; }
int constraint_width() const { return test_config_.constraint_width; }
int constraint_height() const { return test_config_.constraint_height; }
void SetUpInProcessBrowserTestFixture() override {
if (enable_hidpi()) {
feature_list_.InitAndEnableFeature(media::kWebContentsCaptureHiDpi);
} else {
feature_list_.InitAndDisableFeature(media::kWebContentsCaptureHiDpi);
}
WebRtcTestBase::SetUpInProcessBrowserTestFixture();
DetectErrorsInJavaScript();
}
void SetUpOnMainThread() override {
WebRtcTestBase::SetUpOnMainThread();
ASSERT_TRUE(embedded_test_server()->Start());
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// The picker itself shows previews which are unsupported in Lacros tests.
base::Value::List matchlist;
matchlist.Append("*");
browser()->profile()->GetPrefs()->SetList(
prefs::kTabCaptureAllowedByOrigins, std::move(matchlist));
#endif
// Fire up the page.
tab_ = OpenTestPageInNewTab(kMainHtmlPage);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
WebRtcTestBase::SetUpCommandLine(command_line);
command_line->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
command_line->AppendSwitch(switches::kThisTabCaptureAutoAccept);
command_line->AppendSwitchASCII(
switches::kWindowSize,
base::StringPrintf("%d,%d", kBrowserWindowWidth, kBrowserWindowHeight));
// Optionally, in case the test isn't working correctly, you can turn on
// debug logging for the feature to help track down problems. For example:
// command_line->AppendSwitchASCII(switches::kVModule,
// "*host_view*=1,*frame_tracker*=3");
}
std::string ResizeVideoForHiDpiCapture(int width, int height) {
return RunJs(base::StringPrintf("resizeVideoForHiDpiCapture(%d, %d);",
width, height));
}
double GetDevicePixelRatio() {
std::string result = RunJs("getDevicePixelRatio();");
double device_pixel_ratio;
EXPECT_TRUE(base::StringToDouble(result, &device_pixel_ratio));
return device_pixel_ratio;
}
std::string GetDisplaySurfaceSetting() {
return RunJs("getDisplaySurfaceSetting();");
}
std::string GetLogicalSurfaceSetting() {