File: audio_context_test.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1234 lines) | stat: -rw-r--r-- 54,167 bytes parent folder | download | duplicates (5)
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
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/webaudio/audio_context.h"

#include <array>
#include <memory>

#include "base/synchronization/waitable_event.h"
#include "media/base/audio_timestamp_helper.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/remote_set.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/frame/lifecycle.mojom-blink.h"
#include "third_party/blink/public/mojom/media/capture_handle_config.mojom-blink.h"
#include "third_party/blink/public/platform/web_audio_device.h"
#include "third_party/blink/public/platform/web_audio_latency_hint.h"
#include "third_party/blink/public/platform/web_audio_sink_descriptor.h"
#include "third_party/blink/public/platform/web_runtime_features.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_sink_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_union_audiocontextlatencycategory_double.h"
#include "third_party/blink/renderer/core/core_initializer.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/modules/mediastream/sub_capture_target.h"
#include "third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.h"
#include "third_party/blink/renderer/modules/webaudio/audio_playout_stats.h"
#include "third_party/blink/renderer/modules/webaudio/realtime_audio_destination_node.h"
#include "third_party/blink/renderer/modules/webrtc/webrtc_audio_device_impl.h"
#include "third_party/blink/renderer/platform/scheduler/public/event_loop.h"
#include "third_party/blink/renderer/platform/scheduler/public/non_main_thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/scoped_mocked_url.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_base.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_media.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"

namespace blink {

namespace {

constexpr char kFakeAudioOutput1[] = "fake_audio_output_1";
constexpr char kFakeAudioOutput2[] = "fake_audio_output_2";
constexpr char kInvalidAudioOutput[] = "INVALID_AUDIO_OUTPUT";
constexpr char kSecurityOrigin[] = "https://example.com";
constexpr char kTestData[] = "simple_div.html";
constexpr char kDefaultDeviceId[] = "";

bool web_audio_device_paused_;

class MockMediaDevicesDispatcherHost final
    : public mojom::blink::MediaDevicesDispatcherHost {
 public:
  MockMediaDevicesDispatcherHost()
      : enumeration_(
            {{},
             {},
             {
                 {kFakeAudioOutput1, "Fake Audio Output 1", "common_group_1"},
                 {kFakeAudioOutput2, "Fake Audio Output 2", "common_group_2"},
             }}) {}

  ~MockMediaDevicesDispatcherHost() override = default;

  void BindRequest(mojo::ScopedMessagePipeHandle handle) {
    receivers_.Add(
        this, mojo::PendingReceiver<mojom::blink::MediaDevicesDispatcherHost>(
                  std::move(handle)));
  }

  void Flush() {
    receivers_.FlushForTesting();
    listeners_.FlushForTesting();
  }

  void EnumerateDevices(bool request_audio_input,
                        bool request_video_input,
                        bool request_audio_output,
                        bool request_video_input_capabilities,
                        bool request_audio_input_capabilities,
                        EnumerateDevicesCallback callback) override {
    Vector<Vector<WebMediaDeviceInfo>> enumeration(static_cast<size_t>(
        blink::mojom::blink::MediaDeviceType::kNumMediaDeviceTypes));
    Vector<mojom::blink::VideoInputDeviceCapabilitiesPtr>
        video_input_capabilities;
    Vector<mojom::blink::AudioInputDeviceCapabilitiesPtr>
        audio_input_capabilities;
    if (request_audio_output) {
      wtf_size_t index = static_cast<wtf_size_t>(
          blink::mojom::blink::MediaDeviceType::kMediaAudioOutput);
      enumeration[index] = enumeration_[index];
    }
    std::move(callback).Run(std::move(enumeration),
                            std::move(video_input_capabilities),
                            std::move(audio_input_capabilities));
  }
  void SelectAudioOutput(const String& device_id,
                         SelectAudioOutputCallback callback) override {}

  void GetVideoInputCapabilities(GetVideoInputCapabilitiesCallback) override {}

  void GetAllVideoInputDeviceFormats(
      const String&,
      GetAllVideoInputDeviceFormatsCallback) override {}

  void GetAvailableVideoInputDeviceFormats(
      const String&,
      GetAvailableVideoInputDeviceFormatsCallback) override {}

  void GetAudioInputCapabilities(GetAudioInputCapabilitiesCallback) override {}

  void AddMediaDevicesListener(
      bool subscribe_audio_input,
      bool subscribe_video_input,
      bool subscribe_audio_output,
      mojo::PendingRemote<mojom::blink::MediaDevicesListener> listener)
      override {
    listeners_.Add(std::move(listener));
  }

  void SetCaptureHandleConfig(
      mojom::blink::CaptureHandleConfigPtr config) override {}

  void SetPreferredSinkId(const String& sink_id,
                          SetPreferredSinkIdCallback callback) override {}

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  void CloseFocusWindowOfOpportunity(const String& label) override {}

  void ProduceSubCaptureTargetId(
      SubCaptureTarget::Type type,
      ProduceSubCaptureTargetIdCallback callback) override {}
#endif

 private:
  mojo::RemoteSet<mojom::blink::MediaDevicesListener> listeners_;
  mojo::ReceiverSet<mojom::blink::MediaDevicesDispatcherHost> receivers_;

  Vector<Vector<WebMediaDeviceInfo>> enumeration_{static_cast<size_t>(
      blink::mojom::blink::MediaDeviceType::kNumMediaDeviceTypes)};
};

class MockWebAudioDeviceForAudioContext : public WebAudioDevice {
 public:
  explicit MockWebAudioDeviceForAudioContext(double sample_rate,
                                             int frames_per_buffer)
      : sample_rate_(sample_rate), frames_per_buffer_(frames_per_buffer) {}
  ~MockWebAudioDeviceForAudioContext() override = default;

