Back out 3 changesets (bug 1135424) on suspicion of causing frequent hangs in test_playback.html on mochitest-e10s

CLOSED TREE

Backed out changeset 584d91ffdf88 (bug 1135424)
Backed out changeset d86806ea63f4 (bug 1135424)
Backed out changeset e52401d30a67 (bug 1135424)
This commit is contained in:
Phil Ringnalda 2015-03-12 23:05:11 -07:00
Родитель 0378f66c84
Коммит 345a4eca93
13 изменённых файлов: 425 добавлений и 507 удалений

Просмотреть файл

@ -191,12 +191,12 @@ void MediaDecoder::UpdateDormantState(bool aDormantTimeout, bool aActivity)
if (mIsDormant) {
DECODER_LOG("UpdateDormantState() entering DORMANT state");
// enter dormant state
RefPtr<nsRunnable> event =
nsCOMPtr<nsIRunnable> event =
NS_NewRunnableMethodWithArg<bool>(
mDecoderStateMachine,
&MediaDecoderStateMachine::SetDormant,
true);
mDecoderStateMachine->TaskQueue()->Dispatch(event);
mDecoderStateMachine->GetStateMachineThread()->Dispatch(event, NS_DISPATCH_NORMAL);
if (IsEnded()) {
mWasEndedWhenEnteredDormant = true;
@ -207,12 +207,12 @@ void MediaDecoder::UpdateDormantState(bool aDormantTimeout, bool aActivity)
DECODER_LOG("UpdateDormantState() leaving DORMANT state");
// exit dormant state
// trigger to state machine.
RefPtr<nsRunnable> event =
nsCOMPtr<nsIRunnable> event =
NS_NewRunnableMethodWithArg<bool>(
mDecoderStateMachine,
&MediaDecoderStateMachine::SetDormant,
false);
mDecoderStateMachine->TaskQueue()->Dispatch(event);
mDecoderStateMachine->GetStateMachineThread()->Dispatch(event, NS_DISPATCH_NORMAL);
}
}
@ -750,8 +750,7 @@ nsresult MediaDecoder::ScheduleStateMachineThread()
if (mShuttingDown)
return NS_OK;
ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
mDecoderStateMachine->ScheduleStateMachine();
return NS_OK;
return mDecoderStateMachine->ScheduleStateMachine();
}
nsresult MediaDecoder::Play()
@ -764,7 +763,8 @@ nsresult MediaDecoder::Play()
if (mPausedForPlaybackRateNull) {
return NS_OK;
}
ScheduleStateMachineThread();
nsresult res = ScheduleStateMachineThread();
NS_ENSURE_SUCCESS(res,res);
if (IsEnded()) {
return Seek(0, SeekTarget::PrevSyncPoint);
} else if (mPlayState == PLAY_STATE_LOADING || mPlayState == PLAY_STATE_SEEKING) {
@ -1317,7 +1317,7 @@ void MediaDecoder::ApplyStateToStateMachine(PlayState aState)
mDecoderStateMachine->Play();
break;
case PLAY_STATE_SEEKING:
mSeekRequest.Begin(ProxyMediaCall(mDecoderStateMachine->TaskQueue(),
mSeekRequest.Begin(ProxyMediaCall(mDecoderStateMachine->GetStateMachineThread(),
mDecoderStateMachine.get(), __func__,
&MediaDecoderStateMachine::Seek, mRequestedSeekTarget)
->RefableThen(NS_GetCurrentThread(), __func__, this,

Просмотреть файл

@ -13,7 +13,7 @@
#include <stdint.h>
#include "MediaDecoderStateMachine.h"
#include "MediaTimer.h"
#include "MediaDecoderStateMachineScheduler.h"
#include "AudioSink.h"
#include "nsTArray.h"
#include "MediaDecoder.h"
@ -201,9 +201,9 @@ MediaDecoderStateMachine::MediaDecoderStateMachine(MediaDecoder* aDecoder,
MediaDecoderReader* aReader,
bool aRealTime) :
mDecoder(aDecoder),
mRealTime(aRealTime),
mDispatchedStateMachine(false),
mDelayedScheduler(this),
mScheduler(new MediaDecoderStateMachineScheduler(
aDecoder->GetReentrantMonitor(),
&MediaDecoderStateMachine::TimeoutExpired, this, aRealTime)),
mState(DECODER_STATE_DECODING_NONE),
mPlayDuration(0),
mStartTime(-1),
@ -248,11 +248,6 @@ MediaDecoderStateMachine::MediaDecoderStateMachine(MediaDecoder* aDecoder,
MOZ_COUNT_CTOR(MediaDecoderStateMachine);
NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");
// Set up our task queue.
RefPtr<SharedThreadPool> threadPool(
SharedThreadPool::Get(NS_LITERAL_CSTRING("Media State Machine"), 1));
mTaskQueue = new MediaTaskQueue(threadPool.forget());
static bool sPrefCacheInit = false;
if (!sPrefCacheInit) {
sPrefCacheInit = true;
@ -392,7 +387,7 @@ void MediaDecoderStateMachine::SendStreamData()
{
MOZ_ASSERT(OnStateMachineThread(), "Should be on state machine thread");
AssertCurrentThreadInMonitor();
MOZ_ASSERT(!mAudioSink, "Should've been stopped in RunStateMachine()");
MOZ_ASSERT(!mAudioSink, "Should've been stopped in CallRunStateMachine()");
DecodedStreamData* stream = mDecoder->GetDecodedStream();
@ -410,7 +405,7 @@ void MediaDecoderStateMachine::SendStreamData()
mediaStream->AddAudioTrack(audioTrackId, mInfo.mAudio.mRate, 0, audio,
SourceMediaStream::ADDTRACK_QUEUED);
stream->mStream->DispatchWhenNotEnoughBuffered(audioTrackId,
TaskQueue(), GetWakeDecoderRunnable());
GetStateMachineThread(), GetWakeDecoderRunnable());
stream->mNextAudioTime = mStartTime + stream->mInitialTime;
}
if (mInfo.HasVideo()) {
@ -419,7 +414,7 @@ void MediaDecoderStateMachine::SendStreamData()
mediaStream->AddTrack(videoTrackId, 0, video,
SourceMediaStream::ADDTRACK_QUEUED);
stream->mStream->DispatchWhenNotEnoughBuffered(videoTrackId,
TaskQueue(), GetWakeDecoderRunnable());
GetStateMachineThread(), GetWakeDecoderRunnable());
// TODO: We can't initialize |mNextVideoTime| until |mStartTime|
// is set. This is a good indication that DecodedStreamData is in
@ -575,7 +570,7 @@ bool MediaDecoderStateMachine::HaveEnoughDecodedAudio(int64_t aAmpleAudioUSecs)
return false;
}
stream->mStream->DispatchWhenNotEnoughBuffered(audioTrackId,
TaskQueue(), GetWakeDecoderRunnable());
GetStateMachineThread(), GetWakeDecoderRunnable());
}
return true;
@ -598,7 +593,7 @@ bool MediaDecoderStateMachine::HaveEnoughDecodedVideo()
return false;
}
stream->mStream->DispatchWhenNotEnoughBuffered(videoTrackId,
TaskQueue(), GetWakeDecoderRunnable());
GetStateMachineThread(), GetWakeDecoderRunnable());
}
return true;
@ -860,7 +855,7 @@ MediaDecoderStateMachine::OnNotDecoded(MediaData::Type aType,
"Readers that send WAITING_FOR_DATA need to implement WaitForData");
WaitRequestRef(aType).Begin(ProxyMediaCall(DecodeTaskQueue(), mReader.get(), __func__,
&MediaDecoderReader::WaitForData, aType)
->RefableThen(TaskQueue(), __func__, this,
->RefableThen(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::OnWaitForDataResolved,
&MediaDecoderStateMachine::OnWaitForDataRejected));
return;
@ -1089,7 +1084,7 @@ MediaDecoderStateMachine::CheckIfSeekComplete()
mDecodeToSeekTarget = false;
RefPtr<nsIRunnable> task(
NS_NewRunnableMethod(this, &MediaDecoderStateMachine::SeekCompleted));
nsresult rv = TaskQueue()->Dispatch(task);
nsresult rv = GetStateMachineThread()->Dispatch(task, NS_DISPATCH_NORMAL);
if (NS_FAILED(rv)) {
DecodeError();
}
@ -1151,7 +1146,10 @@ nsresult MediaDecoderStateMachine::Init(MediaDecoderStateMachine* aCloneDonor)
cloneReader = aCloneDonor->mReader;
}
nsresult rv = mReader->Init(cloneReader);
nsresult rv = mScheduler->Init();
NS_ENSURE_SUCCESS(rv, rv);
rv = mReader->Init(cloneReader);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
@ -1345,7 +1343,7 @@ int64_t MediaDecoderStateMachine::GetCurrentTimeUs() const
}
bool MediaDecoderStateMachine::IsRealTime() const {
return mRealTime;
return mScheduler->IsRealTime();
}
int64_t MediaDecoderStateMachine::GetDuration()
@ -1515,8 +1513,9 @@ void MediaDecoderStateMachine::Shutdown()
// Change state before issuing shutdown request to threads so those
// threads can start exiting cleanly during the Shutdown call.
ScheduleStateMachine();
DECODER_LOG("Changed state to SHUTDOWN");
SetState(DECODER_STATE_SHUTDOWN);
mScheduler->ScheduleAndShutdown();
if (mAudioSink) {
mAudioSink->PrepareToShutdown();
}
@ -1775,7 +1774,7 @@ MediaDecoderStateMachine::EnqueueDecodeFirstFrameTask()
RefPtr<nsIRunnable> task(
NS_NewRunnableMethod(this, &MediaDecoderStateMachine::CallDecodeFirstFrame));
nsresult rv = TaskQueue()->Dispatch(task);
nsresult rv = GetStateMachineThread()->Dispatch(task, NS_DISPATCH_NORMAL);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
@ -1922,7 +1921,7 @@ MediaDecoderStateMachine::InitiateSeek()
mSeekRequest.Begin(ProxyMediaCall(DecodeTaskQueue(), mReader.get(), __func__,
&MediaDecoderReader::Seek, mCurrentSeek.mTarget.mTime,
GetEndTime())
->RefableThen(TaskQueue(), __func__, this,
->RefableThen(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::OnSeekCompleted,
&MediaDecoderStateMachine::OnSeekFailed));
}
@ -1970,7 +1969,7 @@ MediaDecoderStateMachine::EnsureAudioDecodeTaskQueued()
mAudioDataRequest.Begin(ProxyMediaCall(DecodeTaskQueue(), mReader.get(),
__func__, &MediaDecoderReader::RequestAudioData)
->RefableThen(TaskQueue(), __func__, this,
->RefableThen(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::OnAudioDecoded,
&MediaDecoderStateMachine::OnAudioNotDecoded));
@ -2030,7 +2029,7 @@ MediaDecoderStateMachine::EnsureVideoDecodeTaskQueued()
mVideoDataRequest.Begin(ProxyMediaCall(DecodeTaskQueue(), mReader.get(), __func__,
&MediaDecoderReader::RequestVideoData,
skipToNextKeyFrame, currentTime)
->RefableThen(TaskQueue(), __func__, this,
->RefableThen(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::OnVideoDecoded,
&MediaDecoderStateMachine::OnVideoNotDecoded));
return NS_OK;
@ -2168,9 +2167,9 @@ MediaDecoderStateMachine::DecodeError()
// Change state to shutdown before sending error report to MediaDecoder
// and the HTMLMediaElement, so that our pipeline can start exiting
// cleanly during the sync dispatch below.
ScheduleStateMachine();
SetState(DECODER_STATE_SHUTDOWN);
DECODER_WARN("Decode error, changed state to SHUTDOWN due to error");
SetState(DECODER_STATE_SHUTDOWN);
mScheduler->ScheduleAndShutdown();
mDecoder->GetReentrantMonitor().NotifyAll();
// Dispatch the event to call DecodeError synchronously. This ensures
@ -2323,12 +2322,12 @@ MediaDecoderStateMachine::DecodeFirstFrame()
if (HasAudio()) {
RefPtr<nsIRunnable> decodeTask(
NS_NewRunnableMethod(this, &MediaDecoderStateMachine::DispatchAudioDecodeTaskIfNeeded));
AudioQueue().AddPopListener(decodeTask, TaskQueue());
AudioQueue().AddPopListener(decodeTask, GetStateMachineThread());
}
if (HasVideo()) {
RefPtr<nsIRunnable> decodeTask(
NS_NewRunnableMethod(this, &MediaDecoderStateMachine::DispatchVideoDecodeTaskIfNeeded));
VideoQueue().AddPopListener(decodeTask, TaskQueue());
VideoQueue().AddPopListener(decodeTask, GetStateMachineThread());
}
if (IsRealTime()) {
@ -2346,7 +2345,7 @@ MediaDecoderStateMachine::DecodeFirstFrame()
if (HasAudio()) {
mAudioDataRequest.Begin(ProxyMediaCall(DecodeTaskQueue(), mReader.get(),
__func__, &MediaDecoderReader::RequestAudioData)
->RefableThen(TaskQueue(), __func__, this,
->RefableThen(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::OnAudioDecoded,
&MediaDecoderStateMachine::OnAudioNotDecoded));
}
@ -2354,7 +2353,7 @@ MediaDecoderStateMachine::DecodeFirstFrame()
mVideoDecodeStartTime = TimeStamp::Now();
mVideoDataRequest.Begin(ProxyMediaCall(DecodeTaskQueue(), mReader.get(),
__func__, &MediaDecoderReader::RequestVideoData, false, int64_t(0))
->RefableThen(TaskQueue(), __func__, this,
->RefableThen(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::OnVideoDecoded,
&MediaDecoderStateMachine::OnVideoNotDecoded));
}
@ -2561,8 +2560,6 @@ public:
NS_ASSERTION(NS_IsMainThread(), "Must be on main thread.");
MOZ_ASSERT(mStateMachine);
MOZ_ASSERT(mDecoder);
mStateMachine->TaskQueue()->BeginShutdown();
mStateMachine->TaskQueue()->AwaitShutdownAndIdle();
mStateMachine->BreakCycles();
mDecoder->BreakCycles();
mStateMachine = nullptr;
@ -2597,7 +2594,7 @@ void
MediaDecoderStateMachine::ShutdownReader()
{
MOZ_ASSERT(OnDecodeThread());
mReader->Shutdown()->Then(TaskQueue(), __func__, this,
mReader->Shutdown()->Then(mScheduler.get(), __func__, this,
&MediaDecoderStateMachine::FinishShutdown,
&MediaDecoderStateMachine::FinishShutdown);
}
@ -2633,24 +2630,15 @@ MediaDecoderStateMachine::FinishShutdown()
// finished and released its monitor/references. That event then will
// dispatch an event to the main thread to release the decoder and
// state machine.
RefPtr<nsIRunnable> task = new nsDispatchDisposeEvent(mDecoder, this);
TaskQueue()->Dispatch(task);
GetStateMachineThread()->Dispatch(
new nsDispatchDisposeEvent(mDecoder, this), NS_DISPATCH_NORMAL);
DECODER_LOG("Dispose Event Dispatched");
}
nsresult MediaDecoderStateMachine::RunStateMachine()
{
MOZ_ASSERT(OnStateMachineThread());
ReentrantMonitorAutoEnter mon(mDecoder->GetReentrantMonitor());
mDelayedScheduler.Reset(); // Must happen on state machine thread.
mDispatchedStateMachine = false;
// If audio is being captured, stop the audio sink if it's running
if (mAudioCaptured) {
StopAudioThread();
}
AssertCurrentThreadInMonitor();
MediaResource* resource = mDecoder->GetResource();
NS_ENSURE_TRUE(resource, NS_ERROR_NULL_POINTER);
@ -2751,7 +2739,7 @@ nsresult MediaDecoderStateMachine::RunStateMachine()
DECODER_LOG("Buffering: wait %ds, timeout in %.3lfs %s",
mBufferingWait, mBufferingWait - elapsed.ToSeconds(),
(mQuickBuffering ? "(quick exit)" : ""));
ScheduleStateMachineIn(USECS_PER_S);
ScheduleStateMachine(USECS_PER_S);
return NS_OK;
}
} else if (OutOfDecodedAudio() || OutOfDecodedVideo()) {
@ -3075,7 +3063,7 @@ void MediaDecoderStateMachine::AdvanceFrame()
// Don't go straight back to the state machine loop since that might
// cause us to start decoding again and we could flip-flop between
// decoding and quick-buffering.
ScheduleStateMachineIn(USECS_PER_S);
ScheduleStateMachine(USECS_PER_S);
return;
}
}
@ -3137,12 +3125,7 @@ void MediaDecoderStateMachine::AdvanceFrame()
// ready state. Post an update to do so.
UpdateReadyState();
int64_t delay = remainingTime / mPlaybackRate;
if (delay > 0) {
ScheduleStateMachineIn(delay);
} else {
ScheduleStateMachine();
}
ScheduleStateMachine(remainingTime / mPlaybackRate);
}
nsresult
@ -3388,59 +3371,33 @@ void MediaDecoderStateMachine::SetPlayStartTime(const TimeStamp& aTimeStamp)
}
}
nsresult MediaDecoderStateMachine::CallRunStateMachine()
{
AssertCurrentThreadInMonitor();
NS_ASSERTION(OnStateMachineThread(), "Should be on state machine thread.");
// If audio is being captured, stop the audio sink if it's running
if (mAudioCaptured) {
StopAudioThread();
}
return RunStateMachine();
}
nsresult MediaDecoderStateMachine::TimeoutExpired(void* aClosure)
{
MediaDecoderStateMachine* p = static_cast<MediaDecoderStateMachine*>(aClosure);
return p->CallRunStateMachine();
}
void MediaDecoderStateMachine::ScheduleStateMachineWithLockAndWakeDecoder() {
ReentrantMonitorAutoEnter mon(mDecoder->GetReentrantMonitor());
DispatchAudioDecodeTaskIfNeeded();
DispatchVideoDecodeTaskIfNeeded();
}
void
MediaDecoderStateMachine::ScheduleStateMachine() {
AssertCurrentThreadInMonitor();
if (mState == DECODER_STATE_SHUTDOWN) {
NS_WARNING("Refusing to schedule shutdown state machine");
return;
}
if (mDispatchedStateMachine) {
return;
}
mDispatchedStateMachine = true;
RefPtr<nsIRunnable> task =
NS_NewRunnableMethod(this, &MediaDecoderStateMachine::RunStateMachine);
nsresult rv = TaskQueue()->Dispatch(task);
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
(void) rv;
}
void
MediaDecoderStateMachine::ScheduleStateMachineIn(int64_t aMicroseconds)
{
AssertCurrentThreadInMonitor();
MOZ_ASSERT(OnStateMachineThread()); // mDelayedScheduler.Ensure() may Disconnect()
// the promise, which must happen on the state
// machine thread.
MOZ_ASSERT(aMicroseconds > 0);
if (mState == DECODER_STATE_SHUTDOWN) {
NS_WARNING("Refusing to schedule shutdown state machine");
return;
}
if (mDispatchedStateMachine) {
return;
}
// Real-time weirdness.
if (IsRealTime()) {
aMicroseconds = std::min(aMicroseconds, int64_t(40000));
}
TimeStamp now = TimeStamp::Now();
TimeStamp target = now + TimeDuration::FromMicroseconds(aMicroseconds);
SAMPLE_LOG("Scheduling state machine for %lf ms from now", (target - now).ToMilliseconds());
mDelayedScheduler.Ensure(target);
nsresult MediaDecoderStateMachine::ScheduleStateMachine(int64_t aUsecs) {
return mScheduler->Schedule(aUsecs);
}
bool MediaDecoderStateMachine::OnDecodeThread() const
@ -3450,12 +3407,17 @@ bool MediaDecoderStateMachine::OnDecodeThread() const
bool MediaDecoderStateMachine::OnStateMachineThread() const
{
return TaskQueue()->IsCurrentThreadIn();
return mScheduler->OnStateMachineThread();
}
nsIEventTarget* MediaDecoderStateMachine::GetStateMachineThread() const
{
return mScheduler->GetStateMachineThread();
}
bool MediaDecoderStateMachine::IsStateMachineScheduled() const
{
return mDispatchedStateMachine || mDelayedScheduler.IsScheduled();
return mScheduler->IsScheduled();
}
void MediaDecoderStateMachine::SetPlaybackRate(double aPlaybackRate)

Просмотреть файл

@ -89,8 +89,8 @@ hardware (via AudioStream).
#include "MediaDecoderReader.h"
#include "MediaDecoderOwner.h"
#include "MediaMetadataManager.h"
#include "MediaDecoderStateMachineScheduler.h"
#include "mozilla/RollingMean.h"
#include "MediaTimer.h"
class nsITimer;
@ -211,8 +211,8 @@ public:
void Play()
{
MOZ_ASSERT(NS_IsMainThread());
RefPtr<nsRunnable> r = NS_NewRunnableMethod(this, &MediaDecoderStateMachine::PlayInternal);
TaskQueue()->Dispatch(r);
nsRefPtr<nsRunnable> r = NS_NewRunnableMethod(this, &MediaDecoderStateMachine::PlayInternal);
GetStateMachineThread()->Dispatch(r, NS_DISPATCH_NORMAL);
}
private:
@ -311,30 +311,21 @@ public:
void NotifyDataArrived(const char* aBuffer, uint32_t aLength, int64_t aOffset);
// Returns the state machine task queue.
MediaTaskQueue* TaskQueue() const { return mTaskQueue; }
// Returns the shared state machine thread.
nsIEventTarget* GetStateMachineThread() const;
// Calls ScheduleStateMachine() after taking the decoder lock. Also
// notifies the decoder thread in case it's waiting on the decoder lock.
void ScheduleStateMachineWithLockAndWakeDecoder();
// Schedules the shared state machine thread to run the state machine.
void ScheduleStateMachine();
// Schedules the shared state machine thread to run the state machine
// in aUsecs microseconds from now, if it's not already scheduled to run
// earlier, in which case the request is discarded.
nsresult ScheduleStateMachine(int64_t aUsecs = 0);
// Invokes ScheduleStateMachine to run in |aMicroseconds| microseconds,
// unless it's already scheduled to run earlier, in which case the
// request is discarded.
void ScheduleStateMachineIn(int64_t aMicroseconds);
void OnDelayedSchedule()
{
MOZ_ASSERT(OnStateMachineThread());
ReentrantMonitorAutoEnter mon(mDecoder->GetReentrantMonitor());
mDelayedScheduler.CompleteRequest();
ScheduleStateMachine();
}
void NotReached() { MOZ_DIAGNOSTIC_ASSERT(false); }
// Callback function registered with MediaDecoderStateMachineScheduler
// to run state machine cycles.
static nsresult TimeoutExpired(void* aClosure);
// Set the media fragment end time. aEndTime is in microseconds.
void SetFragmentEndTime(int64_t aEndTime);
@ -698,6 +689,9 @@ protected:
void SendStreamAudio(AudioData* aAudio, DecodedStreamData* aStream,
AudioSegment* aOutput);
// State machine thread run function. Defers to RunStateMachine().
nsresult CallRunStateMachine();
// Performs one "cycle" of the state machine. Polls the state, and may send
// a video frame to be displayed, and generally manages the decode. Called
// periodically via timer to ensure the video stays in sync.
@ -751,60 +745,9 @@ protected:
// state machine, audio and main threads.
nsRefPtr<MediaDecoder> mDecoder;
// Task queue for running the state machine.
nsRefPtr<MediaTaskQueue> mTaskQueue;
// True is we are decoding a realtime stream, like a camera stream.
bool mRealTime;
// True if we've dispatched a task to run the state machine but the task has
// yet to run.
bool mDispatchedStateMachine;
// Class for managing delayed dispatches of the state machine.
class DelayedScheduler {
public:
explicit DelayedScheduler(MediaDecoderStateMachine* aSelf)
: mSelf(aSelf), mMediaTimer(new MediaTimer()) {}
bool IsScheduled() const { return !mTarget.IsNull(); }
void Reset()
{
MOZ_ASSERT(mSelf->OnStateMachineThread(),
"Must be on state machine queue to disconnect");
if (IsScheduled()) {
mRequest.Disconnect();
mTarget = TimeStamp();
}
}
void Ensure(mozilla::TimeStamp& aTarget)
{
if (IsScheduled() && mTarget <= aTarget) {
return;
}
Reset();
mTarget = aTarget;
mRequest.Begin(mMediaTimer->WaitUntil(mTarget, __func__)->RefableThen(
mSelf->TaskQueue(), __func__, mSelf,
&MediaDecoderStateMachine::OnDelayedSchedule,
&MediaDecoderStateMachine::NotReached));
}
void CompleteRequest()
{
mRequest.Complete();
mTarget = TimeStamp();
}
private:
MediaDecoderStateMachine* mSelf;
nsRefPtr<MediaTimer> mMediaTimer;
MediaPromiseConsumerHolder<mozilla::MediaTimerPromise> mRequest;
TimeStamp mTarget;
} mDelayedScheduler;
// Used to schedule state machine cycles. This should never outlive
// the life cycle of the state machine.
const nsRefPtr<MediaDecoderStateMachineScheduler> mScheduler;
// Time at which the last video sample was requested. If it takes too long
// before the sample arrives, we will increase the amount of audio we buffer.
@ -1012,7 +955,7 @@ protected:
// samples we must consume before are considered to be finished prerolling.
uint32_t AudioPrerollUsecs() const
{
if (IsRealTime()) {
if (mScheduler->IsRealTime()) {
return 0;
}
@ -1023,7 +966,7 @@ protected:
uint32_t VideoPrerollFrames() const
{
return IsRealTime() ? 0 : GetAmpleVideoFrames() / 2;
return mScheduler->IsRealTime() ? 0 : GetAmpleVideoFrames() / 2;
}
bool DonePrerollingAudio()

Просмотреть файл

@ -0,0 +1,194 @@
/* 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 "MediaDecoderStateMachineScheduler.h"
#include "SharedThreadPool.h"
#include "mozilla/Preferences.h"
#include "mozilla/ReentrantMonitor.h"
#include "nsITimer.h"
#include "nsComponentManagerUtils.h"
#include "VideoUtils.h"
namespace {
class TimerEvent : public nsITimerCallback, public nsRunnable {
typedef mozilla::MediaDecoderStateMachineScheduler Scheduler;
NS_DECL_ISUPPORTS_INHERITED
public:
TimerEvent(Scheduler* aScheduler, int aTimerId)
: mScheduler(aScheduler), mTimerId(aTimerId) {}
NS_IMETHOD Run() MOZ_OVERRIDE {
return mScheduler->TimeoutExpired(mTimerId);
}
NS_IMETHOD Notify(nsITimer* aTimer) MOZ_OVERRIDE {
return mScheduler->TimeoutExpired(mTimerId);
}
private:
~TimerEvent() {}
Scheduler* const mScheduler;
const int mTimerId;
};
NS_IMPL_ISUPPORTS_INHERITED(TimerEvent, nsRunnable, nsITimerCallback);
} // anonymous namespace
static already_AddRefed<nsIEventTarget>
CreateStateMachineThread()
{
using mozilla::SharedThreadPool;
using mozilla::RefPtr;
RefPtr<SharedThreadPool> threadPool(
SharedThreadPool::Get(NS_LITERAL_CSTRING("Media State Machine"), 1));
nsCOMPtr<nsIEventTarget> rv = threadPool.get();
return rv.forget();
}
namespace mozilla {
MediaDecoderStateMachineScheduler::MediaDecoderStateMachineScheduler(
ReentrantMonitor& aMonitor,
nsresult (*aTimeoutCallback)(void*),
void* aClosure, bool aRealTime)
: mTimeoutCallback(aTimeoutCallback)
, mClosure(aClosure)
// Only enable realtime mode when "media.realtime_decoder.enabled" is true.
, mRealTime(aRealTime &&
Preferences::GetBool("media.realtime_decoder.enabled", false))
, mMonitor(aMonitor)
, mEventTarget(CreateStateMachineThread())
, mTimer(do_CreateInstance("@mozilla.org/timer;1"))
, mTimerId(0)
, mState(SCHEDULER_STATE_NONE)
, mInRunningStateMachine(false)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_COUNT_CTOR(MediaDecoderStateMachineScheduler);
}
MediaDecoderStateMachineScheduler::~MediaDecoderStateMachineScheduler()
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_COUNT_DTOR(MediaDecoderStateMachineScheduler);
}
nsresult
MediaDecoderStateMachineScheduler::Init()
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mEventTarget, NS_ERROR_FAILURE);
nsresult rv = mTimer->SetTarget(mEventTarget);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult
MediaDecoderStateMachineScheduler::Schedule(int64_t aUsecs)
{
mMonitor.AssertCurrentThreadIn();
if (NS_WARN_IF(mState == SCHEDULER_STATE_SHUTDOWN)) {
return NS_ERROR_FAILURE;
}
aUsecs = std::max<int64_t>(aUsecs, 0);
TimeStamp timeout = TimeStamp::Now() +
TimeDuration::FromMilliseconds(static_cast<double>(aUsecs) / USECS_PER_MS);
if (!mTimeout.IsNull() && timeout >= mTimeout) {
// We've already scheduled a timer set to expire at or before this time,
// or have an event dispatched to run the state machine.
return NS_OK;
}
uint32_t ms = static_cast<uint32_t>((aUsecs / USECS_PER_MS) & 0xFFFFFFFF);
if (IsRealTime() && ms > 40) {
ms = 40;
}
// Don't cancel the timer here for this function will be called from
// different threads.
nsresult rv = NS_ERROR_FAILURE;
nsRefPtr<TimerEvent> event = new TimerEvent(this, mTimerId+1);
if (ms == 0) {
// Dispatch a runnable to the state machine thread when delay is 0.
// It will has less latency than dispatching a runnable to the state
// machine thread which will then schedule a zero-delay timer.
rv = mEventTarget->Dispatch(event, NS_DISPATCH_NORMAL);
} else if (OnStateMachineThread()) {
rv = mTimer->InitWithCallback(event, ms, nsITimer::TYPE_ONE_SHOT);
} else {
MOZ_ASSERT(false, "non-zero delay timer should be only "
"scheduled in state machine thread");
}
if (NS_SUCCEEDED(rv)) {
mTimeout = timeout;
++mTimerId;
} else {
NS_WARNING("Failed to schedule state machine");
}
return rv;
}
nsresult
MediaDecoderStateMachineScheduler::TimeoutExpired(int aTimerId)
{
ReentrantMonitorAutoEnter mon(mMonitor);
MOZ_ASSERT(OnStateMachineThread());
MOZ_ASSERT(!mInRunningStateMachine,
"State machine cycles must run in sequence!");
mInRunningStateMachine = true;
// Only run state machine cycles when id matches.
nsresult rv = NS_OK;
if (mTimerId == aTimerId) {
ResetTimer();
rv = mTimeoutCallback(mClosure);
}
mInRunningStateMachine = false;
return rv;
}
void
MediaDecoderStateMachineScheduler::ScheduleAndShutdown()
{
mMonitor.AssertCurrentThreadIn();
// Schedule next cycle to handle SHUTDOWN in state machine thread.
Schedule();
// This must be set after calling Schedule()
// which does nothing in shutdown state.
mState = SCHEDULER_STATE_SHUTDOWN;
}
bool
MediaDecoderStateMachineScheduler::OnStateMachineThread() const
{
bool rv = false;
mEventTarget->IsOnCurrentThread(&rv);
return rv;
}
bool
MediaDecoderStateMachineScheduler::IsScheduled() const
{
mMonitor.AssertCurrentThreadIn();
return !mTimeout.IsNull();
}
void
MediaDecoderStateMachineScheduler::ResetTimer()
{
mMonitor.AssertCurrentThreadIn();
mTimer->Cancel();
mTimeout = TimeStamp();
}
} // namespace mozilla

Просмотреть файл

@ -0,0 +1,78 @@
/* -*- 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/. */
#ifndef MediaDecoderStateMachineScheduler_h__
#define MediaDecoderStateMachineScheduler_h__
#include "nsCOMPtr.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/DebugOnly.h"
class nsITimer;
class nsIEventTarget;
namespace mozilla {
class ReentrantMonitor;
class MediaDecoderStateMachineScheduler {
enum State {
SCHEDULER_STATE_NONE,
SCHEDULER_STATE_SHUTDOWN
};
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MediaDecoderStateMachineScheduler)
MediaDecoderStateMachineScheduler(ReentrantMonitor& aMonitor,
nsresult (*aTimeoutCallback)(void*),
void* aClosure, bool aRealTime);
nsresult Init();
nsresult Schedule(int64_t aUsecs = 0);
void ScheduleAndShutdown();
nsresult TimeoutExpired(int aTimerId);
bool OnStateMachineThread() const;
bool IsScheduled() const;
bool IsRealTime() const {
return mRealTime;
}
nsIEventTarget* GetStateMachineThread() const {
return mEventTarget;
}
private:
~MediaDecoderStateMachineScheduler();
void ResetTimer();
// Callback function provided by MediaDecoderStateMachine to run
// state machine cycles.
nsresult (*const mTimeoutCallback)(void*);
// Since StateMachineScheduler will never outlive the state machine,
// it is safe to keep a raw pointer only to avoid reference cycles.
void* const mClosure;
// True is we are decoding a realtime stream, like a camera stream
const bool mRealTime;
// Monitor of the decoder
ReentrantMonitor& mMonitor;
// State machine thread
const nsCOMPtr<nsIEventTarget> mEventTarget;
// Timer to schedule callbacks to run the state machine cycles.
nsCOMPtr<nsITimer> mTimer;
// Timestamp at which the next state machine cycle will run.
TimeStamp mTimeout;
// The id of timer tasks, timer callback will only run if id matches.
int mTimerId;
// No more state machine cycles in shutdown state.
State mState;
// Used to check if state machine cycles are running in sequence.
DebugOnly<bool> mInRunningStateMachine;
};
} // namespace mozilla
#endif // MediaDecoderStateMachineScheduler_h__

Просмотреть файл

@ -6,6 +6,7 @@
#include "MediaPromise.h"
#include "MediaDecoderStateMachineScheduler.h"
#include "MediaTaskQueue.h"
#include "nsThreadUtils.h"
@ -24,6 +25,12 @@ DispatchMediaPromiseRunnable(nsIEventTarget* aEventTarget, nsIRunnable* aRunnabl
return aEventTarget->Dispatch(aRunnable, NS_DISPATCH_NORMAL);
}
nsresult
DispatchMediaPromiseRunnable(MediaDecoderStateMachineScheduler* aScheduler, nsIRunnable* aRunnable)
{
return aScheduler->GetStateMachineThread()->Dispatch(aRunnable, NS_DISPATCH_NORMAL);
}
void
AssertOnThread(MediaTaskQueue* aQueue)
{
@ -37,5 +44,11 @@ void AssertOnThread(nsIEventTarget* aTarget)
MOZ_ASSERT(NS_GetCurrentThread() == targetThread);
}
void
AssertOnThread(MediaDecoderStateMachineScheduler* aScheduler)
{
MOZ_ASSERT(aScheduler->OnStateMachineThread());
}
}
} // namespace mozilla

