File: live_caption_speech_recognition_host_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; 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,811; 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 (471 lines) | stat: -rw-r--r-- 20,188 bytes parent folder | download | duplicates (4)
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
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/accessibility/live_caption/live_caption_speech_recognition_host_browsertest.h"

#include <string>
#include <vector>

#include "chrome/browser/accessibility/live_caption/live_caption_controller_factory.h"
#include "chrome/browser/accessibility/live_caption/live_caption_speech_recognition_host.h"
#include "chrome/browser/accessibility/live_caption/live_caption_test_util.h"
#include "chrome/browser/accessibility/live_translate_controller_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/live_caption/caption_bubble_controller.h"
#include "components/live_caption/live_caption_controller.h"
#include "components/live_caption/live_translate_controller.h"
#include "components/live_caption/pref_names.h"
#include "components/live_caption/translation_util.h"
#include "components/prefs/pref_service.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "media/mojo/mojom/speech_recognition.mojom.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"

namespace {
// A WebContentsObserver that allows waiting for some media to start or stop
// playing fullscreen.
class FullscreenEventsWaiter : public content::WebContentsObserver {
 public:
  explicit FullscreenEventsWaiter(content::WebContents* web_contents)
      : WebContentsObserver(web_contents) {}
  FullscreenEventsWaiter(const FullscreenEventsWaiter& rhs) = delete;
  FullscreenEventsWaiter& operator=(const FullscreenEventsWaiter& rhs) = delete;
  ~FullscreenEventsWaiter() override = default;

  void MediaEffectivelyFullscreenChanged(bool value) override {
    if (run_loop_) {
      run_loop_->Quit();
    }
  }

  // Wait for the current media playing fullscreen mode to be equal to
  // |expected_media_fullscreen_mode|.
  void Wait() {
    run_loop_ = std::make_unique<base::RunLoop>();
    run_loop_->Run();
  }

 private:
  std::unique_ptr<base::RunLoop> run_loop_;
};
}  // namespace