  void Start() override {}
  void Stop() override {}
  void Pause() override { web_audio_device_paused_ = true; }
  void Resume() override { web_audio_device_paused_ = false; }
  double SampleRate() override { return sample_rate_; }
  int FramesPerBuffer() override { return frames_per_buffer_; }
  int MaxChannelCount() override { return 2; }
  void SetDetectSilence(bool detect_silence) override {}
  media::OutputDeviceStatus MaybeCreateSinkAndGetStatus() override {
    // In this test, we assume the sink creation always succeeds.
    return media::OUTPUT_DEVICE_STATUS_OK;
  }

 private:
  double sample_rate_;
  int frames_per_buffer_;
};

class AudioContextTestPlatform : public TestingPlatformSupport {
 public:
  std::unique_ptr<WebAudioDevice> CreateAudioDevice(
      const WebAudioSinkDescriptor& sink_descriptor,
      unsigned number_of_output_channels,
      const WebAudioLatencyHint& latency_hint,
      std::optional<float> context_sample_rate,
      media::AudioRendererSink::RenderCallback*) override {
    double buffer_size = 0;
    const double interactive_size = AudioHardwareBufferSize();
    const double balanced_size = AudioHardwareBufferSize() * 2;
    const double playback_size = AudioHardwareBufferSize() * 4;
    switch (latency_hint.Category()) {
      case WebAudioLatencyHint::kCategoryInteractive:
        buffer_size = interactive_size;
        break;
      case WebAudioLatencyHint::kCategoryBalanced:
        buffer_size = balanced_size;
        break;
      case WebAudioLatencyHint::kCategoryPlayback:
        buffer_size = playback_size;
        break;
      case WebAudioLatencyHint::kCategoryExact:
        buffer_size =
            ClampTo(latency_hint.Seconds() * AudioHardwareSampleRate(),
                    static_cast<double>(AudioHardwareBufferSize()),
                    static_cast<double>(playback_size));
        break;
      default:
        NOTREACHED();
    }

    return std::make_unique<MockWebAudioDeviceForAudioContext>(
        context_sample_rate.value_or(AudioHardwareSampleRate()), buffer_size);
  }

  double AudioHardwareSampleRate() override { return 44100; }
  size_t AudioHardwareBufferSize() override { return 128; }
};

String GetAecDevice(ExecutionContext* execution_context) {
  return PeerConnectionDependencyFactory::From(*execution_context)
      .GetWebRtcAudioDevice()
      ->GetOutputDeviceForAecForTesting();
}

}  // namespace

class AudioContextTest : public PageTestBase {
 protected:
  AudioContextTest() {
    mock_media_devices_dispatcher_host_ =
        std::make_unique<MockMediaDevicesDispatcherHost>();
  }

  ~AudioContextTest() override = default;

  void FlushMediaDevicesDispatcherHost() {
    mock_media_devices_dispatcher_host_->Flush();
  }

  void SetUp() override {
    PageTestBase::SetUp(gfx::Size());
    CoreInitializer::GetInstance().ProvideModulesToPage(GetPage(),
                                                        std::string());

    GetFrame().DomWindow()->GetBrowserInterfaceBroker().SetBinderForTesting(
        mojom::blink::MediaDevicesDispatcherHost::Name_,
        WTF::BindRepeating(
            &MockMediaDevicesDispatcherHost::BindRequest,
            WTF::Unretained(mock_media_devices_dispatcher_host_.get())));
  }

  void TearDown() override {
    GetFrame().DomWindow()->GetBrowserInterfaceBroker().SetBinderForTesting(
        mojom::blink::MediaDevicesDispatcherHost::Name_, {});
  }

  void ResetAudioContextManagerForAudioContext(AudioContext* audio_context) {
    audio_context->audio_context_manager_.reset();
  }

  void SetContextState(AudioContext* audio_context,
                       V8AudioContextState::Enum state) {
    audio_context->SetContextState(state);
  }

  AudioContextTestPlatform* platform() {
    return platform_.GetTestingPlatformSupport();
  }

  void VerifyPlayoutStats(AudioPlayoutStats* playout_stats,
                          ScriptState* script_state,
                          int total_processed_frames,
                          const media::AudioGlitchInfo& total_glitches,
                          base::TimeDelta average_delay,
                          base::TimeDelta min_delay,
                          base::TimeDelta max_delay,
                          int source_line) {
    EXPECT_EQ(playout_stats->fallbackFramesEvents(script_state),
              total_glitches.count)
        << " LINE " << source_line;
    EXPECT_FLOAT_EQ(playout_stats->fallbackFramesDuration(script_state),
                    total_glitches.duration.InMillisecondsF())
        << " LINE " << source_line;
    EXPECT_EQ(playout_stats->averageLatency(script_state),
              average_delay.InMillisecondsF())
        << " LINE " << source_line;
    EXPECT_EQ(playout_stats->minimumLatency(script_state),
              min_delay.InMillisecondsF())
        << " LINE " << source_line;
    EXPECT_EQ(playout_stats->maximumLatency(script_state),
              max_delay.InMillisecondsF())
        << " LINE " << source_line;
    EXPECT_NEAR(
        playout_stats->totalFramesDuration(script_state),
        (media::AudioTimestampHelper::FramesToTime(
             total_processed_frames, platform()->AudioHardwareSampleRate()) +
         total_glitches.duration)
            .InMillisecondsF(),
        0.01)
        << " LINE " << source_line;
  }