Просмотреть файл

@ -16,7 +16,6 @@
#include "mozilla/Maybe.h"
#include "mozilla/Mutex.h"
#include "mozilla/Monitor.h"
#include "mozilla/unused.h"
/* Polyfill __func__ on MSVC for consumers to pass to the MediaPromise API. */
#ifdef _MSC_VER
@ -33,14 +32,17 @@ extern PRLogModuleInfo* gMediaPromiseLog;
PR_LOG(gMediaPromiseLog, PR_LOG_DEBUG, (x, ##__VA_ARGS__))
class MediaTaskQueue;
class MediaDecoderStateMachineScheduler;
namespace detail {
nsresult DispatchMediaPromiseRunnable(MediaTaskQueue* aQueue, nsIRunnable* aRunnable);
nsresult DispatchMediaPromiseRunnable(nsIEventTarget* aTarget, nsIRunnable* aRunnable);
nsresult DispatchMediaPromiseRunnable(MediaDecoderStateMachineScheduler* aScheduler, nsIRunnable* aRunnable);
#ifdef DEBUG
void AssertOnThread(MediaTaskQueue* aQueue);
void AssertOnThread(nsIEventTarget* aTarget);
void AssertOnThread(MediaDecoderStateMachineScheduler* aScheduler);
#endif
} // namespace detail
@ -106,11 +108,18 @@ public:
public:
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(Consumer)
virtual void Disconnect() = 0;
void Disconnect()
{
AssertOnDispatchThread();
MOZ_DIAGNOSTIC_ASSERT(!mComplete);
mDisconnected = true;
}
// MSVC complains when an inner class (ThenValueBase::{Resolve,Reject}Runnable)
// tries to access an inherited protected member.
bool IsDisconnected() const { return mDisconnected; }
#ifdef DEBUG
virtual void AssertOnDispatchThread() = 0;
#else
void AssertOnDispatchThread() {}
#endif
protected:
Consumer() : mComplete(false), mDisconnected(false) {}
@ -140,7 +149,7 @@ protected:
~ResolveRunnable()
{
MOZ_DIAGNOSTIC_ASSERT(!mThenValue || mThenValue->IsDisconnected());
MOZ_ASSERT(!mThenValue);
}
NS_IMETHODIMP Run()
@ -165,7 +174,7 @@ protected:
~RejectRunnable()
{
MOZ_DIAGNOSTIC_ASSERT(!mThenValue || mThenValue->IsDisconnected());
MOZ_ASSERT(!mThenValue);
}
NS_IMETHODIMP Run()
@ -243,54 +252,35 @@ protected:
PROMISE_LOG("%s Then() call made from %s [Runnable=%p, Promise=%p, ThenValue=%p]",
resolved ? "Resolving" : "Rejecting", ThenValueBase::mCallSite,
runnable.get(), aPromise, this);
nsresult rv = detail::DispatchMediaPromiseRunnable(mResponseTarget, runnable);
unused << rv;
// NB: mDisconnected is only supposed to be accessed on the dispatch
// thread. However, we require the consumer to have disconnected any
// oustanding promise requests _before_ initiating shutdown on the
// thread or task queue. So the only non-buggy scenario for dispatch
// failing involves the target thread being unable to manipulate the
// ThenValue (since it's been disconnected), so it's safe to read here.
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv) || Consumer::mDisconnected);
DebugOnly<nsresult> rv = detail::DispatchMediaPromiseRunnable(mResponseTarget, runnable);
MOZ_ASSERT(NS_SUCCEEDED(rv));
}
#ifdef DEBUG
void AssertOnDispatchThread()
virtual void AssertOnDispatchThread() MOZ_OVERRIDE
{
detail::AssertOnThread(mResponseTarget);
}
#else
void AssertOnDispatchThread() {}
#endif
virtual void Disconnect() MOZ_OVERRIDE
{
AssertOnDispatchThread();
MOZ_DIAGNOSTIC_ASSERT(!Consumer::mComplete);
Consumer::mDisconnected = true;
// If a Consumer has been disconnected, we don't guarantee that the
// resolve/reject runnable will be dispatched. Null out our refcounted
// this-value now so that it's released predictably on the dispatch thread.
mThisVal = nullptr;
}
protected:
virtual void DoResolve(ResolveValueType aResolveValue) MOZ_OVERRIDE
{
Consumer::mComplete = true;
if (Consumer::mDisconnected) {
MOZ_ASSERT(!mThisVal);
PROMISE_LOG("ThenValue::DoResolve disconnected - bailing out [this=%p]", this);
// Null these out for the same reasons described below.
mResponseTarget = nullptr;
mThisVal = nullptr;
return;
}
InvokeCallbackMethod(mThisVal.get(), mResolveMethod, aResolveValue);
// Null out mThisVal after invoking the callback so that any references are
// released predictably on the dispatch thread. Otherwise, it would be
// Null these out after invoking the callback so that any references are
// released predictably on the target thread. Otherwise, they would be
// released on whatever thread last drops its reference to the ThenValue,
// which may or may not be ok.
mResponseTarget = nullptr;
mThisVal = nullptr;
}
@ -298,22 +288,25 @@ protected:
{
Consumer::mComplete = true;
if (Consumer::mDisconnected) {
MOZ_ASSERT(!mThisVal);
PROMISE_LOG("ThenValue::DoReject disconnected - bailing out [this=%p]", this);
// Null these out for the same reasons described below.
mResponseTarget = nullptr;
mThisVal = nullptr;
return;
}
InvokeCallbackMethod(mThisVal.get(), mRejectMethod, aRejectValue);
// Null out mThisVal after invoking the callback so that any references are
// released predictably on the dispatch thread. Otherwise, it would be
// Null these out after invoking the callback so that any references are
// released predictably on the target thread. Otherwise, they would be
// released on whatever thread last drops its reference to the ThenValue,
// which may or may not be ok.
mResponseTarget = nullptr;
mThisVal = nullptr;
}
private:
nsRefPtr<TargetType> mResponseTarget; // May be released on any thread.
nsRefPtr<ThisType> mThisVal; // Only accessed and refcounted on dispatch thread.
nsRefPtr<TargetType> mResponseTarget;
nsRefPtr<ThisType> mThisVal;
ResolveMethodType mResolveMethod;
RejectMethodType mRejectMethod;
};
@ -668,7 +661,7 @@ ProxyInternal(TargetType* aTarget, MethodCallBase<PromiseType>* aMethodCall, con
nsRefPtr<ProxyRunnable<PromiseType>> r = new ProxyRunnable<PromiseType>(p, aMethodCall);
nsresult rv = detail::DispatchMediaPromiseRunnable(aTarget, r);
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
unused << rv;
(void) rv; // Avoid compilation failures in builds with MOZ_DIAGNOSTIC_ASSERT disabled.
return Move(p);
}

