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 (c68fe15a81fc)

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
/* This Source Code Form is subject to the terms of the Mozilla Public
/* 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 "MediaStatusManager.h"

#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/MediaControlUtils.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/StaticPrefs_media.h"
#include "mozilla/StaticPrefs_media.h"
#include "nsIChromeRegistry.h"
#include "nsIObserverService.h"
#include "nsIXULAppInfo.h"

#ifdef MOZ_PLACES
#ifdef MOZ_PLACES
#  include "nsIFaviconService.h"
#endif  // MOZ_PLACES

extern mozilla::LazyLogModule gMediaControlLog;


// avoid redefined macro in unified build
#undef LOG
#define LOG(msg, ...)                        \
  MOZ_LOG(gMediaControlLog, LogLevel::Debug, \
          ("MediaStatusManager=%p, " msg, this, ##__VA_ARGS__))
          ("MediaStatusManager=%p, " msg, this, ##__VA_ARGS__))

namespace mozilla {
namespace dom {

static bool IsMetadataEmpty(const Maybe<MediaMetadataBase>& aMetadata) {
  // Media session's metadata is null.
  if (!aMetadata) {
  if (!aMetadata) {
    return true;
  }

  // All attirbutes in metadata are empty.
  // https://w3c.github.io/mediasession/#empty-metadata
  // https://w3c.github.io/mediasession/#empty-metadata
  const MediaMetadataBase& metadata = *aMetadata;
  return metadata.mTitle.IsEmpty() && metadata.mArtist.IsEmpty() &&
         metadata.mAlbum.IsEmpty() && metadata.mArtwork.IsEmpty();
}


MediaStatusManager::MediaStatusManager(uint64_t aBrowsingContextId)
    : mTopLevelBrowsingContextId(aBrowsingContextId) {
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess(),
                        "MediaStatusManager only runs on Chrome process!");
}
}

void MediaStatusManager::NotifyMediaAudibleChanged(uint64_t aBrowsingContextId,
                                                   MediaAudibleState aState) {
  Maybe<uint64_t> oldAudioFocusOwnerId =
  Maybe<uint64_t> oldAudioFocusOwnerId =
      mPlaybackStatusDelegate.GetAudioFocusOwnerContextId();
  mPlaybackStatusDelegate.UpdateMediaAudibleState(aBrowsingContextId, aState);
  Maybe<uint64_t> newAudioFocusOwnerId =
      mPlaybackStatusDelegate.GetAudioFocusOwnerContextId();
  if (oldAudioFocusOwnerId != newAudioFocusOwnerId) {
  if (oldAudioFocusOwnerId != newAudioFocusOwnerId) {
    HandleAudioFocusOwnerChanged(newAudioFocusOwnerId);
  }
}

void MediaStatusManager::NotifySessionCreated(uint64_t aBrowsingContextId) {
void MediaStatusManager::NotifySessionCreated(uint64_t aBrowsingContextId) {
  if (mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
    return;
    return;
  }

  LOG("Session %" PRIu64 " has been created", aBrowsingContextId);
  mMediaSessionInfoMap.Put(aBrowsingContextId, MediaSessionInfo::EmptyInfo());
  if (IsSessionOwningAudioFocus(aBrowsingContextId)) {
  if (IsSessionOwningAudioFocus(aBrowsingContextId)) {
    SetActiveMediaSessionContextId(aBrowsingContextId);
  }
}

void MediaStatusManager::NotifySessionDestroyed(uint64_t aBrowsingContextId) {
void MediaStatusManager::NotifySessionDestroyed(uint64_t aBrowsingContextId) {
  if (!mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
    return;
  }
  LOG("Session %" PRIu64 " has been destroyed", aBrowsingContextId);
  LOG("Session %" PRIu64 " has been destroyed", aBrowsingContextId);
  mMediaSessionInfoMap.Remove(aBrowsingContextId);
  if (mActiveMediaSessionContextId &&
      *mActiveMediaSessionContextId == aBrowsingContextId) {
    ClearActiveMediaSessionContextIdIfNeeded();
  }
  }
}

void MediaStatusManager::UpdateMetadata(
    uint64_t aBrowsingContextId, const Maybe<MediaMetadataBase>& aMetadata) {
  if (!mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
  if (!mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
    return;
  }

  MediaSessionInfo* info = mMediaSessionInfoMap.GetValue(aBrowsingContextId);
  if (IsMetadataEmpty(aMetadata)) {
  if (IsMetadataEmpty(aMetadata)) {
    LOG("Reset metadata for session %" PRIu64, aBrowsingContextId);
    info->mMetadata.reset();
  } else {
    LOG("Update metadata for session %" PRIu64 " title=%s artist=%s album=%s",
        aBrowsingContextId, NS_ConvertUTF16toUTF8((*aMetadata).mTitle).get(),
        NS_ConvertUTF16toUTF8(aMetadata->mArtist).get(),
        NS_ConvertUTF16toUTF8(aMetadata->mAlbum).get());
    info->mMetadata = aMetadata;
    info->mMetadata = aMetadata;
  }
  // Only notify the event if the changed metadata belongs to the active media
  // session.
  if (!mActiveMediaSessionContextId ||
    if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
      *mActiveMediaSessionContextId == aBrowsingContextId) {
    mMetadataChangedEvent.Notify(GetCurrentMediaMetadata());
  }
  if (StaticPrefs::media_mediacontrol_testingevents_enabled()) {
    if (nsCOMPtr<nsIObserverService> obs = services::GetObserverService()) {
}
      obs->NotifyObservers(nullptr, "media-session-controller-metadata-changed",
                           nullptr);
    }
  }
}
  if (!aBrowsingContextId) {

void MediaStatusManager::HandleAudioFocusOwnerChanged(
    Maybe<uint64_t>& aBrowsingContextId) {
  // No one is holding the audio focus.
  if (!aBrowsingContextId) {
  // This owner of audio focus doesn't have media session, so we should deactive
    LOG("No one is owning audio focus");
    return ClearActiveMediaSessionContextIdIfNeeded();
  }

  // This owner of audio focus doesn't have media session, so we should deactive
  }
  // the active session because the active session must own the audio focus.
  if (!mMediaSessionInfoMap.Contains(*aBrowsingContextId)) {
    LOG("The owner of audio focus doesn't have media session");
    return ClearActiveMediaSessionContextIdIfNeeded();
  }


  // This owner has media session so it should become an active session context.
  SetActiveMediaSessionContextId(*aBrowsingContextId);
}

    LOG("Active session context %" PRIu64 " keeps unchanged",
void MediaStatusManager::SetActiveMediaSessionContextId(
    uint64_t aBrowsingContextId) {
  if (mActiveMediaSessionContextId &&
      *mActiveMediaSessionContextId == aBrowsingContextId) {
    LOG("Active session context %" PRIu64 " keeps unchanged",
  LOG("context %" PRIu64 " becomes active session context",
        *mActiveMediaSessionContextId);
    return;
  }

  mActiveMediaSessionContextId = Some(aBrowsingContextId);
  LOG("context %" PRIu64 " becomes active session context",
      *mActiveMediaSessionContextId);
  mMetadataChangedEvent.Notify(GetCurrentMediaMetadata());
  mSupportedActionsChangedEvent.Notify(GetSupportedActions());
  LOG("Clear active session context");
}

void MediaStatusManager::ClearActiveMediaSessionContextIdIfNeeded() {
  if (!mActiveMediaSessionContextId) {
    return;
bool MediaStatusManager::IsSessionOwningAudioFocus(
  }
  LOG("Clear active session context");
  mActiveMediaSessionContextId.reset();
  mMetadataChangedEvent.Notify(GetCurrentMediaMetadata());
  mSupportedActionsChangedEvent.Notify(GetSupportedActions());
                             : false;
}

bool MediaStatusManager::IsSessionOwningAudioFocus(
    uint64_t aBrowsingContextId) const {
  Maybe<uint64_t> audioFocusContextId =
  metadata.mTitle = GetDefaultTitle();
      mPlaybackStatusDelegate.GetAudioFocusOwnerContextId();
  return audioFocusContextId ? *audioFocusContextId == aBrowsingContextId
                             : false;
}

MediaMetadataBase MediaStatusManager::CreateDefaultMetadata() const {
  MediaMetadataBase metadata;
  metadata.mTitle = GetDefaultTitle();
  metadata.mArtwork.AppendElement()->mSrc = GetDefaultFaviconURL();


  LOG("Default media metadata, title=%s, album src=%s",
      NS_ConvertUTF16toUTF8(metadata.mTitle).get(),
      NS_ConvertUTF16toUTF8(metadata.mArtwork[0].mSrc).get());
  return metadata;
    return EmptyString();
}

nsString MediaStatusManager::GetDefaultTitle() const {
  RefPtr<CanonicalBrowsingContext> bc =
      CanonicalBrowsingContext::Get(mTopLevelBrowsingContextId);
    return EmptyString();
  if (!bc) {
    return EmptyString();
  }

  RefPtr<WindowGlobalParent> globalParent = bc->GetCurrentWindowGlobal();
  if (!globalParent) {
  // expose details about what website the user is browsing on the lockscreen.
    return EmptyString();
  }

  // The media metadata would be shown on the virtual controller interface. For
  // example, on Android, the interface would be shown on both notification bar
            do_GetService("@mozilla.org/xre/app-info;1")) {
  // and lockscreen. Therefore, what information we provide via metadata is
  // quite important, because if we're in private browsing, we don't want to
  // expose details about what website the user is browsing on the lockscreen.
  nsString defaultTitle;
  if (IsInPrivateBrowsing()) {
      defaultTitle.AssignLiteral("Firefox");
    // TODO : maybe need l10n?
    if (nsCOMPtr<nsIXULAppInfo> appInfo =
            do_GetService("@mozilla.org/xre/app-info;1")) {
      nsCString appName;
      appInfo->GetName(appName);
      CopyUTF8toUTF16(appName, defaultTitle);
    } else {
      defaultTitle.AssignLiteral("Firefox");

    }
    defaultTitle.AppendLiteral(" is playing media");
  } else {
    globalParent->GetDocumentTitle(defaultTitle);
  }
  return defaultTitle;
                          NS_LITERAL_CSTRING(FAVICON_DEFAULT_URL));
}

nsString MediaStatusManager::GetDefaultFaviconURL() const {
#ifdef MOZ_PLACES
  nsCOMPtr<nsIURI> faviconURI;
  // to show the icon on virtual controller interface.
  nsresult rv = NS_NewURI(getter_AddRefs(faviconURI),
                          NS_LITERAL_CSTRING(FAVICON_DEFAULT_URL));
  NS_ENSURE_SUCCESS(rv, NS_LITERAL_STRING(""));

  // Convert URI from `chrome://XXX` to `file://XXX` because we would like to
  nsCOMPtr<nsIURI> processedURI;
  // let OS related frameworks, such as SMTC and MPRIS, handle this URL in order
  // to show the icon on virtual controller interface.
  nsCOMPtr<nsIChromeRegistry> regService = services::GetChromeRegistryService();
  if (!regService) {
    return EmptyString();
  }
  return NS_ConvertUTF8toUTF16(spec);
  nsCOMPtr<nsIURI> processedURI;
  regService->ConvertChromeURL(faviconURI, getter_AddRefs(processedURI));

  nsAutoCString spec;
  if (NS_FAILED(processedURI->GetSpec(spec))) {
void MediaStatusManager::SetDeclaredPlaybackState(
    return EmptyString();
  }
  return NS_ConvertUTF8toUTF16(spec);
#endif
  return EmptyString();
}
  MediaSessionInfo* info = mMediaSessionInfoMap.GetValue(aBrowsingContextId);

      ToMediaSessionPlaybackStateStr(info->mDeclaredPlaybackState),
void MediaStatusManager::SetDeclaredPlaybackState(
    uint64_t aBrowsingContextId, MediaSessionPlaybackState aState) {
  if (!mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
    return;
  }

  MediaSessionInfo* info = mMediaSessionInfoMap.GetValue(aBrowsingContextId);
  LOG("SetDeclaredPlaybackState from %s to %s",
      ToMediaSessionPlaybackStateStr(info->mDeclaredPlaybackState),
      ToMediaSessionPlaybackStateStr(aState));
  info->mDeclaredPlaybackState = aState;
  }
  UpdateActualPlaybackState();
}

MediaSessionPlaybackState MediaStatusManager::GetCurrentDeclaredPlaybackState()
    const {
void MediaStatusManager::NotifyMediaPlaybackChanged(uint64_t aBrowsingContextId,
  if (!mActiveMediaSessionContextId) {
    return MediaSessionPlaybackState::None;
  }
  return mMediaSessionInfoMap.Get(*mActiveMediaSessionContextId)
      .mDeclaredPlaybackState;
  mPlaybackStatusDelegate.UpdateMediaPlaybackState(aBrowsingContextId, aState);
}

void MediaStatusManager::NotifyMediaPlaybackChanged(uint64_t aBrowsingContextId,
                                                    MediaPlaybackState aState) {
  LOG("UpdateMediaPlaybackState %s for context %" PRIu64,
  if (mPlaybackStatusDelegate.IsPlaying() == oldPlaying) {
      ToMediaPlaybackStateStr(aState), aBrowsingContextId);
  const bool oldPlaying = mPlaybackStatusDelegate.IsPlaying();
  mPlaybackStatusDelegate.UpdateMediaPlaybackState(aBrowsingContextId, aState);

  // Playback state doesn't change, we don't need to update the guessed playback
  // state. This is used to prevent the state from changing from `none` to
  // `paused` when receiving `MediaPlaybackState::eStarted`.
  if (mPlaybackStatusDelegate.IsPlaying() == oldPlaying) {
  }
    return;
  }
  if (mPlaybackStatusDelegate.IsPlaying()) {
    SetGuessedPlayState(MediaSessionPlaybackState::Playing);
  } else {
    SetGuessedPlayState(MediaSessionPlaybackState::Paused);
  }
  }
}

void MediaStatusManager::SetGuessedPlayState(MediaSessionPlaybackState aState) {
  if (aState == mGuessedPlaybackState) {

    return;
  }
  LOG("SetGuessedPlayState : '%s'", ToMediaSessionPlaybackStateStr(aState));
  mGuessedPlaybackState = aState;
  UpdateActualPlaybackState();
      GetCurrentDeclaredPlaybackState() == MediaSessionPlaybackState::Playing
}

void MediaStatusManager::UpdateActualPlaybackState() {
  // The way to compute the actual playback state is based on the spec.
  // https://w3c.github.io/mediasession/#actual-playback-state
  }
  MediaSessionPlaybackState newState =
      GetCurrentDeclaredPlaybackState() == MediaSessionPlaybackState::Playing
          ? MediaSessionPlaybackState::Playing
          : mGuessedPlaybackState;
  if (mActualPlaybackState == newState) {
}
    return;
  }
  mActualPlaybackState = newState;
  LOG("UpdateActualPlaybackState : '%s'",
      ToMediaSessionPlaybackStateStr(mActualPlaybackState));
  // default metadata which is using website's title and favicon as title and
  HandleActualPlaybackStateChanged();
}

void MediaStatusManager::EnableAction(uint64_t aBrowsingContextId,
                                      MediaSessionAction aAction) {
  if (!mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
    return;
  }
    MediaMetadataBase& metadata = *(info.mMetadata);
  MediaSessionInfo* info = mMediaSessionInfoMap.GetValue(aBrowsingContextId);
  MOZ_DIAGNOSTIC_ASSERT(!info->IsActionSupported(aAction),
                        "Action has already been enabled!");
  LOG("Enable action %s for context %" PRIu64, ToMediaSessionActionStr(aAction),
      aBrowsingContextId);
}
  info->EnableAction(aAction);
  NotifySupportedKeysChangedIfNeeded(aBrowsingContextId);
}

void MediaStatusManager::DisableAction(uint64_t aBrowsingContextId,
  // to use default title and favicon instead in order to prevent showing
                                       MediaSessionAction aAction) {
  if (!mMediaSessionInfoMap.Contains(aBrowsingContextId)) {
    return;
  }
  MediaSessionInfo* info = mMediaSessionInfoMap.GetValue(aBrowsingContextId);
  if (aMetadata.mArtwork.IsEmpty()) {
  MOZ_DIAGNOSTIC_ASSERT(info->IsActionSupported(aAction),
                        "Action hasn't been enabled yet!");
  LOG("Disable action %s for context %" PRIu64,
      ToMediaSessionActionStr(aAction), aBrowsingContextId);
  info->DisableAction(aAction);
bool MediaStatusManager::IsInPrivateBrowsing() const {
  NotifySupportedKeysChangedIfNeeded(aBrowsingContextId);
}

    return false;
void MediaStatusManager::NotifySupportedKeysChangedIfNeeded(
    uint64_t aBrowsingContextId) {
  // Only the active media session's supported actions would be shown in virtual
  // control interface, so we only notify the event when supported actions
  // change happens on the active media session.
  }
  if (!mActiveMediaSessionContextId ||
      *mActiveMediaSessionContextId != aBrowsingContextId) {
    return;
  }
  mSupportedActionsChangedEvent.Notify(GetSupportedActions());
  return mActualPlaybackState;
}

CopyableTArray<MediaSessionAction> MediaStatusManager::GetSupportedActions()
    const {
  CopyableTArray<MediaSessionAction> supportedActions;
  return mPlaybackStatusDelegate.IsAudible();
  if (!mActiveMediaSessionContextId) {
    return supportedActions;
  }

  MediaSessionInfo info =
      mMediaSessionInfoMap.Get(*mActiveMediaSessionContextId);
bool MediaStatusManager::IsAnyMediaBeingControlled() const {
  const uint8_t actionNums = uint8_t(MediaSessionAction::EndGuard_);
  for (uint8_t actionValue = 0; actionValue < actionNums; actionValue++) {
    MediaSessionAction action = ConvertToMediaSessionAction(actionValue);
    if (info.IsActionSupported(action)) {
      supportedActions.AppendElement(action);
}  // namespace mozilla
    }
  }
  return supportedActions;
}

MediaMetadataBase MediaStatusManager::GetCurrentMediaMetadata() const {
  // If we don't have active media session, active media session doesn't have
  // media metadata, or we're in private browsing mode, then we should create a
  // default metadata which is using website's title and favicon as title and
  // artwork.
  if (mActiveMediaSessionContextId && !IsInPrivateBrowsing()) {
    MediaSessionInfo info =
        mMediaSessionInfoMap.Get(*mActiveMediaSessionContextId);
    if (!info.mMetadata) {
      return CreateDefaultMetadata();
    }
    MediaMetadataBase& metadata = *(info.mMetadata);
    FillMissingTitleAndArtworkIfNeeded(metadata);
    return metadata;
  }
  return CreateDefaultMetadata();
}

void MediaStatusManager::FillMissingTitleAndArtworkIfNeeded(
    MediaMetadataBase& aMetadata) const {
  // If the metadata doesn't set its title and artwork properly, we would like
  // to use default title and favicon instead in order to prevent showing
  // nothing on the virtual control interface.
  if (aMetadata.mTitle.IsEmpty()) {
    aMetadata.mTitle = GetDefaultTitle();
  }
  if (aMetadata.mArtwork.IsEmpty()) {
    aMetadata.mArtwork.AppendElement()->mSrc = GetDefaultFaviconURL();
  }
}

bool MediaStatusManager::IsInPrivateBrowsing() const {
  RefPtr<CanonicalBrowsingContext> bc =
      CanonicalBrowsingContext::Get(mTopLevelBrowsingContextId);
  if (!bc) {
    return false;
  }
  RefPtr<Element> element = bc->GetEmbedderElement();
  if (!element) {
    return false;
  }
  return nsContentUtils::IsInPrivateBrowsing(element->OwnerDoc());
}

MediaSessionPlaybackState MediaStatusManager::GetState() const {
  return mActualPlaybackState;
}

bool MediaStatusManager::IsMediaAudible() const {
  return mPlaybackStatusDelegate.IsAudible();
}

bool MediaStatusManager::IsMediaPlaying() const {
  return mActualPlaybackState == MediaSessionPlaybackState::Playing;
}

bool MediaStatusManager::IsAnyMediaBeingControlled() const {
  return mPlaybackStatusDelegate.IsAnyMediaBeingControlled();
}

}  // namespace dom
}  // namespace mozilla