 private:
  ScopedTestingPlatformSupport<AudioContextTestPlatform> platform_;
  std::unique_ptr<MockMediaDevicesDispatcherHost>
      mock_media_devices_dispatcher_host_;
};

TEST_F(AudioContextTest, AudioContextOptions_WebAudioLatencyHint) {
  AudioContextOptions* interactive_options = AudioContextOptions::Create();
  interactive_options->setLatencyHint(
      MakeGarbageCollected<V8UnionAudioContextLatencyCategoryOrDouble>(
          V8AudioContextLatencyCategory(
              V8AudioContextLatencyCategory::Enum::kInteractive)));
  AudioContext* interactive_context = AudioContext::Create(
      GetFrame().DomWindow(), interactive_options, ASSERT_NO_EXCEPTION);

  AudioContextOptions* balanced_options = AudioContextOptions::Create();
  balanced_options->setLatencyHint(
      MakeGarbageCollected<V8UnionAudioContextLatencyCategoryOrDouble>(
          V8AudioContextLatencyCategory(
              V8AudioContextLatencyCategory::Enum::kBalanced)));
  AudioContext* balanced_context = AudioContext::Create(
      GetFrame().DomWindow(), balanced_options, ASSERT_NO_EXCEPTION);
  EXPECT_GT(balanced_context->baseLatency(),
            interactive_context->baseLatency());

  AudioContextOptions* playback_options = AudioContextOptions::Create();
  playback_options->setLatencyHint(
      MakeGarbageCollected<V8UnionAudioContextLatencyCategoryOrDouble>(
          V8AudioContextLatencyCategory(
              V8AudioContextLatencyCategory::Enum::kPlayback)));
  AudioContext* playback_context = AudioContext::Create(
      GetFrame().DomWindow(), playback_options, ASSERT_NO_EXCEPTION);
  EXPECT_GT(playback_context->baseLatency(), balanced_context->baseLatency());

  AudioContextOptions* exact_too_small_options = AudioContextOptions::Create();
  exact_too_small_options->setLatencyHint(
      MakeGarbageCollected<V8UnionAudioContextLatencyCategoryOrDouble>(
          interactive_context->baseLatency() / 2));
  AudioContext* exact_too_small_context = AudioContext::Create(
      GetFrame().DomWindow(), exact_too_small_options, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(exact_too_small_context->baseLatency(),
            interactive_context->baseLatency());

  const double exact_latency_sec =
      (interactive_context->baseLatency() + playback_context->baseLatency()) /
      2;
  AudioContextOptions* exact_ok_options = AudioContextOptions::Create();
  exact_ok_options->setLatencyHint(
      MakeGarbageCollected<V8UnionAudioContextLatencyCategoryOrDouble>(
          exact_latency_sec));
  AudioContext* exact_ok_context = AudioContext::Create(
      GetFrame().DomWindow(), exact_ok_options, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(exact_ok_context->baseLatency(), exact_latency_sec);

  AudioContextOptions* exact_too_big_options = AudioContextOptions::Create();
  exact_too_big_options->setLatencyHint(
      MakeGarbageCollected<V8UnionAudioContextLatencyCategoryOrDouble>(
          playback_context->baseLatency() * 2));
  AudioContext* exact_too_big_context = AudioContext::Create(
      GetFrame().DomWindow(), exact_too_big_options, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(exact_too_big_context->baseLatency(),
            playback_context->baseLatency());
}

TEST_F(AudioContextTest, AudioContextAudibility_ServiceUnbind) {
  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);

  audio_context->set_was_audible_for_testing(true);
  ResetAudioContextManagerForAudioContext(audio_context);
  SetContextState(audio_context, V8AudioContextState::Enum::kSuspended);

  platform()->RunUntilIdle();
}

TEST_F(AudioContextTest, ExecutionContextPaused) {
  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);

  audio_context->set_was_audible_for_testing(true);
  EXPECT_FALSE(web_audio_device_paused_);
  GetFrame().DomWindow()->SetLifecycleState(
      mojom::FrameLifecycleState::kFrozen);
  EXPECT_TRUE(web_audio_device_paused_);
  GetFrame().DomWindow()->SetLifecycleState(
      mojom::FrameLifecycleState::kRunning);
  EXPECT_FALSE(web_audio_device_paused_);
}

// Test initialization/uninitialization of MediaDeviceService.
TEST_F(AudioContextTest, MediaDevicesService) {
  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);

  EXPECT_FALSE(audio_context->is_media_device_service_initialized_);
  audio_context->InitializeMediaDeviceService();
  EXPECT_TRUE(audio_context->is_media_device_service_initialized_);
  audio_context->UninitializeMediaDeviceService();
  EXPECT_FALSE(audio_context->media_device_service_.is_bound());
  EXPECT_FALSE(audio_context->media_device_service_receiver_.is_bound());
}

TEST_F(AudioContextTest, OnRenderErrorFromPlatformDestination) {
  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(audio_context->ContextState(), V8AudioContextState::Enum::kRunning);

  audio_context->invoke_onrendererror_from_platform_for_testing();
  EXPECT_TRUE(audio_context->render_error_occurred_);
}

class ContextRenderer : public GarbageCollected<ContextRenderer> {
 public:
  explicit ContextRenderer(AudioContext* context)
      : context_(context),
        audio_thread_(NonMainThread::CreateThread(
            ThreadCreationParams(ThreadType::kRealtimeAudioWorkletThread))) {}
  ~ContextRenderer() = default;

