Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "MediaDecoder.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "AudioDeviceInfo.h"
#include "DOMMediaStream.h"
#include "DecoderBenchmark.h"
#include "ImageContainer.h"
#include "MediaDecoderStateMachineBase.h"
#include "MediaFormatReader.h"
#include "MediaResource.h"
#include "MediaShutdownManager.h"
#include "MediaTrackGraph.h"
#include "TelemetryProbesReporter.h"
#include "VideoFrameContainer.h"
#include "VideoUtils.h"
#include "WindowRenderer.h"
#include "mozilla/AbstractThread.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_media.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/DOMTypes.h"
#include "mozilla/glean/GleanMetrics.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsError.h"
#include "nsIMemoryReporter.h"
#include "nsPrintfCString.h"
#include "nsServiceManagerUtils.h"
#include "nsTArray.h"
using namespace mozilla::dom;
using namespace mozilla::layers;
using namespace mozilla::media;
namespace mozilla {
// avoid redefined macro in unified build
#undef LOG
#undef DUMP
LazyLogModule gMediaDecoderLog("MediaDecoder");
#define LOG(x, ...) \
DDMOZ_LOG(gMediaDecoderLog, LogLevel::Debug, x, ##__VA_ARGS__)
#define DUMP(x, ...) printf_stderr(x "\n", ##__VA_ARGS__)
#define NS_DispatchToMainThread(...) CompileError_UseAbstractMainThreadInstead
class MediaMemoryTracker : public nsIMemoryReporter {
virtual ~MediaMemoryTracker();
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIMEMORYREPORTER
MOZ_DEFINE_MALLOC_SIZE_OF(MallocSizeOf);
MediaMemoryTracker();
void InitMemoryReporter();
static StaticRefPtr<MediaMemoryTracker> sUniqueInstance;
static MediaMemoryTracker* UniqueInstance() {
if (!sUniqueInstance) {
sUniqueInstance = new MediaMemoryTracker();
sUniqueInstance->InitMemoryReporter();
}
return sUniqueInstance;
}
using DecodersArray = nsTArray<MediaDecoder*>;
static DecodersArray& Decoders() { return UniqueInstance()->mDecoders; }
DecodersArray mDecoders;
public:
static void AddMediaDecoder(MediaDecoder* aDecoder) {
Decoders().AppendElement(aDecoder);
}
static void RemoveMediaDecoder(MediaDecoder* aDecoder) {
DecodersArray& decoders = Decoders();
decoders.RemoveElement(aDecoder);
if (decoders.IsEmpty()) {
sUniqueInstance = nullptr;
}
}
};
StaticRefPtr<MediaMemoryTracker> MediaMemoryTracker::sUniqueInstance;
LazyLogModule gMediaTimerLog("MediaTimer");
constexpr TimeUnit MediaDecoder::DEFAULT_NEXT_FRAME_AVAILABLE_BUFFERED;
void MediaDecoder::InitStatics() {
MOZ_ASSERT(NS_IsMainThread());
// Eagerly init gMediaDecoderLog to work around bug 1415441.
MOZ_LOG(gMediaDecoderLog, LogLevel::Info, ("MediaDecoder::InitStatics"));
#if defined(NIGHTLY_BUILD)
// Allow people to force a bit but try to warn them about filing bugs if audio
// decoding does not work on utility
static const bool allowLockPrefs =
PR_GetEnv("MOZ_DONT_LOCK_UTILITY_PLZ_FILE_A_BUG") == nullptr;
if (XRE_IsParentProcess() && allowLockPrefs) {
// Lock Utility process preferences so that people cannot opt-out of
// Utility process
Preferences::Lock("media.utility-process.enabled");
# if defined(MOZ_FFMPEG)
Preferences::Lock("media.utility-ffmpeg.enabled");
# endif // defined(MOZ_FFMPEG)
Preferences::Lock("media.utility-ffvpx.enabled");
# if defined(MOZ_WMF)
Preferences::Lock("media.utility-wmf.enabled");
# endif // defined(MOZ_WMF)
# if defined(MOZ_APPLEMEDIA)
Preferences::Lock("media.utility-applemedia.enabled");
# endif // defined(MOZ_APPLEMEDIA)
Preferences::Lock("media.utility-vorbis.enabled");
Preferences::Lock("media.utility-wav.enabled");
Preferences::Lock("media.utility-opus.enabled");
}
#endif // defined(NIGHTLY_BUILD)
}
NS_IMPL_ISUPPORTS(MediaMemoryTracker, nsIMemoryReporter)
void MediaDecoder::NotifyOwnerActivityChanged(bool aIsOwnerInvisible,
bool aIsOwnerConnected,
bool aIsOwnerInBackground,
bool aHasOwnerPendingCallbacks) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
SetElementVisibility(aIsOwnerInvisible, aIsOwnerConnected,
aIsOwnerInBackground, aHasOwnerPendingCallbacks);
NotifyCompositor();
}
void MediaDecoder::Pause() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
LOG("Pause");
if (mPlayState == PLAY_STATE_LOADING || IsEnded()) {
mNextState = PLAY_STATE_PAUSED;
return;
}
ChangeState(PLAY_STATE_PAUSED);
}
void MediaDecoder::SetVolume(double aVolume) {
MOZ_ASSERT(NS_IsMainThread());
mVolume = aVolume;
}
RefPtr<GenericPromise> MediaDecoder::SetSink(AudioDeviceInfo* aSinkDevice) {
MOZ_ASSERT(NS_IsMainThread());
mSinkDevice = aSinkDevice;
return GetStateMachine()->InvokeSetSink(aSinkDevice);
}
void MediaDecoder::SetOutputCaptureState(OutputCaptureState aState,
SharedDummyTrack* aDummyTrack) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mDecoderStateMachine, "Must be called after Load().");
MOZ_ASSERT_IF(aState == OutputCaptureState::Capture, aDummyTrack);
if (mOutputCaptureState.Ref() != aState) {
LOG("Capture state change from %s to %s",
EnumValueToString(mOutputCaptureState.Ref()),
EnumValueToString(aState));
}
mOutputCaptureState = aState;
if (mOutputDummyTrack.Ref().get() != aDummyTrack) {
mOutputDummyTrack = nsMainThreadPtrHandle<SharedDummyTrack>(
MakeAndAddRef<nsMainThreadPtrHolder<SharedDummyTrack>>(
"MediaDecoder::mOutputDummyTrack", aDummyTrack));
}
}
void MediaDecoder::AddOutputTrack(RefPtr<ProcessedMediaTrack> aTrack) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mDecoderStateMachine, "Must be called after Load().");
CopyableTArray<RefPtr<ProcessedMediaTrack>> tracks = mOutputTracks;
tracks.AppendElement(std::move(aTrack));
mOutputTracks = tracks;
}
void MediaDecoder::RemoveOutputTrack(
const RefPtr<ProcessedMediaTrack>& aTrack) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mDecoderStateMachine, "Must be called after Load().");
CopyableTArray<RefPtr<ProcessedMediaTrack>> tracks = mOutputTracks;
if (tracks.RemoveElement(aTrack)) {
mOutputTracks = tracks;
}
}
void MediaDecoder::SetOutputTracksPrincipal(
const RefPtr<nsIPrincipal>& aPrincipal) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mDecoderStateMachine, "Must be called after Load().");
mOutputPrincipal = MakePrincipalHandle(aPrincipal);
}
double MediaDecoder::GetDuration() {
MOZ_ASSERT(NS_IsMainThread());
return ToMicrosecondResolution(mDuration.match(DurationToDouble()));
}
bool MediaDecoder::IsInfinite() const {
MOZ_ASSERT(NS_IsMainThread());
return std::isinf(mDuration.match(DurationToDouble()));
}
#define INIT_MIRROR(name, val) \
name(mOwner->AbstractMainThread(), val, "MediaDecoder::" #name " (Mirror)")
#define INIT_CANONICAL(name, val) \
name(mOwner->AbstractMainThread(), val, "MediaDecoder::" #name " (Canonical)")
MediaDecoder::MediaDecoder(MediaDecoderInit& aInit)
: mWatchManager(this, aInit.mOwner->AbstractMainThread()),
mLogicalPosition(0.0),
mDuration(TimeUnit::Invalid()),
mOwner(aInit.mOwner),
mAbstractMainThread(aInit.mOwner->AbstractMainThread()),
mFrameStats(new FrameStatistics()),
mDecoderBenchmark(new DecoderBenchmark()),
mVideoFrameContainer(aInit.mOwner->GetVideoFrameContainer()),
mMinimizePreroll(aInit.mMinimizePreroll),
mFiredMetadataLoaded(false),
mIsOwnerInvisible(false),
mIsOwnerConnected(false),
mIsOwnerInBackground(false),
mHasOwnerPendingCallbacks(false),
mForcedHidden(false),
mHasSuspendTaint(aInit.mHasSuspendTaint),
mShouldResistFingerprinting(
aInit.mOwner->ShouldResistFingerprinting(RFPTarget::AudioSampleRate)),
mPlaybackRate(aInit.mPlaybackRate),
mLogicallySeeking(false, "MediaDecoder::mLogicallySeeking"),
INIT_MIRROR(mBuffered, TimeIntervals()),
INIT_MIRROR(mCurrentPosition, TimeUnit::Zero()),
INIT_MIRROR(mStateMachineDuration, NullableTimeUnit()),
INIT_MIRROR(mIsAudioDataAudible, false),
INIT_CANONICAL(mVolume, aInit.mVolume),
INIT_CANONICAL(mPreservesPitch, aInit.mPreservesPitch),
INIT_CANONICAL(mLooping, aInit.mLooping),
INIT_CANONICAL(mStreamName, aInit.mStreamName),
INIT_CANONICAL(mSinkDevice, nullptr),
INIT_CANONICAL(mSecondaryVideoContainer, nullptr),
INIT_CANONICAL(mOutputCaptureState, OutputCaptureState::None),
INIT_CANONICAL(mOutputDummyTrack, nullptr),
INIT_CANONICAL(mOutputTracks, nsTArray<RefPtr<ProcessedMediaTrack>>()),
INIT_CANONICAL(mOutputPrincipal, PRINCIPAL_HANDLE_NONE),
INIT_CANONICAL(mPlayState, PLAY_STATE_LOADING),
mSameOriginMedia(false),
mVideoDecodingOberver(
new BackgroundVideoDecodingPermissionObserver(this)),
mIsBackgroundVideoDecodingAllowed(false),
mTelemetryReported(false),
mContainerType(aInit.mContainerType),
mTelemetryProbesReporter(
new TelemetryProbesReporter(aInit.mReporterOwner)) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mAbstractMainThread);
MediaMemoryTracker::AddMediaDecoder(this);
//
// Initialize watchers.
//
// mDuration
mWatchManager.Watch(mStateMachineDuration, &MediaDecoder::DurationChanged);
// readyState
mWatchManager.Watch(mPlayState, &MediaDecoder::UpdateReadyState);
// ReadyState computation depends on MediaDecoder::CanPlayThrough, which
// depends on the download rate.
mWatchManager.Watch(mBuffered, &MediaDecoder::UpdateReadyState);
// mLogicalPosition
mWatchManager.Watch(mCurrentPosition, &MediaDecoder::UpdateLogicalPosition);
mWatchManager.Watch(mPlayState, &MediaDecoder::UpdateLogicalPosition);
mWatchManager.Watch(mLogicallySeeking, &MediaDecoder::UpdateLogicalPosition);
mWatchManager.Watch(mIsAudioDataAudible,
&MediaDecoder::NotifyAudibleStateChanged);
mWatchManager.Watch(mVolume, &MediaDecoder::NotifyVolumeChanged);
mVideoDecodingOberver->RegisterEvent();
}
#undef INIT_MIRROR
#undef INIT_CANONICAL
void MediaDecoder::Shutdown() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
// Unwatch all watch targets to prevent further notifications.
mWatchManager.Shutdown();
DiscardOngoingSeekIfExists();
// This changes the decoder state to SHUTDOWN and does other things
// necessary to unblock the state machine thread if it's blocked, so
// the asynchronous shutdown in nsDestroyStateMachine won't deadlock.
if (mDecoderStateMachine) {
ShutdownStateMachine()->Then(mAbstractMainThread, __func__, this,
&MediaDecoder::FinishShutdown,
&MediaDecoder::FinishShutdown);
} else {
// Ensure we always unregister asynchronously in order not to disrupt
// the hashtable iterating in MediaShutdownManager::Shutdown().
RefPtr<MediaDecoder> self = this;
nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction(
"MediaDecoder::Shutdown", [self]() { self->ShutdownInternal(); });
mAbstractMainThread->Dispatch(r.forget());
}
ChangeState(PLAY_STATE_SHUTDOWN);
mVideoDecodingOberver->UnregisterEvent();
mVideoDecodingOberver = nullptr;
mOwner = nullptr;
}
void MediaDecoder::NotifyXPCOMShutdown() {
MOZ_ASSERT(NS_IsMainThread());
// NotifyXPCOMShutdown will clear its reference to mDecoder. So we must ensure
// that this MediaDecoder stays alive until completion.
RefPtr<MediaDecoder> kungFuDeathGrip = this;
if (auto* owner = GetOwner()) {
owner->NotifyXPCOMShutdown();
} else if (!IsShutdown()) {
Shutdown();
}
MOZ_DIAGNOSTIC_ASSERT(IsShutdown());
}
MediaDecoder::~MediaDecoder() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(IsShutdown());
MediaMemoryTracker::RemoveMediaDecoder(this);
}
void MediaDecoder::OnPlaybackEvent(MediaPlaybackEvent&& aEvent) {
switch (aEvent.mType) {
case MediaPlaybackEvent::PlaybackEnded:
PlaybackEnded();
break;
case MediaPlaybackEvent::SeekStarted:
SeekingStarted();
break;
case MediaPlaybackEvent::Invalidate:
Invalidate();
break;
case MediaPlaybackEvent::EnterVideoSuspend:
GetOwner()->DispatchAsyncEvent(u"mozentervideosuspend"_ns);
mIsVideoDecodingSuspended = true;
break;
case MediaPlaybackEvent::ExitVideoSuspend:
GetOwner()->DispatchAsyncEvent(u"mozexitvideosuspend"_ns);
mIsVideoDecodingSuspended = false;
break;
case MediaPlaybackEvent::StartVideoSuspendTimer:
GetOwner()->DispatchAsyncEvent(u"mozstartvideosuspendtimer"_ns);
break;
case MediaPlaybackEvent::CancelVideoSuspendTimer:
GetOwner()->DispatchAsyncEvent(u"mozcancelvideosuspendtimer"_ns);
break;
case MediaPlaybackEvent::VideoOnlySeekBegin:
GetOwner()->DispatchAsyncEvent(u"mozvideoonlyseekbegin"_ns);
break;
case MediaPlaybackEvent::VideoOnlySeekCompleted:
GetOwner()->DispatchAsyncEvent(u"mozvideoonlyseekcompleted"_ns);
break;
default:
break;
}
}
bool MediaDecoder::IsVideoDecodingSuspended() const {
return mIsVideoDecodingSuspended;
}
void MediaDecoder::OnPlaybackErrorEvent(const MediaResult& aError) {
MOZ_ASSERT(NS_IsMainThread());
#ifndef MOZ_WMF_MEDIA_ENGINE
DecodeError(aError);
#else
if (aError != NS_ERROR_DOM_MEDIA_EXTERNAL_ENGINE_NOT_SUPPORTED_ERR &&
aError != NS_ERROR_DOM_MEDIA_CDM_PROXY_NOT_SUPPORTED_ERR) {
DecodeError(aError);
return;
}
// Already in shutting down decoder, no need to create another state machine.
if (mPlayState == PLAY_STATE_SHUTDOWN) {
return;
}
// External engine can't play the resource or we intentionally disable it, try
// to use our own state machine again. Here we will create a new state machine
// immediately and asynchrously shutdown the old one because we don't want to
// dispatch any task to the old state machine. Therefore, we will disconnect
// anything related with the old state machine, create a new state machine and
// setup events/mirror/etc, then shutdown the old one and release its
// reference once it finishes shutdown.
RefPtr<MediaDecoderStateMachineBase> discardStateMachine =
mDecoderStateMachine;
// Disconnect mirror and events first.
SetStateMachine(nullptr);
DisconnectEvents();
// Recreate a state machine and shutdown the old one.
bool needExternalEngine = false;
if (aError == NS_ERROR_DOM_MEDIA_CDM_PROXY_NOT_SUPPORTED_ERR) {
# ifdef MOZ_WMF_CDM
if (aError.GetCDMProxy()->AsWMFCDMProxy()) {
needExternalEngine = true;
}
# endif
}
LOG("Need to create a new %s state machine",
needExternalEngine ? "external engine" : "normal");
nsresult rv = CreateAndInitStateMachine(
false /* live stream */,
!needExternalEngine /* disable external engine */);
if (NS_WARN_IF(NS_FAILED(rv))) {
LOG("Failed to create a new state machine!");
glean::mfcdm::ErrorExtra extraData;
extraData.errorName = Some("FAILED_TO_FALLBACK_TO_STATE_MACHINE"_ns);
nsAutoCString resolution;
if (mInfo) {
if (mInfo->HasAudio()) {
extraData.audioCodec = Some(mInfo->mAudio.mMimeType);
}
if (mInfo->HasVideo()) {
extraData.videoCodec = Some(mInfo->mVideo.mMimeType);
DetermineResolutionForTelemetry(*mInfo, resolution);
extraData.resolution = Some(resolution);
}
}
glean::mfcdm::error.Record(Some(extraData));
if (MOZ_LOG_TEST(gMediaDecoderLog, LogLevel::Debug)) {
nsPrintfCString logMessage{"MFCDM Error event, error=%s",
extraData.errorName->get()};
if (mInfo) {
if (mInfo->HasAudio()) {
logMessage.Append(
nsPrintfCString{", audio=%s", mInfo->mAudio.mMimeType.get()});
}
if (mInfo->HasVideo()) {
logMessage.Append(nsPrintfCString{", video=%s, resolution=%s",
mInfo->mVideo.mMimeType.get(),
resolution.get()});
}
}
LOG("%s", logMessage.get());
}
}
// Some attributes might have been set on the destroyed state machine, and
// won't be reflected on the new MDSM by the state mirroring. We need to
// update them manually later, after MDSM finished reading the
// metadata because the MDSM might not be ready to perform the operations yet.
mPendingStatusUpdateForNewlyCreatedStateMachine = true;
// If there is ongoing seek performed on the old MDSM, cancel it because we
// will perform seeking later again and don't want the old seeking affecting
// us.
DiscardOngoingSeekIfExists();
discardStateMachine->BeginShutdown()->Then(
AbstractThread::MainThread(), __func__, [discardStateMachine] {});
#endif
}
void MediaDecoder::OnDecoderDoctorEvent(DecoderDoctorEvent aEvent) {
MOZ_ASSERT(NS_IsMainThread());
// OnDecoderDoctorEvent is disconnected at shutdown time.
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
Document* doc = GetOwner()->GetDocument();
if (!doc) {
return;
}
DecoderDoctorDiagnostics diags;
diags.StoreEvent(doc, aEvent, __func__);
}
void MediaDecoder::OnNextFrameStatus(
MediaDecoderOwner::NextFrameStatus aStatus) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
if (mNextFrameStatus != aStatus) {
LOG("Changed mNextFrameStatus to %s",
MediaDecoderOwner::EnumValueToString(aStatus));
mNextFrameStatus = aStatus;
UpdateReadyState();
}
}
void MediaDecoder::OnTrackInfoUpdated(const VideoInfo& aVideoInfo,
const AudioInfo& aAudioInfo) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
// Note that we don't check HasVideo() or HasAudio() here, because
// those are checks for existing validity. If we always set the values
// to what we receive, then we can go from not-video to video, for
// example.
mInfo->mVideo = aVideoInfo;
mInfo->mAudio = aAudioInfo;
Invalidate();
EnsureTelemetryReported();
}
void MediaDecoder::OnSecondaryVideoContainerInstalled(
const RefPtr<VideoFrameContainer>& aSecondaryVideoContainer) {
MOZ_ASSERT(NS_IsMainThread());
GetOwner()->OnSecondaryVideoContainerInstalled(aSecondaryVideoContainer);
}
void MediaDecoder::OnStoreDecoderBenchmark(const VideoInfo& aInfo) {
MOZ_ASSERT(NS_IsMainThread());
int32_t videoFrameRate = aInfo.GetFrameRate().ref();
if (mFrameStats && videoFrameRate) {
DecoderBenchmarkInfo benchmarkInfo{
aInfo.mMimeType,
aInfo.mDisplay.width,
aInfo.mDisplay.height,
videoFrameRate,
BitDepthForColorDepth(aInfo.mColorDepth),
};
LOG("Store benchmark: Video width=%d, height=%d, frameRate=%d, content "
"type = %s\n",
benchmarkInfo.mWidth, benchmarkInfo.mHeight, benchmarkInfo.mFrameRate,
benchmarkInfo.mContentType.BeginReading());
mDecoderBenchmark->Store(benchmarkInfo, mFrameStats);
}
}
void MediaDecoder::ShutdownInternal() {
MOZ_ASSERT(NS_IsMainThread());
mVideoFrameContainer = nullptr;
mSecondaryVideoContainer = nullptr;
MediaShutdownManager::Instance().Unregister(this);
}
void MediaDecoder::FinishShutdown() {
MOZ_ASSERT(NS_IsMainThread());
SetStateMachine(nullptr);
ShutdownInternal();
}
nsresult MediaDecoder::CreateAndInitStateMachine(bool aIsLiveStream,
bool aDisableExternalEngine) {
MOZ_ASSERT(NS_IsMainThread());
SetStateMachine(CreateStateMachine(aDisableExternalEngine));
NS_ENSURE_TRUE(GetStateMachine(), NS_ERROR_FAILURE);
GetStateMachine()->DispatchIsLiveStream(aIsLiveStream);
mMDSMCreationTime = Some(TimeStamp::Now());
nsresult rv = mDecoderStateMachine->Init(this);
NS_ENSURE_SUCCESS(rv, rv);
// If some parameters got set before the state machine got created,
// set them now
SetStateMachineParameters();
return NS_OK;
}
void MediaDecoder::SetStateMachineParameters() {
MOZ_ASSERT(NS_IsMainThread());
if (mPlaybackRate != 1 && mPlaybackRate != 0) {
mDecoderStateMachine->DispatchSetPlaybackRate(mPlaybackRate);
}
mTimedMetadataListener = mDecoderStateMachine->TimedMetadataEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::OnMetadataUpdate);
mMetadataLoadedListener = mDecoderStateMachine->MetadataLoadedEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::MetadataLoaded);
mFirstFrameLoadedListener =
mDecoderStateMachine->FirstFrameLoadedEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::FirstFrameLoaded);
mOnPlaybackEvent = mDecoderStateMachine->OnPlaybackEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::OnPlaybackEvent);
mOnPlaybackErrorEvent = mDecoderStateMachine->OnPlaybackErrorEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::OnPlaybackErrorEvent);
mOnDecoderDoctorEvent = mDecoderStateMachine->OnDecoderDoctorEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::OnDecoderDoctorEvent);
mOnMediaNotSeekable = mDecoderStateMachine->OnMediaNotSeekable().Connect(
mAbstractMainThread, this, &MediaDecoder::OnMediaNotSeekable);
mOnNextFrameStatus = mDecoderStateMachine->OnNextFrameStatus().Connect(
mAbstractMainThread, this, &MediaDecoder::OnNextFrameStatus);
mOnTrackInfoUpdated = mDecoderStateMachine->OnTrackInfoUpdatedEvent().Connect(
mAbstractMainThread, this, &MediaDecoder::OnTrackInfoUpdated);
mOnSecondaryVideoContainerInstalled =
mDecoderStateMachine->OnSecondaryVideoContainerInstalled().Connect(
mAbstractMainThread, this,
&MediaDecoder::OnSecondaryVideoContainerInstalled);
mOnStoreDecoderBenchmark = mReader->OnStoreDecoderBenchmark().Connect(
mAbstractMainThread, this, &MediaDecoder::OnStoreDecoderBenchmark);
mOnEncrypted = mReader->OnEncrypted().Connect(
mAbstractMainThread, GetOwner(), &MediaDecoderOwner::DispatchEncrypted);
mOnWaitingForKey = mReader->OnWaitingForKey().Connect(
mAbstractMainThread, GetOwner(), &MediaDecoderOwner::NotifyWaitingForKey);
mOnDecodeWarning = mReader->OnDecodeWarning().Connect(
mAbstractMainThread, GetOwner(), &MediaDecoderOwner::DecodeWarning);
}
void MediaDecoder::DisconnectEvents() {
MOZ_ASSERT(NS_IsMainThread());
mTimedMetadataListener.Disconnect();
mMetadataLoadedListener.Disconnect();
mFirstFrameLoadedListener.Disconnect();
mOnPlaybackEvent.Disconnect();
mOnPlaybackErrorEvent.Disconnect();
mOnDecoderDoctorEvent.Disconnect();
mOnMediaNotSeekable.Disconnect();
mOnEncrypted.Disconnect();
mOnWaitingForKey.Disconnect();
mOnDecodeWarning.Disconnect();
mOnNextFrameStatus.Disconnect();
mOnTrackInfoUpdated.Disconnect();
mOnSecondaryVideoContainerInstalled.Disconnect();
mOnStoreDecoderBenchmark.Disconnect();
}
RefPtr<ShutdownPromise> MediaDecoder::ShutdownStateMachine() {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(GetStateMachine());
DisconnectEvents();
return mDecoderStateMachine->BeginShutdown();
}
void MediaDecoder::Play() {
MOZ_ASSERT(NS_IsMainThread());
NS_ASSERTION(mDecoderStateMachine != nullptr, "Should have state machine.");
LOG("Play");
if (mPlaybackRate == 0) {
return;
}
if (IsEnded()) {
Seek(0, SeekTarget::PrevSyncPoint);
return;
}
if (mPlayState == PLAY_STATE_LOADING) {
mNextState = PLAY_STATE_PLAYING;
return;
}
ChangeState(PLAY_STATE_PLAYING);
}
void MediaDecoder::Seek(double aTime, SeekTarget::Type aSeekType) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
LOG("Seek, target=%f", aTime);
MOZ_ASSERT(aTime >= 0.0, "Cannot seek to a negative value.");
auto time = TimeUnit::FromSeconds(aTime);
mLogicalPosition = aTime;
mLogicallySeeking = true;
SeekTarget target = SeekTarget(time, aSeekType);
CallSeek(target);
if (mPlayState == PLAY_STATE_ENDED) {
ChangeState(GetOwner()->GetPaused() ? PLAY_STATE_PAUSED
: PLAY_STATE_PLAYING);
}
}
void MediaDecoder::SetDelaySeekMode(bool aShouldDelaySeek) {
MOZ_ASSERT(NS_IsMainThread());
LOG("SetDelaySeekMode, shouldDelaySeek=%d", aShouldDelaySeek);
if (mShouldDelaySeek == aShouldDelaySeek) {
return;
}
mShouldDelaySeek = aShouldDelaySeek;
if (!mShouldDelaySeek && mDelayedSeekTarget) {
Seek(mDelayedSeekTarget->GetTime().ToSeconds(),
mDelayedSeekTarget->GetType());
mDelayedSeekTarget.reset();
}
}
void MediaDecoder::DiscardOngoingSeekIfExists() {
MOZ_ASSERT(NS_IsMainThread());
mSeekRequest.DisconnectIfExists();
}
void MediaDecoder::CallSeek(const SeekTarget& aTarget) {
MOZ_ASSERT(NS_IsMainThread());
if (mShouldDelaySeek) {
LOG("Delay seek to %f and store it to delayed seek target",
mDelayedSeekTarget->GetTime().ToSeconds());
mDelayedSeekTarget = Some(aTarget);
return;
}
DiscardOngoingSeekIfExists();
mDecoderStateMachine->InvokeSeek(aTarget)
->Then(mAbstractMainThread, __func__, this, &MediaDecoder::OnSeekResolved,
&MediaDecoder::OnSeekRejected)
->Track(mSeekRequest);
}
double MediaDecoder::GetCurrentTime() {
MOZ_ASSERT(NS_IsMainThread());
return mLogicalPosition;
}
void MediaDecoder::OnMetadataUpdate(TimedMetadata&& aMetadata) {
MOZ_ASSERT(NS_IsMainThread());
MetadataLoaded(MakeUnique<MediaInfo>(*aMetadata.mInfo),
UniquePtr<MetadataTags>(std::move(aMetadata.mTags)),
MediaDecoderEventVisibility::Observable);
FirstFrameLoaded(std::move(aMetadata.mInfo),
MediaDecoderEventVisibility::Observable);
}
void MediaDecoder::MetadataLoaded(
UniquePtr<MediaInfo> aInfo, UniquePtr<MetadataTags> aTags,
MediaDecoderEventVisibility aEventVisibility) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
LOG("MetadataLoaded, channels=%u rate=%u hasAudio=%d hasVideo=%d",
aInfo->mAudio.mChannels, aInfo->mAudio.mRate, aInfo->HasAudio(),
aInfo->HasVideo());
mMediaSeekable = aInfo->mMediaSeekable;
mMediaSeekableOnlyInBufferedRanges =
aInfo->mMediaSeekableOnlyInBufferedRanges;
mInfo = std::move(aInfo);
mTelemetryProbesReporter->OnMediaContentChanged(
TelemetryProbesReporter::MediaInfoToMediaContent(*mInfo));
// Make sure the element and the frame (if any) are told about
// our new size.
if (aEventVisibility != MediaDecoderEventVisibility::Suppressed) {
mFiredMetadataLoaded = true;
GetOwner()->MetadataLoaded(mInfo.get(), std::move(aTags));
}
// Invalidate() will end up calling GetOwner()->UpdateMediaSize with the last
// dimensions retrieved from the video frame container. The video frame
// container contains more up to date dimensions than aInfo.
// So we call Invalidate() after calling GetOwner()->MetadataLoaded to ensure
// the media element has the latest dimensions.
Invalidate();
#ifdef MOZ_WMF_MEDIA_ENGINE
SetStatusUpdateForNewlyCreatedStateMachineIfNeeded();
#endif
EnsureTelemetryReported();
}
#ifdef MOZ_WMF_MEDIA_ENGINE
void MediaDecoder::SetStatusUpdateForNewlyCreatedStateMachineIfNeeded() {
if (!mPendingStatusUpdateForNewlyCreatedStateMachine) {
return;
}
mPendingStatusUpdateForNewlyCreatedStateMachine = false;
LOG("Set pending statuses if necessary (mLogicallySeeking=%d, "
"mLogicalPosition=%f, mPlaybackRate=%f)",
mLogicallySeeking.Ref(), mLogicalPosition, mPlaybackRate);
if (mLogicalPosition != 0) {
Seek(mLogicalPosition, SeekTarget::Accurate);
}
if (mPlaybackRate != 0 && mPlaybackRate != 1.0) {
mDecoderStateMachine->DispatchSetPlaybackRate(mPlaybackRate);
}
}
#endif
void MediaDecoder::EnsureTelemetryReported() {
MOZ_ASSERT(NS_IsMainThread());
if (mTelemetryReported || !mInfo) {
// Note: sometimes we get multiple MetadataLoaded calls (for example
// for chained ogg). So we ensure we don't report duplicate results for
// these resources.
return;
}
nsTArray<nsCString> codecs;
if (mInfo->HasAudio() &&
!mInfo->mAudio.GetAsAudioInfo()->mMimeType.IsEmpty()) {
codecs.AppendElement(mInfo->mAudio.GetAsAudioInfo()->mMimeType);
}
if (mInfo->HasVideo() &&
!mInfo->mVideo.GetAsVideoInfo()->mMimeType.IsEmpty()) {
codecs.AppendElement(mInfo->mVideo.GetAsVideoInfo()->mMimeType);
}
if (codecs.IsEmpty()) {
codecs.AppendElement(nsPrintfCString(
"resource; %s", ContainerType().OriginalString().Data()));
}
for (const nsCString& codec : codecs) {
LOG("Telemetry MEDIA_CODEC_USED= '%s'", codec.get());
Telemetry::Accumulate(Telemetry::HistogramID::MEDIA_CODEC_USED, codec);
}
mTelemetryReported = true;
}
void MediaDecoder::FirstFrameLoaded(
UniquePtr<MediaInfo> aInfo, MediaDecoderEventVisibility aEventVisibility) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(!IsShutdown());
LOG("FirstFrameLoaded, channels=%u rate=%u hasAudio=%d hasVideo=%d "
"mPlayState=%s transportSeekable=%d",
aInfo->mAudio.mChannels, aInfo->mAudio.mRate, aInfo->HasAudio(),
aInfo->HasVideo(), EnumValueToString(mPlayState), IsTransportSeekable());
mInfo = std::move(aInfo);
mTelemetryProbesReporter->OnMediaContentChanged(
TelemetryProbesReporter::MediaInfoToMediaContent(*mInfo));
Invalidate();
// The element can run javascript via events
// before reaching here, so only change the
// state if we're still set to the original
// loading state.
if (mPlayState == PLAY_STATE_LOADING) {
ChangeState(mNextState);
}
// We only care about video first frame.
if (mInfo->HasVideo() && mMDSMCreationTime) {
auto info = MakeUnique<dom::MediaDecoderDebugInfo>();
RequestDebugInfo(*info)->Then(
GetMainThreadSerialEventTarget(), __func__,
[self = RefPtr<MediaDecoder>{this}, this, now = TimeStamp::Now(),
creationTime = *mMDSMCreationTime, result = std::move(info)](
GenericPromise::ResolveOrRejectValue&& aValue) mutable {
if (IsShutdown()) {
return;
}
if (aValue.IsReject()) {