Просмотреть файл

@ -157,7 +157,7 @@ template <class T> class MediaQueue : private nsDeque {
mPopListeners.Clear();
}
void AddPopListener(nsIRunnable* aRunnable, MediaTaskQueue* aTarget) {
void AddPopListener(nsIRunnable* aRunnable, nsIEventTarget* aTarget) {
ReentrantMonitorAutoEnter mon(mReentrantMonitor);
mPopListeners.AppendElement(Listener(aRunnable, aTarget));
}
@ -166,7 +166,7 @@ private:
mutable ReentrantMonitor mReentrantMonitor;
struct Listener {
Listener(nsIRunnable* aRunnable, MediaTaskQueue* aTarget)
Listener(nsIRunnable* aRunnable, nsIEventTarget* aTarget)
: mRunnable(aRunnable)
, mTarget(aTarget)
{
@ -177,7 +177,7 @@ private:
{
}
RefPtr<nsIRunnable> mRunnable;
RefPtr<MediaTaskQueue> mTarget;
RefPtr<nsIEventTarget> mTarget;
};
nsTArray<Listener> mPopListeners;
@ -185,7 +185,7 @@ private:
void NotifyPopListeners() {
for (uint32_t i = 0; i < mPopListeners.Length(); i++) {
Listener& l = mPopListeners[i];
l.mTarget->Dispatch(l.mRunnable);
l.mTarget->Dispatch(l.mRunnable, NS_DISPATCH_NORMAL);
}
}

Просмотреть файл

@ -278,7 +278,7 @@ MediaStreamGraphImpl::UpdateBufferSufficiencyState(SourceMediaStream* aStream)
}
for (uint32_t i = 0; i < runnables.Length(); ++i) {
runnables[i].mTarget->Dispatch(runnables[i].mRunnable);
runnables[i].mTarget->Dispatch(runnables[i].mRunnable, 0);
}
}
@ -2476,21 +2476,21 @@ SourceMediaStream::GetEndOfAppendedData(TrackID aID)
void
SourceMediaStream::DispatchWhenNotEnoughBuffered(TrackID aID,
MediaTaskQueue* aSignalQueue, nsIRunnable* aSignalRunnable)
nsIEventTarget* aSignalThread, nsIRunnable* aSignalRunnable)
{
MutexAutoLock lock(mMutex);
TrackData* data = FindDataForTrack(aID);
if (!data) {
aSignalQueue->Dispatch(aSignalRunnable);
aSignalThread->Dispatch(aSignalRunnable, 0);
return;
}
if (data->mHaveEnough) {
if (data->mDispatchWhenNotEnough.IsEmpty()) {
data->mDispatchWhenNotEnough.AppendElement()->Init(aSignalQueue, aSignalRunnable);
data->mDispatchWhenNotEnough.AppendElement()->Init(aSignalThread, aSignalRunnable);
}
} else {
aSignalQueue->Dispatch(aSignalRunnable);
aSignalThread->Dispatch(aSignalRunnable, 0);
}
}