  void Init() {
    PostCrossThreadTask(
        *audio_thread_->GetTaskRunner(), FROM_HERE,
        CrossThreadBindOnce(&ContextRenderer::SetContextAudioThread,
                            WrapCrossThreadWeakPersistent(this)));
    event_.Wait();
  }

  void Render(uint32_t frames_to_process,
              base::TimeDelta playout_delay,
              const media::AudioGlitchInfo& glitch_info) {
    PostCrossThreadTask(
        *audio_thread_->GetTaskRunner(), FROM_HERE,
        CrossThreadBindOnce(&ContextRenderer::RenderOnAudioThread,
                            WrapCrossThreadWeakPersistent(this),
                            frames_to_process, playout_delay, glitch_info));
    event_.Wait();
  }

  void Trace(Visitor* visitor) const { visitor->Trace(context_); }

 private:
  void SetContextAudioThread() {
    static_cast<AudioContext*>(context_)
        ->GetDeferredTaskHandler()
        .SetAudioThreadToCurrentThread();
    event_.Signal();
  }

  void RenderOnAudioThread(uint32_t frames_to_process,
                           base::TimeDelta playout_delay,
                           const media::AudioGlitchInfo& glitch_info) {
    const AudioIOPosition output_position{0, 0, 0};
    const AudioCallbackMetric audio_callback_metric;
    static_cast<AudioContext*>(context_)->HandlePreRenderTasks(
        frames_to_process, &output_position, &audio_callback_metric,
        playout_delay, glitch_info);
    event_.Signal();
  }

  WeakMember<AudioContext> context_;
  const std::unique_ptr<blink::NonMainThread> audio_thread_;
  base::WaitableEvent event_{base::WaitableEvent::ResetPolicy::AUTOMATIC};
};

TEST_F(AudioContextTest, PlayoutStats) {
  blink::WebRuntimeFeatures::EnableFeatureFromString("AudioContextPlayoutStats",
                                                     true);
  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);

  constexpr int kNumberOfRenderEvents = 9;
  std::array<uint32_t, kNumberOfRenderEvents> frames_to_process{
      100, 200, 300, 10, 500, 120, 120, 30, 100};
  std::array<base::TimeDelta, kNumberOfRenderEvents> playout_delay{
      base::Milliseconds(10),  base::Milliseconds(20), base::Milliseconds(300),
      base::Milliseconds(107), base::Milliseconds(17), base::Milliseconds(3),
      base::Milliseconds(500), base::Milliseconds(10), base::Milliseconds(112)};
  const std::array<media::AudioGlitchInfo, kNumberOfRenderEvents> glitch_info{
      media::AudioGlitchInfo{.duration = base::Milliseconds(5), .count = 1},
      {},
      {.duration = base::Milliseconds(60), .count = 3},
      {},
      {.duration = base::Milliseconds(600), .count = 20},
      {.duration = base::Milliseconds(200), .count = 5},
      {},
      {.duration = base::Milliseconds(2), .count = 1},
      {.duration = base::Milliseconds(15), .count = 5}};

  media::AudioGlitchInfo total_glitches;
  int total_processed_frames = 0;
  int interval_processed_frames = 0;
  base::TimeDelta interval_delay_sum;
  base::TimeDelta last_delay;
  base::TimeDelta max_delay;
  base::TimeDelta min_delay = base::TimeDelta::Max();

  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  AudioPlayoutStats* playout_stats = audio_context->playoutStats();

  ContextRenderer* renderer =
      MakeGarbageCollected<ContextRenderer>(audio_context);
  renderer->Init();

