Texture.cpp revision efb4b06493fe7b1604c762a448b13c7af2845a8d
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "Caches.h"
18#include "Texture.h"
19#include "utils/GLUtils.h"
20#include "utils/TraceUtils.h"
21
22#include <utils/Log.h>
23
24#include <SkCanvas.h>
25
26namespace android {
27namespace uirenderer {
28
29// Number of bytes used by a texture in the given format
30static int bytesPerPixel(GLint glFormat) {
31    switch (glFormat) {
32    // The wrapped-texture case, usually means a SurfaceTexture
33    case 0:
34        return 0;
35    case GL_LUMINANCE:
36    case GL_ALPHA:
37        return 1;
38    case GL_SRGB8:
39    case GL_RGB:
40        return 3;
41    case GL_SRGB8_ALPHA8:
42    case GL_RGBA:
43        return 4;
44    case GL_RGBA16F:
45        return 8;
46    default:
47        LOG_ALWAYS_FATAL("UNKNOWN FORMAT 0x%x", glFormat);
48    }
49}
50
51bool Texture::isLinear() const {
52    return mInternalFormat == GL_RGBA16F;
53}
54
55void Texture::setWrapST(GLenum wrapS, GLenum wrapT, bool bindTexture, bool force) {
56
57    if (force || wrapS != mWrapS || wrapT != mWrapT) {
58        mWrapS = wrapS;
59        mWrapT = wrapT;
60
61        if (bindTexture) {
62            mCaches.textureState().bindTexture(mTarget, mId);
63        }
64
65        glTexParameteri(mTarget, GL_TEXTURE_WRAP_S, wrapS);
66        glTexParameteri(mTarget, GL_TEXTURE_WRAP_T, wrapT);
67    }
68}
69
70void Texture::setFilterMinMag(GLenum min, GLenum mag, bool bindTexture, bool force) {
71    if (force || min != mMinFilter || mag != mMagFilter) {
72        mMinFilter = min;
73        mMagFilter = mag;
74
75        if (bindTexture) {
76            mCaches.textureState().bindTexture(mTarget, mId);
77        }
78
79        if (mipMap && min == GL_LINEAR) min = GL_LINEAR_MIPMAP_LINEAR;
80
81        glTexParameteri(mTarget, GL_TEXTURE_MIN_FILTER, min);
82        glTexParameteri(mTarget, GL_TEXTURE_MAG_FILTER, mag);
83    }
84}
85
86void Texture::deleteTexture() {
87    mCaches.textureState().deleteTexture(mId);
88    mId = 0;
89    mTarget = GL_NONE;
90    if (mEglImageHandle != EGL_NO_IMAGE_KHR) {
91        EGLDisplay eglDisplayHandle = eglGetCurrentDisplay();
92        eglDestroyImageKHR(eglDisplayHandle, mEglImageHandle);
93        mEglImageHandle = EGL_NO_IMAGE_KHR;
94    }
95}
96
97bool Texture::updateSize(uint32_t width, uint32_t height, GLint internalFormat,
98        GLint format, GLenum target) {
99    if (mWidth == width
100            && mHeight == height
101            && mFormat == format
102            && mInternalFormat == internalFormat
103            && mTarget == target) {
104        return false;
105    }
106    mWidth = width;
107    mHeight = height;
108    mFormat = format;
109    mInternalFormat = internalFormat;
110    mTarget = target;
111    notifySizeChanged(mWidth * mHeight * bytesPerPixel(internalFormat));
112    return true;
113}
114
115void Texture::resetCachedParams() {
116    mWrapS = GL_REPEAT;
117    mWrapT = GL_REPEAT;
118    mMinFilter = GL_NEAREST_MIPMAP_LINEAR;
119    mMagFilter = GL_LINEAR;
120}
121
122void Texture::upload(GLint internalFormat, uint32_t width, uint32_t height,
123        GLenum format, GLenum type, const void* pixels) {
124    GL_CHECKPOINT(MODERATE);
125    bool needsAlloc = updateSize(width, height, internalFormat, format, GL_TEXTURE_2D);
126    if (!mId) {
127        glGenTextures(1, &mId);
128        needsAlloc = true;
129        resetCachedParams();
130    }
131    mCaches.textureState().bindTexture(GL_TEXTURE_2D, mId);
132    if (needsAlloc) {
133        glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, mWidth, mHeight, 0,
134                format, type, pixels);
135    } else if (pixels) {
136        glTexSubImage2D(GL_TEXTURE_2D, 0, internalFormat, mWidth, mHeight, 0,
137                format, type, pixels);
138    }
139    GL_CHECKPOINT(MODERATE);
140}
141
142void Texture::uploadHardwareBitmapToTexture(GraphicBuffer* buffer) {
143    EGLDisplay eglDisplayHandle = eglGetCurrentDisplay();
144    if (mEglImageHandle != EGL_NO_IMAGE_KHR) {
145        eglDestroyImageKHR(eglDisplayHandle, mEglImageHandle);
146        mEglImageHandle = EGL_NO_IMAGE_KHR;
147    }
148    mEglImageHandle = eglCreateImageKHR(eglDisplayHandle, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
149            buffer->getNativeBuffer(), 0);
150    glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, mEglImageHandle);
151}
152
153static void uploadToTexture(bool resize, GLint internalFormat, GLenum format, GLenum type,
154        GLsizei stride, GLsizei bpp, GLsizei width, GLsizei height, const GLvoid * data) {
155
156    const bool useStride = stride != width
157            && Caches::getInstance().extensions().hasUnpackRowLength();
158    if ((stride == width) || useStride) {
159        if (useStride) {
160            glPixelStorei(GL_UNPACK_ROW_LENGTH, stride);
161        }
162
163        if (resize) {
164            glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, data);
165        } else {
166            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data);
167        }
168
169        if (useStride) {
170            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
171        }
172    } else {
173        //  With OpenGL ES 2.0 we need to copy the bitmap in a temporary buffer
174        //  if the stride doesn't match the width
175
176        GLvoid * temp = (GLvoid *) malloc(width * height * bpp);
177        if (!temp) return;
178
179        uint8_t * pDst = (uint8_t *)temp;
180        uint8_t * pSrc = (uint8_t *)data;
181        for (GLsizei i = 0; i < height; i++) {
182            memcpy(pDst, pSrc, width * bpp);
183            pDst += width * bpp;
184            pSrc += stride * bpp;
185        }
186
187        if (resize) {
188            glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, temp);
189        } else {
190            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, temp);
191        }
192
193        free(temp);
194    }
195}
196
197void Texture::colorTypeToGlFormatAndType(const Caches& caches, SkColorType colorType,
198        bool needSRGB, GLint* outInternalFormat, GLint* outFormat, GLint* outType) {
199    switch (colorType) {
200    case kAlpha_8_SkColorType:
201        *outFormat = GL_ALPHA;
202        *outInternalFormat = GL_ALPHA;
203        *outType = GL_UNSIGNED_BYTE;
204        break;
205    case kRGB_565_SkColorType:
206        if (needSRGB) {
207            // We would ideally use a GL_RGB/GL_SRGB8 texture but the
208            // intermediate Skia bitmap needs to be ARGB_8888
209            *outFormat = GL_RGBA;
210            *outInternalFormat = caches.rgbaInternalFormat();
211            *outType = GL_UNSIGNED_BYTE;
212        } else {
213            *outFormat = GL_RGB;
214            *outInternalFormat = GL_RGB;
215            *outType = GL_UNSIGNED_SHORT_5_6_5;
216        }
217        break;
218    // ARGB_4444 and Index_8 are both upconverted to RGBA_8888
219    case kARGB_4444_SkColorType:
220    case kIndex_8_SkColorType:
221    case kN32_SkColorType:
222        *outFormat = GL_RGBA;
223        *outInternalFormat = caches.rgbaInternalFormat(needSRGB);
224        *outType = GL_UNSIGNED_BYTE;
225        break;
226    case kGray_8_SkColorType:
227        // TODO: Handle sRGB
228        *outFormat = GL_LUMINANCE;
229        *outInternalFormat = GL_LUMINANCE;
230        *outType = GL_UNSIGNED_BYTE;
231        break;
232    case kRGBA_F16_SkColorType:
233        // This format is always linear
234        *outFormat = GL_RGBA;
235        *outInternalFormat = GL_RGBA16F;
236        *outType = GL_HALF_FLOAT;
237        break;
238    default:
239        LOG_ALWAYS_FATAL("Unsupported bitmap colorType: %d", colorType);
240        break;
241    }
242}
243
244SkBitmap Texture::uploadToN32(const SkBitmap& bitmap, bool hasLinearBlending,
245        sk_sp<SkColorSpace> sRGB) {
246    SkBitmap rgbaBitmap;
247    rgbaBitmap.allocPixels(SkImageInfo::MakeN32(bitmap.width(), bitmap.height(),
248            bitmap.info().alphaType(), hasLinearBlending ? sRGB : nullptr));
249    rgbaBitmap.eraseColor(0);
250    SkCanvas canvas(rgbaBitmap);
251    canvas.drawBitmap(bitmap, 0.0f, 0.0f, nullptr);
252    return rgbaBitmap;
253}
254
255bool Texture::hasUnsupportedColorType(const SkImageInfo& info, bool hasLinearBlending,
256        SkColorSpace* sRGB) {
257    bool needSRGB = info.colorSpace() == sRGB;
258    return info.colorType() == kARGB_4444_SkColorType
259        || info.colorType() == kIndex_8_SkColorType
260        || (info.colorType() == kRGB_565_SkColorType && hasLinearBlending && needSRGB);
261}
262
263
264void Texture::upload(Bitmap& bitmap) {
265    if (!bitmap.readyToDraw()) {
266        ALOGE("Cannot generate texture from bitmap");
267        return;
268    }
269
270    ATRACE_FORMAT("Upload %ux%u Texture", bitmap.width(), bitmap.height());
271
272    // We could also enable mipmapping if both bitmap dimensions are powers
273    // of 2 but we'd have to deal with size changes. Let's keep this simple
274    const bool canMipMap = mCaches.extensions().hasNPot();
275
276    // If the texture had mipmap enabled but not anymore,
277    // force a glTexImage2D to discard the mipmap levels
278    bool needsAlloc = canMipMap && mipMap && !bitmap.hasHardwareMipMap();
279    bool setDefaultParams = false;
280
281    if (!mId) {
282        glGenTextures(1, &mId);
283        needsAlloc = true;
284        setDefaultParams = true;
285    }
286
287    sk_sp<SkColorSpace> sRGB = SkColorSpace::MakeSRGB();
288    bool needSRGB = bitmap.info().colorSpace() == sRGB.get();
289
290    GLint internalFormat, format, type;
291    colorTypeToGlFormatAndType(mCaches, bitmap.colorType(), needSRGB, &internalFormat, &format, &type);
292
293    GLenum target = bitmap.isHardware() ? GL_TEXTURE_EXTERNAL_OES : GL_TEXTURE_2D;
294    needsAlloc |= updateSize(bitmap.width(), bitmap.height(), internalFormat, format, target);
295
296    blend = !bitmap.isOpaque();
297    mCaches.textureState().bindTexture(mTarget, mId);
298
299    // TODO: Handle sRGB gray bitmaps
300    bool hasLinearBlending = mCaches.extensions().hasLinearBlending();
301    if (CC_UNLIKELY(hasUnsupportedColorType(bitmap.info(), hasLinearBlending, sRGB.get()))) {
302        SkBitmap skBitmap;
303        bitmap.getSkBitmap(&skBitmap);
304        SkBitmap rgbaBitmap = uploadToN32(skBitmap, hasLinearBlending, std::move(sRGB));
305        uploadToTexture(needsAlloc, internalFormat, format, type, rgbaBitmap.rowBytesAsPixels(),
306                rgbaBitmap.bytesPerPixel(), rgbaBitmap.width(),
307                rgbaBitmap.height(), rgbaBitmap.getPixels());
308    } else if (bitmap.isHardware()) {
309        uploadHardwareBitmapToTexture(bitmap.graphicBuffer());
310    } else {
311        uploadToTexture(needsAlloc, internalFormat, format, type, bitmap.rowBytesAsPixels(),
312                bitmap.info().bytesPerPixel(), bitmap.width(), bitmap.height(), bitmap.pixels());
313    }
314
315    if (canMipMap) {
316        mipMap = bitmap.hasHardwareMipMap();
317        if (mipMap) {
318            glGenerateMipmap(GL_TEXTURE_2D);
319        }
320    }
321
322    if (setDefaultParams) {
323        setFilter(GL_NEAREST);
324        setWrap(GL_CLAMP_TO_EDGE);
325    }
326}
327
328void Texture::wrap(GLuint id, uint32_t width, uint32_t height,
329        GLint internalFormat, GLint format, GLenum target) {
330    mId = id;
331    mWidth = width;
332    mHeight = height;
333    mFormat = format;
334    mInternalFormat = internalFormat;
335    mTarget = target;
336    // We're wrapping an existing texture, so don't double count this memory
337    notifySizeChanged(0);
338}
339
340}; // namespace uirenderer
341}; // namespace android
342