File: camera_effects_controller_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (966 lines) | stat: -rw-r--r-- 38,596 bytes parent folder | download | duplicates (3)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/camera/camera_effects_controller.h"

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/style/tab_slider.h"
#include "ash/style/tab_slider_button.h"
#include "ash/system/camera/autozoom_controller_impl.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/status_area_widget_test_helper.h"
#include "ash/system/video_conference/bubble/bubble_view_ids.h"
#include "ash/system/video_conference/bubble/set_value_effects_view.h"
#include "ash/system/video_conference/effects/video_conference_tray_effects_manager_types.h"
#include "ash/system/video_conference/fake_video_conference_tray_controller.h"
#include "ash/system/video_conference/video_conference_tray.h"
#include "ash/system/video_conference/video_conference_tray_controller.h"
#include "ash/test/ash_test_base.h"
#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_view_util.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "media/capture/video/chromeos/mojom/cros_camera_service.mojom-shared.h"
#include "media/capture/video/chromeos/mojom/effects_pipeline.mojom.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/jpeg_codec.h"

namespace ash {

using ::testing::ElementsAre;
using BackgroundImageInfo = CameraEffectsController::BackgroundImageInfo;

constexpr char kMetadataSuffix[] = ".metadata";

// Helper for converting `bitmap` into string.
std::string SkBitmapToString(const SkBitmap& bitmap) {
  std::optional<std::vector<uint8_t>> data =
      gfx::JPEGCodec::Encode(bitmap, /*quality=*/100);
  CHECK(data);
  return std::string(base::as_string_view(data.value()));
}

// Create fake Jpg image bytes.
std::string CreateJpgBytes(SkColor color) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(CameraEffectsController::kImageAsIconWidth,
                        CameraEffectsController::kImageAsIconWidth);
  bitmap.eraseColor(color);
  return SkBitmapToString(bitmap);
}

// Matcher defined to compare BackgroundImageInfo.
// We ignore the creation_time and last_accessed for now, because that were
// obtained from the filesystem, which is hard to mock for now.
auto BackgroundImageInfoMatcher(const base::FilePath& basename,
                                const std::string& jpeg_bytes,
                                const std::string& metadata) {
  return testing::AllOf(
      testing::Field("basename", &BackgroundImageInfo::basename,
                     testing::Eq(basename)),
      testing::ResultOf(
          [](BackgroundImageInfo info) {
            info.image.SetReadOnly();
            return SkBitmapToString(*info.image.bitmap());
          },
          testing::Eq(jpeg_bytes)),
      testing::Field("metadata", &BackgroundImageInfo::metadata,
                     testing::Eq(metadata)));
}

constexpr char kTestAccount[] = "testuser@gmail.com";
class CameraEffectsControllerTest : public NoSessionAshTestBase {
 public:
  // NoSessionAshTestBase:
  void SetUp() override {
    scoped_feature_list_.InitAndEnableFeature(
        features::kFeatureManagementVideoConference);

    // Instantiates a fake controller (the real one is created in
    // ChromeBrowserMainExtraPartsAsh::PreProfileInit() which is not called in
    // ash unit tests).
    controller_ = std::make_unique<FakeVideoConferenceTrayController>();

    AshTestBase::SetUp();

    camera_effects_controller_ = Shell::Get()->camera_effects_controller();

    // Enable test mode to mock the SetCameraEffects calls.
    camera_effects_controller_->bypass_set_camera_effects_for_testing(true);

    // Create fake camera_background_img_dir_ and camera_background_run_dir_.
    ASSERT_TRUE(file_tmp_dir_.CreateUniqueTempDir());
    camera_background_img_dir_ =
        file_tmp_dir_.GetPath().AppendASCII("camera_background_img_dir_");
    camera_background_run_dir_ =
        file_tmp_dir_.GetPath().AppendASCII("camera_background_run_dir_");
    ASSERT_TRUE(base::CreateDirectory(camera_background_img_dir_));
    ASSERT_TRUE(base::CreateDirectory(camera_background_run_dir_));
  }

  void TearDown() override {
    NoSessionAshTestBase::TearDown();
    controller_.reset();
  }

  // Sets background blur state.
  void SetBackgroundBlurEffectState(std::optional<int> state) {
    camera_effects_controller_->OnEffectControlActivated(
        VcEffectId::kBackgroundBlur, state);
  }

  // Gets the state of the background blur effect from the effect's host,
  // `camera_effects_controller_`.
  int GetBackgroundBlurEffectState() {
    std::optional<int> effect_state =
        camera_effects_controller_->GetEffectState(VcEffectId::kBackgroundBlur);
    DCHECK(effect_state.has_value());
    return effect_state.value();
  }