  // Empty stats in be beginning, all latencies are zero.
  VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                     total_glitches, last_delay, last_delay, last_delay,
                     __LINE__);

  int i = 0;
  for (; i < 3; ++i) {
    // Do some rendering.
    renderer->Render(frames_to_process[i], playout_delay[i], glitch_info[i]);

    total_glitches += glitch_info[i];
    last_delay = playout_delay[i];
    total_processed_frames += frames_to_process[i];
    interval_processed_frames += frames_to_process[i];
    interval_delay_sum += playout_delay[i] * frames_to_process[i];
    max_delay = std::max<base::TimeDelta>(max_delay, playout_delay[i]);
    min_delay = std::min<base::TimeDelta>(min_delay, playout_delay[i]);

    // New execution cycle.
    ToEventLoop(script_state).PerformMicrotaskCheckpoint();

    // Stats updated.
    VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                       total_glitches,
                       interval_delay_sum / interval_processed_frames,
                       min_delay, max_delay, __LINE__);
  }

  // Same stats, since we are within the same execution cycle.
  VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                     total_glitches,
                     interval_delay_sum / interval_processed_frames, min_delay,
                     max_delay, __LINE__);

  // Reset stats.
  playout_stats->resetLatency(script_state);

  min_delay = base::TimeDelta::Max();
  max_delay = base::TimeDelta();
  interval_processed_frames = 0;
  interval_delay_sum = base::TimeDelta();

  // Getting reset stats.
  VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                     total_glitches, last_delay, last_delay, last_delay,
                     __LINE__);

  // New execution cycle.
  ToEventLoop(script_state).PerformMicrotaskCheckpoint();

  // Stats are still the same, since there have been no rendering yet.
  VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                     total_glitches, last_delay, last_delay, last_delay,
                     __LINE__);

  for (; i < 4; ++i) {
    // Do some rendering after reset.
    renderer->Render(frames_to_process[i], playout_delay[i], glitch_info[i]);

    total_glitches += glitch_info[i];
    last_delay = playout_delay[i];
    total_processed_frames += frames_to_process[i];
    interval_processed_frames += frames_to_process[i];
    interval_delay_sum += playout_delay[i] * frames_to_process[i];
    max_delay = std::max<base::TimeDelta>(max_delay, playout_delay[i]);
    min_delay = std::min<base::TimeDelta>(min_delay, playout_delay[i]);

    // New execution cycle.
    ToEventLoop(script_state).PerformMicrotaskCheckpoint();

    // Stats reflect the state after the last reset.
    VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                       total_glitches,
                       interval_delay_sum / interval_processed_frames,
                       min_delay, max_delay, __LINE__);
  }

  // Cache the current state: we'll be doing rendering several times without
  // advancing to the next execution cycle.
  const media::AudioGlitchInfo observed_total_glitches = total_glitches;
  const int observed_total_processed_frames = total_processed_frames;
  const base::TimeDelta observed_average_delay =
      interval_delay_sum / interval_processed_frames;
  const base::TimeDelta observed_max_delay = max_delay;
  const base::TimeDelta observed_min_delay = min_delay;

  VerifyPlayoutStats(playout_stats, script_state,
                     observed_total_processed_frames, observed_total_glitches,
                     observed_average_delay, observed_min_delay,
                     observed_max_delay, __LINE__);

  // Starting the execution cycle.
  ToEventLoop(script_state).PerformMicrotaskCheckpoint();

  // Still same stats: there has been no new rendering.
  VerifyPlayoutStats(playout_stats, script_state,
                     observed_total_processed_frames, observed_total_glitches,
                     observed_average_delay, observed_min_delay,
                     observed_max_delay, __LINE__);

  for (; i < 8; ++i) {
    // Render.
    renderer->Render(frames_to_process[i], playout_delay[i], glitch_info[i]);

    // Still same stats: we are in the same execution cycle.
    VerifyPlayoutStats(playout_stats, script_state,
                       observed_total_processed_frames, observed_total_glitches,
                       observed_average_delay, observed_min_delay,
                       observed_max_delay, __LINE__);

    total_glitches += glitch_info[i];
    last_delay = playout_delay[i];
    total_processed_frames += frames_to_process[i];
    interval_processed_frames += frames_to_process[i];
    interval_delay_sum += playout_delay[i] * frames_to_process[i];
    max_delay = std::max<base::TimeDelta>(max_delay, playout_delay[i]);
    min_delay = std::min<base::TimeDelta>(min_delay, playout_delay[i]);
  }

  // New execution cycle.
  ToEventLoop(script_state).PerformMicrotaskCheckpoint();

  // Stats are updated with all the new info.
  VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                     total_glitches,
                     interval_delay_sum / interval_processed_frames, min_delay,
                     max_delay, __LINE__);

  // Reset stats.
  playout_stats->resetLatency(script_state);

  // Cache the current state: we'll be doing rendering several times without
  // advancing to the next execution cycle.
  const media::AudioGlitchInfo reset_total_glitches = total_glitches;
  const int reset_total_processed_frames = total_processed_frames;
  const base::TimeDelta reset_average_delay = last_delay;
  const base::TimeDelta reset_max_delay = last_delay;
  const base::TimeDelta reset_min_delay = last_delay;

  // Still same stats: we are in the same execution cycle.
  VerifyPlayoutStats(playout_stats, script_state, reset_total_processed_frames,
                     reset_total_glitches, reset_average_delay, reset_min_delay,
                     reset_max_delay, __LINE__);

  min_delay = base::TimeDelta::Max();
  max_delay = base::TimeDelta();
  interval_processed_frames = 0;
  interval_delay_sum = base::TimeDelta();

  // Render while in the same execution cycle.
  for (; i < kNumberOfRenderEvents; ++i) {
    renderer->Render(frames_to_process[i], playout_delay[i], glitch_info[i]);

    // Still same stats we got after reset: we are in the same execution cycle.
    VerifyPlayoutStats(playout_stats, script_state,
                       reset_total_processed_frames, reset_total_glitches,
                       reset_average_delay, reset_min_delay, reset_max_delay,
                       __LINE__);

    total_glitches += glitch_info[i];
    last_delay = playout_delay[i];
    total_processed_frames += frames_to_process[i];
    interval_processed_frames += frames_to_process[i];
    interval_delay_sum += playout_delay[i] * frames_to_process[i];
    max_delay = std::max<base::TimeDelta>(max_delay, playout_delay[i]);
    min_delay = std::min<base::TimeDelta>(min_delay, playout_delay[i]);
  }

  // New execution cycle.
  ToEventLoop(script_state).PerformMicrotaskCheckpoint();

  // In the new execution cycle stats have all the info received after the last
  // reset.
  VerifyPlayoutStats(playout_stats, script_state, total_processed_frames,
                     total_glitches,
                     interval_delay_sum / interval_processed_frames, min_delay,
                     max_delay, __LINE__);
}