Просмотреть файл

@ -16,7 +16,6 @@
#include "VideoFrameContainer.h"
#include "VideoSegment.h"
#include "MainThreadUtils.h"
#include "MediaTaskQueue.h"
#include "nsAutoRef.h"
#include "GraphDriver.h"
#include <speex/speex_resampler.h>
@ -784,7 +783,7 @@ public:
* does not exist. No op if a runnable is already present for this track.
*/
void DispatchWhenNotEnoughBuffered(TrackID aID,
MediaTaskQueue* aSignalQueue, nsIRunnable* aSignalRunnable);
nsIEventTarget* aSignalThread, nsIRunnable* aSignalRunnable);
/**
* Indicate that a track has ended. Do not do any more API calls
* affecting this track.
@ -848,14 +847,14 @@ public:
protected:
struct ThreadAndRunnable {
void Init(MediaTaskQueue* aTarget, nsIRunnable* aRunnable)
void Init(nsIEventTarget* aTarget, nsIRunnable* aRunnable)
{
mTarget = aTarget;
mRunnable = aRunnable;
}
nsRefPtr<MediaTaskQueue> mTarget;
RefPtr<nsIRunnable> mRunnable;
nsCOMPtr<nsIEventTarget> mTarget;
nsCOMPtr<nsIRunnable> mRunnable;
};
enum TrackCommands {
TRACK_CREATE = MediaStreamListener::TRACK_EVENT_CREATED,

Просмотреть файл

@ -1,165 +0,0 @@
/* -*- 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 "MediaTimer.h"
#include <math.h>
#include "nsComponentManagerUtils.h"
#include "nsThreadUtils.h"
namespace mozilla {
NS_IMPL_ADDREF(MediaTimer)
NS_IMPL_RELEASE_WITH_DESTROY(MediaTimer, DispatchDestroy())
MediaTimer::MediaTimer()
: mMonitor("MediaTimer Monitor")
, mTimer(do_CreateInstance("@mozilla.org/timer;1"))
, mUpdateScheduled(false)
{
// Use the SharedThreadPool to create an nsIThreadPool with a maximum of one
// thread, which is equivalent to an nsIThread for our purposes.
RefPtr<SharedThreadPool> threadPool(
SharedThreadPool::Get(NS_LITERAL_CSTRING("MediaTimer"), 1));
mThread = threadPool.get();
mTimer->SetTarget(mThread);
}
void
MediaTimer::DispatchDestroy()
{
nsCOMPtr<nsIRunnable> task = NS_NewNonOwningRunnableMethod(this, &MediaTimer::Destroy);
nsresult rv = mThread->Dispatch(task, NS_DISPATCH_NORMAL);
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
(void) rv;
}
void
MediaTimer::Destroy()
{
MOZ_ASSERT(OnMediaTimerThread());
// Reject any outstanding entries. There's no need to acquire the monitor
// here, because we're on the timer thread and all other references to us
// must be gone.
while (!mEntries.empty()) {
mEntries.top().mPromise->Reject(false, __func__);
mEntries.pop();
}
// Cancel the timer if necessary.
CancelTimerIfArmed();
delete this;
}
bool
MediaTimer::OnMediaTimerThread()
{
bool rv = false;
mThread->IsOnCurrentThread(&rv);
return rv;
}
nsRefPtr<MediaTimerPromise>
MediaTimer::WaitUntil(const TimeStamp& aTimeStamp, const char* aCallSite)
{
MonitorAutoLock mon(mMonitor);
Entry e(aTimeStamp, aCallSite);
nsRefPtr<MediaTimerPromise> p = e.mPromise.get();
mEntries.push(e);
ScheduleUpdate();
return p;
}
void
MediaTimer::ScheduleUpdate()
{
mMonitor.AssertCurrentThreadOwns();
if (mUpdateScheduled) {
return;
}
mUpdateScheduled = true;
nsCOMPtr<nsIRunnable> task = NS_NewRunnableMethod(this, &MediaTimer::Update);
nsresult rv = mThread->Dispatch(task, NS_DISPATCH_NORMAL);
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
(void) rv;
}
void
MediaTimer::Update()
{
MonitorAutoLock mon(mMonitor);
UpdateLocked();
}
void
MediaTimer::UpdateLocked()
{
MOZ_ASSERT(OnMediaTimerThread());
mMonitor.AssertCurrentThreadOwns();
mUpdateScheduled = false;
// Resolve all the promises whose time is up.
TimeStamp now = TimeStamp::Now();
while (!mEntries.empty() && mEntries.top().mTimeStamp < now) {
mEntries.top().mPromise->Resolve(true, __func__);
mEntries.pop();
}
// If we've got no more entries, cancel any pending timer and bail out.
if (mEntries.empty()) {
CancelTimerIfArmed();
return;
}
// We've got more entries - (re)arm the timer for the soonest one.
if (!TimerIsArmed() || mEntries.top().mTimeStamp < mCurrentTimerTarget) {
CancelTimerIfArmed();
ArmTimer(mEntries.top().mTimeStamp, now);
}
}
/*
* We use a callback function, rather than a callback method, to ensure that
* the nsITimer does not artifically keep the refcount of the MediaTimer above
* zero. When the MediaTimer is destroyed, it safely cancels the nsITimer so that
* we never fire against a dangling closure.
*/
/* static */ void
MediaTimer::TimerCallback(nsITimer* aTimer, void* aClosure)
{
static_cast<MediaTimer*>(aClosure)->TimerFired();
}
void
MediaTimer::TimerFired()
{
MonitorAutoLock mon(mMonitor);
MOZ_ASSERT(OnMediaTimerThread());
mCurrentTimerTarget = TimeStamp();
UpdateLocked();
}
void
MediaTimer::ArmTimer(const TimeStamp& aTarget, const TimeStamp& aNow)
{
MOZ_DIAGNOSTIC_ASSERT(!TimerIsArmed());
MOZ_DIAGNOSTIC_ASSERT(aTarget > aNow);
// XPCOM timer resolution is in milliseconds. It's important to never resolve
// a timer when mTarget might compare < now (even if very close), so round up.
unsigned long delay = std::ceil((aTarget - aNow).ToMilliseconds());
mCurrentTimerTarget = aTarget;
nsresult rv = mTimer->InitWithFuncCallback(&TimerCallback, this, delay, nsITimer::TYPE_ONE_SHOT);
MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
(void) rv;
}
} // namespace mozilla

