DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (1aeaa33a64f9)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsISpeechService.h"
#include "nsServiceManagerUtils.h"
#include "nsCategoryManagerUtils.h"

#include "MediaPrefs.h"
#include "SpeechSynthesisUtterance.h"
#include "SpeechSynthesisVoice.h"
#include "nsSynthVoiceRegistry.h"
#include "nsSpeechTask.h"
#include "AudioChannelService.h"

#include "nsString.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/intl/LocaleService.h"
#include "mozilla/Unused.h"

#include "SpeechSynthesisChild.h"
#include "SpeechSynthesisParent.h"

using mozilla::intl::LocaleService;

#undef LOG
extern mozilla::LogModule* GetSpeechSynthLog();
#define LOG(type, msg) MOZ_LOG(GetSpeechSynthLog(), type, msg)

namespace {

void GetAllSpeechSynthActors(
    InfallibleTArray<mozilla::dom::SpeechSynthesisParent*>& aActors) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aActors.IsEmpty());

  AutoTArray<mozilla::dom::ContentParent*, 20> contentActors;
  mozilla::dom::ContentParent::GetAll(contentActors);

  for (uint32_t contentIndex = 0; contentIndex < contentActors.Length();
       ++contentIndex) {
    MOZ_ASSERT(contentActors[contentIndex]);

    AutoTArray<mozilla::dom::PSpeechSynthesisParent*, 5> speechsynthActors;
    contentActors[contentIndex]->ManagedPSpeechSynthesisParent(
        speechsynthActors);

    for (uint32_t speechsynthIndex = 0;
         speechsynthIndex < speechsynthActors.Length(); ++speechsynthIndex) {
      MOZ_ASSERT(speechsynthActors[speechsynthIndex]);

      mozilla::dom::SpeechSynthesisParent* actor =
          static_cast<mozilla::dom::SpeechSynthesisParent*>(
              speechsynthActors[speechsynthIndex]);
      aActors.AppendElement(actor);
    }
  }
}

}  // namespace

namespace mozilla {
namespace dom {

// VoiceData

class VoiceData final {
 private:
  // Private destructor, to discourage deletion outside of Release():
  ~VoiceData() {}

 public:
  VoiceData(nsISpeechService* aService, const nsAString& aUri,
            const nsAString& aName, const nsAString& aLang, bool aIsLocal,
            bool aQueuesUtterances)
      : mService(aService),
        mUri(aUri),
        mName(aName),
        mLang(aLang),
        mIsLocal(aIsLocal),
        mIsQueued(aQueuesUtterances) {}

  NS_INLINE_DECL_REFCOUNTING(VoiceData)

  nsCOMPtr<nsISpeechService> mService;

  nsString mUri;

  nsString mName;

  nsString mLang;

  bool mIsLocal;

  bool mIsQueued;
};

// GlobalQueueItem

class GlobalQueueItem final {
 private:
  // Private destructor, to discourage deletion outside of Release():
  ~GlobalQueueItem() {}

 public:
  GlobalQueueItem(VoiceData* aVoice, nsSpeechTask* aTask,
                  const nsAString& aText, const float& aVolume,
                  const float& aRate, const float& aPitch)
      : mVoice(aVoice),
        mTask(aTask),
        mText(aText),
        mVolume(aVolume),
        mRate(aRate),
        mPitch(aPitch) {}

  NS_INLINE_DECL_REFCOUNTING(GlobalQueueItem)

  RefPtr<VoiceData> mVoice;

  RefPtr<nsSpeechTask> mTask;

  nsString mText;

  float mVolume;

  float mRate;

  float mPitch;