TEST_F(AudioContextTest, ChannelCountRunning) {
  // Changing the channel count on a running AudioContext should result in a
  // running context and running platform destination.
  test::ScopedMockedURLLoad scoped_mocked_url_load(
      KURL(kSecurityOrigin), test::CoreTestDataPath(kTestData));
  frame_test_helpers::WebViewHelper web_view_helper;
  WebViewImpl* web_view_impl =
      web_view_helper.InitializeAndLoad(kSecurityOrigin);
  LocalFrame* main_frame = web_view_impl->MainFrameImpl()->GetFrame();
  ScriptState* script_state = ToScriptStateForMainWorld(main_frame);
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = main_frame->DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext should result in the context running and the
  // destination playing.
  AudioContext* context = AudioContext::Create(
      execution_context, AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());

  // Changing the channel count should should result in the same running and
  // playing state.
  context->destination()->setChannelCount(
      context->destination()->maxChannelCount(), ASSERT_NO_EXCEPTION);
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());
}

TEST_F(AudioContextTest, ChannelCountSuspended) {
  // Changing the channel count on suspended AudioContexts should not cause the
  // destination to start.
  test::ScopedMockedURLLoad scoped_mocked_url_load(
      KURL(kSecurityOrigin), test::CoreTestDataPath(kTestData));
  frame_test_helpers::WebViewHelper web_view_helper;
  WebViewImpl* web_view_impl =
      web_view_helper.InitializeAndLoad(kSecurityOrigin);
  LocalFrame* main_frame = web_view_impl->MainFrameImpl()->GetFrame();
  ScriptState* script_state = ToScriptStateForMainWorld(main_frame);
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = main_frame->DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext should result in the context running and the
  // destination playing.
  AudioContext* context = AudioContext::Create(
      execution_context, AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());

  // Suspending the AudioContext should result in the context being suspended
  // and the destination not playing.
  context->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kSuspended);
  EXPECT_FALSE(context->GetRealtimeAudioDestinationNode()
                   ->GetOwnHandler()
                   .get_platform_destination_is_playing_for_testing());

  // Changing the channel count on a suspended context should not change the
  // suspended or playing states.
  context->destination()->setChannelCount(
      context->destination()->maxChannelCount(), ASSERT_NO_EXCEPTION);
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kSuspended);
  EXPECT_FALSE(context->GetRealtimeAudioDestinationNode()
                   ->GetOwnHandler()
                   .get_platform_destination_is_playing_for_testing());

  // Resuming the context should make everything start playing again.
  context->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  ContextRenderer* renderer = MakeGarbageCollected<ContextRenderer>(context);
  renderer->Init();
  renderer->Render(128, base::Milliseconds(0), {});
  platform()->RunUntilIdle();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());
}

TEST_F(AudioContextTest, SetSinkIdRunning) {
  // Calling setSinkId on a running AudioContext should result in a running
  // context and running platform destination.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = GetFrame().DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext should result in the context running and the
  // destination playing.
  AudioContext* context = AudioContext::Create(
      execution_context, AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());

  // Calling setSinkId with a valid device ID should result in the same running
  // and playing state.
  context->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput1),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());
}

TEST_F(AudioContextTest, SetSinkIdSuspended) {
  // Calling setSinkId on suspended AudioContexts should not cause the
  // destination to start.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = GetFrame().DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext should result in the context running and the
  // destination playing.
  AudioContext* context = AudioContext::Create(
      execution_context, AudioContextOptions::Create(), ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());

  // Suspending the AudioContext should result in the context being suspended
  // and the destination not playing.
  context->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kSuspended);
  EXPECT_FALSE(context->GetRealtimeAudioDestinationNode()
                   ->GetOwnHandler()
                   .get_platform_destination_is_playing_for_testing());

  // Calling setSinkId with an invalid device ID on a suspended context should
  // not change the suspended or playing states.
  context->setSinkId(script_state,
                     MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(
                         kInvalidAudioOutput),
                     ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kSuspended);
  EXPECT_FALSE(context->GetRealtimeAudioDestinationNode()
                   ->GetOwnHandler()
                   .get_platform_destination_is_playing_for_testing());

  // Calling setSinkId with a valid device ID on a suspended context should not
  // change the suspended or playing states.
  context->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput1),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kSuspended);
  EXPECT_FALSE(context->GetRealtimeAudioDestinationNode()
                   ->GetOwnHandler()
                   .get_platform_destination_is_playing_for_testing());

  // Resuming the context should make everything start playing again.
  context->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  ContextRenderer* renderer = MakeGarbageCollected<ContextRenderer>(context);
  renderer->Init();
  renderer->Render(128, base::Milliseconds(0), {});
  platform()->RunUntilIdle();
  EXPECT_EQ(context->ContextState(), V8AudioContextState::Enum::kRunning);
  EXPECT_TRUE(context->GetRealtimeAudioDestinationNode()
                  ->GetOwnHandler()
                  .get_platform_destination_is_playing_for_testing());
}