Просмотреть файл

@ -1,99 +0,0 @@
/* -*- 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/. */
#if !defined(MediaTimer_h_)
#define MediaTimer_h_
#include "MediaPromise.h"
#include <queue>
#include "nsITimer.h"
#include "nsRefPtr.h"
#include "mozilla/Monitor.h"
#include "mozilla/TimeStamp.h"
namespace mozilla {
// This promise type is only exclusive because so far there isn't a reason for
// it not to be. Feel free to change that.
typedef MediaPromise<bool, bool, /* IsExclusive = */ true> MediaTimerPromise;
// Timers only know how to fire at a given thread, which creates an impedence
// mismatch with code that operates with MediaTaskQueues. This class solves
// that mismatch with a dedicated (but shared) thread and a nice MediaPromise-y
// interface.
class MediaTimer
{
public:
MediaTimer();
// We use a release with a custom Destroy().
NS_IMETHOD_(MozExternalRefCountType) AddRef(void);
NS_IMETHOD_(MozExternalRefCountType) Release(void);
nsRefPtr<MediaTimerPromise> WaitUntil(const TimeStamp& aTimeStamp, const char* aCallSite);
private:
virtual ~MediaTimer() { MOZ_ASSERT(OnMediaTimerThread()); }
void DispatchDestroy(); // Invoked by Release on an arbitrary thread.
void Destroy(); // Runs on the timer thread.
bool OnMediaTimerThread();
void ScheduleUpdate();
void Update();
void UpdateLocked();
static void TimerCallback(nsITimer* aTimer, void* aClosure);
void TimerFired();
void ArmTimer(const TimeStamp& aTarget, const TimeStamp& aNow);
bool TimerIsArmed()
{
return !mCurrentTimerTarget.IsNull();
}
void CancelTimerIfArmed()
{
MOZ_ASSERT(OnMediaTimerThread());
if (TimerIsArmed()) {
mTimer->Cancel();
mCurrentTimerTarget = TimeStamp();
}
}
struct Entry
{
TimeStamp mTimeStamp;
nsRefPtr<MediaTimerPromise::Private> mPromise;
explicit Entry(const TimeStamp& aTimeStamp, const char* aCallSite)
: mTimeStamp(aTimeStamp)
, mPromise(new MediaTimerPromise::Private(aCallSite))
{}
bool operator<(const Entry& aOther) const
{
return mTimeStamp < aOther.mTimeStamp;
}
};
ThreadSafeAutoRefCnt mRefCnt;
NS_DECL_OWNINGTHREAD
nsCOMPtr<nsIEventTarget> mThread;
std::priority_queue<Entry> mEntries;
Monitor mMonitor;
nsCOMPtr<nsITimer> mTimer;
TimeStamp mCurrentTimerTarget;
bool mUpdateScheduled;
};
} // namespace mozilla
#endif

