Files
palemoon27/image/DecodePool.cpp
T
roytam1 e7535dc94b import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1187401 (Part 1) - Simplify the condition that determines whether we set RasterImage::mHasBeenDecoded. r=tn (69be36e7ef)
- Bug 1187401 (Part 2) - Eliminate the nsresult return value from RasterImage::SetMetadata, since it's not used anymore. r=tn (dc521c4b9f)
- Bug 1187401 (Part 3) - For consistency, call DoError if SetMetadata sees a negative size. r=tn (d9ca8ec91b)
- Bug 1207183 - micro-optimize removing work items from DecodePool's queues; r=seth (6bd2717e3a)
- No bug - Fix out-of-date comment in Decoder.cpp. r=me (54fdbbd444)
- Bug 1181324 - Eliminate the duplicate mRefCnt member in MultipartImage. r=seth (c4512a443e)
- Bug 1180105 - Do not leak the SourceSurface returned from imgIContainer::GetFrame in BlockUntilDecodedAndFinishObserving; r=seth (1cadbffc53)
- Bug 1181909 - Fix potential null dereference in NextPartObserver. r=tn (cfd8ad0119)
- Bug 108603 - Remove NS_IMPL_QUERY_INTERFACE_INHERITED0. r=mccr8, r=froydnj (4bfa6771fc)
- Bug 1159502 - Don't block onload for multipart images. r=tn (8b50eadf39)
- Bug 1200413 - Part 1: Re-write RefCountedInsideLambdaChecker to use captures instead of checking for DeclRef instances, r=ehsan (80ef99efe2)
- Bug 1200413 - Part 2: Make lambdas in ProgressTracker.cpp capture strong references, r=seth (9e4d96dffa)
- Bug 1194557 - Ensure that if the image was locked before RecoverFromLossOfFrames() was called, it's still locked afterwards. r=tn (ea4dc6ea9f)
- code style (ad3773ba42)
- Bug 1167590 - Mark imgRequestProxy::mListener as MOZ_UNSAFE_REF. r=seth (946ffaed8a)
- Bug 1148397 - Fix data race on imgRequest::mHadInsecureRedirect. r=tanvi (e73d0664f3)
- No bug - Tweak formatting of logging statement in imgRequest. r=me (cab2bcb014)
- Bug 1180126 - Read content disposition regardless of content type in imgRequest::PrepareForNewPart. r=tn (2934597743)
- Bug 1139225 - Followup - Remove duplicate multiPartChannel variable. (7f7f555a0b)
- Bug 1141398 - Do not always revalidate image cache entries for file URIs. r=tn (31d73cb508)
- Bug 1183563 - Fix incorrect mixed content warning after internal redirects. r=tanvi, r=seth (12a6c8a15f)
- Bug 1150127 - Stop leaking windows via imgCacheValidator. r=baku (a7809c5fa7)
- bits of Bug 1102048 (Part 20, imgLoader) (b2098c8a5a)
- (No bug) - Correct blatantly lying comment in imgLoader.cpp. r=me DONTBUILD (64c42a5b09)
- Bug 1160592 - Report image source size again in about:memory. r=dholbert (4e04cf3c3e)
- Add an assertion for the first argument of NewImageChannel, no bug (4c8f087a8f)
- Bug 1127534 - Remove assertion before creating a channel (r=sicking) (988692dc91)
- Bug 1175371 - Make VectorImage wait to deliver LOAD_COMPLETE until its size is available. r=dholbert (3c81e0daff)
- Bug 1181323 - Move nsSVGRenderingObserver's isupports/refcounting decl to subclasses, since one subclass (nsSVGFilterReference) already has its own redundant copy of the decl. r=dholbert (6171171c2c)
- Bug 1161722 - If we're shutting down, don't warn about untracked unlocked surfaces. r=dholbert (f7e18ce481)
- Bug 1170877 - Track how many times the SurfaceCache has overflowed and report it in about:memory. r=dholbert (884176cb1d)
- Bug 1161743 - Upgrade 'WARNING: Not expiration-tracking an unlocked surface' to an assertion. r=dholbert (9900169e7b)
- Bug 1167557 - Crash when a null surface is passed to SurfaceCache::Insert. r=dholbert (b3c4cf60aa)
- remove bypass cache not fonud either in FF nor TF (3ed4056a27)
- Missing bit Bug 1102048 (Part 25, header guards) - Make image/src files comply (cb8ed2428f)
- No bug - Remove obsolete comment in SourceBuffer.h. r=me (6e9c233448)
- coding style (94b7269690)
- Bug 1157065 - GFX: 2D: Add Loongson3 MMI helpers. r=jrmuizel (ebce946c91)
- reverto to FF52 and TFF settings (e147a8c7b5)
- Bug 1134599 - Fix rpi build target. r=jrmuizel, r=shuang (b9722f860c)
- Bug 1129147 - Part 1. Take CanvasPath into a separate file, to avoid circular dependency. r=roc (859bcad807)
- Bug 1129147 - Part 2. Path option to addHitRegion. r=ehsan r=gw280 (b2ab08a8a1)
- Bug 1206076: Use a specialized PersistentBufferProvider for Canvas2D when using a SkiaGL DrawTarget. r=jrmuizel (859589caf8)
- Bug 1188752 - Addendum: Make PersistentBufferProviderBasic constructor explicit. r=bustage on a CLOSED TREE (a27a4dc974)
- style (72a65dcb26)
- Bug 1198574 - Remove unnecessary argument for PersistentBufferProvider. r=bas (dca718bba8)
- Bug 1163124 - The initial value of the canvas filter property should be "none". r=roc (59df6a01d8)
2022-05-20 09:45:08 +08:00

