Files
palemoon27/gfx/gl/GLReadTexImageHelper.cpp
T
roytam1 10160cd03d import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1240749 - Fixes for DPI support in Gtk widget interface: remove incorrect Get[Avail]RectDisplayPix overrides, as desktop pixels == device pixels for the Gtk widget backend, and implement nsScreenGtk::GetDefaultCSSScaleFactor, required by nsGlobalWindow since per-monitor DPI patches in bug 890156. r=karlt (9975cac985)
- Bug 1033488 - Part 2. Make PuppetBidiKeyboard correctly on content process. r=masayuki (3a91ce60a8)
- Bug 1257067 - modified XF86XK_ keysyms to GDK_ ones r=masayuki (4b922f9365)
- Bug 1251984 - allow gfx.xrender.enabled pref to work for compositing even if content backend is not Cairo. r=jrmuizel (257a163074)
- Bug 1235941 - Detect DPI change for GTK3. r=karlt (f8ca209d4b)
- Bug 1256728: Add environment variable to disable force present from bug 1232042. r=BenWa (c3b12a085b)
- Bug 1257124: Add null check for IDWriteFactory in gfxDWriteFontFileLoader::CreateCustomFontFile. r=bas (d33af4b9e1)
- Bug 1266209 - log failure reason when PathBuilderD2D::Finish fails. r=bas.schouten (360d7c2ada)
- Bug 1256552 - Disable C4577 to unblock compilation on VS2015; r=jrmuizel (7375fbf42a)
- Bug 1265960 - Remove gfxReusable* r=Bas (ed0b3aca14)
- Bug 1246290 - Refactoring to get rid of SampleContentTransformForFrame from AsyncPanZoomController. r=botond (3be6b4c1f9)
- Bug 1246290 - Add the ability for APZCs to not expose async transforms. r=botond (48942ceddf)
- Bug 1259296 - Scroll snap in the compositor in response to wheel events. r=kats (5fc694c804)
- Bug 1249040 - Allow wheel scrolls to accumulate in the presence of scroll snapping. r=kats (7514e3f6d6)
- Bug 1237343 - Replace uses of mozilla::Vector with nsTArray. r=botond (b721de19cd)
- Bug 1236046 - Don't use a stupidly small time delta to compute a velocity. r=botond (6c8f298ab6)
- Bug 1257959 - Dynamic toolbar transition seems to slow down flings r=kats (47ec4d0d54)
- Bug 1265513 - Do a fuzzy match when checking to see if a scroll will result in overscroll. r=botond (03ee304916)
- Bug 1254252 - Have Axis::ClampOriginToScrollableRect just return the original value if it falls with in the page bounds. r=kats (f88c0b4d7d)
- Bug 1261373 - Record how long it takes for content response notifications to be delivered to APZ. r=botond f=bsmedberg (b4b24d7602)
- Bug 1265515 - Update nsAutoPtr.h includes in gfx/layers/apz to RefPtr.h. r=kats (48bbc2cda8)
- Bug 1259296 - Make sure APZ smooth scroll animations end at their exact destination scroll offset. r=kats (36cace259b)
- Bug 1251837, part 1 - Use pushPrefEnv in setDeltaMultiplierSettings in window_wheel_default_action.html. r=masayuki (d673d55f02)
- Bug 1251837, part 2 - Use pushPrefEnv in doTestActionOverride in window_wheel_default_action.html. r=masayuki (f0375a3820)
- Bug 1251837, part 3 - Use pushPrefEnv in doTestWholeScroll in window_wheel_default_action.html. r=masayuki (0a7af4e103)
- Bug 1251837, part 4 - Use pushPrefEnv in doTestActionOverride in window_wheel_default_action.html. r=masayuki (51bd9cd1e2)
- Bug 1251837, part 5 - Make prepare() in doTestScroll take a callback, and use pushPrefEnv. r=masayuki (856056a947)
- Bug 1251837, part 6 - Make cleanup() in doTestScroll take a callback, and use pushPrefEnv. r=masayuki (34aa62b7f3)
- Bug 1255173 - Fix onZoomReset() in test_wheel_default_action.html to work with e10s. r=masayuki, r=jmaher (0c248c7587)
- Bug 1255178 - Part 1: Remove a leftover use of clearUserPref. r=masayuki Also, remove some trailing whitespace. (c067affdba)
- Bug 1255178 - Part 2: Remove extraneous argument to sendWheelAndWait. r=masayuki (80ce47c89b)
- Bug 1255634 - APZ should scroll by more than a page with large values of mousewheel.default.delta_multiplier_{x,y}. r=masayuki,kats (d72f77daed)
- Bug 1251638 - Don't clamp the displayport to the scrollable rect on the compositor side. r=botond (5dae2ba82e)
- Bug 1251638 - Do a bit of cleanup on the displayport margin computation in APZC; no functional changes. r=botond (575453b538)
- Bug 1266154 - Don't start a scroll snap animation if we're already at the destination. r=kats (2926d33a07)
- Bug 1258851 - Update HitTestingTreeNode::IsScrollbarNode to include the scrollbar track layers. r=rbarker (1e68081a6a)
- Bug 1265806 - Update scrollbar finding code to deal with layer trees on both OS X and Windows properly. r=rbarker (e8df49352e)
- Bug 1255224 - Add pref to force glFinish in DXGL path. (default:false) - r=dvander (8d399f8a49)
- Bug 1224199 - Destroy SharedSurfaces before ~GLContext(). - r=jrmuizel (5ad8d11f8e)
- Bug 1232480. Use 'precision' instead of 'prevision' (c7310988fa)
- Bug 1232668. Allow using kTex2DBlit_FragShaderSource on non-ES targets. (1951af5c1c)
- Bug 1235299 - Fix WebGL assertions for copyTexImage2D. r=jgilbert (226b7c14a8)
- Bug 1249189 - Use GL_RED to replace GL_ALPHA in YCbCr convert. r=jgilbert (e1d8ae2513)
- Bug 1256552 - fix int-to-float conversions in RadialGradientEffectD2D1. r=jrmuizel (36bb7f7f0f)
- Bug 1249279 - Let subdocuments' presContexts inherit the DPI setting of their parent, instead of retrieving it from their widget, to avoid using stale values from a currently-hidden widget on a screen with a different DPI. r=bz (4b8f6e0960)
- Bug 1237479 -- nsScriptSecurityManager needs to use the correct user context id in the origin attributes in a few places. r=sicking (90504a4130)
- Bug 1105556 - Call Create(originAttributes) when loadinfo->loadingPrincipal is null, instead of CreatePrincipalWithInheritedAttributes(). r=sicking (fdb341ca53)
- Bug 1253788 - Don't reload inline chrome:// style sheets in nsXBLPrototypeResources. r=bzbarsky (862464ea6c)
- Bug 1261123 - don't needlessly construct nsAutoCString temporaries in nsDefaultURIFixup; r=smaug (08f13674a8)
- Bug 1253673, r=bz (03caab3cce)
- Bug 1259511 - Overwrite loadInfo within AboutProtocolHandler and log warning to console. r=sicking (e2fc868326)
- Bug 905460 - Convert http legacy refs to smart pointers r=dragana a=kwierso (d4bdd102fa)
- Bug 1248564 - "Default authentication credentials (NTLM, Kerb) used in private mode". r=mayhemer (37c5674a0d)
- Bug 345580 - Problem decoding quoted-printable question mark in subject r=biesi (00f66a34a7)
- Bug 906986 - Rework fix for Bug 1241690 to avoid reliance on NrIceCtx inside NrIceMediaStream. r=bwc, r=drno (3d6aabeab6)
- Bug 906986 - Disable TestSrflxCandPairingFilter until bug 1226838 is fixed. r=bwc, r=drno (687281bf8b)
- Bug 906986 - Use the streams from the ice_ctx, don't hold a separate set. r=bwc, r=drno (269cd38ed2)
- Bug 906986 - Genericize some of the test setup and improve logging. r=bwc, r=drno (ad735f2459)
- Bug 906986 - Wrap NrIceCtx in NrIceCtxHandler which will allow us to handle ice restart. r=bwc, r=drno (4f2c1e5866)
- Bug 911216 - Part 12: Windows build bustage fix on a CLOSED TREE. r=efaust (f81e40df57)
- Bug 1261329 - Fix OOM handling in shell dissrc function r=efaust (d61eb121de)
- Bug 1263868 - Properly recover from OOM in ShellAutoEntryMonitor. r=jonco (3830ce7aae)
- Bug 1257722 - Prevent stdout/stderr from getting closed, r=jorendorff (48629efc06)
- Bug 1258847 - Set PTHREAD_MUTEX_ERRORCHECK for js::Mutex in debug builds. r=sfink (48cb353190)
- Bug 1252464 - Remove FrameRange cray cray in favor of using GCVectors. (r=jimb) (60ad943599)
- Bug 1257194: Tracelogger - Check for oom in drainTracelogger, r=bbouvier (7d8299958f)
- Bug 1264961 - Fix OOM case in Debugger::replaceFrameGuts. (r=jimb) (203816a8b3)
- Bug 1257588 - Don't ignore self-hosted frames when getting a saved frame's async cause. r=fitzgen (15b467a950)
- Bug 1258535 - Part 0: Add more and stronger asserts that SavedStacks-related JSAPI methods are called correctly; r=jandem (187251c401)
- Bug 1258535 - Check for the existence of a global before checking if its standard classes are resolved; r=jandem (18f7bbcc69)
- Bug 1264975 - Fix assertion in DebugScope wrapping non-syntactic scopes. (r=jimb) (753e315ddb)
- Bug 1259403 - Tracelogger: Always make sure there are 3 free slots for events, r=bbouvier (67a13b7a14)
- Bug 1231926 - add assertions on BYTEOFFSET_SLOT. r=waldo (3508ea1943)
- Bug 1260725 - Handle and report OOM in census breakdown parsing; r=jorendorff a=kwierso (de669940d1)
- Bug 1263074 - Change the JavaScript syntax error message for the old octal literal notation to suggest the new notation. r=Waldo (4e2457b27a)
- Bug 1257096, don't try to report about unusual unhandled rejected Promises, r=bz,waldo (682e4720d9)
- Bug 1262402: Use the new int64 testing features; r=luke (d213bb4f2c)
- Bug 1263882: Set a default value in DescribeScriptedCaller if the filename is null; r=luke (f66ec211f5)
2024-05-09 21:38:16 +08:00

