Files
palemoon27/image/imgFrame.cpp
T
roytam1 69d1f32ff7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1268085 - Remove unused post barrier callbacks r=terrence (0ab13411c9)
- Bug 1267699 - Move some public types to the right namespace; r=sfink (3d5008e610)
- Bug 1267550 (part 1) - Rename MOZ_MUST_USE as MOZ_MUST_USE_TYPE. r=ehsan. (6f47375796)
- Bug 1259021 - Rename Vector::extractRawBuffer to extractOrCopyRawBuffer r=Waldo (97ca94495b)
- Bug 1259021 - Add Vector::extractRawBuffer method that doesn't copy the buffer r=Waldo (e58deec48f)
- Bug 1265892 - Change Vector to use Impl::new_ consistently. r=Waldo (7a52d21b29)
- Bug 1267912 - Rename nsNetUtil.inl as nsNetUtilInlines.h. r=valentin. (548a41b293)
- Bug 1265690 part 1 - Mark StringBuffer methods WARN_UNUSED_RESULT, fix OOM issues. r=jonco (0d7e6837e3)
- Bug 1265690 part 2 - Fix some more OOM issues in TypedObject code. r=jonco (b60902453e)
- Bug 1263490 - Part 2: Add GetFirstDollarIndex intrinsic and use it inRegExpReplace. r=till (4ba19db8c4)
- Bug 1263490 - Part 3: Inline GetFirstDollarIndex intrinsic. r=h4writer (e7d9b5d1cc)
- Bug 1263490 - Part 4: Fold GetFirstDollarIndex into a integer constant. r=h4writer (3479c7d1af)
- Bug 1267269 - Make MIRType an enum class. r=bbouvier (d580ef372a)
- Bug 1259295 - BaldrMonkey: Postorder (r=luke) (6ef7a77663)
- Bug 1254142: BaldrMonkey: make br_table yield (r=luke) (80e7635e58)
- Bug 1263202 - BaldrMonkey: switch to arities on branches, calls and return (r=bbouvier) (f5a0358634)
- Bug 1236358 - Improper reading of string16 in Pickle::ReadString16. r=jld (8370ba6a0b)
- Bug 1263205 - BaldrMonkey: Update section headers for proposed spec changes (r=luke) (0def2e6bc2)
- Bug 1263205 - BaldrMonkey: Update for proposed new section names (r=luke) (e57f0e3367)
- Bug 1263205 - BaldrMonkey: Add 'form' field to types section (r=bbouvier) (794edc890f)
- Bug 1259021 - Use in-place storage in AutoStableStringChars to avoid allocation for short strings r=jandem r=Waldo (ffb53cbcf4)
- Bug 1267550 (part 2) - Rename MOZ_WARN_UNUSED_RESULT as MOZ_MUST_USE. r=froydnj. (47bc674b86)
- Bug 1268518: Baldr: implement int32/int64 rotations; r=luke (0d5eedccce)
- Bug 1255008: IonMonkey - Add a by default disabled flow sensitive alias analysis pass, r=jandem (521c585d75)
- Bug 1266781: Baldr: implement proper checked truncations to integer types; r=sunfish (46078fb3d3)
- Bug 1266781: Rename MTruncateToInt64 into MWasmTruncateInt64; r=sunfish (c7d7d1ac11)
- Bug 1266781: Add new traps; r=luke (b7ed3d44e6)
- Bug 1268024: Pass the atomic attribute down to EmitHeapAccess; r=luke (6195f7d7a3)
- Bug 1268024: A few cleanups related to loads/stores; r=luke (88141e3a01)
- Bug 1258312 - Make Pickle::Resize infallible r=jld (241ee9b60d)
- Bug 1162772, part 1 - Allow CompartmentCreationOptions to store Secure Context state. r=jorendorff (ff666384cf)
- Bug 1162772, part 2 - Expose whether SEC_FORCE_INHERIT_PRINCIPAL was dropped from an nsILoadInfo. r=bz (ada46f86bf)
- Bug 1162772, part 3 - Add a getChannelResultPrincipalIfNotSandboxed method to nsIScriptSecurityManager. r=bz (5b1d9f6807)
- Bug 1162772, part 4 - Implement nsGlobalWindow::IsSecureContext. r=bz (f392f439c9)
- Bug 1162772, part 5 - Expose Window.isSecureContext to content. r=bz (e7296e2cf1)
- Bug 1267509 - Make nsContentSecurityManager::IsURIPotentiallyTrustworthy act on an nsIPrincipal. r=bz (83de80350a)
- Bug 1219098 - Use UniquePtr in UncompressedSourceCache, for it is good (r=jandem) (b68769c729)
- Bug 1244279 - Part 1: Take a bit in ObjectElements::Flags to indicate whether the object is in the whole cell store buffer. r=terrence (968cf373f9)
- Bug 1244279 - Part 0: Add a GC ubench for large arrays with both elements and properties. r=terrence (ec76b48323)
- Bug 1255925 - Give a name to getters/setters and integer-named methods. r=efaust (f978cc6916)
- Bug 888969 - Make the getPrototypeOf/setPrototypeOf traps scriptable. r=efaust, r=bholley (eb2325a9ea)
- Bug 1267557 part 0 - Move JS poison constants to jsutil.h. r=jonco (65afc690d2)
- Bug 1267557 part 1 - Also poison bytes allocated before the actual jitcode. r=nbp (70f0b327d3)
- Bug 1267557 part 2 - Use different jitcode poison values. r=nbp (08008ab9dc)
- Bug 1267557 part 3 - Define JS_SWEPT_CODE_PATTERN for mips. r=nbp (17e894d59d)
- Bug 1267449 - Do not infinite loop in js_fputs; r=jimb (67f961b6cd)
- Bug 1219098 - Reenable compression on large sources, but revert to uncompressed if decompression happens (r=jandem) (b44ee8d77d)
- Bug 1267551 (part 1) - Use MOZ_MUST_USE more in jsnum.h. r=jonco. (d2476bf8f4)
- Bug 1267551 (part 2) - Use MOZ_MUST_USE more in js/src/ds/. r=jonco. (4ff5d9aa88)
- Bug 1267412 - Use MutableHandleValue instead of pointer-to-AutoValueVector; r=sfink (3f6dd284bb)
- Bug 1266406 - Use EnumSet<AllocKind> to simplify GC sweeping phase information r=terrence (64811500e7)
- Bug 1266457 - Update pointers in GC things in two phases when compacting r=terrence (f6f5bc4e4d)
- Bug 1266457 - Simplify typed object trace hook r=terence (3b06c8d1e5)
- Bug 1268541 - Compact arenas containing base shapes r=terrence (b458b92eea)
- Bug 1268805 - Implement PrivateGCThingValue. (r=terrence) (deec9a83ae)
- Bug 1268415: Initialize members in UpdatePointerTasks; r=jonco (6cb219005a)
- Bug 1268501 - Release the GC lock periodically when releasing arenas on the backgound thread r=terrence (37f0997682)
- Bug 1263572 - Wait for background sweeping to finish before checking base shapes r=terrence (354801a411)
- Bug 1266887 - Store Rooted heads on the Zone; r=sfink (91c0101ee3)
- Bug 1266402 - Add iteration to EnumSet<T> so that it can be used in range-based for loops r=Waldo (e9507a2524)
- Bug 1266404 - Allow construction of an EnumSet<T> using an initializer list r=Waldo (1b6d340e99)
- Bug 1254020 - Always compute theme scaling factor when per-monitor dpi aware, even if only a single display is currently present. r=emk (a00cda21f4)
- Bug 1263525 - Add dedicated function for std_Array self-hosted intrinsic. r=efaust (449d8bb7eb)
- Bug 1255925 - Change JSFunction::name to return a JSAtom. r=efaust (5ab396ce83)
- Bug 888969 - Make our tree's sole implementation of nsIRemoteTagService.getRemoteObjectTag not depend upon the infallibility of [[GetPrototypeOf]] on the object provided to it. r=bz (f388f4bf1f)
- Bug 1264896 - Kill off nsIRemoteTagService and do what it does, in its sole caller, in far-faster C++. r=billm (5ed3fb103d)
- Bug 1268246 - Add a simple Poison class lifetime checker. r=froydnj (7b237bc70e)
- Bug 1249496 - Don't apply dpi-based scaling for window titlebar dimensions when on a secondary display, because windows doesn't scale it. r=emk (64dd706dbc)
- Bug 1164518 - Avoid unnecessary DB updates when caching Safe Browsing results. r=gcp (3cafd9a4df)
- Bug 1264472 - Use nsRunnables in FIDO U2F. r=keeler (3aa9570132)
- Bug 1236060 - Dispatch error should advance queue. r=smaug (74155b75dd)
- Bug 1251697 part 1. Thread an ErrorResult reference through the worker XHR WorkerThreadProxySyncRunnable implementations. r=khuey (77804cbb7c)
- Bug 1251697 part 2. Have WorkerThreadProxySyncRunnable hand the ErrorResult reference it holds to its ResponseRunnable so it can report exceptions on there instead of on a JSContext. r=khuey (355c9ee313)
- Bug 1251697 part 3. Remove the JSContext argument of StopSyncLoopRunnable::MaybeSetException. r=khuey (010f5b1058)
- Bug 1155328. r=smaug (e1f8dac304)
- Bug 1265927: Move nsRunnable to mozilla::Runnable, CancelableRunnable to mozilla::CancelableRunnable. r=froydnj (f83bfcae02)
- Bug 1239946 - Change test to return error on Speak. r=eeejay (1d402beb02)
- Bug 1254378 - Update synth tests and introduce no voiceschanged test. r=smaug (f5823bb70e)
- Bug 1251627. Fix XMLHttpRequest.send() to follow the spec better in terms of the exceptions it throws. r=khuey (cd0e321948)
- Bug 1268868: [MSE] P1. Re-enable gap detection within a media segment. r=gerald (b8b8df4bc2)
- Bug 1268868: [MSE] P2. Reset longest duration after keyframe is seen. r=gerald (2b1401465c)
- Bug 1268868: [MSE] P3. Prevent crash should gap be detected in content. r=gerald (063d9376fc)
- Bug 1254378 - Implement nsISynthVoiceRegistry.notifyVoicesChanged. r=smaug (4b63b1c360)
- Bug 1266804 - Un-inline js::Unbox(); r=jorendorff (0f288b6173)
- Bug 1268863 - Report ScriptSources that are only reachable via AsmJSModule (r=njn) (5ba40acb64)
- bump version to 45.1b1 (1414db0ca8)
- Bug 1262062 - remove old futex names. r=bbouvier (62662bdd2e)
- memory: build fix after renaming MOZ_WARN_UNUSED_RESULT (7254dc8d53)
- import from mozilla:
 - Bug 1268725 - BaldrMonkey: Refactor away the internal storage from ExprIter. r=luke (1931bd636f17)
 - Bug 1268725 - BaldrMonkey: Convert default arguments into explicit arguments. r=luke (c8a11b8b6bbd) (867ec715d6)
