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
|
// Copyright 2024 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/speech/on_device_speech_recognition_impl.h"
#include "base/rand_util.h"
#include "base/strings/string_util.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/prefs/pref_service.h"
#include "components/soda/constants.h"
#include "components/soda/pref_names.h"
#include "components/soda/soda_installer.h"
#include "content/public/browser/document_user_data.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "media/base/media_switches.h"
#include "media/mojo/mojom/speech_recognizer.mojom.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#if !BUILDFLAG(IS_ANDROID)
#include "components/soda/soda_util.h"
namespace {
const char kOnDeviceLanguagesDownloadedKey[] = "ondevice-languages-downloaded";
// Returns a boolean indicating whether the language is enabled.
bool IsLanguageInstallable(const std::string& language_code,
bool is_soda_binary_installed) {
return base::Contains(
speech::SodaInstaller::GetInstance()->GetLiveCaptionEnabledLanguages(),
language_code);
}
bool IsLanguageInstalled(const std::string& language_code) {
for (const auto& language : g_browser_process->local_state()->GetList(
prefs::kSodaRegisteredLanguagePacks)) {
if (language.GetString() == language_code) {
return true;
}
}
return false;
}
} // namespace
#endif // !BUILDFLAG(IS_ANDROID)
namespace speech {
OnDeviceSpeechRecognitionImpl::~OnDeviceSpeechRecognitionImpl() {
#if !BUILDFLAG(IS_ANDROID)
speech::SodaInstaller* soda_installer = speech::SodaInstaller::GetInstance();
// `soda_installer` is not guaranteed to be valid, since it's possible for
// this class to out-live it. This means that this class cannot use
// ScopedObservation and needs to manage removing the observer itself.
if (soda_installer) {
soda_installer->RemoveObserver(this);
}
#endif // !BUILDFLAG(IS_ANDROID)
}
void OnDeviceSpeechRecognitionImpl::Bind(
mojo::PendingReceiver<media::mojom::OnDeviceSpeechRecognition> receiver) {
receiver_.Bind(std::move(receiver));
}
void OnDeviceSpeechRecognitionImpl::Available(
const std::vector<std::string>& languages,
OnDeviceSpeechRecognitionImpl::AvailableCallback callback) {
#if BUILDFLAG(IS_ANDROID)
std::move(callback).Run(media::mojom::AvailabilityStatus::kUnavailable);
#else
if (!CanRenderFrameHostUseOnDeviceSpeechRecognition()) {
std::move(callback).Run(media::mojom::AvailabilityStatus::kUnavailable);
return;
}
if (languages.empty()) {
std::move(callback).Run(media::mojom::AvailabilityStatus::kUnavailable);
return;
}
media::mojom::AvailabilityStatus overall_status =
media::mojom::AvailabilityStatus::kAvailable;
for (const std::string& language : languages) {
std::optional<speech::SodaLanguagePackComponentConfig> language_config =
speech::GetLanguageComponentConfigMatchingLanguageSubtag(language);
if (!language_config.has_value()) {
std::move(callback).Run(media::mojom::AvailabilityStatus::kUnavailable);
return;
}
// According to the spec, the status returned by this API should be the
// minimum status. I.e., the API returns:
// 'available' if all languages are available
// 'downloading' if all languages are either downloading or available
// 'downloadable' if all languages are either available, downloading, or
// downloadable 'unavailable' in if one or more language is unavailable
media::mojom::AvailabilityStatus status =
GetMaskedAvailabilityStatus(language_config.value().language_name);
if (status < overall_status) {
overall_status = status;
}
}
std::move(callback).Run(overall_status);
#endif // BUILDFLAG(IS_ANDROID)
}
void OnDeviceSpeechRecognitionImpl::Install(
const std::vector<std::string>& languages,
OnDeviceSpeechRecognitionImpl::InstallCallback callback) {
#if BUILDFLAG(IS_ANDROID)
std::move(callback).Run(false);
}
#else
for (const std::string& language : languages) {
std::optional<speech::SodaLanguagePackComponentConfig> language_config =
speech::GetLanguageComponentConfigMatchingLanguageSubtag(language);
if (!language_config.has_value() ||
!IsLanguageInstallable(
language_config.value().language_name,
speech::SodaInstaller::GetInstance()->IsSodaBinaryInstalled())) {
std::move(callback).Run(false);
return;
}
}
if (!CanRenderFrameHostUseOnDeviceSpeechRecognition()) {
std::move(callback).Run(false);
return;
}
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&OnDeviceSpeechRecognitionImpl::InstallLanguageInternal,
weak_ptr_factory_.GetWeakPtr(), languages,
std::move(callback)),
GetDownloadDelay(languages));
}
void OnDeviceSpeechRecognitionImpl::OnSodaInstalled(
speech::LanguageCode language_code) {
ProcessLanguageInstallationUpdate(GetLanguageName(language_code),
/*installation_success=*/true);
}
void OnDeviceSpeechRecognitionImpl::OnSodaInstallError(
speech::LanguageCode language_code,
speech::SodaInstaller::ErrorCode error_code) {
ProcessLanguageInstallationUpdate(GetLanguageName(language_code),
/*installation_success=*/false);
}
#endif // !BUILDFLAG(IS_ANDROID)
OnDeviceSpeechRecognitionImpl::OnDeviceSpeechRecognitionImpl(
content::RenderFrameHost* frame_host)
: content::DocumentUserData<OnDeviceSpeechRecognitionImpl>(frame_host) {
#if !BUILDFLAG(IS_ANDROID)
speech::SodaInstaller* soda_installer = speech::SodaInstaller::GetInstance();
if (soda_installer) {
soda_installer->AddObserver(this);
}
#endif // !BUILDFLAG(IS_ANDROID)
}
bool OnDeviceSpeechRecognitionImpl::
CanRenderFrameHostUseOnDeviceSpeechRecognition() {
if (render_frame_host().GetStoragePartition() !=
render_frame_host().GetBrowserContext()->GetDefaultStoragePartition()) {
return !render_frame_host().GetLastCommittedURL().SchemeIsHTTPOrHTTPS();
}
return true;
}
#if !BUILDFLAG(IS_ANDROID)
void OnDeviceSpeechRecognitionImpl::InstallLanguageInternal(
const std::vector<std::string>& languages,
OnDeviceSpeechRecognitionImpl::InstallCallback callback) {
std::set<std::string> language_names_key;
for (const std::string& subtag : languages) {
std::optional<speech::SodaLanguagePackComponentConfig> lang_config =
speech::GetLanguageComponentConfigMatchingLanguageSubtag(subtag);
if (lang_config.has_value()) {
language_names_key.insert(lang_config.value().language_name);
}
}
if (language_names_key.empty()) {
std::move(callback).Run(false);
return;
}
language_installation_callbacks_[language_names_key].push_back(
std::move(callback));
// `InstallSoda` will only install the SODA binary if it is not already
// installed.
speech::SodaInstaller::GetInstance()->InstallSoda(
g_browser_process->local_state());
// `InstallLanguage` will only install languages that are not already
// installed.
for (const std::string& language : language_names_key) {
speech::SodaInstaller::GetInstance()->InstallLanguage(
language, g_browser_process->local_state());
SetOnDeviceLanguageDownloaded(language);
}
}
void OnDeviceSpeechRecognitionImpl::ProcessLanguageInstallationUpdate(
const std::string& language,
bool installation_success) {
for (auto it = language_installation_callbacks_.begin();
it != language_installation_callbacks_.end();) {
std::set<std::string> pending_languages_key = it->first;
if (pending_languages_key.count(language)) {
// This callback group was waiting for the processed `language`.
std::list<InstallCallback> moved_callbacks = std::move(it->second);
it = language_installation_callbacks_.erase(it);
if (!installation_success) {
// Installation failed for this language; fail all callbacks in this
// group.
for (auto& callback : moved_callbacks) {
std::move(callback).Run(false);
}
} else {
// Installation succeeded for this language.
// Remove it from the pending set for this group.
std::set<std::string> updated_key = pending_languages_key;
updated_key.erase(language);
if (updated_key.empty()) {
// All languages for this group are now installed.
for (auto& callback : moved_callbacks) {
std::move(callback).Run(true);
}
} else {
// Still waiting for other languages in this group.
// Re-insert with the updated key, merging if the key now matches an
// existing one.
auto [inserted_it, success] =
language_installation_callbacks_.emplace(
std::move(updated_key), std::list<InstallCallback>());
inserted_it->second.splice(inserted_it->second.end(),
moved_callbacks);
}
}
} else {
// This group of callbacks was not waiting for the current `language`.
++it;
}
}
}
base::Value
OnDeviceSpeechRecognitionImpl::GetOnDeviceLanguagesDownloadedValue() {
GURL url = render_frame_host().GetLastCommittedOrigin().GetURL();
return HostContentSettingsMapFactory::GetForProfile(
render_frame_host().GetBrowserContext())
->GetWebsiteSetting(url, url,
ContentSettingsType::
ON_DEVICE_SPEECH_RECOGNITION_LANGUAGES_DOWNLOADED,
/*info=*/nullptr);
}
void OnDeviceSpeechRecognitionImpl::
SetOnDeviceLanguagesDownloadedContentSetting(
base::Value on_device_languages_downloaded) {
GURL url = render_frame_host().GetLastCommittedOrigin().GetURL();
HostContentSettingsMapFactory::GetForProfile(
render_frame_host().GetBrowserContext())
->SetWebsiteSettingDefaultScope(
url, url,
ContentSettingsType::
ON_DEVICE_SPEECH_RECOGNITION_LANGUAGES_DOWNLOADED,
std::move(on_device_languages_downloaded));
}
media::mojom::AvailabilityStatus
OnDeviceSpeechRecognitionImpl::GetMaskedAvailabilityStatus(
const std::string& language) {
media::mojom::AvailabilityStatus availability_status =
IsOnDeviceSpeechRecognitionAvailable(language);
if (availability_status == media::mojom::AvailabilityStatus::kAvailable &&
!HasOnDeviceLanguageDownloaded(language)) {
return media::mojom::AvailabilityStatus::kDownloadable;
}
return availability_status;
}
bool OnDeviceSpeechRecognitionImpl::HasOnDeviceLanguageDownloaded(
const std::string& language) {
base::Value on_device_languages_downloaded_value =
GetOnDeviceLanguagesDownloadedValue();
if (on_device_languages_downloaded_value.is_dict()) {
return on_device_languages_downloaded_value.GetDict()
.EnsureList(kOnDeviceLanguagesDownloadedKey)
->contains(language);
}
return false;
}
void OnDeviceSpeechRecognitionImpl::SetOnDeviceLanguageDownloaded(
const std::string& language) {
base::Value on_device_languages_downloaded_value =
GetOnDeviceLanguagesDownloadedValue();
// Initialize a list to store data, if none exists.
if (!on_device_languages_downloaded_value.is_dict()) {
on_device_languages_downloaded_value = base::Value(base::Value::Dict());
}
// Update or initialize the list of targets for the source language.
base::Value::List* on_device_languages_downloaded_list =
on_device_languages_downloaded_value.GetDict().EnsureList(
kOnDeviceLanguagesDownloadedKey);
if (!on_device_languages_downloaded_list->contains(language)) {
on_device_languages_downloaded_list->Append(language);
}
SetOnDeviceLanguagesDownloadedContentSetting(
std::move(on_device_languages_downloaded_value));
}
base::TimeDelta OnDeviceSpeechRecognitionImpl::GetDownloadDelay(
const std::vector<std::string>& languages) {
for (const std::string& language_subtag : languages) {
std::optional<speech::SodaLanguagePackComponentConfig> lang_config =
speech::GetLanguageComponentConfigMatchingLanguageSubtag(
language_subtag);
if (!lang_config.has_value()) {
// If the subtag is invalid or doesn't map to a SODA language,
// skip it for delay calculation.
continue;
}
const std::string& soda_language_name = lang_config.value().language_name;
// Check if SODA is already installed for the given language. If it is and
// the origin isn't supposed to know that, then add a delay to simulate a
// real download before proceeding.
if (GetMaskedAvailabilityStatus(soda_language_name) ==
media::mojom::AvailabilityStatus::kDownloadable &&
IsLanguageInstalled(soda_language_name)) {
return base::RandTimeDelta(base::Seconds(2), base::Seconds(3));
}
}
return base::TimeDelta();
}
#endif // !BUILDFLAG(IS_ANDROID)
DOCUMENT_USER_DATA_KEY_IMPL(OnDeviceSpeechRecognitionImpl);
} // namespace speech
|