namespace captions {
MockLiveTranslateController::MockLiveTranslateController(
    PrefService* profile_prefs,
    content::BrowserContext* browser_context)
    : LiveTranslateController(profile_prefs, browser_context) {}

MockLiveTranslateController::~MockLiveTranslateController() = default;

void MockLiveTranslateController::GetTranslation(
    const std::string& result,
    std::string source_language,
    std::string target_language,
    TranslateEventCallback callback) {
  translation_requests_.push_back(result);
  std::move(callback).Run(TranslateEvent(result));
}

std::vector<std::string> MockLiveTranslateController::GetTranslationRequests() {
  return translation_requests_;
}

LiveCaptionSpeechRecognitionHostTest::LiveCaptionSpeechRecognitionHostTest() =
    default;
LiveCaptionSpeechRecognitionHostTest::~LiveCaptionSpeechRecognitionHostTest() =
    default;

std::unique_ptr<KeyedService>
LiveCaptionSpeechRecognitionHostTest::SetLiveTranslateController(
    content::BrowserContext* context) {
  return std::make_unique<testing::NiceMock<MockLiveTranslateController>>(
      browser()->profile()->GetPrefs(), browser()->profile());
}

void LiveCaptionSpeechRecognitionHostTest::SetUp() {
  // This is required for the fullscreen video tests.
  embedded_test_server()->ServeFilesFromSourceDirectory(
      base::FilePath(FILE_PATH_LITERAL("content/test/data")));
  LiveCaptionBrowserTest::SetUp();
}

void LiveCaptionSpeechRecognitionHostTest::SetUpOnMainThread() {
  LiveTranslateControllerFactory::GetInstance()->SetTestingFactory(
      browser()->profile(),
      base::BindRepeating(
          &LiveCaptionSpeechRecognitionHostTest::SetLiveTranslateController,
          base::Unretained(this)));
  LiveCaptionBrowserTest::SetUpOnMainThread();
  ASSERT_TRUE(embedded_test_server()->Start());
}

void LiveCaptionSpeechRecognitionHostTest::
    CreateLiveCaptionSpeechRecognitionHost(
        content::RenderFrameHost* frame_host) {
  mojo::Remote<media::mojom::SpeechRecognitionRecognizerClient> remote;
  mojo::PendingReceiver<media::mojom::SpeechRecognitionRecognizerClient>
      receiver;
  remote.Bind(receiver.InitWithNewPipeAndPassRemote());
  LiveCaptionSpeechRecognitionHost::Create(frame_host, std::move(receiver));
  remotes_.emplace(frame_host, std::move(remote));
}

void LiveCaptionSpeechRecognitionHostTest::OnSpeechRecognitionRecognitionEvent(
    content::RenderFrameHost* frame_host,
    std::string text,
    bool expected_success,
    bool is_final) {
  remotes_[frame_host]->OnSpeechRecognitionRecognitionEvent(
      media::SpeechRecognitionResult(text, is_final),
      base::BindOnce(
          &LiveCaptionSpeechRecognitionHostTest::DispatchTranscriptionCallback,
          base::Unretained(this), expected_success));
}

void LiveCaptionSpeechRecognitionHostTest::OnLanguageIdentificationEvent(
    content::RenderFrameHost* frame_host,
    const std::string& language,
    const media::mojom::ConfidenceLevel confidence_level,
    const media::mojom::AsrSwitchResult asr_switch_result) {
  remotes_[frame_host]->OnLanguageIdentificationEvent(
      media::mojom::LanguageIdentificationEvent::New(language, confidence_level,
                                                     asr_switch_result));
}

void LiveCaptionSpeechRecognitionHostTest::OnSpeechRecognitionError(
    content::RenderFrameHost* frame_host) {
  remotes_[frame_host]->OnSpeechRecognitionError();
}

bool LiveCaptionSpeechRecognitionHostTest::HasBubbleController() {
  return LiveCaptionControllerFactory::GetForProfile(browser()->profile())
             ->caption_bubble_controller_for_testing() != nullptr;
}

void LiveCaptionSpeechRecognitionHostTest::ExpectIsWidgetVisible(bool visible) {
#if defined(TOOLKIT_VIEWS)
    CaptionBubbleController* bubble_controller =
        LiveCaptionControllerFactory::GetForProfile(browser()->profile())
            ->caption_bubble_controller_for_testing();
    EXPECT_EQ(visible, bubble_controller->IsWidgetVisibleForTesting());
#endif
}

std::vector<std::string>
LiveCaptionSpeechRecognitionHostTest::GetTranslationRequests() {
  return static_cast<MockLiveTranslateController*>(
             LiveTranslateControllerFactory::GetForProfile(
                 browser()->profile()))
      ->GetTranslationRequests();
}

void LiveCaptionSpeechRecognitionHostTest::DispatchTranscriptionCallback(
    bool expected_success,
    bool success) {
  EXPECT_EQ(expected_success, success);
}

// Disabled due to flaky crashes; https://crbug.com/1216304.
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
                       DISABLED_DestroysWithoutCrashing) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  SetLiveCaptionEnabled(true);
  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pandas' coloring helps them camouflage in snowy environments.",
      /* expected_success= */ true);
  base::RunLoop().RunUntilIdle();
  ExpectIsWidgetVisible(true);

  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), GURL("http://www.google.com")));
  content::WaitForLoadStop(
      browser()->tab_strip_model()->GetActiveWebContents());
  content::RenderFrameHost* new_frame_host = browser()
                                                 ->tab_strip_model()
                                                 ->GetActiveWebContents()
                                                 ->GetPrimaryMainFrame();
  // After navigating to a new URL, the main frame should be different from the
  // former frame host.
  CreateLiveCaptionSpeechRecognitionHost(new_frame_host);
  ExpectIsWidgetVisible(false);
  // Test passes if the following line runs without crashing.
  OnSpeechRecognitionRecognitionEvent(new_frame_host,
                                      "Pandas have vertical slits for pupils.",
                                      /* expected_success= */ true);
  base::RunLoop().RunUntilIdle();
  ExpectIsWidgetVisible(true);
}

IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
                       OnSpeechRecognitionRecognitionEvent) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  SetLiveCaptionEnabled(true);
  OnSpeechRecognitionRecognitionEvent(frame_host,
                                      "Pandas learn to climb at 5 months old.",
                                      /* expected_success= */ true);
  base::RunLoop().RunUntilIdle();
  ExpectIsWidgetVisible(true);

  SetLiveCaptionEnabled(false);
  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pandas have an extended wrist bone which they use like a thumb.",
      /* expected_success= */ false);
  base::RunLoop().RunUntilIdle();
}

IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
                       OnLanguageIdentificationEvent) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  SetLiveCaptionEnabled(true);
  OnLanguageIdentificationEvent(
      frame_host, "en-US", media::mojom::ConfidenceLevel::kHighlyConfident,
      media::mojom::AsrSwitchResult::kSwitchSucceeded);
}

IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
                       OnSpeechRecognitionError) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  SetLiveCaptionEnabled(true);
  OnSpeechRecognitionError(frame_host);
}

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
                       MediaEffectivelyFullscreenChanged) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  content::RenderFrameHost* frame_host = web_contents->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);
  EXPECT_TRUE(content::NavigateToURL(
      web_contents, embedded_test_server()->GetURL("/media/fullscreen.html")));

  SetLiveCaptionEnabled(true);
  EXPECT_TRUE(HasBubbleController());

  FullscreenEventsWaiter waiter(web_contents);
  EXPECT_TRUE(content::ExecJs(web_contents, "makeFullscreen('small_video')"));
  waiter.Wait();
  EXPECT_TRUE(HasBubbleController());

  EXPECT_TRUE(content::ExecJs(web_contents, "exitFullscreen()"));
  waiter.Wait();
  EXPECT_TRUE(HasBubbleController());
}
#endif

IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest, LiveTranslate) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  SetLiveCaptionEnabled(true);
  SetLiveTranslateEnabled(true);

  OnSpeechRecognitionRecognitionEvent(
      frame_host, "Elephants can live over 90 years in captivity.",
      /* expected_success= */ true);
  base::RunLoop().RunUntilIdle();
  ExpectIsWidgetVisible(true);
}

IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest, TranslationCache) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  SetLiveCaptionEnabled(true);
  SetLiveTranslateEnabled(true);

  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pomeranians come in 23 different color combinations. Some Pomeranians",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ExpectIsWidgetVisible(true);

  ASSERT_EQ(1u, GetTranslationRequests().size());
  ASSERT_EQ(
      "Pomeranians come in 23 different color combinations. Some Pomeranians",
      GetTranslationRequests().back());

  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pomeranians come in 23 different color combinations. Some Pomeranians",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(2u, GetTranslationRequests().size());
  ASSERT_EQ("Some Pomeranians", GetTranslationRequests().back());

  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pomeranians come in 23 different color combinations. Some Pomeranians "
      "are even tricolored! Are",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(3u, GetTranslationRequests().size());
  ASSERT_EQ("Some Pomeranians are even tricolored! Are",
            GetTranslationRequests().back());

  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pomeranians come in 23 different color combinations. Some Pomeranians "
      "are even tricolored! Are they the cutest dog breed in the",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(4u, GetTranslationRequests().size());
  ASSERT_EQ("Are they the cutest dog breed in the",
            GetTranslationRequests().back());

  OnSpeechRecognitionRecognitionEvent(
      frame_host,
      "Pomeranians come in 23 different color combinations. Some Pomeranians "
      "are even tricolored! Are they the cutest dog breed in the world? "
      "Absolutely.",
      /* expected_success= */ true, /* is_final= */ true);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(5u, GetTranslationRequests().size());
  ASSERT_EQ("Are they the cutest dog breed in the world? Absolutely.",
            GetTranslationRequests().back());

  // The previous final event clears the translation cache.
  OnSpeechRecognitionRecognitionEvent(
      frame_host, "Pomeranians come in 23 different color combinations.",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(6u, GetTranslationRequests().size());
  ASSERT_EQ("Pomeranians come in 23 different color combinations.",
            GetTranslationRequests().back());

  // Ensure that cached strings aren't retrieved out of order.
  OnSpeechRecognitionRecognitionEvent(frame_host, "First sentence. Second",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  OnSpeechRecognitionRecognitionEvent(frame_host, "Third sentence. Fourth",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(8u, GetTranslationRequests().size());
  OnSpeechRecognitionRecognitionEvent(
      frame_host, "First sentence. Second sentence. Third sentence.",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(9u, GetTranslationRequests().size());
  ASSERT_EQ("Second sentence. Third sentence.",
            GetTranslationRequests().back());

  // Ensure that partial sentences aren't cached.
  OnSpeechRecognitionRecognitionEvent(frame_host, "Fourth sentence",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  OnSpeechRecognitionRecognitionEvent(frame_host, "Fourth sentence",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(11u, GetTranslationRequests().size());

  // Ensure that punctuation marks aren't cached.
  OnSpeechRecognitionRecognitionEvent(frame_host, "Possums can play dead! Wow",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(12u, GetTranslationRequests().size());
  ASSERT_EQ("Possums can play dead! Wow", GetTranslationRequests().back());

  OnSpeechRecognitionRecognitionEvent(frame_host, "Possums can play dead? Wow",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(13u, GetTranslationRequests().size());
  ASSERT_EQ("Wow", GetTranslationRequests().back());

  // Ensure that phrases are cached without capitalization.
  OnSpeechRecognitionRecognitionEvent(
      frame_host, "Possums can play DEAD? Amazing",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(14u, GetTranslationRequests().size());
  ASSERT_EQ("Amazing", GetTranslationRequests().back());

  // Ensure that strings are cached without whitespace.
  OnSpeechRecognitionRecognitionEvent(
      frame_host, "Flying squirrels can glide up to 300 feet. Wow",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(15u, GetTranslationRequests().size());
  ASSERT_EQ("Flying squirrels can glide up to 300 feet. Wow",
            GetTranslationRequests().back());
  OnSpeechRecognitionRecognitionEvent(
      frame_host, "Flying squirrels can glide up to 300 feet.\nThat's so far",
      /* expected_success= */ true, /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(16u, GetTranslationRequests().size());
  ASSERT_EQ("That's so far", GetTranslationRequests().back());
}

IN_PROC_BROWSER_TEST_F(LiveCaptionSpeechRecognitionHostTest,
                       IdeographicTranslationCache) {
  content::RenderFrameHost* frame_host = browser()
                                             ->tab_strip_model()
                                             ->GetActiveWebContents()
                                             ->GetPrimaryMainFrame();
  SetLiveCaptionEnabled(true);
  SetLiveTranslateEnabled(true);

  // Ensure that ideographic to non-ideographic translations are not cached.
  browser()->profile()->GetPrefs()->SetString(prefs::kLiveCaptionLanguageCode,
                                              "ja-JP");
  CreateLiveCaptionSpeechRecognitionHost(frame_host);

  OnSpeechRecognitionRecognitionEvent(frame_host,
                                      "Tanuki are canids, similar to dogs but "
                                      "with larger ears and tails. So cool",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  OnSpeechRecognitionRecognitionEvent(frame_host,
                                      "Tanuki are canids, similar to dogs but "
                                      "with larger ears and tails. So cool",
                                      /* expected_success= */ true,
                                      /* is_final= */ false);
  base::RunLoop().RunUntilIdle();
  ASSERT_EQ(2u, GetTranslationRequests().size());
  ASSERT_EQ(
      "Tanuki are canids, similar to dogs but with larger ears and tails. So "
      "cool",
      GetTranslationRequests().back());
}

}  // namespace captions