  // Retrieves the value of `prefs::kBackgroundBlur`.
  int GetBackgroundBlurPref() {
    return Shell::Get()
        ->session_controller()
        ->GetActivePrefService()
        ->GetInteger(prefs::kBackgroundBlur);
  }

  // Returns a pair of <replace-enabled, background-image-filepath>.
  std::pair<bool, std::string> GetBackgroundReplacePref() {
    const auto* prefs =
        Shell::Get()->session_controller()->GetActivePrefService();

    return {prefs->GetBoolean(prefs::kBackgroundReplace),
            prefs->GetFilePath(prefs::kBackgroundImagePath).value()};
  }

  // Simulates toggling portrait relighting effect state. Note that the `state`
  // argument doesn't matter for toggle effects.
  void TogglePortraitRelightingEffectState() {
    camera_effects_controller_->OnEffectControlActivated(
        VcEffectId::kPortraitRelighting, /*state=*/std::nullopt);
  }

  // Simulates toggling camera framing effect state. Note that the `state`
  // argument doesn't matter for toggle effects.
  void ToggleCameraFramingEffectState() {
    camera_effects_controller_->OnEffectControlActivated(
        VcEffectId::kCameraFraming, /*state=*/std::nullopt);
  }

  // Gets the state of the portrait relighting effect from the effect's host,
  // `camera_effects_controller_`.
  bool GetPortraitRelightingEffectState() {
    std::optional<int> effect_state =
        camera_effects_controller_->GetEffectState(
            VcEffectId::kPortraitRelighting);
    DCHECK(effect_state.has_value());
    return static_cast<bool>(effect_state.value());
  }

  // Retrieves the value of `prefs::kPortraitRelighting`.
  bool GetPortraitRelightingPref() {
    return Shell::Get()
        ->session_controller()
        ->GetActivePrefService()
        ->GetBoolean(prefs::kPortraitRelighting);
  }

  void SetAutozoomSupportState(bool autozoom_supported) {
    auto* autozoom_controller = Shell::Get()->autozoom_controller();

    autozoom_controller->SetAutozoomSupported(autozoom_supported);

    if (!autozoom_supported) {
      return;
    }

    // Autozoom is only supported if there's an active camera client, so we
    // simulate that here.
    autozoom_controller->OnActiveClientChange(
        cros::mojom::CameraClientType::ASH_CHROME,
        /*is_new_active_client=*/true,
        /*active_device_ids=*/{"fake_id"});
  }

  CameraEffectsController* camera_effects_controller() {
    return camera_effects_controller_;
  }

  FakeVideoConferenceTrayController* tray_controller() {
    return controller_.get();
  }

  base::FilePath GetFileInBackgroundRunDir() {
    base::FileEnumerator enumerator(camera_background_run_dir_,
                                    /*recursive=*/false,
                                    base::FileEnumerator::FILES);
    std::vector<base::FilePath> files;
    for (auto path = enumerator.Next(); !path.empty();
         path = enumerator.Next()) {
      files.push_back(enumerator.GetInfo().GetName());
    }

    // We should always see 1 file in the camera_background_run_dir_.
    CHECK_EQ(files.size(), 1u);

    return files[0];
  }

 protected:
  const SeaPenImage content1_ =
      SeaPenImage(CreateJpgBytes(SK_ColorBLACK), 12345);
  const SeaPenImage content2_ = SeaPenImage(CreateJpgBytes(SK_ColorWHITE), 888);
  const std::string metadata1_ = "metadata1_";
  const std::string metadata2_ = "metadata2_";

  const base::FilePath filename1_ = base::FilePath("12345.jpg");
  const base::FilePath filename2_ = base::FilePath("888.jpg");
  const base::FilePath metadata_filename1_ =
      filename1_.AddExtensionASCII(kMetadataSuffix);
  base::FilePath metadata_filename2_ =
      filename2_.AddExtensionASCII(kMetadataSuffix);

  base::ScopedTempDir file_tmp_dir_;
  base::FilePath camera_background_img_dir_;
  base::FilePath camera_background_run_dir_;

  raw_ptr<CameraEffectsController, DanglingUntriaged>
      camera_effects_controller_ = nullptr;

  std::unique_ptr<FakeVideoConferenceTrayController> controller_;
  base::test::ScopedFeatureList scoped_feature_list_;

  base::WeakPtrFactory<CameraEffectsControllerTest> weak_factory_{this};
};