693 lines
22 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=8 sts=4 et sw=4 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 "GLReadTexImageHelper.h"
#include "gfx2DGlue.h"
#include "gfxColor.h"
#include "gfxTypes.h"
#include "GLContext.h"
#include "OGLShaderProgram.h"
#include "ScopedGLHelpers.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/Move.h"
namespace mozilla {
namespace gl {
using namespace mozilla::gfx;
GLReadTexImageHelper::GLReadTexImageHelper(GLContext* gl)
: mGL(gl)
{
mPrograms[0] = 0;
mPrograms[1] = 0;
mPrograms[2] = 0;
mPrograms[3] = 0;
}
GLReadTexImageHelper::~GLReadTexImageHelper()
{
if (!mGL->MakeCurrent())
return;
mGL->fDeleteProgram(mPrograms[0]);
mGL->fDeleteProgram(mPrograms[1]);
mGL->fDeleteProgram(mPrograms[2]);
mGL->fDeleteProgram(mPrograms[3]);
}
static const GLchar
readTextureImageVS[] =
"attribute vec2 aVertex;\n"
"attribute vec2 aTexCoord;\n"
"varying vec2 vTexCoord;\n"
"void main() { gl_Position = vec4(aVertex, 0, 1); vTexCoord = aTexCoord; }";
static const GLchar
readTextureImageFS_TEXTURE_2D[] =
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"varying vec2 vTexCoord;\n"
"uniform sampler2D uTexture;\n"
"void main() { gl_FragColor = texture2D(uTexture, vTexCoord); }";
static const GLchar
readTextureImageFS_TEXTURE_2D_BGRA[] =
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"varying vec2 vTexCoord;\n"
"uniform sampler2D uTexture;\n"
"void main() { gl_FragColor = texture2D(uTexture, vTexCoord).bgra; }";
static const GLchar
readTextureImageFS_TEXTURE_EXTERNAL[] =
"#extension GL_OES_EGL_image_external : require\n"
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"varying vec2 vTexCoord;\n"
"uniform samplerExternalOES uTexture;\n"
"void main() { gl_FragColor = texture2D(uTexture, vTexCoord); }";
static const GLchar
readTextureImageFS_TEXTURE_RECTANGLE[] =
"#extension GL_ARB_texture_rectangle\n"
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"varying vec2 vTexCoord;\n"
"uniform sampler2DRect uTexture;\n"
"void main() { gl_FragColor = texture2DRect(uTexture, vTexCoord).bgra; }";
GLuint
GLReadTexImageHelper::TextureImageProgramFor(GLenum aTextureTarget,
int aConfig)
{
int variant = 0;
const GLchar* readTextureImageFS = nullptr;
if (aTextureTarget == LOCAL_GL_TEXTURE_2D) {
if (aConfig & mozilla::layers::ENABLE_TEXTURE_RB_SWAP) {
// Need to swizzle R/B.
readTextureImageFS = readTextureImageFS_TEXTURE_2D_BGRA;
variant = 1;
} else {
readTextureImageFS = readTextureImageFS_TEXTURE_2D;
variant = 0;
}
} else if (aTextureTarget == LOCAL_GL_TEXTURE_EXTERNAL) {
readTextureImageFS = readTextureImageFS_TEXTURE_EXTERNAL;
variant = 2;
} else if (aTextureTarget == LOCAL_GL_TEXTURE_RECTANGLE) {
readTextureImageFS = readTextureImageFS_TEXTURE_RECTANGLE;
variant = 3;
}
/* This might be overkill, but assure that we don't access out-of-bounds */
MOZ_ASSERT((size_t) variant < ArrayLength(mPrograms));
if (!mPrograms[variant]) {
GLuint vs = mGL->fCreateShader(LOCAL_GL_VERTEX_SHADER);
const GLchar* vsSourcePtr = &readTextureImageVS[0];
mGL->fShaderSource(vs, 1, &vsSourcePtr, nullptr);
mGL->fCompileShader(vs);
GLuint fs = mGL->fCreateShader(LOCAL_GL_FRAGMENT_SHADER);
mGL->fShaderSource(fs, 1, &readTextureImageFS, nullptr);
mGL->fCompileShader(fs);
GLuint program = mGL->fCreateProgram();
mGL->fAttachShader(program, vs);
mGL->fAttachShader(program, fs);
mGL->fBindAttribLocation(program, 0, "aVertex");
mGL->fBindAttribLocation(program, 1, "aTexCoord");
mGL->fLinkProgram(program);
GLint success;
mGL->fGetProgramiv(program, LOCAL_GL_LINK_STATUS, &success);
if (!success) {
mGL->fDeleteProgram(program);
program = 0;
}
mGL->fDeleteShader(vs);
mGL->fDeleteShader(fs);
mPrograms[variant] = program;
}
return mPrograms[variant];
}
bool
GLReadTexImageHelper::DidGLErrorOccur(const char* str)
{
GLenum error = mGL->fGetError();
if (error != LOCAL_GL_NO_ERROR) {
printf_stderr("GL ERROR: %s (0x%04x) %s\n",
mGL->GLErrorToString(error), error, str);
return true;
}
return false;
}
bool
GetActualReadFormats(GLContext* gl,
GLenum destFormat, GLenum destType,
GLenum* out_readFormat, GLenum* out_readType)
{
MOZ_ASSERT(out_readFormat);
MOZ_ASSERT(out_readType);
if (destFormat == LOCAL_GL_RGBA &&
destType == LOCAL_GL_UNSIGNED_BYTE)
{
*out_readFormat = destFormat;
*out_readType = destType;
return true;
}
bool fallback = true;
if (gl->IsGLES()) {
GLenum auxFormat = 0;
GLenum auxType = 0;
gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_FORMAT, (GLint*)&auxFormat);
gl->fGetIntegerv(LOCAL_GL_IMPLEMENTATION_COLOR_READ_TYPE, (GLint*)&auxType);
if (destFormat == auxFormat &&
destType == auxType)
{
fallback = false;
}
} else {
switch (destFormat) {
case LOCAL_GL_RGB: {
if (destType == LOCAL_GL_UNSIGNED_SHORT_5_6_5_REV)
fallback = false;
break;
}
case LOCAL_GL_BGRA: {
if (destType == LOCAL_GL_UNSIGNED_BYTE ||
destType == LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV)
{
fallback = false;
}
break;
}
}
}
if (fallback) {
*out_readFormat = LOCAL_GL_RGBA;
*out_readType = LOCAL_GL_UNSIGNED_BYTE;
return false;
} else {
*out_readFormat = destFormat;
*out_readType = destType;
return true;
}
}
void
SwapRAndBComponents(DataSourceSurface* surf)
{
DataSourceSurface::MappedSurface map;
if (!surf->Map(DataSourceSurface::MapType::READ_WRITE, &map)) {
MOZ_ASSERT(false, "SwapRAndBComponents: Failed to map surface.");
return;
}
MOZ_ASSERT(map.mStride >= 0);
const size_t rowBytes = surf->GetSize().width*4;
const size_t rowHole = map.mStride - rowBytes;
uint8_t* row = map.mData;
if (!row) {
MOZ_ASSERT(false, "SwapRAndBComponents: Failed to get data from"
" DataSourceSurface.");
surf->Unmap();
return;
}
const size_t rows = surf->GetSize().height;
for (size_t i = 0; i < rows; i++) {
const uint8_t* rowEnd = row + rowBytes;
while (row != rowEnd) {
Swap(row[0], row[2]);
row += 4;
}
row += rowHole;
}
surf->Unmap();
}
static int
CalcRowStride(int width, int pixelSize, int alignment)
{
MOZ_ASSERT(alignment);
int rowStride = width * pixelSize;
if (rowStride % alignment) { // Extra at the end of the line?
int alignmentCount = rowStride / alignment;
rowStride = (alignmentCount+1) * alignment;
}
return rowStride;
}
static int
GuessAlignment(int width, int pixelSize, int rowStride)
{
int alignment = 8; // Max GLES allows.
while (CalcRowStride(width, pixelSize, alignment) != rowStride) {
alignment /= 2;
if (!alignment) {
NS_WARNING("Bad alignment for GLES. Will use temp surf for readback.");
return 0;
}
}
return alignment;
}
void
ReadPixelsIntoDataSurface(GLContext* gl, DataSourceSurface* dest)
{
gl->MakeCurrent();
MOZ_ASSERT(dest->GetSize().width != 0);
MOZ_ASSERT(dest->GetSize().height != 0);
bool hasAlpha = dest->GetFormat() == SurfaceFormat::B8G8R8A8 ||
dest->GetFormat() == SurfaceFormat::R8G8B8A8;
int destPixelSize;
GLenum destFormat;
GLenum destType;
switch (dest->GetFormat()) {
case SurfaceFormat::B8G8R8A8:
case SurfaceFormat::B8G8R8X8:
// Needs host (little) endian ARGB.
destFormat = LOCAL_GL_BGRA;
destType = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV;
break;
case SurfaceFormat::R8G8B8A8:
case SurfaceFormat::R8G8B8X8:
// Needs host (little) endian ABGR.
destFormat = LOCAL_GL_RGBA;
destType = LOCAL_GL_UNSIGNED_BYTE;
break;
case SurfaceFormat::R5G6B5_UINT16:
destFormat = LOCAL_GL_RGB;
destType = LOCAL_GL_UNSIGNED_SHORT_5_6_5_REV;
break;
default:
MOZ_CRASH("GFX: Bad format, read pixels.");
}
destPixelSize = BytesPerPixel(dest->GetFormat());
MOZ_ASSERT(dest->GetSize().width * destPixelSize <= dest->Stride());
GLenum readFormat = destFormat;
GLenum readType = destType;
bool needsTempSurf = !GetActualReadFormats(gl,
destFormat, destType,
&readFormat, &readType);
RefPtr<DataSourceSurface> tempSurf;
DataSourceSurface* readSurf = dest;
int readAlignment = GuessAlignment(dest->GetSize().width,
destPixelSize,
dest->Stride());
if (!readAlignment) {
needsTempSurf = true;
}
if (needsTempSurf) {
if (gl->DebugMode()) {
NS_WARNING("Needing intermediary surface for ReadPixels. This will be slow!");
}
SurfaceFormat readFormatGFX;
switch (readFormat) {
case LOCAL_GL_RGBA: {
readFormatGFX = hasAlpha ? SurfaceFormat::R8G8B8A8
: SurfaceFormat::R8G8B8X8;
break;
}
case LOCAL_GL_BGRA: {
readFormatGFX = hasAlpha ? SurfaceFormat::B8G8R8A8
: SurfaceFormat::B8G8R8X8;
break;
}
case LOCAL_GL_RGB: {
MOZ_ASSERT(destPixelSize == 2);
MOZ_ASSERT(readType == LOCAL_GL_UNSIGNED_SHORT_5_6_5_REV);
readFormatGFX = SurfaceFormat::R5G6B5_UINT16;
break;
}
default: {
MOZ_CRASH("GFX: Bad read format, read format.");
}
}
switch (readType) {
case LOCAL_GL_UNSIGNED_BYTE: {
MOZ_ASSERT(readFormat == LOCAL_GL_RGBA);
readAlignment = 1;
break;
}
case LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV: {
MOZ_ASSERT(readFormat == LOCAL_GL_BGRA);
readAlignment = 4;
break;
}
case LOCAL_GL_UNSIGNED_SHORT_5_6_5_REV: {
MOZ_ASSERT(readFormat == LOCAL_GL_RGB);
readAlignment = 2;
break;
}
default: {
MOZ_CRASH("GFX: Bad read type, read type.");
}
}
int32_t stride = dest->GetSize().width * BytesPerPixel(readFormatGFX);
tempSurf = Factory::CreateDataSourceSurfaceWithStride(dest->GetSize(),
readFormatGFX,
stride);
if (NS_WARN_IF(!tempSurf)) {
return;
}
readSurf = tempSurf;
}
MOZ_ASSERT(readAlignment);
MOZ_ASSERT(reinterpret_cast<uintptr_t>(readSurf->GetData()) % readAlignment == 0);
GLint currentPackAlignment = 0;
gl->fGetIntegerv(LOCAL_GL_PACK_ALIGNMENT, &currentPackAlignment);
if (currentPackAlignment != readAlignment)
gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, readAlignment);
GLsizei width = dest->GetSize().width;
GLsizei height = dest->GetSize().height;
gl->fReadPixels(0, 0,
width, height,
readFormat, readType,
readSurf->GetData());
if (currentPackAlignment != readAlignment)
gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, currentPackAlignment);
if (readSurf != dest) {
MOZ_ASSERT(readFormat == LOCAL_GL_RGBA);
MOZ_ASSERT(readType == LOCAL_GL_UNSIGNED_BYTE);
gfx::Factory::CopyDataSourceSurface(readSurf, dest);
}
// Check if GL is giving back 1.0 alpha for
// RGBA reads to RGBA images from no-alpha buffers.
#ifdef XP_MACOSX
if (gl->WorkAroundDriverBugs() &&
gl->Vendor() == gl::GLVendor::NVIDIA &&
hasAlpha &&
width && height)
{
GLint alphaBits = 0;
gl->fGetIntegerv(LOCAL_GL_ALPHA_BITS, &alphaBits);
if (!alphaBits) {
const uint32_t alphaMask = gfxPackedPixelNoPreMultiply(0xff,0,0,0);
MOZ_ASSERT(dest->GetSize().width * destPixelSize == dest->Stride());
uint32_t* itr = (uint32_t*)dest->GetData();
uint32_t testPixel = *itr;
if ((testPixel & alphaMask) != alphaMask) {
// We need to set the alpha channel to 1.0 manually.
uint32_t* itrEnd = itr + width*height; // Stride is guaranteed to be width*4.
for (; itr != itrEnd; itr++) {
*itr |= alphaMask;
}
}
}
}
#endif
}
already_AddRefed<gfx::DataSourceSurface>
YInvertImageSurface(gfx::DataSourceSurface* aSurf)
{
RefPtr<DataSourceSurface> temp =
Factory::CreateDataSourceSurfaceWithStride(aSurf->GetSize(),
aSurf->GetFormat(),
aSurf->Stride());
if (NS_WARN_IF(!temp)) {
return nullptr;
}
DataSourceSurface::MappedSurface map;
if (!temp->Map(DataSourceSurface::MapType::WRITE, &map)) {
return nullptr;
}
RefPtr<DrawTarget> dt =
Factory::CreateDrawTargetForData(BackendType::CAIRO,
map.mData,
temp->GetSize(),
map.mStride,
temp->GetFormat());
if (!dt) {
temp->Unmap();
return nullptr;
}
dt->SetTransform(Matrix::Scaling(1.0, -1.0) *
Matrix::Translation(0.0, aSurf->GetSize().height));
Rect rect(0, 0, aSurf->GetSize().width, aSurf->GetSize().height);
dt->DrawSurface(aSurf, rect, rect, DrawSurfaceOptions(),
DrawOptions(1.0, CompositionOp::OP_SOURCE, AntialiasMode::NONE));
temp->Unmap();
return temp.forget();
}
already_AddRefed<DataSourceSurface>
ReadBackSurface(GLContext* gl, GLuint aTexture, bool aYInvert, SurfaceFormat aFormat)
{
gl->MakeCurrent();
gl->GuaranteeResolve();
gl->fActiveTexture(LOCAL_GL_TEXTURE0);
gl->fBindTexture(LOCAL_GL_TEXTURE_2D, aTexture);
IntSize size;
gl->fGetTexLevelParameteriv(LOCAL_GL_TEXTURE_2D, 0, LOCAL_GL_TEXTURE_WIDTH, &size.width);
gl->fGetTexLevelParameteriv(LOCAL_GL_TEXTURE_2D, 0, LOCAL_GL_TEXTURE_HEIGHT, &size.height);
RefPtr<DataSourceSurface> surf =
Factory::CreateDataSourceSurfaceWithStride(size, SurfaceFormat::B8G8R8A8,
GetAlignedStride<4>(size.width * BytesPerPixel(SurfaceFormat::B8G8R8A8)));
if (NS_WARN_IF(!surf)) {
return nullptr;
}
uint32_t currentPackAlignment = 0;
gl->fGetIntegerv(LOCAL_GL_PACK_ALIGNMENT, (GLint*)&currentPackAlignment);
if (currentPackAlignment != 4) {
gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, 4);
}
gl->fGetTexImage(LOCAL_GL_TEXTURE_2D, 0, LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE, surf->GetData());
if (currentPackAlignment != 4) {
gl->fPixelStorei(LOCAL_GL_PACK_ALIGNMENT, currentPackAlignment);
}
if (aFormat == SurfaceFormat::R8G8B8A8 || aFormat == SurfaceFormat::R8G8B8X8) {
SwapRAndBComponents(surf);
}
if (aYInvert) {
surf = YInvertImageSurface(surf);
}
return surf.forget();
}
#define CLEANUP_IF_GLERROR_OCCURRED(x) \
if (DidGLErrorOccur(x)) { \
return false; \
}
already_AddRefed<DataSourceSurface>
GLReadTexImageHelper::ReadTexImage(GLuint aTextureId,
GLenum aTextureTarget,
const gfx::IntSize& aSize,
/* ShaderConfigOGL.mFeature */ int aConfig,
bool aYInvert)
{
/* Allocate resulting image surface */
int32_t stride = aSize.width * BytesPerPixel(SurfaceFormat::R8G8B8A8);
RefPtr<DataSourceSurface> isurf =
Factory::CreateDataSourceSurfaceWithStride(aSize,
SurfaceFormat::R8G8B8A8,
stride);
if (NS_WARN_IF(!isurf)) {
return nullptr;
}
if (!ReadTexImage(isurf, aTextureId, aTextureTarget, aSize, aConfig, aYInvert)) {
return nullptr;
}
return isurf.forget();
}
bool
GLReadTexImageHelper::ReadTexImage(DataSourceSurface* aDest,
GLuint aTextureId,
GLenum aTextureTarget,
const gfx::IntSize& aSize,
/* ShaderConfigOGL.mFeature */ int aConfig,
bool aYInvert)
{
MOZ_ASSERT(aTextureTarget == LOCAL_GL_TEXTURE_2D ||
aTextureTarget == LOCAL_GL_TEXTURE_EXTERNAL ||
aTextureTarget == LOCAL_GL_TEXTURE_RECTANGLE_ARB);
mGL->MakeCurrent();
GLint oldrb, oldfb, oldprog, oldTexUnit, oldTex;
GLuint rb, fb;
do {
mGL->fGetIntegerv(LOCAL_GL_RENDERBUFFER_BINDING, &oldrb);
mGL->fGetIntegerv(LOCAL_GL_FRAMEBUFFER_BINDING, &oldfb);
mGL->fGetIntegerv(LOCAL_GL_CURRENT_PROGRAM, &oldprog);
mGL->fGetIntegerv(LOCAL_GL_ACTIVE_TEXTURE, &oldTexUnit);
mGL->fActiveTexture(LOCAL_GL_TEXTURE0);
switch (aTextureTarget) {
case LOCAL_GL_TEXTURE_2D:
mGL->fGetIntegerv(LOCAL_GL_TEXTURE_BINDING_2D, &oldTex);
break;
case LOCAL_GL_TEXTURE_EXTERNAL:
mGL->fGetIntegerv(LOCAL_GL_TEXTURE_BINDING_EXTERNAL, &oldTex);
break;
case LOCAL_GL_TEXTURE_RECTANGLE:
mGL->fGetIntegerv(LOCAL_GL_TEXTURE_BINDING_RECTANGLE, &oldTex);
break;
default: /* Already checked above */
break;
}
ScopedGLState scopedScissorTestState(mGL, LOCAL_GL_SCISSOR_TEST, false);
ScopedGLState scopedBlendState(mGL, LOCAL_GL_BLEND, false);
ScopedViewportRect scopedViewportRect(mGL, 0, 0, aSize.width, aSize.height);
/* Setup renderbuffer */
mGL->fGenRenderbuffers(1, &rb);
mGL->fBindRenderbuffer(LOCAL_GL_RENDERBUFFER, rb);
GLenum rbInternalFormat =
mGL->IsGLES()
? (mGL->IsExtensionSupported(GLContext::OES_rgb8_rgba8) ? LOCAL_GL_RGBA8 : LOCAL_GL_RGBA4)
: LOCAL_GL_RGBA;
mGL->fRenderbufferStorage(LOCAL_GL_RENDERBUFFER, rbInternalFormat, aSize.width, aSize.height);
CLEANUP_IF_GLERROR_OCCURRED("when binding and creating renderbuffer");
/* Setup framebuffer */
mGL->fGenFramebuffers(1, &fb);
mGL->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, fb);
mGL->fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0,
LOCAL_GL_RENDERBUFFER, rb);
CLEANUP_IF_GLERROR_OCCURRED("when binding and creating framebuffer");
MOZ_ASSERT(mGL->fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER) == LOCAL_GL_FRAMEBUFFER_COMPLETE);
/* Setup vertex and fragment shader */
GLuint program = TextureImageProgramFor(aTextureTarget, aConfig);
MOZ_ASSERT(program);
mGL->fUseProgram(program);
CLEANUP_IF_GLERROR_OCCURRED("when using program");
mGL->fUniform1i(mGL->fGetUniformLocation(program, "uTexture"), 0);
CLEANUP_IF_GLERROR_OCCURRED("when setting uniform location");
/* Setup quad geometry */
mGL->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, 0);
float w = (aTextureTarget == LOCAL_GL_TEXTURE_RECTANGLE) ? (float) aSize.width : 1.0f;
float h = (aTextureTarget == LOCAL_GL_TEXTURE_RECTANGLE) ? (float) aSize.height : 1.0f;
const float
vertexArray[4*2] = {
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f
};
ScopedVertexAttribPointer autoAttrib0(mGL, 0, 2, LOCAL_GL_FLOAT, LOCAL_GL_FALSE, 0, 0, vertexArray);
const float u0 = 0.0f;
const float u1 = w;
const float v0 = aYInvert ? h : 0.0f;
const float v1 = aYInvert ? 0.0f : h;
const float texCoordArray[8] = { u0, v0,
u1, v0,
u0, v1,
u1, v1 };
ScopedVertexAttribPointer autoAttrib1(mGL, 1, 2, LOCAL_GL_FLOAT, LOCAL_GL_FALSE, 0, 0, texCoordArray);
/* Bind the texture */
if (aTextureId) {
mGL->fBindTexture(aTextureTarget, aTextureId);
CLEANUP_IF_GLERROR_OCCURRED("when binding texture");
}
/* Draw quad */
mGL->fClearColor(1.0f, 0.0f, 1.0f, 1.0f);
mGL->fClear(LOCAL_GL_COLOR_BUFFER_BIT);
CLEANUP_IF_GLERROR_OCCURRED("when clearing color buffer");
mGL->fDrawArrays(LOCAL_GL_TRIANGLE_STRIP, 0, 4);
CLEANUP_IF_GLERROR_OCCURRED("when drawing texture");
/* Read-back draw results */
ReadPixelsIntoDataSurface(mGL, aDest);
CLEANUP_IF_GLERROR_OCCURRED("when reading pixels into surface");
} while (false);
/* Restore GL state */
mGL->fBindRenderbuffer(LOCAL_GL_RENDERBUFFER, oldrb);
mGL->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, oldfb);
mGL->fUseProgram(oldprog);
// note that deleting 0 has no effect in any of these calls
mGL->fDeleteRenderbuffers(1, &rb);
mGL->fDeleteFramebuffers(1, &fb);
if (aTextureId)
mGL->fBindTexture(aTextureTarget, oldTex);
if (oldTexUnit != LOCAL_GL_TEXTURE0)
mGL->fActiveTexture(oldTexUnit);
return true;
}
#undef CLEANUP_IF_GLERROR_OCCURRED
} // namespace gl
} // namespace mozilla