504 lines
12 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "DecodePool.h"
#include <algorithm>
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Monitor.h"
#include "nsAutoPtr.h"
#include "nsCOMPtr.h"
#include "nsIObserverService.h"
#include "nsIThreadPool.h"
#include "nsThreadManager.h"
#include "nsThreadUtils.h"
#include "nsXPCOMCIDInternal.h"
#include "prsystem.h"
#ifdef MOZ_NUWA_PROCESS
#include "ipc/Nuwa.h"
#endif
#include "gfxPrefs.h"
#include "Decoder.h"
#include "RasterImage.h"
using std::max;
using std::min;
namespace mozilla {
namespace image {
///////////////////////////////////////////////////////////////////////////////
// Helper runnables.
///////////////////////////////////////////////////////////////////////////////
class NotifyProgressWorker : public nsRunnable
{
public:
/**
* Called by the DecodePool when it's done some significant portion of
* decoding, so that progress can be recorded and notifications can be sent.
*/
static void Dispatch(RasterImage* aImage,
Progress aProgress,
const nsIntRect& aInvalidRect,
SurfaceFlags aSurfaceFlags)
{
MOZ_ASSERT(aImage);
nsCOMPtr<nsIRunnable> worker =
new NotifyProgressWorker(aImage, aProgress, aInvalidRect, aSurfaceFlags);
NS_DispatchToMainThread(worker);
}
NS_IMETHOD Run() override
{
MOZ_ASSERT(NS_IsMainThread());
mImage->NotifyProgress(mProgress, mInvalidRect, mSurfaceFlags);
return NS_OK;
}
private:
NotifyProgressWorker(RasterImage* aImage,
Progress aProgress,
const nsIntRect& aInvalidRect,
SurfaceFlags aSurfaceFlags)
: mImage(aImage)
, mProgress(aProgress)
, mInvalidRect(aInvalidRect)
, mSurfaceFlags(aSurfaceFlags)
{ }
nsRefPtr<RasterImage> mImage;
const Progress mProgress;
const nsIntRect mInvalidRect;
const SurfaceFlags mSurfaceFlags;
};
class NotifyDecodeCompleteWorker : public nsRunnable
{
public:
/**
* Called by the DecodePool when decoding is complete, so that final cleanup
* can be performed.
*/
static void Dispatch(Decoder* aDecoder)
{
MOZ_ASSERT(aDecoder);
nsCOMPtr<nsIRunnable> worker = new NotifyDecodeCompleteWorker(aDecoder);
NS_DispatchToMainThread(worker);
}
NS_IMETHOD Run() override
{
MOZ_ASSERT(NS_IsMainThread());
mDecoder->GetImage()->FinalizeDecoder(mDecoder);
return NS_OK;
}
private:
explicit NotifyDecodeCompleteWorker(Decoder* aDecoder)
: mDecoder(aDecoder)
{ }
nsRefPtr<Decoder> mDecoder;
};
#ifdef MOZ_NUWA_PROCESS
class RegisterDecodeIOThreadWithNuwaRunnable : public nsRunnable
{
public:
NS_IMETHOD Run()
{
NuwaMarkCurrentThread(static_cast<void(*)(void*)>(nullptr), nullptr);
return NS_OK;
}
};
#endif // MOZ_NUWA_PROCESS
///////////////////////////////////////////////////////////////////////////////
// DecodePool implementation.
///////////////////////////////////////////////////////////////////////////////
/* static */ StaticRefPtr<DecodePool> DecodePool::sSingleton;
/* static */ uint32_t DecodePool::sNumCores = 0;
NS_IMPL_ISUPPORTS(DecodePool, nsIObserver)
struct Work
{
enum class Type {
DECODE,
SHUTDOWN
} mType;
nsRefPtr<Decoder> mDecoder;
};
class DecodePoolImpl
{
public:
MOZ_DECLARE_REFCOUNTED_TYPENAME(DecodePoolImpl)
NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DecodePoolImpl)
DecodePoolImpl()
: mMonitor("DecodePoolImpl")
, mShuttingDown(false)
{ }
/// Initialize the current thread for use by the decode pool.
void InitCurrentThread()
{
MOZ_ASSERT(!NS_IsMainThread());
mThreadNaming.SetThreadPoolName(NS_LITERAL_CSTRING("ImgDecoder"));
#ifdef MOZ_NUWA_PROCESS
if (IsNuwaProcess()) {
NuwaMarkCurrentThread(static_cast<void(*)(void*)>(nullptr), nullptr);
}
#endif // MOZ_NUWA_PROCESS
}
/// Shut down the provided decode pool thread.
static void ShutdownThread(nsIThread* aThisThread)
{
// Threads have to be shut down from another thread, so we'll ask the
// main thread to do it for us.
nsCOMPtr<nsIRunnable> runnable =
NS_NewRunnableMethod(aThisThread, &nsIThread::Shutdown);
NS_DispatchToMainThread(runnable);
}
/**
* Requests shutdown. New work items will be dropped on the floor, and all
* decode pool threads will be shut down once existing work items have been
* processed.
*/
void RequestShutdown()
{
MonitorAutoLock lock(mMonitor);
mShuttingDown = true;
mMonitor.NotifyAll();
}
/// Pushes a new decode work item.
void PushWork(Decoder* aDecoder)
{
MOZ_ASSERT(aDecoder);
nsRefPtr<Decoder> decoder(aDecoder);
MonitorAutoLock lock(mMonitor);
if (mShuttingDown) {
// Drop any new work on the floor if we're shutting down.
return;
}
if (aDecoder->IsMetadataDecode()) {
mMetadataDecodeQueue.AppendElement(Move(decoder));
} else {
mFullDecodeQueue.AppendElement(Move(decoder));
}
mMonitor.Notify();
}
/// Pops a new work item, blocking if necessary.
Work PopWork()
{
MonitorAutoLock lock(mMonitor);
do {
// Prioritize metadata decodes over full decodes.
if (!mMetadataDecodeQueue.IsEmpty()) {
return PopWorkFromQueue(mMetadataDecodeQueue);
}
if (!mFullDecodeQueue.IsEmpty()) {
return PopWorkFromQueue(mFullDecodeQueue);
}
if (mShuttingDown) {
Work work;
work.mType = Work::Type::SHUTDOWN;
return work;
}
// Nothing to do; block until some work is available.
mMonitor.Wait();
} while (true);
}
private:
~DecodePoolImpl() { }
Work PopWorkFromQueue(nsTArray<nsRefPtr<Decoder>>& aQueue)
{
Work work;
work.mType = Work::Type::DECODE;
work.mDecoder = aQueue.LastElement().forget();
aQueue.RemoveElementAt(aQueue.Length() - 1);
return work;
}
nsThreadPoolNaming mThreadNaming;
// mMonitor guards the queues and mShuttingDown.
Monitor mMonitor;
nsTArray<nsRefPtr<Decoder>> mMetadataDecodeQueue;
nsTArray<nsRefPtr<Decoder>> mFullDecodeQueue;
bool mShuttingDown;
};
class DecodePoolWorker : public nsRunnable
{
public:
explicit DecodePoolWorker(DecodePoolImpl* aImpl) : mImpl(aImpl) { }
NS_IMETHOD Run()
{
MOZ_ASSERT(!NS_IsMainThread());
mImpl->InitCurrentThread();
nsCOMPtr<nsIThread> thisThread;
nsThreadManager::get()->GetCurrentThread(getter_AddRefs(thisThread));
do {
Work work = mImpl->PopWork();
switch (work.mType) {
case Work::Type::DECODE:
DecodePool::Singleton()->Decode(work.mDecoder);
break;
case Work::Type::SHUTDOWN:
DecodePoolImpl::ShutdownThread(thisThread);
return NS_OK;
default:
MOZ_ASSERT_UNREACHABLE("Unknown work type");
}
} while (true);
MOZ_ASSERT_UNREACHABLE("Exiting thread without Work::Type::SHUTDOWN");
return NS_OK;
}
private:
nsRefPtr<DecodePoolImpl> mImpl;
};
/* static */ void
DecodePool::Initialize()
{
MOZ_ASSERT(NS_IsMainThread());
sNumCores = PR_GetNumberOfProcessors();
DecodePool::Singleton();
}
/* static */ DecodePool*
DecodePool::Singleton()
{
if (!sSingleton) {
MOZ_ASSERT(NS_IsMainThread());
sSingleton = new DecodePool();
ClearOnShutdown(&sSingleton);
}
return sSingleton;
}
/* static */ uint32_t
DecodePool::NumberOfCores()
{
return sNumCores;
}
DecodePool::DecodePool()
: mImpl(new DecodePoolImpl)
, mMutex("image::DecodePool")
{
// Determine the number of threads we want.
int32_t prefLimit = gfxPrefs::ImageMTDecodingLimit();
uint32_t limit;
if (prefLimit <= 0) {
int32_t numCores = NumberOfCores();
if (numCores <= 1) {
limit = 1;
} else if (numCores == 2) {
// On an otherwise mostly idle system, having two image decoding threads
// doubles decoding performance, so it's worth doing on dual-core devices,
// even if under load we can't actually get that level of parallelism.
limit = 2;
} else {
limit = numCores - 1;
}
} else {
limit = static_cast<uint32_t>(prefLimit);
}
// Initialize the thread pool.
for (uint32_t i = 0 ; i < limit ; ++i) {
nsCOMPtr<nsIRunnable> worker = new DecodePoolWorker(mImpl);
nsCOMPtr<nsIThread> thread;
nsresult rv = NS_NewThread(getter_AddRefs(thread), worker);
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && thread,
"Should successfully create image decoding threads");
mThreads.AppendElement(Move(thread));
}
// Initialize the I/O thread.
nsresult rv = NS_NewNamedThread("ImageIO", getter_AddRefs(mIOThread));
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv) && mIOThread,
"Should successfully create image I/O thread");
#ifdef MOZ_NUWA_PROCESS
nsCOMPtr<nsIRunnable> worker = new RegisterDecodeIOThreadWithNuwaRunnable();
rv = mIOThread->Dispatch(worker, NS_DISPATCH_NORMAL);
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv),
"Should register decode IO thread with Nuwa process");
#endif
nsCOMPtr<nsIObserverService> obsSvc = services::GetObserverService();
if (obsSvc) {
obsSvc->AddObserver(this, "xpcom-shutdown-threads", false);
}
}
DecodePool::~DecodePool()
{
MOZ_ASSERT(NS_IsMainThread(), "Must shut down DecodePool on main thread!");
}
NS_IMETHODIMP
DecodePool::Observe(nsISupports*, const char* aTopic, const char16_t*)
{
MOZ_ASSERT(strcmp(aTopic, "xpcom-shutdown-threads") == 0, "Unexpected topic");
nsCOMArray<nsIThread> threads;
nsCOMPtr<nsIThread> ioThread;
{
MutexAutoLock lock(mMutex);
threads.AppendElements(mThreads);
mThreads.Clear();
ioThread.swap(mIOThread);
}
mImpl->RequestShutdown();
for (int32_t i = 0 ; i < threads.Count() ; ++i) {
threads[i]->Shutdown();
}
if (ioThread) {
ioThread->Shutdown();
}
return NS_OK;
}
void
DecodePool::AsyncDecode(Decoder* aDecoder)
{
MOZ_ASSERT(aDecoder);
mImpl->PushWork(aDecoder);
}
void
DecodePool::SyncDecodeIfSmall(Decoder* aDecoder)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aDecoder);
if (aDecoder->ShouldSyncDecode(gfxPrefs::ImageMemDecodeBytesAtATime())) {
Decode(aDecoder);
return;
}
AsyncDecode(aDecoder);
}
void
DecodePool::SyncDecodeIfPossible(Decoder* aDecoder)
{
MOZ_ASSERT(NS_IsMainThread());
Decode(aDecoder);
}
already_AddRefed<nsIEventTarget>
DecodePool::GetIOEventTarget()
{
MutexAutoLock threadPoolLock(mMutex);
nsCOMPtr<nsIEventTarget> target = do_QueryInterface(mIOThread);
return target.forget();
}
void
DecodePool::Decode(Decoder* aDecoder)
{
MOZ_ASSERT(aDecoder);
nsresult rv = aDecoder->Decode();
if (NS_SUCCEEDED(rv) && !aDecoder->GetDecodeDone()) {
// If this isn't a metadata decode, notify for the progress we've made so
// far. It's important that metadata decode results are delivered
// atomically, so for those decodes we wait until NotifyDecodeComplete.
if (aDecoder->HasProgress() && !aDecoder->IsMetadataDecode()) {
NotifyProgress(aDecoder);
}
// The decoder will ensure that a new worker gets enqueued to continue
// decoding when more data is available.
} else {
NotifyDecodeComplete(aDecoder);
}
}
void
DecodePool::NotifyProgress(Decoder* aDecoder)
{
MOZ_ASSERT(aDecoder);
if (!NS_IsMainThread() ||
(aDecoder->GetDecoderFlags() & DecoderFlags::ASYNC_NOTIFY)) {
NotifyProgressWorker::Dispatch(aDecoder->GetImage(),
aDecoder->TakeProgress(),
aDecoder->TakeInvalidRect(),
aDecoder->GetSurfaceFlags());
return;
}
aDecoder->GetImage()->NotifyProgress(aDecoder->TakeProgress(),
aDecoder->TakeInvalidRect(),
aDecoder->GetSurfaceFlags());
}
void
DecodePool::NotifyDecodeComplete(Decoder* aDecoder)
{
MOZ_ASSERT(aDecoder);
if (!NS_IsMainThread() ||
(aDecoder->GetDecoderFlags() & DecoderFlags::ASYNC_NOTIFY)) {
NotifyDecodeCompleteWorker::Dispatch(aDecoder);
return;
}
aDecoder->GetImage()->FinalizeDecoder(aDecoder);
}
} // namespace image
} // namespace mozilla