TEST_F(CameraEffectsControllerTest, IsEffectControlAvailable) {
  {
    base::test::ScopedFeatureList scoped_feature_list;
    scoped_feature_list.InitWithFeatures(
        {}, {features::kFeatureManagementVideoConference});
    EXPECT_FALSE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundBlur));
    EXPECT_FALSE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kPortraitRelight));
    EXPECT_FALSE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundReplace));
  }

  {
    base::test::ScopedFeatureList scoped_feature_list;
    scoped_feature_list.InitWithFeatures(
        {features::kFeatureManagementVideoConference}, {});
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundBlur));
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kPortraitRelight));
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundReplace));
  }

  {
    base::test::ScopedFeatureList scoped_feature_list;
    scoped_feature_list.InitWithFeatures(
        {features::kFeatureManagementVideoConference},
        {features::kVcPortraitRelight});
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundBlur));
    EXPECT_FALSE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kPortraitRelight));
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundReplace));
  }

  {
    base::test::ScopedFeatureList scoped_feature_list;
    scoped_feature_list.InitWithFeatures(
        {features::kFeatureManagementVideoConference},
        {features::kVcBackgroundReplace});
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundBlur));
    EXPECT_TRUE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kPortraitRelight));
    EXPECT_FALSE(camera_effects_controller()->IsEffectControlAvailable(
        cros::mojom::CameraEffect::kBackgroundReplace));
  }
}