2024-08-21 10:45:07 +08:00

1078 lines
28 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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 "imgFrame.h"
#include "ImageRegion.h"
#include "ShutdownTracker.h"
#include "prenv.h"
#include "gfx2DGlue.h"
#include "gfxPlatform.h"
#include "gfxUtils.h"
#include "gfxAlphaRecovery.h"
static bool gDisableOptimize = false;
#include "GeckoProfiler.h"
#include "mozilla/Likely.h"
#include "MainThreadUtils.h"
#include "mozilla/MemoryReporting.h"
#include "nsMargin.h"
#include "nsThreadUtils.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/gfx/Tools.h"
namespace mozilla {
using namespace gfx;
namespace image {
static UserDataKey kVolatileBuffer;
static void
VolatileBufferRelease(void* vbuf)
{
delete static_cast<VolatileBufferPtr<unsigned char>*>(vbuf);
}
static int32_t
VolatileSurfaceStride(const IntSize& size, SurfaceFormat format)
{
// Stride must be a multiple of four or cairo will complain.
return (size.width * BytesPerPixel(format) + 0x3) & ~0x3;
}
static already_AddRefed<DataSourceSurface>
CreateLockedSurface(VolatileBuffer* vbuf,
const IntSize& size,
SurfaceFormat format)
{
VolatileBufferPtr<unsigned char>* vbufptr =
new VolatileBufferPtr<unsigned char>(vbuf);
MOZ_ASSERT(!vbufptr->WasBufferPurged(), "Expected image data!");
int32_t stride = VolatileSurfaceStride(size, format);
RefPtr<DataSourceSurface> surf =
Factory::CreateWrappingDataSourceSurface(*vbufptr, stride, size, format);
if (!surf) {
delete vbufptr;
return nullptr;
}
surf->AddUserData(&kVolatileBuffer, vbufptr, VolatileBufferRelease);
return surf.forget();
}
static already_AddRefed<VolatileBuffer>
AllocateBufferForImage(const IntSize& size, SurfaceFormat format)
{
int32_t stride = VolatileSurfaceStride(size, format);
RefPtr<VolatileBuffer> buf = new VolatileBuffer();
if (buf->Init(stride * size.height,
1 << gfxAlphaRecovery::GoodAlignmentLog2())) {
return buf.forget();
}
return nullptr;
}
// Returns true if an image of aWidth x aHeight is allowed and legal.
static bool
AllowedImageSize(int32_t aWidth, int32_t aHeight)
{
// reject over-wide or over-tall images
const int32_t k64KLimit = 0x0000FFFF;
if (MOZ_UNLIKELY(aWidth > k64KLimit || aHeight > k64KLimit )) {
NS_WARNING("image too big");
return false;
}
// protect against invalid sizes
if (MOZ_UNLIKELY(aHeight <= 0 || aWidth <= 0)) {
return false;
}
// check to make sure we don't overflow a 32-bit
CheckedInt32 requiredBytes = CheckedInt32(aWidth) * CheckedInt32(aHeight) * 4;
if (MOZ_UNLIKELY(!requiredBytes.isValid())) {
NS_WARNING("width or height too large");
return false;
}
#if defined(XP_MACOSX)
// CoreGraphics is limited to images < 32K in *height*, so clamp all surfaces
// on the Mac to that height
if (MOZ_UNLIKELY(aHeight > SHRT_MAX)) {
NS_WARNING("image too big");
return false;
}
#endif
return true;
}
static bool AllowedImageAndFrameDimensions(const nsIntSize& aImageSize,
const nsIntRect& aFrameRect)
{
if (!AllowedImageSize(aImageSize.width, aImageSize.height)) {
return false;
}
if (!AllowedImageSize(aFrameRect.width, aFrameRect.height)) {
return false;
}
nsIntRect imageRect(0, 0, aImageSize.width, aImageSize.height);
if (!imageRect.Contains(aFrameRect)) {
NS_WARNING("Animated image frame does not fit inside bounds of image");
}
return true;
}
imgFrame::imgFrame()
: mMonitor("imgFrame")
, mDecoded(0, 0, 0, 0)
, mLockCount(0)
, mTimeout(100)
, mDisposalMethod(DisposalMethod::NOT_SPECIFIED)
, mBlendMethod(BlendMethod::OVER)
, mHasNoAlpha(false)
, mAborted(false)
, mFinished(false)
, mOptimizable(false)
, mPalettedImageData(nullptr)
, mPaletteDepth(0)
, mNonPremult(false)
, mSinglePixel(false)
, mCompositingFailed(false)
{
static bool hasCheckedOptimize = false;
if (!hasCheckedOptimize) {
if (PR_GetEnv("MOZ_DISABLE_IMAGE_OPTIMIZE")) {
gDisableOptimize = true;
}
hasCheckedOptimize = true;
}
}
imgFrame::~imgFrame()
{
#ifdef DEBUG
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mAborted || AreAllPixelsWritten());
MOZ_ASSERT(mAborted || mFinished);
#endif
moz_free(mPalettedImageData);
mPalettedImageData = nullptr;
}
nsresult
imgFrame::InitForDecoder(const nsIntSize& aImageSize,
const nsIntRect& aRect,
SurfaceFormat aFormat,
uint8_t aPaletteDepth /* = 0 */,
bool aNonPremult /* = false */)
{
// Assert for properties that should be verified by decoders,
// warn for properties related to bad content.
if (!AllowedImageAndFrameDimensions(aImageSize, aRect)) {
NS_WARNING("Should have legal image size");
mAborted = true;
return NS_ERROR_FAILURE;
}
mImageSize = aImageSize;
mOffset.MoveTo(aRect.x, aRect.y);
mSize.SizeTo(aRect.width, aRect.height);
mFormat = aFormat;
mPaletteDepth = aPaletteDepth;
mNonPremult = aNonPremult;
if (aPaletteDepth != 0) {
// We're creating for a paletted image.
if (aPaletteDepth > 8) {
NS_WARNING("Should have legal palette depth");
NS_ERROR("This Depth is not supported");
mAborted = true;
return NS_ERROR_FAILURE;
}
// Use the fallible allocator here. Paletted images always use 1 byte per
// pixel, so calculating the amount of memory we need is straightforward.
mPalettedImageData =
static_cast<uint8_t*>(moz_malloc(PaletteDataLength() +
(mSize.width * mSize.height)));
if (!mPalettedImageData) {
NS_WARNING("malloc for paletted image data should succeed");
}
NS_ENSURE_TRUE(mPalettedImageData, NS_ERROR_OUT_OF_MEMORY);
} else {
MOZ_ASSERT(!mImageSurface, "Called imgFrame::InitForDecoder() twice?");
mVBuf = AllocateBufferForImage(mSize, mFormat);
if (!mVBuf) {
mAborted = true;
return NS_ERROR_OUT_OF_MEMORY;
}
if (mVBuf->OnHeap()) {
int32_t stride = VolatileSurfaceStride(mSize, mFormat);
VolatileBufferPtr<uint8_t> ptr(mVBuf);
memset(ptr, 0, stride * mSize.height);
}
mImageSurface = CreateLockedSurface(mVBuf, mSize, mFormat);
if (!mImageSurface) {
NS_WARNING("Failed to create VolatileDataSourceSurface");
mAborted = true;
return NS_ERROR_OUT_OF_MEMORY;
}
}
return NS_OK;
}
nsresult
imgFrame::InitWithDrawable(gfxDrawable* aDrawable,
const nsIntSize& aSize,
const SurfaceFormat aFormat,
Filter aFilter,
uint32_t aImageFlags)
{
// Assert for properties that should be verified by decoders,
// warn for properties related to bad content.
if (!AllowedImageSize(aSize.width, aSize.height)) {
NS_WARNING("Should have legal image size");
mAborted = true;
return NS_ERROR_FAILURE;
}
mImageSize = aSize;
mOffset.MoveTo(0, 0);
mSize.SizeTo(aSize.width, aSize.height);
mFormat = aFormat;
mPaletteDepth = 0;
RefPtr<DrawTarget> target;
bool canUseDataSurface =
gfxPlatform::GetPlatform()->CanRenderContentToDataSurface();
if (canUseDataSurface) {
// It's safe to use data surfaces for content on this platform, so we can
// get away with using volatile buffers.
MOZ_ASSERT(!mImageSurface, "Called imgFrame::InitWithDrawable() twice?");
mVBuf = AllocateBufferForImage(mSize, mFormat);
if (!mVBuf) {
mAborted = true;
return NS_ERROR_OUT_OF_MEMORY;
}
int32_t stride = VolatileSurfaceStride(mSize, mFormat);
VolatileBufferPtr<uint8_t> ptr(mVBuf);
if (!ptr) {
mAborted = true;
return NS_ERROR_OUT_OF_MEMORY;
}
if (mVBuf->OnHeap()) {
memset(ptr, 0, stride * mSize.height);
}
mImageSurface = CreateLockedSurface(mVBuf, mSize, mFormat);
target = gfxPlatform::GetPlatform()->
CreateDrawTargetForData(ptr, mSize, stride, mFormat);
} else {
// We can't use data surfaces for content, so we'll create an offscreen
// surface instead. This means if someone later calls RawAccessRef(), we
// may have to do an expensive readback, but we warned callers about that in
// the documentation for this method.
MOZ_ASSERT(!mOptSurface, "Called imgFrame::InitWithDrawable() twice?");
target = gfxPlatform::GetPlatform()->
CreateOffscreenContentDrawTarget(mSize, mFormat);
}
if (!target || !target->IsValid()) {
mAborted = true;
return NS_ERROR_OUT_OF_MEMORY;
}
// Draw using the drawable the caller provided.
nsIntRect imageRect(0, 0, mSize.width, mSize.height);
RefPtr<gfxContext> ctx = gfxContext::ForDrawTarget(target);
MOZ_ASSERT(ctx); // already checked the draw target above
gfxUtils::DrawPixelSnapped(ctx, aDrawable, mSize,
ImageRegion::Create(ThebesRect(imageRect)),
mFormat, aFilter, aImageFlags);
if (canUseDataSurface && !mImageSurface) {
NS_WARNING("Failed to create VolatileDataSourceSurface");
mAborted = true;
return NS_ERROR_OUT_OF_MEMORY;
}
if (!canUseDataSurface) {
// We used an offscreen surface, which is an "optimized" surface from
// imgFrame's perspective.
mOptSurface = target->Snapshot();
}
// If we reach this point, we should regard ourselves as complete.
mDecoded = GetRect();
mFinished = true;
#ifdef DEBUG
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(AreAllPixelsWritten());
#endif
return NS_OK;
}
nsresult
imgFrame::Optimize()
{
MOZ_ASSERT(NS_IsMainThread());
mMonitor.AssertCurrentThreadOwns();
MOZ_ASSERT(mLockCount == 1,
"Should only optimize when holding the lock exclusively");
// Don't optimize during shutdown because gfxPlatform may not be available.
if (ShutdownTracker::ShutdownHasStarted()) {
return NS_OK;
}
if (!mOptimizable || gDisableOptimize) {
return NS_OK;
}
if (mPalettedImageData || mOptSurface || mSinglePixel) {
return NS_OK;
}
// Don't do single-color opts on non-premult data.
// Cairo doesn't support non-premult single-colors.
if (mNonPremult) {
return NS_OK;
}
/* Figure out if the entire image is a constant color */
if (gfxPrefs::ImageSingleColorOptimizationEnabled() &&
mImageSurface->Stride() == mSize.width * 4) {
uint32_t* imgData = (uint32_t*) ((uint8_t*) mVBufPtr);
uint32_t firstPixel = * (uint32_t*) imgData;
uint32_t pixelCount = mSize.width * mSize.height + 1;
while (--pixelCount && *imgData++ == firstPixel)
;
if (pixelCount == 0) {
// all pixels were the same
if (mFormat == SurfaceFormat::B8G8R8A8 ||
mFormat == SurfaceFormat::B8G8R8X8) {
mSinglePixel = true;
mSinglePixelColor.a = ((firstPixel >> 24) & 0xFF) * (1.0f / 255.0f);
mSinglePixelColor.r = ((firstPixel >> 16) & 0xFF) * (1.0f / 255.0f);
mSinglePixelColor.g = ((firstPixel >> 8) & 0xFF) * (1.0f / 255.0f);
mSinglePixelColor.b = ((firstPixel >> 0) & 0xFF) * (1.0f / 255.0f);
mSinglePixelColor.r /= mSinglePixelColor.a;
mSinglePixelColor.g /= mSinglePixelColor.a;
mSinglePixelColor.b /= mSinglePixelColor.a;
// blow away the older surfaces (if they exist), to release their memory
mVBuf = nullptr;
mVBufPtr = nullptr;
mImageSurface = nullptr;
mOptSurface = nullptr;
return NS_OK;
}
}
// if it's not RGB24/ARGB32, don't optimize, but we never hit this at the
// moment
}
#ifdef ANDROID
SurfaceFormat optFormat = gfxPlatform::GetPlatform()
->Optimal2DFormatForContent(gfxContentType::COLOR);
if (mFormat != SurfaceFormat::B8G8R8A8 &&
optFormat == SurfaceFormat::R5G6B5_UINT16) {
RefPtr<VolatileBuffer> buf =
AllocateBufferForImage(mSize, optFormat);
if (!buf) {
return NS_OK;
}
RefPtr<DataSourceSurface> surf =
CreateLockedSurface(buf, mSize, optFormat);
if (!surf) {
return NS_ERROR_OUT_OF_MEMORY;
}
DataSourceSurface::MappedSurface mapping;
if (!surf->Map(DataSourceSurface::MapType::WRITE, &mapping)) {
gfxCriticalError() << "imgFrame::Optimize failed to map surface";
return NS_ERROR_FAILURE;
}
RefPtr<DrawTarget> target =
Factory::CreateDrawTargetForData(BackendType::CAIRO,
mapping.mData,
mSize,
mapping.mStride,
optFormat);
if (!target) {
gfxWarning() << "imgFrame::Optimize failed in CreateDrawTargetForData";
return NS_ERROR_OUT_OF_MEMORY;
}
Rect rect(0, 0, mSize.width, mSize.height);
target->DrawSurface(mImageSurface, rect, rect);
target->Flush();
surf->Unmap();
mImageSurface = surf;
mVBuf = buf;
mFormat = optFormat;
}
#else
mOptSurface = gfxPlatform::GetPlatform()
->ScreenReferenceDrawTarget()->OptimizeSourceSurface(mImageSurface);
if (mOptSurface == mImageSurface) {
mOptSurface = nullptr;
}
#endif
if (mOptSurface) {
mVBuf = nullptr;
mVBufPtr = nullptr;
mImageSurface = nullptr;
}
#ifdef MOZ_WIDGET_ANDROID
// On Android, free mImageSurface unconditionally if we're discardable. This
// allows the operating system to free our volatile buffer.
// XXX(seth): We'd eventually like to do this on all platforms, but right now
// converting raw memory to a SourceSurface is expensive on some backends.
mImageSurface = nullptr;
#endif
return NS_OK;
}
DrawableFrameRef
imgFrame::DrawableRef()
{
return DrawableFrameRef(this);
}
RawAccessFrameRef
imgFrame::RawAccessRef()
{
return RawAccessFrameRef(this);
}
void
imgFrame::SetRawAccessOnly()
{
AssertImageDataLocked();
// Lock our data and throw away the key.
LockImageData();
}
imgFrame::SurfaceWithFormat
imgFrame::SurfaceForDrawing(bool aDoPadding,
bool aDoPartialDecode,
bool aDoTile,
gfxContext* aContext,
const nsIntMargin& aPadding,
gfxRect& aImageRect,
ImageRegion& aRegion,
SourceSurface* aSurface)
{
MOZ_ASSERT(NS_IsMainThread());
mMonitor.AssertCurrentThreadOwns();
IntSize size(int32_t(aImageRect.Width()), int32_t(aImageRect.Height()));
if (!aDoPadding && !aDoPartialDecode) {
NS_ASSERTION(!mSinglePixel, "This should already have been handled");
return SurfaceWithFormat(new gfxSurfaceDrawable(aSurface, size), mFormat);
}
gfxRect available = gfxRect(mDecoded.x, mDecoded.y, mDecoded.width,
mDecoded.height);
if (aDoTile || mSinglePixel) {
// Create a temporary surface.
// Give this surface an alpha channel because there are
// transparent pixels in the padding or undecoded area
RefPtr<DrawTarget> target =
gfxPlatform::GetPlatform()->
CreateOffscreenContentDrawTarget(size, SurfaceFormat::B8G8R8A8);
if (!target) {
return SurfaceWithFormat();
}
// Fill 'available' with whatever we've got
if (mSinglePixel) {
target->FillRect(ToRect(aRegion.Intersect(available).Rect()),
ColorPattern(mSinglePixelColor),
DrawOptions(1.0f, CompositionOp::OP_SOURCE));
} else {
SurfacePattern pattern(aSurface,
aRegion.GetExtendMode(),
Matrix::Translation(mDecoded.x, mDecoded.y));
target->FillRect(ToRect(aRegion.Intersect(available).Rect()), pattern);
}
RefPtr<SourceSurface> newsurf = target->Snapshot();
return SurfaceWithFormat(new gfxSurfaceDrawable(newsurf, size),
target->GetFormat());
}
// Not tiling, and we have a surface, so we can account for
// padding and/or a partial decode just by twiddling parameters.
gfxPoint paddingTopLeft(aPadding.left, aPadding.top);
aRegion = aRegion.Intersect(available) - paddingTopLeft;
aContext->Multiply(gfxMatrix::Translation(paddingTopLeft));
aImageRect = gfxRect(0, 0, mSize.width, mSize.height);
IntSize availableSize(mDecoded.width, mDecoded.height);
return SurfaceWithFormat(new gfxSurfaceDrawable(aSurface, availableSize),
mFormat);
}
bool imgFrame::Draw(gfxContext* aContext, const ImageRegion& aRegion,
Filter aFilter, uint32_t aImageFlags)
{
PROFILER_LABEL("imgFrame", "Draw",
js::ProfileEntry::Category::GRAPHICS);
MOZ_ASSERT(NS_IsMainThread());
NS_ASSERTION(!aRegion.Rect().IsEmpty(), "Drawing empty region!");
NS_ASSERTION(!aRegion.IsRestricted() ||
!aRegion.Rect().Intersect(aRegion.Restriction()).IsEmpty(),
"We must be allowed to sample *some* source pixels!");
NS_ASSERTION(!mPalettedImageData, "Directly drawing a paletted image!");
MonitorAutoLock lock(mMonitor);
nsIntMargin padding(mOffset.y,
mImageSize.width - (mOffset.x + mSize.width),
mImageSize.height - (mOffset.y + mSize.height),
mOffset.x);
bool doPadding = padding != nsIntMargin(0,0,0,0);
bool doPartialDecode = !AreAllPixelsWritten();
if (mSinglePixel && !doPadding && !doPartialDecode) {
if (mSinglePixelColor.a == 0.0) {
return true;
}
RefPtr<DrawTarget> dt = aContext->GetDrawTarget();
dt->FillRect(ToRect(aRegion.Rect()),
ColorPattern(mSinglePixelColor),
DrawOptions(1.0f, aContext->CurrentOp()));
return true;
}
RefPtr<SourceSurface> surf = GetSurfaceInternal();
if (!surf && !mSinglePixel) {
return false;
}
gfxRect imageRect(0, 0, mImageSize.width, mImageSize.height);
bool doTile = !imageRect.Contains(aRegion.Rect()) &&
!(aImageFlags & imgIContainer::FLAG_CLAMP);
ImageRegion region(aRegion);
// SurfaceForDrawing changes the current transform, and we need it to still
// be changed when we call gfxUtils::DrawPixelSnapped. We still need to
// restore it before returning though.
// XXXjwatt In general having functions require someone further up the stack
// to undo transform changes that they make is bad practice. We should
// change how this code works.
gfxContextMatrixAutoSaveRestore autoSR(aContext);
SurfaceWithFormat surfaceResult =
SurfaceForDrawing(doPadding, doPartialDecode, doTile, aContext,
padding, imageRect, region, surf);
if (surfaceResult.IsValid()) {
gfxUtils::DrawPixelSnapped(aContext, surfaceResult.mDrawable,
imageRect.Size(), region, surfaceResult.mFormat,
aFilter, aImageFlags);
}
return true;
}
nsresult
imgFrame::ImageUpdated(const nsIntRect& aUpdateRect)
{
MonitorAutoLock lock(mMonitor);
return ImageUpdatedInternal(aUpdateRect);
}
nsresult
imgFrame::ImageUpdatedInternal(const nsIntRect& aUpdateRect)
{
mMonitor.AssertCurrentThreadOwns();
mDecoded.UnionRect(mDecoded, aUpdateRect);
// clamp to bounds, in case someone sends a bogus updateRect (I'm looking at
// you, gif decoder)
nsIntRect boundsRect(mOffset, mSize);
mDecoded.IntersectRect(mDecoded, boundsRect);
return NS_OK;
}
void
imgFrame::Finish(Opacity aFrameOpacity /* = Opacity::SOME_TRANSPARENCY */,
DisposalMethod aDisposalMethod /* = DisposalMethod::KEEP */,
int32_t aRawTimeout /* = 0 */,
BlendMethod aBlendMethod /* = BlendMethod::OVER */)
{
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mLockCount > 0, "Image data should be locked");
if (aFrameOpacity == Opacity::FULLY_OPAQUE) {
mHasNoAlpha = true;
}
mDisposalMethod = aDisposalMethod;
mTimeout = aRawTimeout;
mBlendMethod = aBlendMethod;
ImageUpdatedInternal(GetRect());
mFinished = true;
// The image is now complete, wake up anyone who's waiting.
mMonitor.NotifyAll();
}
nsIntRect
imgFrame::GetRect() const
{
return gfx::IntRect(mOffset, mSize);
}
int32_t
imgFrame::GetStride() const
{
mMonitor.AssertCurrentThreadOwns();
if (mImageSurface) {
return mImageSurface->Stride();
}
return VolatileSurfaceStride(mSize, mFormat);
}
SurfaceFormat
imgFrame::GetFormat() const
{
MonitorAutoLock lock(mMonitor);
return mFormat;
}
uint32_t
imgFrame::GetImageBytesPerRow() const
{
mMonitor.AssertCurrentThreadOwns();
if (mVBuf) {
return mSize.width * BytesPerPixel(mFormat);
}
if (mPaletteDepth) {
return mSize.width;
}
return 0;
}
uint32_t
imgFrame::GetImageDataLength() const
{
return GetImageBytesPerRow() * mSize.height;
}
void
imgFrame::GetImageData(uint8_t** aData, uint32_t* aLength) const
{
MonitorAutoLock lock(mMonitor);
GetImageDataInternal(aData, aLength);
}
void
imgFrame::GetImageDataInternal(uint8_t** aData, uint32_t* aLength) const
{
mMonitor.AssertCurrentThreadOwns();
MOZ_ASSERT(mLockCount > 0, "Image data should be locked");
if (mImageSurface) {
*aData = mVBufPtr;
MOZ_ASSERT(*aData,
"mImageSurface is non-null, but mVBufPtr is null in GetImageData");
} else if (mPalettedImageData) {
*aData = mPalettedImageData + PaletteDataLength();
MOZ_ASSERT(*aData,
"mPalettedImageData is non-null, but result is null in GetImageData");
} else {
MOZ_ASSERT(false,
"Have neither mImageSurface nor mPalettedImageData in GetImageData");
*aData = nullptr;
}
*aLength = GetImageDataLength();
}
uint8_t*
imgFrame::GetImageData() const
{
uint8_t* data;
uint32_t length;
GetImageData(&data, &length);
return data;
}
bool
imgFrame::GetIsPaletted() const
{
return mPalettedImageData != nullptr;
}
void
imgFrame::GetPaletteData(uint32_t** aPalette, uint32_t* length) const
{
AssertImageDataLocked();
if (!mPalettedImageData) {
*aPalette = nullptr;
*length = 0;
} else {
*aPalette = (uint32_t*) mPalettedImageData;
*length = PaletteDataLength();
}
}
uint32_t*
imgFrame::GetPaletteData() const
{
uint32_t* data;
uint32_t length;
GetPaletteData(&data, &length);
return data;
}
nsresult
imgFrame::LockImageData()
{
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mLockCount >= 0, "Unbalanced locks and unlocks");
if (mLockCount < 0) {
return NS_ERROR_FAILURE;
}
mLockCount++;
// If we are not the first lock, there's nothing to do.
if (mLockCount != 1) {
return NS_OK;
}
// If we're the first lock, but have an image surface, we're OK.
if (mImageSurface) {
mVBufPtr = mVBuf;
return NS_OK;
}
// Paletted images don't have surfaces, so there's nothing to do.
if (mPalettedImageData) {
return NS_OK;
}
MOZ_ASSERT_UNREACHABLE("It's illegal to re-lock an optimized imgFrame");
return NS_ERROR_FAILURE;
}
void
imgFrame::AssertImageDataLocked() const
{
#ifdef DEBUG
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mLockCount > 0, "Image data should be locked");
#endif
}
class UnlockImageDataRunnable : public Runnable
{
public:
explicit UnlockImageDataRunnable(imgFrame* aTarget)
: mTarget(aTarget)
{
MOZ_ASSERT(mTarget);
}
NS_IMETHOD Run() { return mTarget->UnlockImageData(); }
private:
RefPtr<imgFrame> mTarget;
};
nsresult
imgFrame::UnlockImageData()
{
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mLockCount > 0, "Unlocking an unlocked image!");
if (mLockCount <= 0) {
return NS_ERROR_FAILURE;
}
MOZ_ASSERT(mLockCount > 1 || mFinished || mAborted,
"Should have Finish()'d or aborted before unlocking");
// If we're about to become unlocked, we don't need to hold on to our data
// surface anymore. (But we don't need to do anything for paletted images,
// which don't have surfaces.)
if (mLockCount == 1 && !mPalettedImageData) {
// We can't safely optimize off-main-thread, so create a runnable to do it.
if (!NS_IsMainThread()) {
nsCOMPtr<nsIRunnable> runnable = new UnlockImageDataRunnable(this);
NS_DispatchToMainThread(runnable);
return NS_OK;
}
// If we're using a surface format with alpha but the image has no alpha,
// change the format. This doesn't change the underlying data at all, but
// allows DrawTargets to avoid blending when drawing known opaque images.
if (mHasNoAlpha && mFormat == SurfaceFormat::B8G8R8A8 && mImageSurface) {
mFormat = SurfaceFormat::B8G8R8X8;
mImageSurface = CreateLockedSurface(mVBuf, mSize, mFormat);
}
// Convert the data surface to a GPU surface or a single color if possible.
// This will also release mImageSurface if possible.
Optimize();
// Allow the OS to release our data surface.
mVBufPtr = nullptr;
}
mLockCount--;
return NS_OK;
}
void
imgFrame::SetOptimizable()
{
AssertImageDataLocked();
MonitorAutoLock lock(mMonitor);
mOptimizable = true;
}
Color
imgFrame::SinglePixelColor() const
{
MOZ_ASSERT(NS_IsMainThread());
return mSinglePixelColor;
}
bool
imgFrame::IsSinglePixel() const
{
MOZ_ASSERT(NS_IsMainThread());
return mSinglePixel;
}
already_AddRefed<SourceSurface>
imgFrame::GetSurface()
{
MonitorAutoLock lock(mMonitor);
return GetSurfaceInternal();
}
already_AddRefed<SourceSurface>
imgFrame::GetSurfaceInternal()
{
mMonitor.AssertCurrentThreadOwns();
if (mOptSurface) {
if (mOptSurface->IsValid()) {
RefPtr<SourceSurface> surf(mOptSurface);
return surf.forget();
} else {
mOptSurface = nullptr;
}
}
if (mImageSurface) {
RefPtr<SourceSurface> surf(mImageSurface);
return surf.forget();
}
if (!mVBuf) {
return nullptr;
}
VolatileBufferPtr<char> buf(mVBuf);
if (buf.WasBufferPurged()) {
return nullptr;
}
return CreateLockedSurface(mVBuf, mSize, mFormat);
}
already_AddRefed<DrawTarget>
imgFrame::GetDrawTarget()
{
MonitorAutoLock lock(mMonitor);
uint8_t* data;
uint32_t length;
GetImageDataInternal(&data, &length);
if (!data) {
return nullptr;
}
int32_t stride = GetStride();
return gfxPlatform::GetPlatform()->
CreateDrawTargetForData(data, mSize, stride, mFormat);
}
AnimationData
imgFrame::GetAnimationData() const
{
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mLockCount > 0, "Image data should be locked");
uint8_t* data;
if (mPalettedImageData) {
data = mPalettedImageData;
} else {
uint32_t length;
GetImageDataInternal(&data, &length);
}
bool hasAlpha = mFormat == SurfaceFormat::B8G8R8A8;
return AnimationData(data, PaletteDataLength(), mTimeout, GetRect(),
mBlendMethod, mDisposalMethod, hasAlpha);
}
ScalingData
imgFrame::GetScalingData() const
{
MonitorAutoLock lock(mMonitor);
MOZ_ASSERT(mLockCount > 0, "Image data should be locked");
MOZ_ASSERT(!GetIsPaletted(), "GetScalingData can't handle paletted images");
uint8_t* data;
uint32_t length;
GetImageDataInternal(&data, &length);
return ScalingData(data, mSize, GetImageBytesPerRow(), mFormat);
}
void
imgFrame::Abort()
{
MonitorAutoLock lock(mMonitor);
mAborted = true;
// Wake up anyone who's waiting.
mMonitor.NotifyAll();
}
bool
imgFrame::IsAborted() const
{
MonitorAutoLock lock(mMonitor);
return mAborted;
}
bool
imgFrame::IsFinished() const
{
MonitorAutoLock lock(mMonitor);
return mFinished;
}
void
imgFrame::WaitUntilFinished() const
{
MonitorAutoLock lock(mMonitor);
while (true) {
// Return if we're aborted or complete.
if (mAborted || mFinished) {
return;
}
// Not complete yet, so we'll have to wait.
mMonitor.Wait();
}
}
bool
imgFrame::AreAllPixelsWritten() const
{
mMonitor.AssertCurrentThreadOwns();
return mDecoded.IsEqualInterior(nsIntRect(mOffset.x, mOffset.y,
mSize.width, mSize.height));
}
bool imgFrame::GetCompositingFailed() const
{
MOZ_ASSERT(NS_IsMainThread());
return mCompositingFailed;
}
void
imgFrame::SetCompositingFailed(bool val)
{
MOZ_ASSERT(NS_IsMainThread());
mCompositingFailed = val;
}
void
imgFrame::AddSizeOfExcludingThis(MallocSizeOf aMallocSizeOf,
size_t& aHeapSizeOut,
size_t& aNonHeapSizeOut) const
{
MonitorAutoLock lock(mMonitor);
if (mPalettedImageData) {
aHeapSizeOut += aMallocSizeOf(mPalettedImageData);
}
if (mImageSurface) {
aHeapSizeOut += aMallocSizeOf(mImageSurface);
}
if (mOptSurface) {
aHeapSizeOut += aMallocSizeOf(mOptSurface);
}
if (mVBuf) {
aHeapSizeOut += aMallocSizeOf(mVBuf);
aHeapSizeOut += mVBuf->HeapSizeOfExcludingThis(aMallocSizeOf);
aNonHeapSizeOut += mVBuf->NonHeapSizeOfExcludingThis();
}
}
} // namespace image
} // namespace mozilla