Просмотреть файл

@ -102,6 +102,7 @@ EXPORTS += [
'MediaDecoderOwner.h',
'MediaDecoderReader.h',
'MediaDecoderStateMachine.h',
'MediaDecoderStateMachineScheduler.h',
'MediaInfo.h',
'MediaMetadataManager.h',
'MediaPromise.h',
@ -111,7 +112,6 @@ EXPORTS += [
'MediaSegment.h',
'MediaStreamGraph.h',
'MediaTaskQueue.h',
'MediaTimer.h',
'MediaTrack.h',
'MediaTrackList.h',
'MP3FrameParser.h',
@ -181,6 +181,7 @@ UNIFIED_SOURCES += [
'MediaDecoder.cpp',
'MediaDecoderReader.cpp',
'MediaDecoderStateMachine.cpp',
'MediaDecoderStateMachineScheduler.cpp',
'MediaDevices.cpp',
'MediaManager.cpp',
'MediaPromise.cpp',
@ -191,7 +192,6 @@ UNIFIED_SOURCES += [
'MediaStreamGraph.cpp',
'MediaStreamTrack.cpp',
'MediaTaskQueue.cpp',
'MediaTimer.cpp',
'MediaTrack.cpp',
'MediaTrackList.cpp',
'MP3FrameParser.cpp',