SRGB_test.cpp revision 6a5d35dd5cd8710c6c9f100076e62ffbdb0b868b
1/*
2 * Copyright 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#define LOG_TAG "SRGB_test"
18//#define LOG_NDEBUG 0
19
20#include "GLTest.h"
21
22#include <gui/CpuConsumer.h>
23#include <gui/Surface.h>
24#include <gui/SurfaceComposerClient.h>
25
26#include <EGL/egl.h>
27#include <EGL/eglext.h>
28#include <GLES3/gl3.h>
29
30#include <android/native_window.h>
31
32#include <gtest/gtest.h>
33
34namespace android {
35
36class SRGBTest : public ::testing::Test {
37protected:
38    // Class constants
39    enum {
40        DISPLAY_WIDTH = 512,
41        DISPLAY_HEIGHT = 512,
42        PIXEL_SIZE = 4, // bytes or components
43        DISPLAY_SIZE = DISPLAY_WIDTH * DISPLAY_HEIGHT * PIXEL_SIZE,
44        ALPHA_VALUE = 223, // should be in [0, 255]
45        TOLERANCE = 1,
46    };
47    static const char SHOW_DEBUG_STRING[];
48
49    SRGBTest() :
50            mInputSurface(), mCpuConsumer(), mLockedBuffer(),
51            mEglDisplay(EGL_NO_DISPLAY), mEglConfig(),
52            mEglContext(EGL_NO_CONTEXT), mEglSurface(EGL_NO_SURFACE),
53            mComposerClient(), mSurfaceControl(), mOutputSurface() {
54    }
55
56    virtual ~SRGBTest() {
57        if (mEglDisplay != EGL_NO_DISPLAY) {
58            if (mEglSurface != EGL_NO_SURFACE) {
59                eglDestroySurface(mEglDisplay, mEglSurface);
60            }
61            if (mEglContext != EGL_NO_CONTEXT) {
62                eglDestroyContext(mEglDisplay, mEglContext);
63            }
64            eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
65                    EGL_NO_CONTEXT);
66            eglTerminate(mEglDisplay);
67        }
68    }
69
70    virtual void SetUp() {
71        mBufferQueue = new BufferQueue();
72        ASSERT_EQ(NO_ERROR, mBufferQueue->setDefaultBufferSize(
73                DISPLAY_WIDTH, DISPLAY_HEIGHT));
74        mCpuConsumer = new CpuConsumer(mBufferQueue, 1);
75        String8 name("CpuConsumer_for_SRGBTest");
76        mCpuConsumer->setName(name);
77        mInputSurface = new Surface(mBufferQueue);
78
79        ASSERT_NO_FATAL_FAILURE(createEGLSurface(mInputSurface.get()));
80        ASSERT_NO_FATAL_FAILURE(createDebugSurface());
81    }
82
83    virtual void TearDown() {
84        ASSERT_NO_FATAL_FAILURE(copyToDebugSurface());
85        ASSERT_EQ(NO_ERROR, mCpuConsumer->unlockBuffer(mLockedBuffer));
86    }
87
88    static float linearToSRGB(float l) {
89        if (l <= 0.0031308f) {
90            return l * 12.92f;
91        } else {
92            return 1.055f * pow(l, (1 / 2.4f)) - 0.055f;
93        }
94    }
95
96    static float srgbToLinear(float s) {
97        if (s <= 0.04045) {
98            return s / 12.92f;
99        } else {
100            return pow(((s + 0.055f) / 1.055f), 2.4f);
101        }
102    }
103
104    static uint8_t srgbToLinear(uint8_t u) {
105        float f = u / 255.0f;
106        return static_cast<uint8_t>(srgbToLinear(f) * 255.0f + 0.5f);
107    }
108
109    void fillTexture(bool writeAsSRGB) {
110        uint8_t* textureData = new uint8_t[DISPLAY_SIZE];
111
112        for (int y = 0; y < DISPLAY_HEIGHT; ++y) {
113            for (int x = 0; x < DISPLAY_WIDTH; ++x) {
114                float realValue = static_cast<float>(x) / (DISPLAY_WIDTH - 1);
115                realValue *= ALPHA_VALUE / 255.0f; // Premultiply by alpha
116                if (writeAsSRGB) {
117                    realValue = linearToSRGB(realValue);
118                }
119
120                int offset = (y * DISPLAY_WIDTH + x) * PIXEL_SIZE;
121                for (int c = 0; c < 3; ++c) {
122                    uint8_t intValue = static_cast<uint8_t>(
123                            realValue * 255.0f + 0.5f);
124                    textureData[offset + c] = intValue;
125                }
126                textureData[offset + 3] = ALPHA_VALUE;
127            }
128        }
129
130        glTexImage2D(GL_TEXTURE_2D, 0, writeAsSRGB ? GL_SRGB8_ALPHA8 : GL_RGBA8,
131                DISPLAY_WIDTH, DISPLAY_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE,
132                textureData);
133        ASSERT_EQ(GL_NO_ERROR, glGetError());
134
135        delete[] textureData;
136    }
137
138    void initShaders() {
139        static const char vertexSource[] =
140            "attribute vec4 vPosition;\n"
141            "varying vec2 texCoords;\n"
142            "void main() {\n"
143            "  texCoords = 0.5 * (vPosition.xy + vec2(1.0, 1.0));\n"
144            "  gl_Position = vPosition;\n"
145            "}\n";
146
147        static const char fragmentSource[] =
148            "precision mediump float;\n"
149            "uniform sampler2D texSampler;\n"
150            "varying vec2 texCoords;\n"
151            "void main() {\n"
152            "  gl_FragColor = texture2D(texSampler, texCoords);\n"
153            "}\n";
154
155        GLuint program;
156        {
157            SCOPED_TRACE("Creating shader program");
158            ASSERT_NO_FATAL_FAILURE(GLTest::createProgram(
159                    vertexSource, fragmentSource, &program));
160        }
161
162        GLint positionHandle = glGetAttribLocation(program, "vPosition");
163        ASSERT_EQ(GL_NO_ERROR, glGetError());
164        ASSERT_NE(-1, positionHandle);
165
166        GLint samplerHandle = glGetUniformLocation(program, "texSampler");
167        ASSERT_EQ(GL_NO_ERROR, glGetError());
168        ASSERT_NE(-1, samplerHandle);
169
170        static const GLfloat vertices[] = {
171            -1.0f, 1.0f,
172            -1.0f, -1.0f,
173            1.0f, -1.0f,
174            1.0f, 1.0f,
175        };
176
177        glVertexAttribPointer(positionHandle, 2, GL_FLOAT, GL_FALSE, 0, vertices);
178        ASSERT_EQ(GL_NO_ERROR, glGetError());
179        glEnableVertexAttribArray(positionHandle);
180        ASSERT_EQ(GL_NO_ERROR, glGetError());
181
182        glUseProgram(program);
183        ASSERT_EQ(GL_NO_ERROR, glGetError());
184        glUniform1i(samplerHandle, 0);
185        ASSERT_EQ(GL_NO_ERROR, glGetError());
186
187        GLuint textureHandle;
188        glGenTextures(1, &textureHandle);
189        ASSERT_EQ(GL_NO_ERROR, glGetError());
190        glBindTexture(GL_TEXTURE_2D, textureHandle);
191        ASSERT_EQ(GL_NO_ERROR, glGetError());
192
193        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
194        ASSERT_EQ(GL_NO_ERROR, glGetError());
195        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
196        ASSERT_EQ(GL_NO_ERROR, glGetError());
197        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
198        ASSERT_EQ(GL_NO_ERROR, glGetError());
199        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
200        ASSERT_EQ(GL_NO_ERROR, glGetError());
201    }
202
203    void drawTexture(bool asSRGB, GLint x, GLint y, GLsizei width,
204            GLsizei height) {
205        ASSERT_NO_FATAL_FAILURE(fillTexture(asSRGB));
206        glViewport(x, y, width, height);
207        ASSERT_EQ(GL_NO_ERROR, glGetError());
208        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
209        ASSERT_EQ(GL_NO_ERROR, glGetError());
210    }
211
212    void checkLockedBuffer(PixelFormat format) {
213        ASSERT_EQ(mLockedBuffer.format, format);
214        ASSERT_EQ(mLockedBuffer.width, DISPLAY_WIDTH);
215        ASSERT_EQ(mLockedBuffer.height, DISPLAY_HEIGHT);
216    }
217
218    static bool withinTolerance(int a, int b) {
219        int diff = a - b;
220        return diff >= 0 ? diff <= TOLERANCE : -diff <= TOLERANCE;
221    }
222
223    // Primary producer and consumer
224    sp<BufferQueue> mBufferQueue;
225    sp<Surface> mInputSurface;
226    sp<CpuConsumer> mCpuConsumer;
227    CpuConsumer::LockedBuffer mLockedBuffer;
228
229    EGLDisplay mEglDisplay;
230    EGLConfig mEglConfig;
231    EGLContext mEglContext;
232    EGLSurface mEglSurface;
233
234    // Auxiliary display output
235    sp<SurfaceComposerClient> mComposerClient;
236    sp<SurfaceControl> mSurfaceControl;
237    sp<Surface> mOutputSurface;
238
239private:
240    void createEGLSurface(Surface* inputSurface) {
241        mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
242        ASSERT_EQ(EGL_SUCCESS, eglGetError());
243        ASSERT_NE(EGL_NO_DISPLAY, mEglDisplay);
244
245        EXPECT_TRUE(eglInitialize(mEglDisplay, NULL, NULL));
246        ASSERT_EQ(EGL_SUCCESS, eglGetError());
247
248        static const EGLint configAttribs[] = {
249            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
250            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR,
251            EGL_RED_SIZE, 8,
252            EGL_GREEN_SIZE, 8,
253            EGL_BLUE_SIZE, 8,
254            EGL_ALPHA_SIZE, 8,
255            EGL_NONE };
256
257        EGLint numConfigs = 0;
258        EXPECT_TRUE(eglChooseConfig(mEglDisplay, configAttribs, &mEglConfig, 1,
259                &numConfigs));
260        ASSERT_EQ(EGL_SUCCESS, eglGetError());
261
262        static const EGLint contextAttribs[] = {
263            EGL_CONTEXT_CLIENT_VERSION, 3,
264            EGL_NONE } ;
265
266        mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT,
267                contextAttribs);
268        ASSERT_EQ(EGL_SUCCESS, eglGetError());
269        ASSERT_NE(EGL_NO_CONTEXT, mEglContext);
270
271        mEglSurface = eglCreateWindowSurface(mEglDisplay, mEglConfig,
272                inputSurface, NULL);
273        ASSERT_EQ(EGL_SUCCESS, eglGetError());
274        ASSERT_NE(EGL_NO_SURFACE, mEglSurface);
275
276        EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
277                mEglContext));
278        ASSERT_EQ(EGL_SUCCESS, eglGetError());
279    }
280
281    void createDebugSurface() {
282        if (getenv(SHOW_DEBUG_STRING) == NULL) return;
283
284        mComposerClient = new SurfaceComposerClient;
285        ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
286
287        mSurfaceControl = mComposerClient->createSurface(
288                String8("SRGBTest Surface"), DISPLAY_WIDTH, DISPLAY_HEIGHT,
289                PIXEL_FORMAT_RGBA_8888);
290
291        ASSERT_TRUE(mSurfaceControl != NULL);
292        ASSERT_TRUE(mSurfaceControl->isValid());
293
294        SurfaceComposerClient::openGlobalTransaction();
295        ASSERT_EQ(NO_ERROR, mSurfaceControl->setLayer(0x7FFFFFFF));
296        ASSERT_EQ(NO_ERROR, mSurfaceControl->show());
297        SurfaceComposerClient::closeGlobalTransaction();
298
299        ANativeWindow_Buffer outBuffer;
300        ARect inOutDirtyBounds;
301        mOutputSurface = mSurfaceControl->getSurface();
302        mOutputSurface->lock(&outBuffer, &inOutDirtyBounds);
303        uint8_t* bytePointer = reinterpret_cast<uint8_t*>(outBuffer.bits);
304        for (int y = 0; y < outBuffer.height; ++y) {
305            int rowOffset = y * outBuffer.stride; // pixels
306            for (int x = 0; x < outBuffer.width; ++x) {
307                int colOffset = (rowOffset + x) * PIXEL_SIZE; // bytes
308                for (int c = 0; c < PIXEL_SIZE; ++c) {
309                    int offset = colOffset + c;
310                    bytePointer[offset] = ((c + 1) * 56) - 1;
311                }
312            }
313        }
314        mOutputSurface->unlockAndPost();
315    }
316
317    void copyToDebugSurface() {
318        if (!mOutputSurface.get()) return;
319
320        size_t bufferSize = mLockedBuffer.height * mLockedBuffer.stride *
321                PIXEL_SIZE;
322
323        ANativeWindow_Buffer outBuffer;
324        ARect outBufferBounds;
325        mOutputSurface->lock(&outBuffer, &outBufferBounds);
326        ASSERT_EQ(mLockedBuffer.width, outBuffer.width);
327        ASSERT_EQ(mLockedBuffer.height, outBuffer.height);
328        ASSERT_EQ(mLockedBuffer.stride, outBuffer.stride);
329
330        if (mLockedBuffer.format == outBuffer.format) {
331            memcpy(outBuffer.bits, mLockedBuffer.data, bufferSize);
332        } else {
333            ASSERT_EQ(mLockedBuffer.format, PIXEL_FORMAT_sRGB_A_8888);
334            ASSERT_EQ(outBuffer.format, PIXEL_FORMAT_RGBA_8888);
335            uint8_t* outPointer = reinterpret_cast<uint8_t*>(outBuffer.bits);
336            for (int y = 0; y < outBuffer.height; ++y) {
337                int rowOffset = y * outBuffer.stride; // pixels
338                for (int x = 0; x < outBuffer.width; ++x) {
339                    int colOffset = (rowOffset + x) * PIXEL_SIZE; // bytes
340
341                    // RGB are converted
342                    for (int c = 0; c < (PIXEL_SIZE - 1); ++c) {
343                        outPointer[colOffset + c] = srgbToLinear(
344                                mLockedBuffer.data[colOffset + c]);
345                    }
346
347                    // Alpha isn't converted
348                    outPointer[colOffset + 3] =
349                            mLockedBuffer.data[colOffset + 3];
350                }
351            }
352        }
353        mOutputSurface->unlockAndPost();
354
355        int sleepSeconds = atoi(getenv(SHOW_DEBUG_STRING));
356        sleep(sleepSeconds);
357    }
358};
359
360const char SRGBTest::SHOW_DEBUG_STRING[] = "DEBUG_OUTPUT_SECONDS";
361
362TEST_F(SRGBTest, GLRenderFromSRGBTexture) {
363    ASSERT_NO_FATAL_FAILURE(initShaders());
364
365    // The RGB texture is displayed in the top half
366    ASSERT_NO_FATAL_FAILURE(drawTexture(false, 0, DISPLAY_HEIGHT / 2,
367            DISPLAY_WIDTH, DISPLAY_HEIGHT / 2));
368
369    // The SRGB texture is displayed in the bottom half
370    ASSERT_NO_FATAL_FAILURE(drawTexture(true, 0, 0,
371            DISPLAY_WIDTH, DISPLAY_HEIGHT / 2));
372
373    eglSwapBuffers(mEglDisplay, mEglSurface);
374    ASSERT_EQ(EGL_SUCCESS, eglGetError());
375
376    // Lock
377    ASSERT_EQ(NO_ERROR, mCpuConsumer->lockNextBuffer(&mLockedBuffer));
378    ASSERT_NO_FATAL_FAILURE(checkLockedBuffer(PIXEL_FORMAT_RGBA_8888));
379
380    // Compare a pixel in the middle of each texture
381    int midSRGBOffset = (DISPLAY_HEIGHT / 4) * mLockedBuffer.stride *
382            PIXEL_SIZE;
383    int midRGBOffset = midSRGBOffset * 3;
384    midRGBOffset += (DISPLAY_WIDTH / 2) * PIXEL_SIZE;
385    midSRGBOffset += (DISPLAY_WIDTH / 2) * PIXEL_SIZE;
386    for (int c = 0; c < PIXEL_SIZE; ++c) {
387        int expectedValue = mLockedBuffer.data[midRGBOffset + c];
388        int actualValue = mLockedBuffer.data[midSRGBOffset + c];
389        ASSERT_PRED2(withinTolerance, expectedValue, actualValue);
390    }
391
392    // mLockedBuffer is unlocked in TearDown so we can copy data from it to
393    // the debug surface if necessary
394}
395
396TEST_F(SRGBTest, RenderToSRGBSurface) {
397    ASSERT_NO_FATAL_FAILURE(initShaders());
398
399    // By default, the first buffer we write into will be RGB
400
401    // Render an RGB texture across the whole surface
402    ASSERT_NO_FATAL_FAILURE(drawTexture(false, 0, 0,
403            DISPLAY_WIDTH, DISPLAY_HEIGHT));
404    eglSwapBuffers(mEglDisplay, mEglSurface);
405    ASSERT_EQ(EGL_SUCCESS, eglGetError());
406
407    // Lock
408    ASSERT_EQ(NO_ERROR, mCpuConsumer->lockNextBuffer(&mLockedBuffer));
409    ASSERT_NO_FATAL_FAILURE(checkLockedBuffer(PIXEL_FORMAT_RGBA_8888));
410
411    // Save the values of the middle pixel for later comparison against SRGB
412    uint8_t values[PIXEL_SIZE] = {};
413    int middleOffset = (DISPLAY_HEIGHT / 2) * mLockedBuffer.stride *
414            PIXEL_SIZE;
415    middleOffset += (DISPLAY_WIDTH / 2) * PIXEL_SIZE;
416    for (int c = 0; c < PIXEL_SIZE; ++c) {
417        values[c] = mLockedBuffer.data[middleOffset + c];
418    }
419
420    // Unlock
421    ASSERT_EQ(NO_ERROR, mCpuConsumer->unlockBuffer(mLockedBuffer));
422
423    // Switch to SRGB window surface
424#define EGL_GL_COLORSPACE_KHR      EGL_VG_COLORSPACE
425#define EGL_GL_COLORSPACE_SRGB_KHR EGL_VG_COLORSPACE_sRGB
426
427    static const int srgbAttribs[] = {
428        EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR,
429        EGL_NONE,
430    };
431
432    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
433            mEglContext));
434    ASSERT_EQ(EGL_SUCCESS, eglGetError());
435
436    EXPECT_TRUE(eglDestroySurface(mEglDisplay, mEglSurface));
437    ASSERT_EQ(EGL_SUCCESS, eglGetError());
438
439    mEglSurface = eglCreateWindowSurface(mEglDisplay, mEglConfig,
440            mInputSurface.get(), srgbAttribs);
441    ASSERT_EQ(EGL_SUCCESS, eglGetError());
442    ASSERT_NE(EGL_NO_SURFACE, mEglSurface);
443
444    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
445            mEglContext));
446    ASSERT_EQ(EGL_SUCCESS, eglGetError());
447
448    // Render the texture again
449    ASSERT_NO_FATAL_FAILURE(drawTexture(false, 0, 0,
450            DISPLAY_WIDTH, DISPLAY_HEIGHT));
451    eglSwapBuffers(mEglDisplay, mEglSurface);
452    ASSERT_EQ(EGL_SUCCESS, eglGetError());
453
454    // Lock
455    ASSERT_EQ(NO_ERROR, mCpuConsumer->lockNextBuffer(&mLockedBuffer));
456
457    // Make sure we actually got the SRGB buffer on the consumer side
458    ASSERT_NO_FATAL_FAILURE(checkLockedBuffer(PIXEL_FORMAT_sRGB_A_8888));
459
460    // Verify that the stored value is the same, accounting for RGB/SRGB
461    for (int c = 0; c < PIXEL_SIZE; ++c) {
462        // The alpha value should be equivalent before linear->SRGB
463        float rgbAsSRGB = (c == 3) ? values[c] / 255.0f :
464                linearToSRGB(values[c] / 255.0f);
465        int expectedValue = rgbAsSRGB * 255.0f + 0.5f;
466        int actualValue = mLockedBuffer.data[middleOffset + c];
467        ASSERT_PRED2(withinTolerance, expectedValue, actualValue);
468    }
469
470    // mLockedBuffer is unlocked in TearDown so we can copy data from it to
471    // the debug surface if necessary
472}
473
474} // namespace android
475