  bool mIsLocal;
};

// nsSynthVoiceRegistry

static StaticRefPtr<nsSynthVoiceRegistry> gSynthVoiceRegistry;

NS_IMPL_ISUPPORTS(nsSynthVoiceRegistry, nsISynthVoiceRegistry)

nsSynthVoiceRegistry::nsSynthVoiceRegistry()
    : mSpeechSynthChild(nullptr), mUseGlobalQueue(false), mIsSpeaking(false) {
  if (XRE_IsContentProcess()) {
    mSpeechSynthChild = new SpeechSynthesisChild();
    ContentChild::GetSingleton()->SendPSpeechSynthesisConstructor(
        mSpeechSynthChild);
  }
}

nsSynthVoiceRegistry::~nsSynthVoiceRegistry() {
  LOG(LogLevel::Debug, ("~nsSynthVoiceRegistry"));

  // mSpeechSynthChild's lifecycle is managed by the Content protocol.
  mSpeechSynthChild = nullptr;

  mUriVoiceMap.Clear();
}

nsSynthVoiceRegistry* nsSynthVoiceRegistry::GetInstance() {
  MOZ_ASSERT(NS_IsMainThread());

  if (!gSynthVoiceRegistry) {
    gSynthVoiceRegistry = new nsSynthVoiceRegistry();
    ClearOnShutdown(&gSynthVoiceRegistry);
    if (XRE_IsParentProcess()) {
      // Start up all speech synth services.
      NS_CreateServicesFromCategory(NS_SPEECH_SYNTH_STARTED, nullptr,
                                    NS_SPEECH_SYNTH_STARTED);
    }
  }

  return gSynthVoiceRegistry;
}

already_AddRefed<nsSynthVoiceRegistry>
nsSynthVoiceRegistry::GetInstanceForService() {
  RefPtr<nsSynthVoiceRegistry> registry = GetInstance();

  return registry.forget();
}

bool nsSynthVoiceRegistry::SendInitialVoicesAndState(
    SpeechSynthesisParent* aParent) {
  MOZ_ASSERT(XRE_IsParentProcess());

  InfallibleTArray<RemoteVoice> voices;
  InfallibleTArray<nsString> defaults;

  for (uint32_t i = 0; i < mVoices.Length(); ++i) {
    RefPtr<VoiceData> voice = mVoices[i];

    voices.AppendElement(RemoteVoice(voice->mUri, voice->mName, voice->mLang,
                                     voice->mIsLocal, voice->mIsQueued));
  }

  for (uint32_t i = 0; i < mDefaultVoices.Length(); ++i) {
    defaults.AppendElement(mDefaultVoices[i]->mUri);
  }

  return aParent->SendInitialVoicesAndState(voices, defaults, IsSpeaking());
}

void nsSynthVoiceRegistry::RecvInitialVoicesAndState(
    const nsTArray<RemoteVoice>& aVoices, const nsTArray<nsString>& aDefaults,
    const bool& aIsSpeaking) {
  // We really should have a local instance since this is a directed response to
  // an Init() call.
  MOZ_ASSERT(gSynthVoiceRegistry);

  for (uint32_t i = 0; i < aVoices.Length(); ++i) {
    RemoteVoice voice = aVoices[i];
    gSynthVoiceRegistry->AddVoiceImpl(nullptr, voice.voiceURI(), voice.name(),
                                      voice.lang(), voice.localService(),
                                      voice.queued());
  }

  for (uint32_t i = 0; i < aDefaults.Length(); ++i) {
    gSynthVoiceRegistry->SetDefaultVoice(aDefaults[i], true);
  }

  gSynthVoiceRegistry->mIsSpeaking = aIsSpeaking;

  if (aVoices.Length()) {
    gSynthVoiceRegistry->NotifyVoicesChanged();
  }
}

void nsSynthVoiceRegistry::RecvRemoveVoice(const nsAString& aUri) {
  // If we dont have a local instance of the registry yet, we will recieve
  // current voices at contruction time.
  if (!gSynthVoiceRegistry) {
    return;
  }

  gSynthVoiceRegistry->RemoveVoice(nullptr, aUri);
}

void nsSynthVoiceRegistry::RecvAddVoice(const RemoteVoice& aVoice) {
  // If we dont have a local instance of the registry yet, we will recieve
  // current voices at contruction time.
  if (!gSynthVoiceRegistry) {
    return;
  }

  gSynthVoiceRegistry->AddVoiceImpl(nullptr, aVoice.voiceURI(), aVoice.name(),
                                    aVoice.lang(), aVoice.localService(),
                                    aVoice.queued());
}

void nsSynthVoiceRegistry::RecvSetDefaultVoice(const nsAString& aUri,
                                               bool aIsDefault) {
  // If we dont have a local instance of the registry yet, we will recieve
  // current voices at contruction time.
  if (!gSynthVoiceRegistry) {
    return;
  }

  gSynthVoiceRegistry->SetDefaultVoice(aUri, aIsDefault);
}

void nsSynthVoiceRegistry::RecvIsSpeakingChanged(bool aIsSpeaking) {
  // If we dont have a local instance of the registry yet, we will get the
  // speaking state on construction.
  if (!gSynthVoiceRegistry) {
    return;
  }

  gSynthVoiceRegistry->mIsSpeaking = aIsSpeaking;
}

void nsSynthVoiceRegistry::RecvNotifyVoicesChanged() {
  // If we dont have a local instance of the registry yet, we don't care.
  if (!gSynthVoiceRegistry) {
    return;
  }

  gSynthVoiceRegistry->NotifyVoicesChanged();
}

NS_IMETHODIMP
nsSynthVoiceRegistry::AddVoice(nsISpeechService* aService,
                               const nsAString& aUri, const nsAString& aName,
                               const nsAString& aLang, bool aLocalService,
                               bool aQueuesUtterances) {
  LOG(LogLevel::Debug,
      ("nsSynthVoiceRegistry::AddVoice uri='%s' name='%s' lang='%s' local=%s "
       "queued=%s",
       NS_ConvertUTF16toUTF8(aUri).get(), NS_ConvertUTF16toUTF8(aName).get(),
       NS_ConvertUTF16toUTF8(aLang).get(), aLocalService ? "true" : "false",
       aQueuesUtterances ? "true" : "false"));

  if (NS_WARN_IF(XRE_IsContentProcess())) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  return AddVoiceImpl(aService, aUri, aName, aLang, aLocalService,
                      aQueuesUtterances);
}

NS_IMETHODIMP
nsSynthVoiceRegistry::RemoveVoice(nsISpeechService* aService,
                                  const nsAString& aUri) {
  LOG(LogLevel::Debug, ("nsSynthVoiceRegistry::RemoveVoice uri='%s' (%s)",
                        NS_ConvertUTF16toUTF8(aUri).get(),
                        (XRE_IsContentProcess()) ? "child" : "parent"));

  bool found = false;
  VoiceData* retval = mUriVoiceMap.GetWeak(aUri, &found);

  if (NS_WARN_IF(!(found))) {
    return NS_ERROR_NOT_AVAILABLE;
  }
  if (NS_WARN_IF(!(aService == retval->mService))) {
    return NS_ERROR_INVALID_ARG;
  }

  mVoices.RemoveElement(retval);
  mDefaultVoices.RemoveElement(retval);
  mUriVoiceMap.Remove(aUri);

  if (retval->mIsQueued && !MediaPrefs::WebSpeechForceGlobal()) {
    // Check if this is the last queued voice, and disable the global queue if
    // it is.
    bool queued = false;
    for (uint32_t i = 0; i < mVoices.Length(); i++) {
      VoiceData* voice = mVoices[i];
      if (voice->mIsQueued) {
        queued = true;
        break;
      }
    }
    if (!queued) {
      mUseGlobalQueue = false;
    }
  }

  nsTArray<SpeechSynthesisParent*> ssplist;
  GetAllSpeechSynthActors(ssplist);

  for (uint32_t i = 0; i < ssplist.Length(); ++i)
    Unused << ssplist[i]->SendVoiceRemoved(nsString(aUri));

  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::NotifyVoicesChanged() {
  if (XRE_IsParentProcess()) {
    nsTArray<SpeechSynthesisParent*> ssplist;
    GetAllSpeechSynthActors(ssplist);

    for (uint32_t i = 0; i < ssplist.Length(); ++i)
      Unused << ssplist[i]->SendNotifyVoicesChanged();
  }

  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  if (NS_WARN_IF(!(obs))) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  obs->NotifyObservers(nullptr, "synth-voices-changed", nullptr);

  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::SetDefaultVoice(const nsAString& aUri, bool aIsDefault) {
  bool found = false;
  VoiceData* retval = mUriVoiceMap.GetWeak(aUri, &found);
  if (NS_WARN_IF(!(found))) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  mDefaultVoices.RemoveElement(retval);

  LOG(LogLevel::Debug,
      ("nsSynthVoiceRegistry::SetDefaultVoice %s %s",
       NS_ConvertUTF16toUTF8(aUri).get(), aIsDefault ? "true" : "false"));

  if (aIsDefault) {
    mDefaultVoices.AppendElement(retval);
  }

  if (XRE_IsParentProcess()) {
    nsTArray<SpeechSynthesisParent*> ssplist;
    GetAllSpeechSynthActors(ssplist);

    for (uint32_t i = 0; i < ssplist.Length(); ++i) {
      Unused << ssplist[i]->SendSetDefaultVoice(nsString(aUri), aIsDefault);
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::GetVoiceCount(uint32_t* aRetval) {
  *aRetval = mVoices.Length();

  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::GetVoice(uint32_t aIndex, nsAString& aRetval) {
  if (NS_WARN_IF(!(aIndex < mVoices.Length()))) {
    return NS_ERROR_INVALID_ARG;
  }

  aRetval = mVoices[aIndex]->mUri;

  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::IsDefaultVoice(const nsAString& aUri, bool* aRetval) {
  bool found;
  VoiceData* voice = mUriVoiceMap.GetWeak(aUri, &found);
  if (NS_WARN_IF(!(found))) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  for (int32_t i = mDefaultVoices.Length(); i > 0;) {
    VoiceData* defaultVoice = mDefaultVoices[--i];

    if (voice->mLang.Equals(defaultVoice->mLang)) {
      *aRetval = voice == defaultVoice;
      return NS_OK;
    }
  }

  *aRetval = false;
  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::IsLocalVoice(const nsAString& aUri, bool* aRetval) {
  bool found;
  VoiceData* voice = mUriVoiceMap.GetWeak(aUri, &found);
  if (NS_WARN_IF(!(found))) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  *aRetval = voice->mIsLocal;
  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::GetVoiceLang(const nsAString& aUri, nsAString& aRetval) {
  bool found;
  VoiceData* voice = mUriVoiceMap.GetWeak(aUri, &found);
  if (NS_WARN_IF(!(found))) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  aRetval = voice->mLang;
  return NS_OK;
}

NS_IMETHODIMP
nsSynthVoiceRegistry::GetVoiceName(const nsAString& aUri, nsAString& aRetval) {
  bool found;
  VoiceData* voice = mUriVoiceMap.GetWeak(aUri, &found);
  if (NS_WARN_IF(!(found))) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  aRetval = voice->mName;
  return NS_OK;
}

nsresult nsSynthVoiceRegistry::AddVoiceImpl(
    nsISpeechService* aService, const nsAString& aUri, const nsAString& aName,
    const nsAString& aLang, bool aLocalService, bool aQueuesUtterances) {
  bool found = false;
  mUriVoiceMap.GetWeak(aUri, &found);
  if (NS_WARN_IF(found)) {
    return NS_ERROR_INVALID_ARG;
  }

  RefPtr<VoiceData> voice = new VoiceData(aService, aUri, aName, aLang,
                                          aLocalService, aQueuesUtterances);

  mVoices.AppendElement(voice);
  mUriVoiceMap.Put(aUri, voice);
  mUseGlobalQueue |= aQueuesUtterances;

  nsTArray<SpeechSynthesisParent*> ssplist;
  GetAllSpeechSynthActors(ssplist);

  if (!ssplist.IsEmpty()) {
    mozilla::dom::RemoteVoice ssvoice(nsString(aUri), nsString(aName),
                                      nsString(aLang), aLocalService,
                                      aQueuesUtterances);

    for (uint32_t i = 0; i < ssplist.Length(); ++i) {
      Unused << ssplist[i]->SendVoiceAdded(ssvoice);
    }
  }

  return NS_OK;
}

bool nsSynthVoiceRegistry::FindVoiceByLang(const nsAString& aLang,
                                           VoiceData** aRetval) {
  nsAString::const_iterator dashPos, start, end;
  aLang.BeginReading(start);
  aLang.EndReading(end);

  while (true) {
    nsAutoString langPrefix(Substring(start, end));

    for (int32_t i = mDefaultVoices.Length(); i > 0;) {
      VoiceData* voice = mDefaultVoices[--i];

      if (StringBeginsWith(voice->mLang, langPrefix)) {
        *aRetval = voice;
        return true;
      }
    }

    for (int32_t i = mVoices.Length(); i > 0;) {
      VoiceData* voice = mVoices[--i];

      if (StringBeginsWith(voice->mLang, langPrefix)) {
        *aRetval = voice;
        return true;
      }
    }

    dashPos = end;
    end = start;

    if (!RFindInReadable(NS_LITERAL_STRING("-"), end, dashPos)) {
      break;
    }
  }

  return false;
}

VoiceData* nsSynthVoiceRegistry::FindBestMatch(const nsAString& aUri,
                                               const nsAString& aLang) {
  if (mVoices.IsEmpty()) {
    return nullptr;
  }

  bool found = false;
  VoiceData* retval = mUriVoiceMap.GetWeak(aUri, &found);

  if (found) {
    LOG(LogLevel::Debug, ("nsSynthVoiceRegistry::FindBestMatch - Matched URI"));
    return retval;
  }

  // Try finding a match for given voice.
  if (!aLang.IsVoid() && !aLang.IsEmpty()) {
    if (FindVoiceByLang(aLang, &retval)) {
      LOG(LogLevel::Debug,
          ("nsSynthVoiceRegistry::FindBestMatch - Matched language (%s ~= %s)",
           NS_ConvertUTF16toUTF8(aLang).get(),
           NS_ConvertUTF16toUTF8(retval->mLang).get()));

      return retval;
    }
  }

  // Try UI language.
  nsAutoCString uiLang;
  LocaleService::GetInstance()->GetAppLocaleAsLangTag(uiLang);

  if (FindVoiceByLang(NS_ConvertASCIItoUTF16(uiLang), &retval)) {
    LOG(LogLevel::Debug,
        ("nsSynthVoiceRegistry::FindBestMatch - Matched UI language (%s ~= %s)",
         uiLang.get(), NS_ConvertUTF16toUTF8(retval->mLang).get()));

    return retval;
  }

  // Try en-US, the language of locale "C"
  if (FindVoiceByLang(NS_LITERAL_STRING("en-US"), &retval)) {
    LOG(LogLevel::Debug, ("nsSynthVoiceRegistry::FindBestMatch - Matched C "
                          "locale language (en-US ~= %s)",
                          NS_ConvertUTF16toUTF8(retval->mLang).get()));

    return retval;
  }

  // The top default voice is better than nothing...
  if (!mDefaultVoices.IsEmpty()) {
    return mDefaultVoices.LastElement();
  }

  return nullptr;
}

already_AddRefed<nsSpeechTask> nsSynthVoiceRegistry::SpeakUtterance(
    SpeechSynthesisUtterance& aUtterance, const nsAString& aDocLang) {
  nsString lang =
      nsString(aUtterance.mLang.IsEmpty() ? aDocLang : aUtterance.mLang);
  nsAutoString uri;

  if (aUtterance.mVoice) {
    aUtterance.mVoice->GetVoiceURI(uri);
  }

  // Get current audio volume to apply speech call
  float volume = aUtterance.Volume();
  RefPtr<AudioChannelService> service = AudioChannelService::GetOrCreate();
  if (service) {
    if (nsCOMPtr<nsPIDOMWindowInner> topWindow = aUtterance.GetOwner()) {
      // TODO : use audio channel agent, open new bug to fix it.
      AudioPlaybackConfig config =
          service->GetMediaConfig(topWindow->GetOuterWindow());
      volume = config.mMuted ? 0.0f : config.mVolume * volume;
    }
  }

  nsCOMPtr<nsPIDOMWindowInner> window = aUtterance.GetOwner();
  nsCOMPtr<nsIDocument> doc = window ? window->GetDoc() : nullptr;

  bool isChrome = nsContentUtils::IsChromeDoc(doc);

  RefPtr<nsSpeechTask> task;
  if (XRE_IsContentProcess()) {
    task = new SpeechTaskChild(&aUtterance, isChrome);
    SpeechSynthesisRequestChild* actor = new SpeechSynthesisRequestChild(
        static_cast<SpeechTaskChild*>(task.get()));
    mSpeechSynthChild->SendPSpeechSynthesisRequestConstructor(
        actor, aUtterance.mText, lang, uri, volume, aUtterance.Rate(),
        aUtterance.Pitch(), isChrome);
  } else {
    task = new nsSpeechTask(&aUtterance, isChrome);
    Speak(aUtterance.mText, lang, uri, volume, aUtterance.Rate(),
          aUtterance.Pitch(), task);
  }

  return task.forget();
}

void nsSynthVoiceRegistry::Speak(const nsAString& aText, const nsAString& aLang,
                                 const nsAString& aUri, const float& aVolume,
                                 const float& aRate, const float& aPitch,
                                 nsSpeechTask* aTask) {
  MOZ_ASSERT(XRE_IsParentProcess());

  if (!aTask->IsChrome() && nsContentUtils::ShouldResistFingerprinting()) {
    aTask->ForceError(0, 0);
    return;
  }

  VoiceData* voice = FindBestMatch(aUri, aLang);

  if (!voice) {
    NS_WARNING("No voices found.");
    aTask->ForceError(0, 0);
    return;
  }

  aTask->SetChosenVoiceURI(voice->mUri);

  if (mUseGlobalQueue || MediaPrefs::WebSpeechForceGlobal()) {
    LOG(LogLevel::Debug,
        ("nsSynthVoiceRegistry::Speak queueing text='%s' lang='%s' uri='%s' "
         "rate=%f pitch=%f",
         NS_ConvertUTF16toUTF8(aText).get(), NS_ConvertUTF16toUTF8(aLang).get(),
         NS_ConvertUTF16toUTF8(aUri).get(), aRate, aPitch));
    RefPtr<GlobalQueueItem> item =
        new GlobalQueueItem(voice, aTask, aText, aVolume, aRate, aPitch);
    mGlobalQueue.AppendElement(item);

    if (mGlobalQueue.Length() == 1) {
      SpeakImpl(item->mVoice, item->mTask, item->mText, item->mVolume,
                item->mRate, item->mPitch);
    }
  } else {
    SpeakImpl(voice, aTask, aText, aVolume, aRate, aPitch);
  }
}

void nsSynthVoiceRegistry::SpeakNext() {
  MOZ_ASSERT(XRE_IsParentProcess());

  LOG(LogLevel::Debug,
      ("nsSynthVoiceRegistry::SpeakNext %d", mGlobalQueue.IsEmpty()));

  SetIsSpeaking(false);

  if (mGlobalQueue.IsEmpty()) {
    return;
  }

  mGlobalQueue.RemoveElementAt(0);

  while (!mGlobalQueue.IsEmpty()) {
    RefPtr<GlobalQueueItem> item = mGlobalQueue.ElementAt(0);
    if (item->mTask->IsPreCanceled()) {
      mGlobalQueue.RemoveElementAt(0);
      continue;
    }
    if (!item->mTask->IsPrePaused()) {
      SpeakImpl(item->mVoice, item->mTask, item->mText, item->mVolume,
                item->mRate, item->mPitch);
    }
    break;
  }
}

void nsSynthVoiceRegistry::ResumeQueue() {
  MOZ_ASSERT(XRE_IsParentProcess());
  LOG(LogLevel::Debug,
      ("nsSynthVoiceRegistry::ResumeQueue %d", mGlobalQueue.IsEmpty()));

  if (mGlobalQueue.IsEmpty()) {
    return;
  }

  RefPtr<GlobalQueueItem> item = mGlobalQueue.ElementAt(0);
  if (!item->mTask->IsPrePaused()) {
    SpeakImpl(item->mVoice, item->mTask, item->mText, item->mVolume,
              item->mRate, item->mPitch);
  }
}

bool nsSynthVoiceRegistry::IsSpeaking() { return mIsSpeaking; }

void nsSynthVoiceRegistry::SetIsSpeaking(bool aIsSpeaking) {
  MOZ_ASSERT(XRE_IsParentProcess());

  // Only set to 'true' if global queue is enabled.
  mIsSpeaking =
      aIsSpeaking && (mUseGlobalQueue || MediaPrefs::WebSpeechForceGlobal());

  nsTArray<SpeechSynthesisParent*> ssplist;
  GetAllSpeechSynthActors(ssplist);
  for (uint32_t i = 0; i < ssplist.Length(); ++i) {
    Unused << ssplist[i]->SendIsSpeakingChanged(aIsSpeaking);
  }
}

void nsSynthVoiceRegistry::SpeakImpl(VoiceData* aVoice, nsSpeechTask* aTask,
                                     const nsAString& aText,
                                     const float& aVolume, const float& aRate,
                                     const float& aPitch) {
  LOG(LogLevel::Debug,
      ("nsSynthVoiceRegistry::SpeakImpl queueing text='%s' uri='%s' rate=%f "
       "pitch=%f",
       NS_ConvertUTF16toUTF8(aText).get(),
       NS_ConvertUTF16toUTF8(aVoice->mUri).get(), aRate, aPitch));

  aTask->Init();

  if (NS_FAILED(aVoice->mService->Speak(aText, aVoice->mUri, aVolume, aRate,
                                        aPitch, aTask))) {
    aTask->DispatchError(0, 0);
  }
}

}  // namespace dom
}  // namespace mozilla