TEST_F(AudioContextTest, AecConstructor) {
  // Constructing AudioContexts with different sinkId values should update the
  // acoustic echo cancellation output device.
  ExecutionContext* execution_context = GetFrame().DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext with no options should not change the AEC device.
  const String initial_aec_device = GetAecDevice(execution_context);
  AudioContextOptions* options_empty = AudioContextOptions::Create();
  AudioContext::Create(execution_context, options_empty, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(GetAecDevice(execution_context), initial_aec_device);

  // Creating an AudioContext with a null sink should not change the AEC device.
  AudioContextOptions* options_null = AudioContextOptions::Create();
  options_null->setSinkId(MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(
      MakeGarbageCollected<AudioSinkOptions>()));
  AudioContext::Create(execution_context, options_null, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(GetAecDevice(execution_context), initial_aec_device);

  // A specific valid ID should change the AEC device.
  AudioContextOptions* options_a = AudioContextOptions::Create();
  options_a->setSinkId(
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput1));
  AudioContext::Create(execution_context, options_a, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);

  // A different specific valid ID on a different AudioContext should change the
  // AEC device again.
  AudioContextOptions* options_b = AudioContextOptions::Create();
  options_b->setSinkId(
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput2));
  AudioContext::Create(execution_context, options_b, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput2);

  // Creating another AudioContext with no options should not change the AEC
  // device.
  AudioContext::Create(execution_context, options_empty, ASSERT_NO_EXCEPTION);
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput2);

  // An explicit default will set the AEC device to default.
  AudioContextOptions* options_explicit_default = AudioContextOptions::Create();
  options_explicit_default->setSinkId(
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kDefaultDeviceId));
  AudioContext::Create(execution_context, options_explicit_default,
                       ASSERT_NO_EXCEPTION);
  EXPECT_EQ(GetAecDevice(execution_context), kDefaultDeviceId);
}

TEST_F(AudioContextTest, AecSetSinkIdSuspended) {
  // Calling setSinkId on suspended AudioContexts should not update the acoustic
  // echo cancellation output device until the contexts are resumed.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = GetFrame().DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating AudioContexts with no options should not change the AEC device.
  const String initial_aec_device = GetAecDevice(execution_context);
  AudioContextOptions* options_empty = AudioContextOptions::Create();
  AudioContext* context_a = AudioContext::Create(
      execution_context, options_empty, ASSERT_NO_EXCEPTION);
  context_a->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  AudioContext* context_b = AudioContext::Create(
      execution_context, options_empty, ASSERT_NO_EXCEPTION);
  context_b->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), initial_aec_device);

  // Calling setSinkId with a valid device ID on a suspended context should not
  // change the AEC device.
  context_a->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput1),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), initial_aec_device);

  // Calling setSinkId on a different suspended context with a valid device ID
  // should not change the AEC device.
  context_b->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput2),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), initial_aec_device);

  // Resuming a suspended AudioContext changes the AEC device.
  context_b->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput2);

  // Resuming the other suspended AudioContext should also change the AEC
  // device.
  context_a->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);

  // Suspending the first audio context should not change the AEC reference
  // again.
  context_b->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);

  // Resuming the first audio context should not change the AEC reference again.
  context_b->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);
}

TEST_F(AudioContextTest, AecSetSinkIdMultiple) {
  // Calling setSinkId multiple times on the same AudioContext should update the
  // acoustic echo cancellation output device each time.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = GetFrame().DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext with no options should not change the AEC device.
  const String initial_aec_device = GetAecDevice(execution_context);
  AudioContextOptions* options_empty = AudioContextOptions::Create();
  AudioContext* context = AudioContext::Create(execution_context, options_empty,
                                               ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), initial_aec_device);

  // Calling setSinkId with a valid device ID should change the AEC device.
  context->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput1),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);

  // Calling setSinkId with an invalid device ID should not change the AEC
  // device.
  context->setSinkId(script_state,
                     MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(
                         kInvalidAudioOutput),
                     ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);

  // Calling setSinkId with another valid device ID on the same context should
  // change the AEC device again.
  context->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput2),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput2);
}

TEST_F(AudioContextTest, AecSetSinkIdAfterConstructor) {
  // Calling setSinkId after constructing an AudioContext with an explicit
  // device ID should update the acoustic echo cancellation output device each
  // time.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);
  ExecutionContext* execution_context = GetFrame().DomWindow();
  SecurityContext& security_context = execution_context->GetSecurityContext();
  security_context.SetSecurityOriginForTesting(nullptr);
  security_context.SetSecurityOrigin(
      SecurityOrigin::CreateFromString(kSecurityOrigin));

  // Creating an AudioContext with a specific ID should change the AEC device.
  AudioContextOptions* options = AudioContextOptions::Create();
  options->setSinkId(
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput1));
  AudioContext* context =
      AudioContext::Create(execution_context, options, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput1);

  // Calling setSinkId with a valid device ID should change the AEC device.
  context->setSinkId(
      script_state,
      MakeGarbageCollected<V8UnionAudioSinkOptionsOrString>(kFakeAudioOutput2),
      ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  EXPECT_EQ(GetAecDevice(execution_context), kFakeAudioOutput2);
}