TEST_F(CameraEffectsControllerTest, BackgroundBlurOnEffectControlActivated) {
  SimulateUserLogin({kTestAccount});

  // Activate the possible values of
  // `CameraEffectsController::BackgroundBlurPrefValue`, verify that the pref
  //  and internal state are all set properly.
  for (const auto state :
       {CameraEffectsController::BackgroundBlurPrefValue::kOff,
        CameraEffectsController::BackgroundBlurPrefValue::kLowest,
        CameraEffectsController::BackgroundBlurPrefValue::kLight,
        CameraEffectsController::BackgroundBlurPrefValue::kMedium,
        CameraEffectsController::BackgroundBlurPrefValue::kHeavy,
        CameraEffectsController::BackgroundBlurPrefValue::kMaximum}) {
    SetBackgroundBlurEffectState(state);
    EXPECT_EQ(GetBackgroundBlurPref(), state);
    EXPECT_EQ(GetBackgroundBlurEffectState(), state);
  }

  // Invalid background blur effect state should set the state to kOff.
  SetBackgroundBlurEffectState(100);
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
  EXPECT_EQ(GetBackgroundBlurEffectState(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);

  // Set the background blur state to be kMaximum.
  SetBackgroundBlurEffectState(
      CameraEffectsController::BackgroundBlurPrefValue::kMaximum);
  // Setting the background blur state to null will reset the effects as
  // kOff.
  SetBackgroundBlurEffectState(std::nullopt);
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
  EXPECT_EQ(GetBackgroundBlurEffectState(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
}

TEST_F(CameraEffectsControllerTest,
       PortraitRelightingOnEffectControlActivated) {
  SimulateUserLogin({kTestAccount});

  // Initial state should be "off".
  EXPECT_FALSE(GetPortraitRelightingEffectState());
  EXPECT_FALSE(GetPortraitRelightingPref());

  // Activating the effect should toggle it to "true."
  TogglePortraitRelightingEffectState();
  EXPECT_TRUE(GetPortraitRelightingEffectState());
  EXPECT_TRUE(GetPortraitRelightingPref());

  // Another toggle should set it to "false."
  TogglePortraitRelightingEffectState();
  EXPECT_FALSE(GetPortraitRelightingEffectState());
  EXPECT_FALSE(GetPortraitRelightingPref());

  // And one more toggle should set it back to "true."
  TogglePortraitRelightingEffectState();
  EXPECT_TRUE(GetPortraitRelightingEffectState());
  EXPECT_TRUE(GetPortraitRelightingPref());
}

TEST_F(CameraEffectsControllerTest, PrefOnCameraEffectChanged) {
  SimulateUserLogin({kTestAccount});

  // Initial state should be "off".
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
  EXPECT_EQ(GetBackgroundBlurEffectState(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
  EXPECT_FALSE(GetPortraitRelightingEffectState());
  EXPECT_FALSE(GetPortraitRelightingPref());

  // Case 1: when observe effects change from `CameraHalDispatcherImp`, the pref
  // is updated.
  cros::mojom::EffectsConfigPtr new_effects = cros::mojom::EffectsConfig::New();
  new_effects->blur_enabled = true;
  new_effects->blur_level = cros::mojom::BlurLevel::kMaximum;
  new_effects->relight_enabled = true;
  camera_effects_controller_->OnCameraEffectChanged(std::move(new_effects));

  // State should be "on".
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kMaximum);
  EXPECT_EQ(GetBackgroundBlurEffectState(),
            CameraEffectsController::BackgroundBlurPrefValue::kMaximum);
  EXPECT_TRUE(GetPortraitRelightingEffectState());
  EXPECT_TRUE(GetPortraitRelightingPref());

  // Case 2: when new effects is null, the pref is unchanged.
  new_effects = cros::mojom::EffectsConfigPtr();
  camera_effects_controller_->OnCameraEffectChanged(std::move(new_effects));

  // State should be "on".
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kMaximum);
  EXPECT_EQ(GetBackgroundBlurEffectState(),
            CameraEffectsController::BackgroundBlurPrefValue::kMaximum);
  EXPECT_TRUE(GetPortraitRelightingEffectState());
  EXPECT_TRUE(GetPortraitRelightingPref());

  // Case 3: when observe default effects from `CameraHalDispatcherImp`, the
  // pref should be back to default.
  new_effects = cros::mojom::EffectsConfig::New();
  camera_effects_controller_->OnCameraEffectChanged(std::move(new_effects));

  // State should be "off".
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
  EXPECT_EQ(GetBackgroundBlurEffectState(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);
  EXPECT_FALSE(GetPortraitRelightingEffectState());
  EXPECT_FALSE(GetPortraitRelightingPref());
}

TEST_F(CameraEffectsControllerTest, ResourceDependencyFlags) {
  SimulateUserLogin({kTestAccount});

  // Makes sure that all registered effects have the correct dependency flag.
  auto* background_blur =
      camera_effects_controller()->GetEffectById(VcEffectId::kBackgroundBlur);
  EXPECT_EQ(VcHostedEffect::ResourceDependency::kCamera,
            background_blur->dependency_flags());

  if (features::IsVcStudioLookEnabled()) {
    auto* studio_look =
        camera_effects_controller()->GetEffectById(VcEffectId::kStudioLook);
    EXPECT_EQ(VcHostedEffect::ResourceDependency::kCamera,
              studio_look->dependency_flags());
  } else {
    auto* portrait_relight = camera_effects_controller()->GetEffectById(
        VcEffectId::kPortraitRelighting);
    EXPECT_EQ(VcHostedEffect::ResourceDependency::kCamera,
              portrait_relight->dependency_flags());
  }
}

TEST_F(CameraEffectsControllerTest, BackgroundBlurEnums) {
  // This test makes sure that `BackgroundBlurState` and
  // `BackgroundBlurPrefValue` is in sync with each other.
  EXPECT_EQ(
      static_cast<int>(CameraEffectsController::BackgroundBlurState::kMaximum),
      CameraEffectsController::BackgroundBlurPrefValue::kMaximum + 1);
}

TEST_F(CameraEffectsControllerTest, BackgroundBlurMetricsRecord) {
  base::HistogramTester histogram_tester;

  SimulateUserLogin({kTestAccount});

  // Update media status to make the video conference tray visible.
  VideoConferenceMediaState state;
  state.has_media_app = true;
  state.has_camera_permission = true;
  state.has_microphone_permission = true;
  state.is_capturing_screen = true;
  tray_controller()->UpdateWithMediaState(state);

  auto* vc_tray = StatusAreaWidgetTestHelper::GetStatusAreaWidget()
                      ->video_conference_tray();

  // Open the vc bubble.
  LeftClickOn(vc_tray->toggle_bubble_button());

  // The set-value effects panel should have only 1 child view, and that view
  // should be the slider associated to the background blur effect.
  auto* set_value_effects_view = vc_tray->GetBubbleView()->GetViewByID(
      video_conference::BubbleViewID::kSetValueEffectsView);

  ASSERT_EQ(1u, set_value_effects_view->children().size());

  auto* background_blur_slider =
      static_cast<video_conference::SetValueEffectSlider*>(
          set_value_effects_view->children()[0]);
  EXPECT_EQ(VcEffectId::kBackgroundBlur, background_blur_slider->effect_id());

  auto* tab_slider = background_blur_slider->tab_slider();
  auto* first_button = tab_slider->GetButtonAtIndex(0);

  // At first, the first button is selected, but there should not be any metrics
  // recorded for that state since it is the default state when opening the
  // bubble.
  EXPECT_TRUE(first_button->selected());
  histogram_tester.ExpectBucketCount(
      "Ash.VideoConferenceTray.BackgroundBlur.Click",
      CameraEffectsController::BackgroundBlurState::kOff, 0);

  // Switching states by clicking slider buttons should record metrics in the
  // associated bucket.
  LeftClickOn(tab_slider->GetButtonAtIndex(1));

  histogram_tester.ExpectBucketCount(
      "Ash.VideoConferenceTray.BackgroundBlur.Click",
      CameraEffectsController::BackgroundBlurState::kLight, 1);

  LeftClickOn(tab_slider->GetButtonAtIndex(2));

  histogram_tester.ExpectBucketCount(
      "Ash.VideoConferenceTray.BackgroundBlur.Click",
      CameraEffectsController::BackgroundBlurState::kMaximum, 1);

  LeftClickOn(first_button);

  histogram_tester.ExpectBucketCount(
      "Ash.VideoConferenceTray.BackgroundBlur.Click",
      CameraEffectsController::BackgroundBlurState::kOff, 1);
}

TEST_F(CameraEffectsControllerTest, CameraFramingSupportState) {
  SimulateUserLogin({kTestAccount});

  // By default autozoom is not supported, so the effect is not added.
  EXPECT_FALSE(
      camera_effects_controller()->GetEffectById(VcEffectId::kCameraFraming));

  SetAutozoomSupportState(true);

  EXPECT_TRUE(
      camera_effects_controller()->GetEffectById(VcEffectId::kCameraFraming));

  SetAutozoomSupportState(false);

  EXPECT_FALSE(
      camera_effects_controller()->GetEffectById(VcEffectId::kCameraFraming));
}

TEST_F(CameraEffectsControllerTest, CameraFramingToggle) {
  SetAutozoomSupportState(true);

  SimulateUserLogin({kTestAccount});

  ASSERT_EQ(Shell::Get()->autozoom_controller()->GetState(),
            cros::mojom::CameraAutoFramingState::OFF);

  ToggleCameraFramingEffectState();
  EXPECT_EQ(Shell::Get()->autozoom_controller()->GetState(),
            cros::mojom::CameraAutoFramingState::ON_SINGLE);

  ToggleCameraFramingEffectState();
  EXPECT_EQ(Shell::Get()->autozoom_controller()->GetState(),
            cros::mojom::CameraAutoFramingState::OFF);
}

TEST_F(CameraEffectsControllerTest, SetBackgroundImageWithFileExists) {
  base::test::ScopedFeatureList scoped_feature_list{
      features::kVcBackgroundReplace};

  SimulateUserLogin({kTestAccount});
  camera_effects_controller()->set_camera_background_img_dir_for_testing(
      camera_background_img_dir_);
  camera_effects_controller()->set_camera_background_run_dir_for_testing(
      camera_background_run_dir_);

  // Apply background blur first.
  const auto state = CameraEffectsController::BackgroundBlurPrefValue::kLowest;
  SetBackgroundBlurEffectState(state);
  EXPECT_EQ(GetBackgroundBlurPref(), state);

  // Create fake image file.
  const std::string relative_path = "background/test.png";
  base::FilePath file_fullpath =
      camera_background_img_dir_.Append(relative_path);
  ASSERT_TRUE(base::CreateDirectory(file_fullpath.DirName()));
  ASSERT_TRUE(base::WriteFile(file_fullpath, ""));

  // Set background image.
  camera_effects_controller()->SetBackgroundImage(
      base::FilePath(relative_path),
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // Check background replace result from pref.
  EXPECT_THAT(GetBackgroundReplacePref(), testing::Pair(true, relative_path));

  // Check the background blur is turned off.
  EXPECT_EQ(GetBackgroundBlurPref(),
            CameraEffectsController::BackgroundBlurPrefValue::kOff);

  // Apply background blur again.
  SetBackgroundBlurEffectState(state);
  EXPECT_EQ(GetBackgroundBlurPref(), state);

  // Background replace should be turned off.
  EXPECT_THAT(GetBackgroundReplacePref(), testing::Pair(false, ""));

  // When background replace is turned off, we want the background_filepath to
  // be empty.
  EXPECT_FALSE(camera_effects_controller()
                   ->GetCameraEffects()
                   ->background_filepath.has_value());

  // Set background image again.
  camera_effects_controller()->SetBackgroundImage(
      base::FilePath(relative_path),
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // Check background replace result from pref.
  EXPECT_THAT(GetBackgroundReplacePref(), testing::Pair(true, relative_path));

  // Turn off backgroundblur or replace.
  const auto off_state = CameraEffectsController::BackgroundBlurPrefValue::kOff;
  SetBackgroundBlurEffectState(off_state);
  EXPECT_EQ(GetBackgroundBlurPref(), off_state);

  // Background replace should be turned off.
  EXPECT_THAT(GetBackgroundReplacePref(), testing::Pair(false, ""));
}

TEST_F(CameraEffectsControllerTest, SetBackgroundImageWithFileDoesNotExist) {
  base::test::ScopedFeatureList scoped_feature_list{
      features::kVcBackgroundReplace};

  SimulateUserLogin({kTestAccount});
  camera_effects_controller()->set_camera_background_img_dir_for_testing(
      camera_background_img_dir_);
  camera_effects_controller()->set_camera_background_run_dir_for_testing(
      camera_background_run_dir_);

  // Apply background blur first.
  const auto state = CameraEffectsController::BackgroundBlurPrefValue::kLowest;
  SetBackgroundBlurEffectState(state);
  EXPECT_EQ(GetBackgroundBlurPref(), state);

  // Set background image.
  camera_effects_controller()->SetBackgroundImage(
      filename1_, base::BindOnce([](bool call_succeeded) {
        EXPECT_FALSE(call_succeeded);
      }));
  task_environment()->RunUntilIdle();

  // Because the image is not created, the above SetBackgroundImage should fail,
  // so that the background replace pref should not be set.
  EXPECT_THAT(GetBackgroundReplacePref(), testing::Pair(false, ""));

  // Check the background blur is not changed.
  EXPECT_EQ(GetBackgroundBlurPref(), state);
}

TEST_F(CameraEffectsControllerTest, SetBackgroundImageFromContent) {
  base::test::ScopedFeatureList scoped_feature_list{
      features::kVcBackgroundReplace};

  SimulateUserLogin({kTestAccount});
  camera_effects_controller()->set_camera_background_img_dir_for_testing(
      camera_background_img_dir_);
  camera_effects_controller()->set_camera_background_run_dir_for_testing(
      camera_background_run_dir_);

  // Set background image from content1_.
  camera_effects_controller()->SetBackgroundImageFromContent(
      content1_, metadata1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // We should see replace-enabled and the filename1_ in prefs.
  EXPECT_THAT(GetBackgroundReplacePref(),
              testing::Pair(true, filename1_.value()));

  // Check saved image info.
  camera_effects_controller()->GetRecentlyUsedBackgroundImages(
      3, base::BindLambdaForTesting(
             [&](const std::vector<BackgroundImageInfo>& info) {
               EXPECT_THAT(info,
                           ElementsAre(BackgroundImageInfoMatcher(
                               filename1_, content1_.jpg_bytes, metadata1_)));
               EXPECT_EQ(GetFileInBackgroundRunDir(), filename1_);
             }));
  task_environment()->RunUntilIdle();

  // Set background image from content2_.
  camera_effects_controller()->SetBackgroundImageFromContent(
      content2_, metadata2_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // We should see replace-enabled and the filename2_ in prefs.
  EXPECT_THAT(GetBackgroundReplacePref(),
              testing::Pair(true, filename2_.value()));

  camera_effects_controller()->GetRecentlyUsedBackgroundImages(
      3, base::BindLambdaForTesting(
             [&](const std::vector<BackgroundImageInfo>& info) {
               EXPECT_THAT(
                   info, ElementsAre(
                             BackgroundImageInfoMatcher(
                                 filename2_, content2_.jpg_bytes, metadata2_),
                             BackgroundImageInfoMatcher(
                                 filename1_, content1_.jpg_bytes, metadata1_)));
               EXPECT_EQ(GetFileInBackgroundRunDir(), filename2_);
             }));
  task_environment()->RunUntilIdle();

  // SetBackgroundImage with filename1_ should update the last activity
  // time of filename1_.
  camera_effects_controller()->SetBackgroundImage(
      filename1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // We should see replace-enabled and the filename1_ in prefs.
  EXPECT_THAT(GetBackgroundReplacePref(),
              testing::Pair(true, filename1_.value()));

  camera_effects_controller()->GetRecentlyUsedBackgroundImages(
      3, base::BindLambdaForTesting(
             [&](const std::vector<BackgroundImageInfo>& info) {
               EXPECT_THAT(
                   info, ElementsAre(
                             BackgroundImageInfoMatcher(
                                 filename1_, content1_.jpg_bytes, metadata1_),
                             BackgroundImageInfoMatcher(
                                 filename2_, content2_.jpg_bytes, metadata2_)));
               EXPECT_EQ(GetFileInBackgroundRunDir(), filename1_);
             }));
  task_environment()->RunUntilIdle();

  // Remove filename2_.
  camera_effects_controller()->RemoveBackgroundImage(
      filename2_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // Pref should not be effect if a irrelevant image is removed.
  EXPECT_THAT(GetBackgroundReplacePref(),
              testing::Pair(true, filename1_.value()));

  camera_effects_controller()->GetRecentlyUsedBackgroundImages(
      3, base::BindLambdaForTesting(
             [&](const std::vector<BackgroundImageInfo>& info) {
               EXPECT_THAT(info,
                           ElementsAre(BackgroundImageInfoMatcher(
                               filename1_, content1_.jpg_bytes, metadata1_)));
             }));
  task_environment()->RunUntilIdle();

  // Remove filename1_.
  camera_effects_controller()->RemoveBackgroundImage(
      filename1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // Since filename2_ is removed, we should see the background image is removed
  // from prefs.
  EXPECT_THAT(GetBackgroundReplacePref(), testing::Pair(false, ""));

  camera_effects_controller()->GetRecentlyUsedBackgroundImages(
      3, base::BindLambdaForTesting(
             [&](const std::vector<BackgroundImageInfo>& info) {
               // We should only see all files removed.
               EXPECT_TRUE(info.empty());
             }));
  task_environment()->RunUntilIdle();
}

TEST_F(CameraEffectsControllerTest, GetBackgroundImageFileNames) {
  base::test::ScopedFeatureList scoped_feature_list{
      features::kVcBackgroundReplace};

  SimulateUserLogin({kTestAccount});
  camera_effects_controller()->set_camera_background_img_dir_for_testing(
      camera_background_img_dir_);
  camera_effects_controller()->set_camera_background_run_dir_for_testing(
      camera_background_run_dir_);

  // Set background image from content1_.
  camera_effects_controller()->SetBackgroundImageFromContent(
      content1_, metadata1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // filename1_ should be created.
  camera_effects_controller()->GetBackgroundImageFileNames(
      base::BindLambdaForTesting([&](const std::vector<base::FilePath>& files) {
        EXPECT_THAT(files, ElementsAre(filename1_));
      }));
  task_environment()->RunUntilIdle();

  // Set background image from content2_.
  camera_effects_controller()->SetBackgroundImageFromContent(
      content2_, metadata2_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // filename2_ should be created.
  camera_effects_controller()->GetBackgroundImageFileNames(
      base::BindLambdaForTesting([&](const std::vector<base::FilePath>& files) {
        EXPECT_THAT(files, ElementsAre(filename2_, filename1_));
      }));
  task_environment()->RunUntilIdle();

  // SetBackgroundImage with filename1_ should update the last activity
  // time of filename1_.
  camera_effects_controller()->SetBackgroundImage(
      filename1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // Returned files order should be changed.
  camera_effects_controller()->GetBackgroundImageFileNames(
      base::BindLambdaForTesting([&](const std::vector<base::FilePath>& files) {
        EXPECT_THAT(files, ElementsAre(filename1_, filename2_));
      }));
  task_environment()->RunUntilIdle();

  // Remove filename1_.
  camera_effects_controller()->RemoveBackgroundImage(
      filename1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // We should only see filename2_.
  camera_effects_controller()->GetBackgroundImageFileNames(
      base::BindLambdaForTesting([&](const std::vector<base::FilePath>& files) {
        EXPECT_THAT(files, ElementsAre(filename2_));
      }));
  task_environment()->RunUntilIdle();
}

TEST_F(CameraEffectsControllerTest, GetBackgroundImageInfo) {
  base::test::ScopedFeatureList scoped_feature_list{
      features::kVcBackgroundReplace};

  SimulateUserLogin({kTestAccount});
  camera_effects_controller()->set_camera_background_img_dir_for_testing(
      camera_background_img_dir_);
  camera_effects_controller()->set_camera_background_run_dir_for_testing(
      camera_background_run_dir_);

  // Set background image from content1_.
  camera_effects_controller()->SetBackgroundImageFromContent(
      content1_, metadata1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  // GetBackgroundImageInfo should return info about filename1_.
  camera_effects_controller()->GetBackgroundImageInfo(
      filename1_, base::BindLambdaForTesting(
                      [&](const std::optional<BackgroundImageInfo>& info) {
                        EXPECT_THAT(
                            info.value(),
                            BackgroundImageInfoMatcher(
                                filename1_, content1_.jpg_bytes, metadata1_));
                      }));
  task_environment()->RunUntilIdle();

  // Delete metadata_filename1_ will return empty metadata.
  camera_effects_controller()->RemoveBackgroundImage(
      metadata_filename1_,
      base::BindOnce([](bool call_succeeded) { EXPECT_TRUE(call_succeeded); }));
  task_environment()->RunUntilIdle();

  camera_effects_controller()->GetBackgroundImageInfo(
      filename1_, base::BindLambdaForTesting(
                      [&](const std::optional<BackgroundImageInfo>& info) {
                        EXPECT_THAT(info.value(),
                                    BackgroundImageInfoMatcher(
                                        filename1_, content1_.jpg_bytes, ""));
                      }));
  task_environment()->RunUntilIdle();

  // GetBackgroundImageInfo should return nullopt for filename2_ because the
  // file is not created.
  camera_effects_controller()->GetBackgroundImageInfo(
      filename2_,
      base::BindOnce([](const std::optional<BackgroundImageInfo>& info) {
        EXPECT_FALSE(info.has_value());
      }));
  task_environment()->RunUntilIdle();
}

TEST_F(CameraEffectsControllerTest, NotEligibleForSeaPen) {
  // Set is_eligible_for_background_replace to false so that the image button
  // will not be constructed.
  GetSessionControllerClient()->set_is_eligible_for_background_replace(
      {false, false});
  SimulateUserLogin({kTestAccount});

  // Update media status to make the video conference tray visible.
  VideoConferenceMediaState state;
  state.has_media_app = true;
  state.has_camera_permission = true;
  state.has_microphone_permission = true;
  state.is_capturing_screen = true;
  tray_controller()->UpdateWithMediaState(state);

  auto effects = VideoConferenceTrayController::Get()
                     ->GetEffectsManager()
                     .GetSetValueEffects();

  EXPECT_EQ(effects.size(), 1u);
  EXPECT_EQ(effects[0]->label_text(), u"Background");
  // Verify that only three states are constructed; the forth one is the image
  // button.
  EXPECT_EQ(effects[0]->GetNumStates(), 3);
}

TEST_F(CameraEffectsControllerTest, UpdateBackgroundBlurImageState) {
  // Set is_eligible_for_background_replace to false so that the image button
  // will not be constructed.
  GetSessionControllerClient()->set_is_eligible_for_background_replace(
      {false, false});
  SimulateUserLogin({kTestAccount});

  // Update media status to make the video conference tray visible.
  VideoConferenceMediaState state;
  state.has_media_app = true;
  state.has_camera_permission = true;
  state.has_microphone_permission = true;
  state.is_capturing_screen = true;
  tray_controller()->UpdateWithMediaState(state);

  auto effects = VideoConferenceTrayController::Get()
                     ->GetEffectsManager()
                     .GetSetValueEffects();

  EXPECT_EQ(effects.size(), 1u);
  EXPECT_EQ(effects[0]->label_text(), u"Background");
  // Verify that only three states are constructed; the forth one is the image
  // button.
  EXPECT_EQ(effects[0]->GetNumStates(), 3);

  // Set background replace eligible state to true and enterprise enabled state
  // to false so that the image button is added but disabled.
  GetSessionControllerClient()->set_is_eligible_for_background_replace(
      {true, false});
  auto* vc_tray = StatusAreaWidgetTestHelper::GetStatusAreaWidget()
                      ->video_conference_tray();

  // Open the vc bubble to notify bubble opened and update Background Blur
  // effect.
  LeftClickOn(vc_tray->toggle_bubble_button());

  effects = VideoConferenceTrayController::Get()
                ->GetEffectsManager()
                .GetSetValueEffects();

  // Now four states are constructed and the forth one is the image button.
  EXPECT_EQ(effects[0]->GetNumStates(), 4) << " four states are constructed";
  const VcEffectState* imageState = effects[0]->GetState(/*index=*/3);
  EXPECT_EQ(imageState->view_id(),
            video_conference::BubbleViewID::kBackgroundBlurImageButton);
  EXPECT_TRUE(imageState->is_disabled_by_enterprise());

  // Update VC Background enterprise enabled state to true so that the Image
  // button is enabled.
  GetSessionControllerClient()->set_is_eligible_for_background_replace(
      {true, true});
  // Close the video conference bubble.
  LeftClickOn(vc_tray->toggle_bubble_button());
  // Reopen the bubble to trigger updating Background Blur effect again.
  LeftClickOn(vc_tray->toggle_bubble_button());

  effects = VideoConferenceTrayController::Get()
                ->GetEffectsManager()
                .GetSetValueEffects();

  // The image button is now enabled.
  EXPECT_EQ(effects[0]->GetNumStates(), 4)
      << "still four states for Background Blur effect";
  const VcEffectState* newImageState = effects[0]->GetState(/*index=*/3);
  EXPECT_EQ(newImageState->view_id(),
            video_conference::BubbleViewID::kBackgroundBlurImageButton);
  EXPECT_FALSE(newImageState->is_disabled_by_enterprise());
}

}  // namespace ash