class AudioContextInterruptedStateTest
    : public testing::WithParamInterface<bool>,
      public AudioContextTest {
 public:
  AudioContextInterruptedStateTest() {
    if (GetParam()) {
      blink::WebRuntimeFeatures::EnableFeatureFromString(
          "AudioContextInterruptedState", true);
    } else {
      blink::WebRuntimeFeatures::EnableFeatureFromString(
          "AudioContextInterruptedState", false);
    }
  }

  bool IsParamFeatureEnabled() { return GetParam(); }

  void ExpectAudioContextRunning(AudioContext* audio_context) {
    EXPECT_EQ(audio_context->ContextState(),
              V8AudioContextState::Enum::kRunning);
    EXPECT_TRUE(audio_context->GetRealtimeAudioDestinationNode()
                    ->GetOwnHandler()
                    .get_platform_destination_is_playing_for_testing());
  }

  void ExpectAudioContextSuspended(AudioContext* audio_context) {
    EXPECT_EQ(audio_context->ContextState(),
              V8AudioContextState::Enum::kSuspended);
    EXPECT_FALSE(audio_context->GetRealtimeAudioDestinationNode()
                     ->GetOwnHandler()
                     .get_platform_destination_is_playing_for_testing());
  }

  void ExpectAudioContextInterrupted(AudioContext* audio_context) {
    EXPECT_EQ(audio_context->ContextState(),
              V8AudioContextState::Enum::kInterrupted);
    EXPECT_FALSE(audio_context->GetRealtimeAudioDestinationNode()
                     ->GetOwnHandler()
                     .get_platform_destination_is_playing_for_testing());
  }
};

TEST_P(AudioContextInterruptedStateTest, InterruptionWhileRunning) {
  // If an interruption occurs while the AudioContext is running, the context
  // should be put into the interrupted state and the platform destination
  // should stop playing.
  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);
  ExpectAudioContextRunning(audio_context);

  audio_context->StartContextInterruption();
  if (IsParamFeatureEnabled()) {
    ExpectAudioContextInterrupted(audio_context);
  } else {
    ExpectAudioContextRunning(audio_context);
  }

  audio_context->EndContextInterruption();
  ExpectAudioContextRunning(audio_context);
}

TEST_P(AudioContextInterruptedStateTest, InterruptionWhileSuspended) {
  // If an interruption occurs while the AudioContext is suspended, the context
  // should remain in the suspended state and the platform destination should
  // not start playing.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);

  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);
  ExpectAudioContextRunning(audio_context);

  audio_context->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  ExpectAudioContextSuspended(audio_context);

  // Starting and ending an interruption while the context is "suspended" should
  // not change the user-facing state.
  audio_context->StartContextInterruption();
  ExpectAudioContextSuspended(audio_context);

  audio_context->EndContextInterruption();
  ExpectAudioContextSuspended(audio_context);
}

TEST_P(AudioContextInterruptedStateTest,
       ResumingSuspendedContextWhileInterrupted) {
  // If an interruption occurs while the AudioContext is suspended, the context
  // should remain in the suspended state and the platform destination should
  // not start playing.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);

  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);
  ExpectAudioContextRunning(audio_context);

  audio_context->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  ExpectAudioContextSuspended(audio_context);

  audio_context->StartContextInterruption();
  ExpectAudioContextSuspended(audio_context);

  // Resuming a "suspended" context while there is an ongoing interruption
  // should change the state to "interrupted" and no audio should be played.
  audio_context->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  if (IsParamFeatureEnabled()) {
    ExpectAudioContextInterrupted(audio_context);
  } else {
    ContextRenderer* renderer =
        MakeGarbageCollected<ContextRenderer>(audio_context);
    renderer->Init();
    renderer->Render(128, base::Milliseconds(0), {});
    platform()->RunUntilIdle();
    ExpectAudioContextRunning(audio_context);
  }

  // Ending the interruption should bring the context back to the running
  // state.
  audio_context->EndContextInterruption();
  ExpectAudioContextRunning(audio_context);
}

TEST_P(AudioContextInterruptedStateTest,
       SuspendingRunningContextWhileInterrupted) {
  // If an interruption happens while the AudioContext is running, the context
  // should be put in the interrupted state. If the context is then suspended,
  // the context should be put in the suspended state immediately.
  ScriptState* script_state = ToScriptStateForMainWorld(&GetFrame());
  ScriptState::Scope scope(script_state);

  AudioContextOptions* options = AudioContextOptions::Create();
  AudioContext* audio_context = AudioContext::Create(
      GetFrame().DomWindow(), options, ASSERT_NO_EXCEPTION);
  ExpectAudioContextRunning(audio_context);

  audio_context->StartContextInterruption();
  if (IsParamFeatureEnabled()) {
    ExpectAudioContextInterrupted(audio_context);
  } else {
    ExpectAudioContextRunning(audio_context);
  }

  audio_context->suspendContext(script_state, ASSERT_NO_EXCEPTION);
  ExpectAudioContextSuspended(audio_context);

  audio_context->EndContextInterruption();
  ExpectAudioContextSuspended(audio_context);

  audio_context->resumeContext(script_state, ASSERT_NO_EXCEPTION);
  FlushMediaDevicesDispatcherHost();
  ContextRenderer* renderer =
      MakeGarbageCollected<ContextRenderer>(audio_context);
  renderer->Init();
  renderer->Render(128, base::Milliseconds(0), {});
  platform()->RunUntilIdle();
  ExpectAudioContextRunning(audio_context);
}

INSTANTIATE_TEST_SUITE_P(AudioContextInterruptedStateTests,
                         AudioContextInterruptedStateTest,
                         testing::Bool());

}  // namespace blink