SurfaceTexture_test.cpp revision a4e19521ac4563f2ff6517bcfd63d9b8d33a6d0b
1/*
2 * Copyright (C) 2011 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 "SurfaceTexture_test"
18//#define LOG_NDEBUG 0
19
20#include <gtest/gtest.h>
21#include <gui/GLConsumer.h>
22#include <ui/GraphicBuffer.h>
23#include <utils/String8.h>
24#include <utils/threads.h>
25
26#include <gui/ISurfaceComposer.h>
27#include <gui/Surface.h>
28#include <gui/SurfaceComposerClient.h>
29
30#include <EGL/egl.h>
31#include <EGL/eglext.h>
32#include <GLES/gl.h>
33#include <GLES/glext.h>
34#include <GLES2/gl2.h>
35#include <GLES2/gl2ext.h>
36
37#include <ui/FramebufferNativeWindow.h>
38#include <utils/UniquePtr.h>
39#include <android/native_window.h>
40
41namespace android {
42
43class GLTest : public ::testing::Test {
44protected:
45
46    GLTest():
47            mEglDisplay(EGL_NO_DISPLAY),
48            mEglSurface(EGL_NO_SURFACE),
49            mEglContext(EGL_NO_CONTEXT) {
50    }
51
52    virtual void SetUp() {
53        const ::testing::TestInfo* const testInfo =
54            ::testing::UnitTest::GetInstance()->current_test_info();
55        ALOGV("Begin test: %s.%s", testInfo->test_case_name(),
56                testInfo->name());
57
58        mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
59        ASSERT_EQ(EGL_SUCCESS, eglGetError());
60        ASSERT_NE(EGL_NO_DISPLAY, mEglDisplay);
61
62        EGLint majorVersion;
63        EGLint minorVersion;
64        EXPECT_TRUE(eglInitialize(mEglDisplay, &majorVersion, &minorVersion));
65        ASSERT_EQ(EGL_SUCCESS, eglGetError());
66        RecordProperty("EglVersionMajor", majorVersion);
67        RecordProperty("EglVersionMajor", minorVersion);
68
69        EGLint numConfigs = 0;
70        EXPECT_TRUE(eglChooseConfig(mEglDisplay, getConfigAttribs(), &mGlConfig,
71                1, &numConfigs));
72        ASSERT_EQ(EGL_SUCCESS, eglGetError());
73
74        char* displaySecsEnv = getenv("GLTEST_DISPLAY_SECS");
75        if (displaySecsEnv != NULL) {
76            mDisplaySecs = atoi(displaySecsEnv);
77            if (mDisplaySecs < 0) {
78                mDisplaySecs = 0;
79            }
80        } else {
81            mDisplaySecs = 0;
82        }
83
84        if (mDisplaySecs > 0) {
85            mComposerClient = new SurfaceComposerClient;
86            ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
87
88            mSurfaceControl = mComposerClient->createSurface(
89                    String8("Test Surface"),
90                    getSurfaceWidth(), getSurfaceHeight(),
91                    PIXEL_FORMAT_RGB_888, 0);
92
93            ASSERT_TRUE(mSurfaceControl != NULL);
94            ASSERT_TRUE(mSurfaceControl->isValid());
95
96            SurfaceComposerClient::openGlobalTransaction();
97            ASSERT_EQ(NO_ERROR, mSurfaceControl->setLayer(0x7FFFFFFF));
98            ASSERT_EQ(NO_ERROR, mSurfaceControl->show());
99            SurfaceComposerClient::closeGlobalTransaction();
100
101            sp<ANativeWindow> window = mSurfaceControl->getSurface();
102            mEglSurface = eglCreateWindowSurface(mEglDisplay, mGlConfig,
103                    window.get(), NULL);
104        } else {
105            EGLint pbufferAttribs[] = {
106                EGL_WIDTH, getSurfaceWidth(),
107                EGL_HEIGHT, getSurfaceHeight(),
108                EGL_NONE };
109
110            mEglSurface = eglCreatePbufferSurface(mEglDisplay, mGlConfig,
111                    pbufferAttribs);
112        }
113        ASSERT_EQ(EGL_SUCCESS, eglGetError());
114        ASSERT_NE(EGL_NO_SURFACE, mEglSurface);
115
116        mEglContext = eglCreateContext(mEglDisplay, mGlConfig, EGL_NO_CONTEXT,
117                getContextAttribs());
118        ASSERT_EQ(EGL_SUCCESS, eglGetError());
119        ASSERT_NE(EGL_NO_CONTEXT, mEglContext);
120
121        EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
122                mEglContext));
123        ASSERT_EQ(EGL_SUCCESS, eglGetError());
124
125        EGLint w, h;
126        EXPECT_TRUE(eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &w));
127        ASSERT_EQ(EGL_SUCCESS, eglGetError());
128        EXPECT_TRUE(eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &h));
129        ASSERT_EQ(EGL_SUCCESS, eglGetError());
130        RecordProperty("EglSurfaceWidth", w);
131        RecordProperty("EglSurfaceHeight", h);
132
133        glViewport(0, 0, w, h);
134        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
135    }
136
137    virtual void TearDown() {
138        // Display the result
139        if (mDisplaySecs > 0 && mEglSurface != EGL_NO_SURFACE) {
140            eglSwapBuffers(mEglDisplay, mEglSurface);
141            sleep(mDisplaySecs);
142        }
143
144        if (mComposerClient != NULL) {
145            mComposerClient->dispose();
146        }
147        if (mEglContext != EGL_NO_CONTEXT) {
148            eglDestroyContext(mEglDisplay, mEglContext);
149        }
150        if (mEglSurface != EGL_NO_SURFACE) {
151            eglDestroySurface(mEglDisplay, mEglSurface);
152        }
153        if (mEglDisplay != EGL_NO_DISPLAY) {
154            eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
155                    EGL_NO_CONTEXT);
156            eglTerminate(mEglDisplay);
157        }
158        ASSERT_EQ(EGL_SUCCESS, eglGetError());
159
160        const ::testing::TestInfo* const testInfo =
161            ::testing::UnitTest::GetInstance()->current_test_info();
162        ALOGV("End test:   %s.%s", testInfo->test_case_name(),
163                testInfo->name());
164    }
165
166    virtual EGLint const* getConfigAttribs() {
167        static EGLint sDefaultConfigAttribs[] = {
168            EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
169            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
170            EGL_RED_SIZE, 8,
171            EGL_GREEN_SIZE, 8,
172            EGL_BLUE_SIZE, 8,
173            EGL_ALPHA_SIZE, 8,
174            EGL_DEPTH_SIZE, 16,
175            EGL_STENCIL_SIZE, 8,
176            EGL_NONE };
177
178        return sDefaultConfigAttribs;
179    }
180
181    virtual EGLint const* getContextAttribs() {
182        static EGLint sDefaultContextAttribs[] = {
183            EGL_CONTEXT_CLIENT_VERSION, 2,
184            EGL_NONE };
185
186        return sDefaultContextAttribs;
187    }
188
189    virtual EGLint getSurfaceWidth() {
190        return 512;
191    }
192
193    virtual EGLint getSurfaceHeight() {
194        return 512;
195    }
196
197    ::testing::AssertionResult checkPixel(int x, int y, int r,
198            int g, int b, int a, int tolerance=2) {
199        GLubyte pixel[4];
200        String8 msg;
201        glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel);
202        GLenum err = glGetError();
203        if (err != GL_NO_ERROR) {
204            msg += String8::format("error reading pixel: %#x", err);
205            while ((err = glGetError()) != GL_NO_ERROR) {
206                msg += String8::format(", %#x", err);
207            }
208            return ::testing::AssertionFailure(
209                    ::testing::Message(msg.string()));
210        }
211        if (r >= 0 && abs(r - int(pixel[0])) > tolerance) {
212            msg += String8::format("r(%d isn't %d)", pixel[0], r);
213        }
214        if (g >= 0 && abs(g - int(pixel[1])) > tolerance) {
215            if (!msg.isEmpty()) {
216                msg += " ";
217            }
218            msg += String8::format("g(%d isn't %d)", pixel[1], g);
219        }
220        if (b >= 0 && abs(b - int(pixel[2])) > tolerance) {
221            if (!msg.isEmpty()) {
222                msg += " ";
223            }
224            msg += String8::format("b(%d isn't %d)", pixel[2], b);
225        }
226        if (a >= 0 && abs(a - int(pixel[3])) > tolerance) {
227            if (!msg.isEmpty()) {
228                msg += " ";
229            }
230            msg += String8::format("a(%d isn't %d)", pixel[3], a);
231        }
232        if (!msg.isEmpty()) {
233            return ::testing::AssertionFailure(
234                    ::testing::Message(msg.string()));
235        } else {
236            return ::testing::AssertionSuccess();
237        }
238    }
239
240    ::testing::AssertionResult assertRectEq(const Rect &r1,
241        const Rect &r2, int tolerance=1) {
242
243        String8 msg;
244
245        if (abs(r1.left - r2.left) > tolerance) {
246            msg += String8::format("left(%d isn't %d)", r1.left, r2.left);
247        }
248        if (abs(r1.top - r2.top) > tolerance) {
249            if (!msg.isEmpty()) {
250                msg += " ";
251            }
252            msg += String8::format("top(%d isn't %d)", r1.top, r2.top);
253        }
254        if (abs(r1.right - r2.right) > tolerance) {
255            if (!msg.isEmpty()) {
256                msg += " ";
257            }
258            msg += String8::format("right(%d isn't %d)", r1.right, r2.right);
259        }
260        if (abs(r1.bottom - r2.bottom) > tolerance) {
261            if (!msg.isEmpty()) {
262                msg += " ";
263            }
264            msg += String8::format("bottom(%d isn't %d)", r1.bottom, r2.bottom);
265        }
266        if (!msg.isEmpty()) {
267            msg += String8::format(" R1: [%d %d %d %d] R2: [%d %d %d %d]",
268                r1.left, r1.top, r1.right, r1.bottom,
269                r2.left, r2.top, r2.right, r2.bottom);
270            fprintf(stderr, "assertRectEq: %s\n", msg.string());
271            return ::testing::AssertionFailure(
272                    ::testing::Message(msg.string()));
273        } else {
274            return ::testing::AssertionSuccess();
275        }
276    }
277
278    int mDisplaySecs;
279    sp<SurfaceComposerClient> mComposerClient;
280    sp<SurfaceControl> mSurfaceControl;
281
282    EGLDisplay mEglDisplay;
283    EGLSurface mEglSurface;
284    EGLContext mEglContext;
285    EGLConfig  mGlConfig;
286};
287
288static void loadShader(GLenum shaderType, const char* pSource,
289        GLuint* outShader) {
290    GLuint shader = glCreateShader(shaderType);
291    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
292    if (shader) {
293        glShaderSource(shader, 1, &pSource, NULL);
294        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
295        glCompileShader(shader);
296        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
297        GLint compiled = 0;
298        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
299        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
300        if (!compiled) {
301            GLint infoLen = 0;
302            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
303            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
304            if (infoLen) {
305                char* buf = (char*) malloc(infoLen);
306                if (buf) {
307                    glGetShaderInfoLog(shader, infoLen, NULL, buf);
308                    printf("Shader compile log:\n%s\n", buf);
309                    free(buf);
310                    FAIL();
311                }
312            } else {
313                char* buf = (char*) malloc(0x1000);
314                if (buf) {
315                    glGetShaderInfoLog(shader, 0x1000, NULL, buf);
316                    printf("Shader compile log:\n%s\n", buf);
317                    free(buf);
318                    FAIL();
319                }
320            }
321            glDeleteShader(shader);
322            shader = 0;
323        }
324    }
325    ASSERT_TRUE(shader != 0);
326    *outShader = shader;
327}
328
329static void createProgram(const char* pVertexSource,
330        const char* pFragmentSource, GLuint* outPgm) {
331    GLuint vertexShader, fragmentShader;
332    {
333        SCOPED_TRACE("compiling vertex shader");
334        ASSERT_NO_FATAL_FAILURE(loadShader(GL_VERTEX_SHADER, pVertexSource,
335                &vertexShader));
336    }
337    {
338        SCOPED_TRACE("compiling fragment shader");
339        ASSERT_NO_FATAL_FAILURE(loadShader(GL_FRAGMENT_SHADER, pFragmentSource,
340                &fragmentShader));
341    }
342
343    GLuint program = glCreateProgram();
344    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
345    if (program) {
346        glAttachShader(program, vertexShader);
347        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
348        glAttachShader(program, fragmentShader);
349        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
350        glLinkProgram(program);
351        GLint linkStatus = GL_FALSE;
352        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
353        if (linkStatus != GL_TRUE) {
354            GLint bufLength = 0;
355            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
356            if (bufLength) {
357                char* buf = (char*) malloc(bufLength);
358                if (buf) {
359                    glGetProgramInfoLog(program, bufLength, NULL, buf);
360                    printf("Program link log:\n%s\n", buf);
361                    free(buf);
362                    FAIL();
363                }
364            }
365            glDeleteProgram(program);
366            program = 0;
367        }
368    }
369    glDeleteShader(vertexShader);
370    glDeleteShader(fragmentShader);
371    ASSERT_TRUE(program != 0);
372    *outPgm = program;
373}
374
375static int abs(int value) {
376    return value > 0 ? value : -value;
377}
378
379
380// XXX: Code above this point should live elsewhere
381
382class MultiTextureConsumerTest : public GLTest {
383protected:
384    enum { TEX_ID = 123 };
385
386    virtual void SetUp() {
387        GLTest::SetUp();
388        sp<BufferQueue> bq = new BufferQueue();
389        mGlConsumer = new GLConsumer(bq, TEX_ID);
390        mSurface = new Surface(mGlConsumer->getBufferQueue());
391        mANW = mSurface.get();
392
393    }
394    virtual void TearDown() {
395        GLTest::TearDown();
396    }
397    virtual EGLint const* getContextAttribs() {
398        return NULL;
399    }
400    virtual EGLint const* getConfigAttribs() {
401        static EGLint sDefaultConfigAttribs[] = {
402            EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
403            EGL_RED_SIZE, 8,
404            EGL_GREEN_SIZE, 8,
405            EGL_BLUE_SIZE, 8,
406            EGL_ALPHA_SIZE, 8,
407            EGL_NONE };
408
409        return sDefaultConfigAttribs;
410    }
411    sp<GLConsumer> mGlConsumer;
412    sp<Surface> mSurface;
413    ANativeWindow* mANW;
414};
415
416
417TEST_F(MultiTextureConsumerTest, EGLImageTargetWorks) {
418    ANativeWindow_Buffer buffer;
419
420    ASSERT_EQ(native_window_set_usage(mANW, GRALLOC_USAGE_SW_WRITE_OFTEN), NO_ERROR);
421    ASSERT_EQ(native_window_set_buffers_format(mANW, HAL_PIXEL_FORMAT_RGBA_8888), NO_ERROR);
422
423    glShadeModel(GL_FLAT);
424    glDisable(GL_DITHER);
425    glDisable(GL_CULL_FACE);
426    glViewport(0, 0, getSurfaceWidth(), getSurfaceHeight());
427    glOrthof(0, getSurfaceWidth(), 0, getSurfaceHeight(), 0, 1);
428    glEnableClientState(GL_VERTEX_ARRAY);
429    glColor4f(1, 1, 1, 1);
430
431    glBindTexture(GL_TEXTURE_EXTERNAL_OES, TEX_ID);
432    glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
433    glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
434    glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
435    glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
436
437    uint32_t texel = 0x80808080;
438    glBindTexture(GL_TEXTURE_2D, TEX_ID+1);
439    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &texel);
440    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
441    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
442    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
443    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
444
445    glActiveTexture(GL_TEXTURE1);
446    glBindTexture(GL_TEXTURE_2D, TEX_ID+1);
447    glEnable(GL_TEXTURE_2D);
448    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
449
450    glActiveTexture(GL_TEXTURE0);
451    glBindTexture(GL_TEXTURE_EXTERNAL_OES, TEX_ID);
452    glEnable(GL_TEXTURE_EXTERNAL_OES);
453    glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
454
455    glClear(GL_COLOR_BUFFER_BIT);
456    for (int i=0 ; i<8 ; i++) {
457        mSurface->lock(&buffer, NULL);
458        memset(buffer.bits, (i&7) * 0x20, buffer.stride * buffer.height * 4);
459        mSurface->unlockAndPost();
460
461        mGlConsumer->updateTexImage();
462
463        GLfloat vertices[][2] = { {i*16.0f, 0}, {(i+1)*16.0f, 0}, {(i+1)*16.0f, 16.0f}, {i*16.0f, 16.0f} };
464        glVertexPointer(2, GL_FLOAT, 0, vertices);
465        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
466
467        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
468    }
469
470    for (int i=0 ; i<8 ; i++) {
471        EXPECT_TRUE(checkPixel(i*16 + 8,  8, i*16, i*16, i*16, i*16, 0));
472    }
473}
474
475
476
477class SurfaceTextureGLTest : public GLTest {
478protected:
479    enum { TEX_ID = 123 };
480
481    virtual void SetUp() {
482        GLTest::SetUp();
483        sp<BufferQueue> bq = new BufferQueue();
484        mST = new GLConsumer(bq, TEX_ID);
485        mSTC = new Surface(mST->getBufferQueue());
486        mANW = mSTC;
487        mTextureRenderer = new TextureRenderer(TEX_ID, mST);
488        ASSERT_NO_FATAL_FAILURE(mTextureRenderer->SetUp());
489        mFW = new FrameWaiter;
490        mST->setFrameAvailableListener(mFW);
491    }
492
493    virtual void TearDown() {
494        mANW.clear();
495        mSTC.clear();
496        mST.clear();
497        GLTest::TearDown();
498    }
499
500    void drawTexture() {
501        mTextureRenderer->drawTexture();
502    }
503
504    class TextureRenderer: public RefBase {
505    public:
506        TextureRenderer(GLuint texName, const sp<GLConsumer>& st):
507                mTexName(texName),
508                mST(st) {
509        }
510
511        void SetUp() {
512            const char vsrc[] =
513                "attribute vec4 vPosition;\n"
514                "varying vec2 texCoords;\n"
515                "uniform mat4 texMatrix;\n"
516                "void main() {\n"
517                "  vec2 vTexCoords = 0.5 * (vPosition.xy + vec2(1.0, 1.0));\n"
518                "  texCoords = (texMatrix * vec4(vTexCoords, 0.0, 1.0)).xy;\n"
519                "  gl_Position = vPosition;\n"
520                "}\n";
521
522            const char fsrc[] =
523                "#extension GL_OES_EGL_image_external : require\n"
524                "precision mediump float;\n"
525                "uniform samplerExternalOES texSampler;\n"
526                "varying vec2 texCoords;\n"
527                "void main() {\n"
528                "  gl_FragColor = texture2D(texSampler, texCoords);\n"
529                "}\n";
530
531            {
532                SCOPED_TRACE("creating shader program");
533                ASSERT_NO_FATAL_FAILURE(createProgram(vsrc, fsrc, &mPgm));
534            }
535
536            mPositionHandle = glGetAttribLocation(mPgm, "vPosition");
537            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
538            ASSERT_NE(-1, mPositionHandle);
539            mTexSamplerHandle = glGetUniformLocation(mPgm, "texSampler");
540            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
541            ASSERT_NE(-1, mTexSamplerHandle);
542            mTexMatrixHandle = glGetUniformLocation(mPgm, "texMatrix");
543            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
544            ASSERT_NE(-1, mTexMatrixHandle);
545        }
546
547        // drawTexture draws the GLConsumer over the entire GL viewport.
548        void drawTexture() {
549            static const GLfloat triangleVertices[] = {
550                -1.0f, 1.0f,
551                -1.0f, -1.0f,
552                1.0f, -1.0f,
553                1.0f, 1.0f,
554            };
555
556            glVertexAttribPointer(mPositionHandle, 2, GL_FLOAT, GL_FALSE, 0,
557                    triangleVertices);
558            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
559            glEnableVertexAttribArray(mPositionHandle);
560            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
561
562            glUseProgram(mPgm);
563            glUniform1i(mTexSamplerHandle, 0);
564            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
565            glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTexName);
566            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
567
568            // XXX: These calls are not needed for GL_TEXTURE_EXTERNAL_OES as
569            // they're setting the defautls for that target, but when hacking
570            // things to use GL_TEXTURE_2D they are needed to achieve the same
571            // behavior.
572            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER,
573                    GL_LINEAR);
574            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
575            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER,
576                    GL_LINEAR);
577            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
578            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S,
579                    GL_CLAMP_TO_EDGE);
580            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
581            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T,
582                    GL_CLAMP_TO_EDGE);
583            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
584
585            GLfloat texMatrix[16];
586            mST->getTransformMatrix(texMatrix);
587            glUniformMatrix4fv(mTexMatrixHandle, 1, GL_FALSE, texMatrix);
588
589            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
590            ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
591        }
592
593        GLuint mTexName;
594        sp<GLConsumer> mST;
595        GLuint mPgm;
596        GLint mPositionHandle;
597        GLint mTexSamplerHandle;
598        GLint mTexMatrixHandle;
599    };
600
601    class FrameWaiter : public GLConsumer::FrameAvailableListener {
602    public:
603        FrameWaiter():
604                mPendingFrames(0) {
605        }
606
607        void waitForFrame() {
608            Mutex::Autolock lock(mMutex);
609            while (mPendingFrames == 0) {
610                mCondition.wait(mMutex);
611            }
612            mPendingFrames--;
613        }
614
615        virtual void onFrameAvailable() {
616            Mutex::Autolock lock(mMutex);
617            mPendingFrames++;
618            mCondition.signal();
619        }
620
621        int mPendingFrames;
622        Mutex mMutex;
623        Condition mCondition;
624    };
625
626    // Note that GLConsumer will lose the notifications
627    // onBuffersReleased and onFrameAvailable as there is currently
628    // no way to forward the events.  This DisconnectWaiter will not let the
629    // disconnect finish until finishDisconnect() is called.  It will
630    // also block until a disconnect is called
631    class DisconnectWaiter : public BnConsumerListener {
632    public:
633        DisconnectWaiter () :
634            mWaitForDisconnect(false),
635            mPendingFrames(0) {
636        }
637
638        void waitForFrame() {
639            Mutex::Autolock lock(mMutex);
640            while (mPendingFrames == 0) {
641                mFrameCondition.wait(mMutex);
642            }
643            mPendingFrames--;
644        }
645
646        virtual void onFrameAvailable() {
647            Mutex::Autolock lock(mMutex);
648            mPendingFrames++;
649            mFrameCondition.signal();
650        }
651
652        virtual void onBuffersReleased() {
653            Mutex::Autolock lock(mMutex);
654            while (!mWaitForDisconnect) {
655                mDisconnectCondition.wait(mMutex);
656            }
657        }
658
659        void finishDisconnect() {
660            Mutex::Autolock lock(mMutex);
661            mWaitForDisconnect = true;
662            mDisconnectCondition.signal();
663        }
664
665    private:
666        Mutex mMutex;
667
668        bool mWaitForDisconnect;
669        Condition mDisconnectCondition;
670
671        int mPendingFrames;
672        Condition mFrameCondition;
673    };
674
675    sp<GLConsumer> mST;
676    sp<Surface> mSTC;
677    sp<ANativeWindow> mANW;
678    sp<TextureRenderer> mTextureRenderer;
679    sp<FrameWaiter> mFW;
680};
681
682// Fill a YV12 buffer with a multi-colored checkerboard pattern
683void fillYV12Buffer(uint8_t* buf, int w, int h, int stride) {
684    const int blockWidth = w > 16 ? w / 16 : 1;
685    const int blockHeight = h > 16 ? h / 16 : 1;
686    const int yuvTexOffsetY = 0;
687    int yuvTexStrideY = stride;
688    int yuvTexOffsetV = yuvTexStrideY * h;
689    int yuvTexStrideV = (yuvTexStrideY/2 + 0xf) & ~0xf;
690    int yuvTexOffsetU = yuvTexOffsetV + yuvTexStrideV * h/2;
691    int yuvTexStrideU = yuvTexStrideV;
692    for (int x = 0; x < w; x++) {
693        for (int y = 0; y < h; y++) {
694            int parityX = (x / blockWidth) & 1;
695            int parityY = (y / blockHeight) & 1;
696            unsigned char intensity = (parityX ^ parityY) ? 63 : 191;
697            buf[yuvTexOffsetY + (y * yuvTexStrideY) + x] = intensity;
698            if (x < w / 2 && y < h / 2) {
699                buf[yuvTexOffsetU + (y * yuvTexStrideU) + x] = intensity;
700                if (x * 2 < w / 2 && y * 2 < h / 2) {
701                    buf[yuvTexOffsetV + (y*2 * yuvTexStrideV) + x*2 + 0] =
702                    buf[yuvTexOffsetV + (y*2 * yuvTexStrideV) + x*2 + 1] =
703                    buf[yuvTexOffsetV + ((y*2+1) * yuvTexStrideV) + x*2 + 0] =
704                    buf[yuvTexOffsetV + ((y*2+1) * yuvTexStrideV) + x*2 + 1] =
705                        intensity;
706                }
707            }
708        }
709    }
710}
711
712// Fill a YV12 buffer with red outside a given rectangle and green inside it.
713void fillYV12BufferRect(uint8_t* buf, int w, int h, int stride,
714        const android_native_rect_t& rect) {
715    const int yuvTexOffsetY = 0;
716    int yuvTexStrideY = stride;
717    int yuvTexOffsetV = yuvTexStrideY * h;
718    int yuvTexStrideV = (yuvTexStrideY/2 + 0xf) & ~0xf;
719    int yuvTexOffsetU = yuvTexOffsetV + yuvTexStrideV * h/2;
720    int yuvTexStrideU = yuvTexStrideV;
721    for (int x = 0; x < w; x++) {
722        for (int y = 0; y < h; y++) {
723            bool inside = rect.left <= x && x < rect.right &&
724                    rect.top <= y && y < rect.bottom;
725            buf[yuvTexOffsetY + (y * yuvTexStrideY) + x] = inside ? 240 : 64;
726            if (x < w / 2 && y < h / 2) {
727                bool inside = rect.left <= 2*x && 2*x < rect.right &&
728                        rect.top <= 2*y && 2*y < rect.bottom;
729                buf[yuvTexOffsetU + (y * yuvTexStrideU) + x] = 16;
730                buf[yuvTexOffsetV + (y * yuvTexStrideV) + x] =
731                        inside ? 16 : 255;
732            }
733        }
734    }
735}
736
737void fillRGBA8Buffer(uint8_t* buf, int w, int h, int stride) {
738    const size_t PIXEL_SIZE = 4;
739    for (int x = 0; x < w; x++) {
740        for (int y = 0; y < h; y++) {
741            off_t offset = (y * stride + x) * PIXEL_SIZE;
742            for (int c = 0; c < 4; c++) {
743                int parityX = (x / (1 << (c+2))) & 1;
744                int parityY = (y / (1 << (c+2))) & 1;
745                buf[offset + c] = (parityX ^ parityY) ? 231 : 35;
746            }
747        }
748    }
749}
750
751void fillRGBA8BufferSolid(uint8_t* buf, int w, int h, int stride, uint8_t r,
752        uint8_t g, uint8_t b, uint8_t a) {
753    const size_t PIXEL_SIZE = 4;
754    for (int y = 0; y < h; y++) {
755        for (int x = 0; x < h; x++) {
756            off_t offset = (y * stride + x) * PIXEL_SIZE;
757            buf[offset + 0] = r;
758            buf[offset + 1] = g;
759            buf[offset + 2] = b;
760            buf[offset + 3] = a;
761        }
762    }
763}
764
765// Produce a single RGBA8 frame by filling a buffer with a checkerboard pattern
766// using the CPU.  This assumes that the ANativeWindow is already configured to
767// allow this to be done (e.g. the format is set to RGBA8).
768//
769// Calls to this function should be wrapped in an ASSERT_NO_FATAL_FAILURE().
770void produceOneRGBA8Frame(const sp<ANativeWindow>& anw) {
771    android_native_buffer_t* anb;
772    ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(anw.get(),
773            &anb));
774    ASSERT_TRUE(anb != NULL);
775
776    sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
777
778    uint8_t* img = NULL;
779    ASSERT_EQ(NO_ERROR, buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN,
780            (void**)(&img)));
781    fillRGBA8Buffer(img, buf->getWidth(), buf->getHeight(), buf->getStride());
782    ASSERT_EQ(NO_ERROR, buf->unlock());
783    ASSERT_EQ(NO_ERROR, anw->queueBuffer(anw.get(), buf->getNativeBuffer(),
784            -1));
785}
786
787TEST_F(SurfaceTextureGLTest, TexturingFromCpuFilledYV12BufferNpot) {
788    const int texWidth = 64;
789    const int texHeight = 66;
790
791    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
792            texWidth, texHeight, HAL_PIXEL_FORMAT_YV12));
793    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
794            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN));
795
796    ANativeWindowBuffer* anb;
797    ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
798            &anb));
799    ASSERT_TRUE(anb != NULL);
800
801    sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
802
803    // Fill the buffer with the a checkerboard pattern
804    uint8_t* img = NULL;
805    buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img));
806    fillYV12Buffer(img, texWidth, texHeight, buf->getStride());
807    buf->unlock();
808    ASSERT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(), buf->getNativeBuffer(),
809            -1));
810
811    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
812
813    glClearColor(0.2, 0.2, 0.2, 0.2);
814    glClear(GL_COLOR_BUFFER_BIT);
815
816    glViewport(0, 0, texWidth, texHeight);
817    drawTexture();
818
819    EXPECT_TRUE(checkPixel( 0,  0, 255, 127, 255, 255, 3));
820    EXPECT_TRUE(checkPixel(63,  0,   0, 133,   0, 255, 3));
821    EXPECT_TRUE(checkPixel(63, 65,   0, 133,   0, 255, 3));
822    EXPECT_TRUE(checkPixel( 0, 65, 255, 127, 255, 255, 3));
823
824    EXPECT_TRUE(checkPixel(22, 44, 255, 127, 255, 255, 3));
825    EXPECT_TRUE(checkPixel(45, 52, 255, 127, 255, 255, 3));
826    EXPECT_TRUE(checkPixel(52, 51,  98, 255,  73, 255, 3));
827    EXPECT_TRUE(checkPixel( 7, 31, 155,   0, 118, 255, 3));
828    EXPECT_TRUE(checkPixel(31,  9, 107,  24,  87, 255, 3));
829    EXPECT_TRUE(checkPixel(29, 35, 255, 127, 255, 255, 3));
830    EXPECT_TRUE(checkPixel(36, 22, 155,  29,   0, 255, 3));
831}
832
833TEST_F(SurfaceTextureGLTest, TexturingFromCpuFilledYV12BufferPow2) {
834    const int texWidth = 64;
835    const int texHeight = 64;
836
837    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
838            texWidth, texHeight, HAL_PIXEL_FORMAT_YV12));
839    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
840            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN));
841
842    ANativeWindowBuffer* anb;
843    ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
844            &anb));
845    ASSERT_TRUE(anb != NULL);
846
847    sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
848
849    // Fill the buffer with the a checkerboard pattern
850    uint8_t* img = NULL;
851    buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img));
852    fillYV12Buffer(img, texWidth, texHeight, buf->getStride());
853    buf->unlock();
854    ASSERT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(), buf->getNativeBuffer(),
855            -1));
856
857    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
858
859    glClearColor(0.2, 0.2, 0.2, 0.2);
860    glClear(GL_COLOR_BUFFER_BIT);
861
862    glViewport(0, 0, texWidth, texHeight);
863    drawTexture();
864
865    EXPECT_TRUE(checkPixel( 0,  0,   0, 133,   0, 255));
866    EXPECT_TRUE(checkPixel(63,  0, 255, 127, 255, 255));
867    EXPECT_TRUE(checkPixel(63, 63,   0, 133,   0, 255));
868    EXPECT_TRUE(checkPixel( 0, 63, 255, 127, 255, 255));
869
870    EXPECT_TRUE(checkPixel(22, 19, 100, 255,  74, 255));
871    EXPECT_TRUE(checkPixel(45, 11, 100, 255,  74, 255));
872    EXPECT_TRUE(checkPixel(52, 12, 155,   0, 181, 255));
873    EXPECT_TRUE(checkPixel( 7, 32, 150, 237, 170, 255));
874    EXPECT_TRUE(checkPixel(31, 54,   0,  71, 117, 255));
875    EXPECT_TRUE(checkPixel(29, 28,   0, 133,   0, 255));
876    EXPECT_TRUE(checkPixel(36, 41, 100, 232, 255, 255));
877}
878
879TEST_F(SurfaceTextureGLTest, TexturingFromCpuFilledYV12BufferWithCrop) {
880    const int texWidth = 64;
881    const int texHeight = 66;
882
883    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
884            texWidth, texHeight, HAL_PIXEL_FORMAT_YV12));
885    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
886            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN));
887
888    android_native_rect_t crops[] = {
889        {4, 6, 22, 36},
890        {0, 6, 22, 36},
891        {4, 0, 22, 36},
892        {4, 6, texWidth, 36},
893        {4, 6, 22, texHeight},
894    };
895
896    for (int i = 0; i < 5; i++) {
897        const android_native_rect_t& crop(crops[i]);
898        SCOPED_TRACE(String8::format("rect{ l: %d t: %d r: %d b: %d }",
899                crop.left, crop.top, crop.right, crop.bottom).string());
900
901        ASSERT_EQ(NO_ERROR, native_window_set_crop(mANW.get(), &crop));
902
903        ANativeWindowBuffer* anb;
904        ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
905                &anb));
906        ASSERT_TRUE(anb != NULL);
907
908        sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
909
910        uint8_t* img = NULL;
911        buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img));
912        fillYV12BufferRect(img, texWidth, texHeight, buf->getStride(), crop);
913        buf->unlock();
914        ASSERT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(),
915                buf->getNativeBuffer(), -1));
916
917        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
918
919        glClearColor(0.2, 0.2, 0.2, 0.2);
920        glClear(GL_COLOR_BUFFER_BIT);
921
922        glViewport(0, 0, 64, 64);
923        drawTexture();
924
925        EXPECT_TRUE(checkPixel( 0,  0,  82, 255,  35, 255));
926        EXPECT_TRUE(checkPixel(63,  0,  82, 255,  35, 255));
927        EXPECT_TRUE(checkPixel(63, 63,  82, 255,  35, 255));
928        EXPECT_TRUE(checkPixel( 0, 63,  82, 255,  35, 255));
929
930        EXPECT_TRUE(checkPixel(25, 14,  82, 255,  35, 255));
931        EXPECT_TRUE(checkPixel(35, 31,  82, 255,  35, 255));
932        EXPECT_TRUE(checkPixel(57,  6,  82, 255,  35, 255));
933        EXPECT_TRUE(checkPixel( 5, 42,  82, 255,  35, 255));
934        EXPECT_TRUE(checkPixel(32, 33,  82, 255,  35, 255));
935        EXPECT_TRUE(checkPixel(16, 26,  82, 255,  35, 255));
936        EXPECT_TRUE(checkPixel(46, 51,  82, 255,  35, 255));
937    }
938}
939
940// This test is intended to catch synchronization bugs between the CPU-written
941// and GPU-read buffers.
942TEST_F(SurfaceTextureGLTest, TexturingFromCpuFilledYV12BuffersRepeatedly) {
943    enum { texWidth = 16 };
944    enum { texHeight = 16 };
945    enum { numFrames = 1024 };
946
947    ASSERT_EQ(NO_ERROR, mST->setDefaultMaxBufferCount(2));
948    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
949            texWidth, texHeight, HAL_PIXEL_FORMAT_YV12));
950    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
951            GRALLOC_USAGE_SW_WRITE_OFTEN));
952
953    struct TestPixel {
954        int x;
955        int y;
956    };
957    const TestPixel testPixels[] = {
958        {  4, 11 },
959        { 12, 14 },
960        {  7,  2 },
961    };
962    enum {numTestPixels = sizeof(testPixels) / sizeof(testPixels[0])};
963
964    class ProducerThread : public Thread {
965    public:
966        ProducerThread(const sp<ANativeWindow>& anw,
967                const TestPixel* testPixels):
968                mANW(anw),
969                mTestPixels(testPixels) {
970        }
971
972        virtual ~ProducerThread() {
973        }
974
975        virtual bool threadLoop() {
976            for (int i = 0; i < numFrames; i++) {
977                ANativeWindowBuffer* anb;
978                if (native_window_dequeue_buffer_and_wait(mANW.get(),
979                        &anb) != NO_ERROR) {
980                    return false;
981                }
982                if (anb == NULL) {
983                    return false;
984                }
985
986                sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
987
988                const int yuvTexOffsetY = 0;
989                int stride = buf->getStride();
990                int yuvTexStrideY = stride;
991                int yuvTexOffsetV = yuvTexStrideY * texHeight;
992                int yuvTexStrideV = (yuvTexStrideY/2 + 0xf) & ~0xf;
993                int yuvTexOffsetU = yuvTexOffsetV + yuvTexStrideV * texHeight/2;
994                int yuvTexStrideU = yuvTexStrideV;
995
996                uint8_t* img = NULL;
997                buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img));
998
999                // Gray out all the test pixels first, so we're more likely to
1000                // see a failure if GL is still texturing from the buffer we
1001                // just dequeued.
1002                for (int j = 0; j < numTestPixels; j++) {
1003                    int x = mTestPixels[j].x;
1004                    int y = mTestPixels[j].y;
1005                    uint8_t value = 128;
1006                    img[y*stride + x] = value;
1007                }
1008
1009                // Fill the buffer with gray.
1010                for (int y = 0; y < texHeight; y++) {
1011                    for (int x = 0; x < texWidth; x++) {
1012                        img[yuvTexOffsetY + y*yuvTexStrideY + x] = 128;
1013                        img[yuvTexOffsetU + (y/2)*yuvTexStrideU + x/2] = 128;
1014                        img[yuvTexOffsetV + (y/2)*yuvTexStrideV + x/2] = 128;
1015                    }
1016                }
1017
1018                // Set the test pixels to either white or black.
1019                for (int j = 0; j < numTestPixels; j++) {
1020                    int x = mTestPixels[j].x;
1021                    int y = mTestPixels[j].y;
1022                    uint8_t value = 0;
1023                    if (j == (i % numTestPixels)) {
1024                        value = 255;
1025                    }
1026                    img[y*stride + x] = value;
1027                }
1028
1029                buf->unlock();
1030                if (mANW->queueBuffer(mANW.get(), buf->getNativeBuffer(), -1)
1031                        != NO_ERROR) {
1032                    return false;
1033                }
1034            }
1035            return false;
1036        }
1037
1038        sp<ANativeWindow> mANW;
1039        const TestPixel* mTestPixels;
1040    };
1041
1042    sp<Thread> pt(new ProducerThread(mANW, testPixels));
1043    pt->run();
1044
1045    glViewport(0, 0, texWidth, texHeight);
1046
1047    glClearColor(0.2, 0.2, 0.2, 0.2);
1048    glClear(GL_COLOR_BUFFER_BIT);
1049
1050    // We wait for the first two frames up front so that the producer will be
1051    // likely to dequeue the buffer that's currently being textured from.
1052    mFW->waitForFrame();
1053    mFW->waitForFrame();
1054
1055    for (int i = 0; i < numFrames; i++) {
1056        SCOPED_TRACE(String8::format("frame %d", i).string());
1057
1058        // We must wait for each frame to come in because if we ever do an
1059        // updateTexImage call that doesn't consume a newly available buffer
1060        // then the producer and consumer will get out of sync, which will cause
1061        // a deadlock.
1062        if (i > 1) {
1063            mFW->waitForFrame();
1064        }
1065        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1066        drawTexture();
1067
1068        for (int j = 0; j < numTestPixels; j++) {
1069            int x = testPixels[j].x;
1070            int y = testPixels[j].y;
1071            uint8_t value = 0;
1072            if (j == (i % numTestPixels)) {
1073                // We must y-invert the texture coords
1074                EXPECT_TRUE(checkPixel(x, texHeight-y-1, 255, 255, 255, 255));
1075            } else {
1076                // We must y-invert the texture coords
1077                EXPECT_TRUE(checkPixel(x, texHeight-y-1, 0, 0, 0, 255));
1078            }
1079        }
1080    }
1081
1082    pt->requestExitAndWait();
1083}
1084
1085TEST_F(SurfaceTextureGLTest, TexturingFromCpuFilledRGBABufferNpot) {
1086    const int texWidth = 64;
1087    const int texHeight = 66;
1088
1089    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
1090            texWidth, texHeight, HAL_PIXEL_FORMAT_RGBA_8888));
1091    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
1092            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN));
1093
1094    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
1095
1096    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1097
1098    glClearColor(0.2, 0.2, 0.2, 0.2);
1099    glClear(GL_COLOR_BUFFER_BIT);
1100
1101    glViewport(0, 0, texWidth, texHeight);
1102    drawTexture();
1103
1104    EXPECT_TRUE(checkPixel( 0,  0,  35,  35,  35,  35));
1105    EXPECT_TRUE(checkPixel(63,  0, 231, 231, 231, 231));
1106    EXPECT_TRUE(checkPixel(63, 65, 231, 231, 231, 231));
1107    EXPECT_TRUE(checkPixel( 0, 65,  35,  35,  35,  35));
1108
1109    EXPECT_TRUE(checkPixel(15, 10,  35, 231, 231, 231));
1110    EXPECT_TRUE(checkPixel(23, 65, 231,  35, 231,  35));
1111    EXPECT_TRUE(checkPixel(19, 40,  35, 231,  35,  35));
1112    EXPECT_TRUE(checkPixel(38, 30, 231,  35,  35,  35));
1113    EXPECT_TRUE(checkPixel(42, 54,  35,  35,  35, 231));
1114    EXPECT_TRUE(checkPixel(37, 34,  35, 231, 231, 231));
1115    EXPECT_TRUE(checkPixel(31,  8, 231,  35,  35, 231));
1116    EXPECT_TRUE(checkPixel(37, 47, 231,  35, 231, 231));
1117    EXPECT_TRUE(checkPixel(25, 38,  35,  35,  35,  35));
1118    EXPECT_TRUE(checkPixel(49,  6,  35, 231,  35,  35));
1119    EXPECT_TRUE(checkPixel(54, 50,  35, 231, 231, 231));
1120    EXPECT_TRUE(checkPixel(27, 26, 231, 231, 231, 231));
1121    EXPECT_TRUE(checkPixel(10,  6,  35,  35, 231, 231));
1122    EXPECT_TRUE(checkPixel(29,  4,  35,  35,  35, 231));
1123    EXPECT_TRUE(checkPixel(55, 28,  35,  35, 231,  35));
1124    EXPECT_TRUE(checkPixel(58, 55,  35,  35, 231, 231));
1125}
1126
1127TEST_F(SurfaceTextureGLTest, TexturingFromCpuFilledRGBABufferPow2) {
1128    const int texWidth = 64;
1129    const int texHeight = 64;
1130
1131    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
1132            texWidth, texHeight, HAL_PIXEL_FORMAT_RGBA_8888));
1133    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
1134            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN));
1135
1136    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
1137
1138    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1139
1140    glClearColor(0.2, 0.2, 0.2, 0.2);
1141    glClear(GL_COLOR_BUFFER_BIT);
1142
1143    glViewport(0, 0, texWidth, texHeight);
1144    drawTexture();
1145
1146    EXPECT_TRUE(checkPixel( 0,  0, 231, 231, 231, 231));
1147    EXPECT_TRUE(checkPixel(63,  0,  35,  35,  35,  35));
1148    EXPECT_TRUE(checkPixel(63, 63, 231, 231, 231, 231));
1149    EXPECT_TRUE(checkPixel( 0, 63,  35,  35,  35,  35));
1150
1151    EXPECT_TRUE(checkPixel(12, 46, 231, 231, 231,  35));
1152    EXPECT_TRUE(checkPixel(16,  1, 231, 231,  35, 231));
1153    EXPECT_TRUE(checkPixel(21, 12, 231,  35,  35, 231));
1154    EXPECT_TRUE(checkPixel(26, 51, 231,  35, 231,  35));
1155    EXPECT_TRUE(checkPixel( 5, 32,  35, 231, 231,  35));
1156    EXPECT_TRUE(checkPixel(13,  8,  35, 231, 231, 231));
1157    EXPECT_TRUE(checkPixel(46,  3,  35,  35, 231,  35));
1158    EXPECT_TRUE(checkPixel(30, 33,  35,  35,  35,  35));
1159    EXPECT_TRUE(checkPixel( 6, 52, 231, 231,  35,  35));
1160    EXPECT_TRUE(checkPixel(55, 33,  35, 231,  35, 231));
1161    EXPECT_TRUE(checkPixel(16, 29,  35,  35, 231, 231));
1162    EXPECT_TRUE(checkPixel( 1, 30,  35,  35,  35, 231));
1163    EXPECT_TRUE(checkPixel(41, 37,  35,  35, 231, 231));
1164    EXPECT_TRUE(checkPixel(46, 29, 231, 231,  35,  35));
1165    EXPECT_TRUE(checkPixel(15, 25,  35, 231,  35, 231));
1166    EXPECT_TRUE(checkPixel( 3, 52,  35, 231,  35,  35));
1167}
1168
1169// Tests if GLConsumer and BufferQueue are robust enough
1170// to handle a special case where updateTexImage is called
1171// in the middle of disconnect.  This ordering is enforced
1172// by blocking in the disconnect callback.
1173TEST_F(SurfaceTextureGLTest, DisconnectStressTest) {
1174
1175    class ProducerThread : public Thread {
1176    public:
1177        ProducerThread(const sp<ANativeWindow>& anw):
1178                mANW(anw) {
1179        }
1180
1181        virtual ~ProducerThread() {
1182        }
1183
1184        virtual bool threadLoop() {
1185            ANativeWindowBuffer* anb;
1186
1187            native_window_api_connect(mANW.get(), NATIVE_WINDOW_API_EGL);
1188
1189            for (int numFrames =0 ; numFrames < 2; numFrames ++) {
1190
1191                if (native_window_dequeue_buffer_and_wait(mANW.get(),
1192                        &anb) != NO_ERROR) {
1193                    return false;
1194                }
1195                if (anb == NULL) {
1196                    return false;
1197                }
1198                if (mANW->queueBuffer(mANW.get(), anb, -1)
1199                        != NO_ERROR) {
1200                    return false;
1201                }
1202            }
1203
1204            native_window_api_disconnect(mANW.get(), NATIVE_WINDOW_API_EGL);
1205
1206            return false;
1207        }
1208
1209    private:
1210        sp<ANativeWindow> mANW;
1211    };
1212
1213    sp<DisconnectWaiter> dw(new DisconnectWaiter());
1214    mST->getBufferQueue()->consumerConnect(dw, false);
1215
1216
1217    sp<Thread> pt(new ProducerThread(mANW));
1218    pt->run();
1219
1220    // eat a frame so GLConsumer will own an at least one slot
1221    dw->waitForFrame();
1222    EXPECT_EQ(OK,mST->updateTexImage());
1223
1224    dw->waitForFrame();
1225    // Could fail here as GLConsumer thinks it still owns the slot
1226    // but bufferQueue has released all slots
1227    EXPECT_EQ(OK,mST->updateTexImage());
1228
1229    dw->finishDisconnect();
1230}
1231
1232
1233// This test ensures that the GLConsumer clears the mCurrentTexture
1234// when it is disconnected and reconnected.  Otherwise it will
1235// attempt to release a buffer that it does not owned
1236TEST_F(SurfaceTextureGLTest, DisconnectClearsCurrentTexture) {
1237    ASSERT_EQ(OK, native_window_api_connect(mANW.get(),
1238            NATIVE_WINDOW_API_EGL));
1239
1240    ANativeWindowBuffer *anb;
1241
1242    EXPECT_EQ (OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1243    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1244
1245    EXPECT_EQ (OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1246    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1247
1248    EXPECT_EQ(OK,mST->updateTexImage());
1249    EXPECT_EQ(OK,mST->updateTexImage());
1250
1251    ASSERT_EQ(OK, native_window_api_disconnect(mANW.get(),
1252            NATIVE_WINDOW_API_EGL));
1253    ASSERT_EQ(OK, native_window_api_connect(mANW.get(),
1254            NATIVE_WINDOW_API_EGL));
1255
1256    EXPECT_EQ(OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1257    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1258
1259    // Will fail here if mCurrentTexture is not cleared properly
1260    mFW->waitForFrame();
1261    EXPECT_EQ(OK,mST->updateTexImage());
1262
1263    ASSERT_EQ(OK, native_window_api_disconnect(mANW.get(),
1264            NATIVE_WINDOW_API_EGL));
1265}
1266
1267TEST_F(SurfaceTextureGLTest, ScaleToWindowMode) {
1268    ASSERT_EQ(OK, native_window_set_scaling_mode(mANW.get(),
1269        NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW));
1270
1271    // The producer image size
1272    ASSERT_EQ(OK, native_window_set_buffers_dimensions(mANW.get(), 512, 512));
1273
1274    // The consumer image size (16 x 9) ratio
1275    mST->setDefaultBufferSize(1280, 720);
1276
1277    ASSERT_EQ(OK, native_window_api_connect(mANW.get(),
1278            NATIVE_WINDOW_API_CPU));
1279
1280    ANativeWindowBuffer *anb;
1281
1282    android_native_rect_t odd = {23, 78, 123, 477};
1283    ASSERT_EQ(OK, native_window_set_crop(mANW.get(), &odd));
1284    EXPECT_EQ (OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1285    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1286    mFW->waitForFrame();
1287    EXPECT_EQ(OK, mST->updateTexImage());
1288    Rect r = mST->getCurrentCrop();
1289    assertRectEq(Rect(23, 78, 123, 477), r);
1290
1291    ASSERT_EQ(OK, native_window_api_disconnect(mANW.get(),
1292            NATIVE_WINDOW_API_CPU));
1293}
1294
1295// This test ensures the scaling mode does the right thing
1296// ie NATIVE_WINDOW_SCALING_MODE_CROP should crop
1297// the image such that it has the same aspect ratio as the
1298// default buffer size
1299TEST_F(SurfaceTextureGLTest, CroppedScalingMode) {
1300    ASSERT_EQ(OK, native_window_set_scaling_mode(mANW.get(),
1301        NATIVE_WINDOW_SCALING_MODE_SCALE_CROP));
1302
1303    // The producer image size
1304    ASSERT_EQ(OK, native_window_set_buffers_dimensions(mANW.get(), 512, 512));
1305
1306    // The consumer image size (16 x 9) ratio
1307    mST->setDefaultBufferSize(1280, 720);
1308
1309    native_window_api_connect(mANW.get(), NATIVE_WINDOW_API_CPU);
1310
1311    ANativeWindowBuffer *anb;
1312
1313    // The crop is in the shape of (320, 180) === 16 x 9
1314    android_native_rect_t standard = {10, 20, 330, 200};
1315    ASSERT_EQ(OK, native_window_set_crop(mANW.get(), &standard));
1316    EXPECT_EQ (OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1317    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1318    mFW->waitForFrame();
1319    EXPECT_EQ(OK, mST->updateTexImage());
1320    Rect r = mST->getCurrentCrop();
1321    // crop should be the same as crop (same aspect ratio)
1322    assertRectEq(Rect(10, 20, 330, 200), r);
1323
1324    // make this wider then desired aspect 239 x 100 (2.39:1)
1325    android_native_rect_t wide = {20, 30, 259, 130};
1326    ASSERT_EQ(OK, native_window_set_crop(mANW.get(), &wide));
1327    EXPECT_EQ (OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1328    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1329    mFW->waitForFrame();
1330    EXPECT_EQ(OK, mST->updateTexImage());
1331    r = mST->getCurrentCrop();
1332    // crop should be the same height, but have cropped left and right borders
1333    // offset is 30.6 px L+, R-
1334    assertRectEq(Rect(51, 30, 228, 130), r);
1335
1336    // This image is taller then desired aspect 400 x 300 (4:3)
1337    android_native_rect_t narrow = {0, 0, 400, 300};
1338    ASSERT_EQ(OK, native_window_set_crop(mANW.get(), &narrow));
1339    EXPECT_EQ (OK, native_window_dequeue_buffer_and_wait(mANW.get(), &anb));
1340    EXPECT_EQ(OK, mANW->queueBuffer(mANW.get(), anb, -1));
1341    mFW->waitForFrame();
1342    EXPECT_EQ(OK, mST->updateTexImage());
1343    r = mST->getCurrentCrop();
1344    // crop should be the same width, but have cropped top and bottom borders
1345    // offset is 37.5 px
1346    assertRectEq(Rect(0, 37, 400, 262), r);
1347
1348    native_window_api_disconnect(mANW.get(), NATIVE_WINDOW_API_CPU);
1349}
1350
1351TEST_F(SurfaceTextureGLTest, AbandonUnblocksDequeueBuffer) {
1352    class ProducerThread : public Thread {
1353    public:
1354        ProducerThread(const sp<ANativeWindow>& anw):
1355                mANW(anw),
1356                mDequeueError(NO_ERROR) {
1357        }
1358
1359        virtual ~ProducerThread() {
1360        }
1361
1362        virtual bool threadLoop() {
1363            Mutex::Autolock lock(mMutex);
1364            ANativeWindowBuffer* anb;
1365
1366            // Frame 1
1367            if (native_window_dequeue_buffer_and_wait(mANW.get(),
1368                    &anb) != NO_ERROR) {
1369                return false;
1370            }
1371            if (anb == NULL) {
1372                return false;
1373            }
1374            if (mANW->queueBuffer(mANW.get(), anb, -1)
1375                    != NO_ERROR) {
1376                return false;
1377            }
1378
1379            // Frame 2
1380            if (native_window_dequeue_buffer_and_wait(mANW.get(),
1381                    &anb) != NO_ERROR) {
1382                return false;
1383            }
1384            if (anb == NULL) {
1385                return false;
1386            }
1387            if (mANW->queueBuffer(mANW.get(), anb, -1)
1388                    != NO_ERROR) {
1389                return false;
1390            }
1391
1392            // Frame 3 - error expected
1393            mDequeueError = native_window_dequeue_buffer_and_wait(mANW.get(),
1394                &anb);
1395            return false;
1396        }
1397
1398        status_t getDequeueError() {
1399            Mutex::Autolock lock(mMutex);
1400            return mDequeueError;
1401        }
1402
1403    private:
1404        sp<ANativeWindow> mANW;
1405        status_t mDequeueError;
1406        Mutex mMutex;
1407    };
1408
1409    ASSERT_EQ(OK, mST->setDefaultMaxBufferCount(2));
1410
1411    sp<Thread> pt(new ProducerThread(mANW));
1412    pt->run();
1413
1414    mFW->waitForFrame();
1415    mFW->waitForFrame();
1416
1417    // Sleep for 100ms to allow the producer thread's dequeueBuffer call to
1418    // block waiting for a buffer to become available.
1419    usleep(100000);
1420
1421    mST->abandon();
1422
1423    pt->requestExitAndWait();
1424    ASSERT_EQ(NO_INIT,
1425            reinterpret_cast<ProducerThread*>(pt.get())->getDequeueError());
1426}
1427
1428TEST_F(SurfaceTextureGLTest, InvalidWidthOrHeightFails) {
1429    int texHeight = 16;
1430    ANativeWindowBuffer* anb;
1431
1432    GLint maxTextureSize;
1433    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
1434
1435    // make sure it works with small textures
1436    mST->setDefaultBufferSize(16, texHeight);
1437    EXPECT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
1438            &anb));
1439    EXPECT_EQ(16, anb->width);
1440    EXPECT_EQ(texHeight, anb->height);
1441    EXPECT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(), anb, -1));
1442    EXPECT_EQ(NO_ERROR, mST->updateTexImage());
1443
1444    // make sure it works with GL_MAX_TEXTURE_SIZE
1445    mST->setDefaultBufferSize(maxTextureSize, texHeight);
1446    EXPECT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
1447            &anb));
1448    EXPECT_EQ(maxTextureSize, anb->width);
1449    EXPECT_EQ(texHeight, anb->height);
1450    EXPECT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(), anb, -1));
1451    EXPECT_EQ(NO_ERROR, mST->updateTexImage());
1452
1453    // make sure it fails with GL_MAX_TEXTURE_SIZE+1
1454    mST->setDefaultBufferSize(maxTextureSize+1, texHeight);
1455    EXPECT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
1456            &anb));
1457    EXPECT_EQ(maxTextureSize+1, anb->width);
1458    EXPECT_EQ(texHeight, anb->height);
1459    EXPECT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(), anb, -1));
1460    ASSERT_NE(NO_ERROR, mST->updateTexImage());
1461}
1462
1463/*
1464 * This test fixture is for testing GL -> GL texture streaming.  It creates an
1465 * EGLSurface and an EGLContext for the image producer to use.
1466 */
1467class SurfaceTextureGLToGLTest : public SurfaceTextureGLTest {
1468protected:
1469    SurfaceTextureGLToGLTest():
1470            mProducerEglSurface(EGL_NO_SURFACE),
1471            mProducerEglContext(EGL_NO_CONTEXT) {
1472    }
1473
1474    virtual void SetUp() {
1475        SurfaceTextureGLTest::SetUp();
1476
1477        mProducerEglSurface = eglCreateWindowSurface(mEglDisplay, mGlConfig,
1478                mANW.get(), NULL);
1479        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1480        ASSERT_NE(EGL_NO_SURFACE, mProducerEglSurface);
1481
1482        mProducerEglContext = eglCreateContext(mEglDisplay, mGlConfig,
1483                EGL_NO_CONTEXT, getContextAttribs());
1484        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1485        ASSERT_NE(EGL_NO_CONTEXT, mProducerEglContext);
1486    }
1487
1488    virtual void TearDown() {
1489        if (mProducerEglContext != EGL_NO_CONTEXT) {
1490            eglDestroyContext(mEglDisplay, mProducerEglContext);
1491        }
1492        if (mProducerEglSurface != EGL_NO_SURFACE) {
1493            eglDestroySurface(mEglDisplay, mProducerEglSurface);
1494        }
1495        SurfaceTextureGLTest::TearDown();
1496    }
1497
1498    EGLSurface mProducerEglSurface;
1499    EGLContext mProducerEglContext;
1500};
1501
1502TEST_F(SurfaceTextureGLToGLTest, TransformHintGetsRespected) {
1503    const uint32_t texWidth = 32;
1504    const uint32_t texHeight = 64;
1505
1506    mST->setDefaultBufferSize(texWidth, texHeight);
1507    mST->setTransformHint(NATIVE_WINDOW_TRANSFORM_ROT_90);
1508
1509    // This test requires 3 buffers to avoid deadlock because we're
1510    // both producer and consumer, and only using one thread.
1511    mST->setDefaultMaxBufferCount(3);
1512
1513    // Do the producer side of things
1514    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1515            mProducerEglSurface, mProducerEglContext));
1516    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1517
1518    // Start a buffer with our chosen size and transform hint moving
1519    // through the system.
1520    glClear(GL_COLOR_BUFFER_BIT);  // give the driver something to do
1521    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1522    mST->updateTexImage();  // consume it
1523    // Swap again.
1524    glClear(GL_COLOR_BUFFER_BIT);
1525    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1526    mST->updateTexImage();
1527
1528    // The current buffer should either show the effects of the transform
1529    // hint (in the form of an inverse transform), or show that the
1530    // transform hint has been ignored.
1531    sp<GraphicBuffer> buf = mST->getCurrentBuffer();
1532    if (mST->getCurrentTransform() == NATIVE_WINDOW_TRANSFORM_ROT_270) {
1533        ASSERT_EQ(texWidth, buf->getHeight());
1534        ASSERT_EQ(texHeight, buf->getWidth());
1535    } else {
1536        ASSERT_EQ(texWidth, buf->getWidth());
1537        ASSERT_EQ(texHeight, buf->getHeight());
1538    }
1539
1540    // Reset the transform hint and confirm that it takes.
1541    mST->setTransformHint(0);
1542    glClear(GL_COLOR_BUFFER_BIT);
1543    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1544    mST->updateTexImage();
1545    glClear(GL_COLOR_BUFFER_BIT);
1546    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1547    mST->updateTexImage();
1548
1549    buf = mST->getCurrentBuffer();
1550    ASSERT_EQ((uint32_t) 0, mST->getCurrentTransform());
1551    ASSERT_EQ(texWidth, buf->getWidth());
1552    ASSERT_EQ(texHeight, buf->getHeight());
1553}
1554
1555TEST_F(SurfaceTextureGLToGLTest, TexturingFromGLFilledRGBABufferPow2) {
1556    const int texWidth = 64;
1557    const int texHeight = 64;
1558
1559    mST->setDefaultBufferSize(texWidth, texHeight);
1560
1561    // This test requires 3 buffers to complete run on a single thread.
1562    mST->setDefaultMaxBufferCount(3);
1563
1564    // Do the producer side of things
1565    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1566            mProducerEglSurface, mProducerEglContext));
1567    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1568
1569    // This is needed to ensure we pick up a buffer of the correct size.
1570    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1571
1572    glClearColor(0.6, 0.6, 0.6, 0.6);
1573    glClear(GL_COLOR_BUFFER_BIT);
1574
1575    glEnable(GL_SCISSOR_TEST);
1576    glScissor(4, 4, 4, 4);
1577    glClearColor(1.0, 0.0, 0.0, 1.0);
1578    glClear(GL_COLOR_BUFFER_BIT);
1579
1580    glScissor(24, 48, 4, 4);
1581    glClearColor(0.0, 1.0, 0.0, 1.0);
1582    glClear(GL_COLOR_BUFFER_BIT);
1583
1584    glScissor(37, 17, 4, 4);
1585    glClearColor(0.0, 0.0, 1.0, 1.0);
1586    glClear(GL_COLOR_BUFFER_BIT);
1587
1588    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1589
1590    // Do the consumer side of things
1591    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
1592            mEglContext));
1593    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1594
1595    glDisable(GL_SCISSOR_TEST);
1596
1597    // Skip the first frame, which was empty
1598    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1599    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1600
1601    glClearColor(0.2, 0.2, 0.2, 0.2);
1602    glClear(GL_COLOR_BUFFER_BIT);
1603
1604    glViewport(0, 0, texWidth, texHeight);
1605    drawTexture();
1606
1607    EXPECT_TRUE(checkPixel( 0,  0, 153, 153, 153, 153));
1608    EXPECT_TRUE(checkPixel(63,  0, 153, 153, 153, 153));
1609    EXPECT_TRUE(checkPixel(63, 63, 153, 153, 153, 153));
1610    EXPECT_TRUE(checkPixel( 0, 63, 153, 153, 153, 153));
1611
1612    EXPECT_TRUE(checkPixel( 4,  7, 255,   0,   0, 255));
1613    EXPECT_TRUE(checkPixel(25, 51,   0, 255,   0, 255));
1614    EXPECT_TRUE(checkPixel(40, 19,   0,   0, 255, 255));
1615    EXPECT_TRUE(checkPixel(29, 51, 153, 153, 153, 153));
1616    EXPECT_TRUE(checkPixel( 5, 32, 153, 153, 153, 153));
1617    EXPECT_TRUE(checkPixel(13,  8, 153, 153, 153, 153));
1618    EXPECT_TRUE(checkPixel(46,  3, 153, 153, 153, 153));
1619    EXPECT_TRUE(checkPixel(30, 33, 153, 153, 153, 153));
1620    EXPECT_TRUE(checkPixel( 6, 52, 153, 153, 153, 153));
1621    EXPECT_TRUE(checkPixel(55, 33, 153, 153, 153, 153));
1622    EXPECT_TRUE(checkPixel(16, 29, 153, 153, 153, 153));
1623    EXPECT_TRUE(checkPixel( 1, 30, 153, 153, 153, 153));
1624    EXPECT_TRUE(checkPixel(41, 37, 153, 153, 153, 153));
1625    EXPECT_TRUE(checkPixel(46, 29, 153, 153, 153, 153));
1626    EXPECT_TRUE(checkPixel(15, 25, 153, 153, 153, 153));
1627    EXPECT_TRUE(checkPixel( 3, 52, 153, 153, 153, 153));
1628}
1629
1630TEST_F(SurfaceTextureGLToGLTest, EglDestroySurfaceUnrefsBuffers) {
1631    sp<GraphicBuffer> buffers[2];
1632
1633    // This test requires async mode to run on a single thread.
1634    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1635            mProducerEglSurface, mProducerEglContext));
1636    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1637    EXPECT_TRUE(eglSwapInterval(mEglDisplay, 0));
1638    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1639
1640    for (int i = 0; i < 2; i++) {
1641        // Produce a frame
1642        EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1643                mProducerEglSurface, mProducerEglContext));
1644        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1645        glClear(GL_COLOR_BUFFER_BIT);
1646        eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1647
1648        // Consume a frame
1649        EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
1650                mEglContext));
1651        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1652        mFW->waitForFrame();
1653        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1654        buffers[i] = mST->getCurrentBuffer();
1655    }
1656
1657    // Destroy the GL texture object to release its ref on buffers[2].
1658    GLuint texID = TEX_ID;
1659    glDeleteTextures(1, &texID);
1660
1661    // Destroy the EGLSurface
1662    EXPECT_TRUE(eglDestroySurface(mEglDisplay, mProducerEglSurface));
1663    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1664    mProducerEglSurface = EGL_NO_SURFACE;
1665
1666    // This test should have the only reference to buffer 0.
1667    EXPECT_EQ(1, buffers[0]->getStrongCount());
1668
1669    // The GLConsumer should hold a single reference to buffer 1 in its
1670    // mCurrentBuffer member.  All of the references in the slots should have
1671    // been released.
1672    EXPECT_EQ(2, buffers[1]->getStrongCount());
1673}
1674
1675TEST_F(SurfaceTextureGLToGLTest, EglDestroySurfaceAfterAbandonUnrefsBuffers) {
1676    sp<GraphicBuffer> buffers[3];
1677
1678    // This test requires async mode to run on a single thread.
1679    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1680            mProducerEglSurface, mProducerEglContext));
1681    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1682    EXPECT_TRUE(eglSwapInterval(mEglDisplay, 0));
1683    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1684
1685    for (int i = 0; i < 3; i++) {
1686        // Produce a frame
1687        EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1688                mProducerEglSurface, mProducerEglContext));
1689        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1690        glClear(GL_COLOR_BUFFER_BIT);
1691        EXPECT_TRUE(eglSwapBuffers(mEglDisplay, mProducerEglSurface));
1692        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1693
1694        // Consume a frame
1695        EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
1696                mEglContext));
1697        ASSERT_EQ(EGL_SUCCESS, eglGetError());
1698        mFW->waitForFrame();
1699        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1700        buffers[i] = mST->getCurrentBuffer();
1701    }
1702
1703    // Abandon the GLConsumer, releasing the ref that the GLConsumer has
1704    // on buffers[2].
1705    mST->abandon();
1706
1707    // Destroy the GL texture object to release its ref on buffers[2].
1708    GLuint texID = TEX_ID;
1709    glDeleteTextures(1, &texID);
1710
1711    // Destroy the EGLSurface.
1712    EXPECT_TRUE(eglDestroySurface(mEglDisplay, mProducerEglSurface));
1713    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1714    mProducerEglSurface = EGL_NO_SURFACE;
1715
1716    EXPECT_EQ(1, buffers[0]->getStrongCount());
1717    EXPECT_EQ(1, buffers[1]->getStrongCount());
1718
1719    // Depending on how lazily the GL driver dequeues buffers, we may end up
1720    // with either two or three total buffers.  If there are three, make sure
1721    // the last one was properly down-ref'd.
1722    if (buffers[2] != buffers[0]) {
1723        EXPECT_EQ(1, buffers[2]->getStrongCount());
1724    }
1725}
1726
1727TEST_F(SurfaceTextureGLToGLTest, EglMakeCurrentBeforeConsumerDeathUnrefsBuffers) {
1728    sp<GraphicBuffer> buffer;
1729
1730    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1731            mProducerEglSurface, mProducerEglContext));
1732
1733    // Produce a frame
1734    glClear(GL_COLOR_BUFFER_BIT);
1735    EXPECT_TRUE(eglSwapBuffers(mEglDisplay, mProducerEglSurface));
1736    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1737
1738    // Destroy the EGLSurface.
1739    EXPECT_TRUE(eglDestroySurface(mEglDisplay, mProducerEglSurface));
1740    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1741    mProducerEglSurface = EGL_NO_SURFACE;
1742    mSTC.clear();
1743    mANW.clear();
1744    mTextureRenderer.clear();
1745
1746    // Consume a frame
1747    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1748    buffer = mST->getCurrentBuffer();
1749
1750    // Destroy the GL texture object to release its ref
1751    GLuint texID = TEX_ID;
1752    glDeleteTextures(1, &texID);
1753
1754    // make un-current, all references to buffer should be gone
1755    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE,
1756            EGL_NO_SURFACE, EGL_NO_CONTEXT));
1757
1758    // Destroy consumer
1759    mST.clear();
1760
1761    EXPECT_EQ(1, buffer->getStrongCount());
1762}
1763
1764TEST_F(SurfaceTextureGLToGLTest, EglMakeCurrentAfterConsumerDeathUnrefsBuffers) {
1765    sp<GraphicBuffer> buffer;
1766
1767    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1768            mProducerEglSurface, mProducerEglContext));
1769
1770    // Produce a frame
1771    glClear(GL_COLOR_BUFFER_BIT);
1772    EXPECT_TRUE(eglSwapBuffers(mEglDisplay, mProducerEglSurface));
1773    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1774
1775    // Destroy the EGLSurface.
1776    EXPECT_TRUE(eglDestroySurface(mEglDisplay, mProducerEglSurface));
1777    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1778    mProducerEglSurface = EGL_NO_SURFACE;
1779    mSTC.clear();
1780    mANW.clear();
1781    mTextureRenderer.clear();
1782
1783    // Consume a frame
1784    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1785    buffer = mST->getCurrentBuffer();
1786
1787    // Destroy the GL texture object to release its ref
1788    GLuint texID = TEX_ID;
1789    glDeleteTextures(1, &texID);
1790
1791    // Destroy consumer
1792    mST.clear();
1793
1794    // make un-current, all references to buffer should be gone
1795    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE,
1796            EGL_NO_SURFACE, EGL_NO_CONTEXT));
1797
1798    EXPECT_EQ(1, buffer->getStrongCount());
1799}
1800
1801TEST_F(SurfaceTextureGLToGLTest, TexturingFromUserSizedGLFilledBuffer) {
1802    enum { texWidth = 64 };
1803    enum { texHeight = 64 };
1804
1805    // This test requires 3 buffers to complete run on a single thread.
1806    mST->setDefaultMaxBufferCount(3);
1807
1808    // Set the user buffer size.
1809    native_window_set_buffers_user_dimensions(mANW.get(), texWidth, texHeight);
1810
1811    // Do the producer side of things
1812    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1813            mProducerEglSurface, mProducerEglContext));
1814    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1815
1816    // This is needed to ensure we pick up a buffer of the correct size.
1817    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1818
1819    glClearColor(0.6, 0.6, 0.6, 0.6);
1820    glClear(GL_COLOR_BUFFER_BIT);
1821
1822    glEnable(GL_SCISSOR_TEST);
1823    glScissor(4, 4, 1, 1);
1824    glClearColor(1.0, 0.0, 0.0, 1.0);
1825    glClear(GL_COLOR_BUFFER_BIT);
1826
1827    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1828
1829    // Do the consumer side of things
1830    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
1831            mEglContext));
1832    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1833
1834    glDisable(GL_SCISSOR_TEST);
1835
1836    // Skip the first frame, which was empty
1837    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1838    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1839
1840    glClearColor(0.2, 0.2, 0.2, 0.2);
1841    glClear(GL_COLOR_BUFFER_BIT);
1842
1843    glViewport(0, 0, texWidth, texHeight);
1844    drawTexture();
1845
1846    EXPECT_TRUE(checkPixel( 0,  0, 153, 153, 153, 153));
1847    EXPECT_TRUE(checkPixel(63,  0, 153, 153, 153, 153));
1848    EXPECT_TRUE(checkPixel(63, 63, 153, 153, 153, 153));
1849    EXPECT_TRUE(checkPixel( 0, 63, 153, 153, 153, 153));
1850
1851    EXPECT_TRUE(checkPixel( 4,  4, 255,   0,   0, 255));
1852    EXPECT_TRUE(checkPixel( 5,  5, 153, 153, 153, 153));
1853    EXPECT_TRUE(checkPixel( 3,  3, 153, 153, 153, 153));
1854    EXPECT_TRUE(checkPixel(45, 52, 153, 153, 153, 153));
1855    EXPECT_TRUE(checkPixel(12, 36, 153, 153, 153, 153));
1856}
1857
1858TEST_F(SurfaceTextureGLToGLTest, TexturingFromPreRotatedUserSizedGLFilledBuffer) {
1859    enum { texWidth = 64 };
1860    enum { texHeight = 16 };
1861
1862    // This test requires 3 buffers to complete run on a single thread.
1863    mST->setDefaultMaxBufferCount(3);
1864
1865    // Set the transform hint.
1866    mST->setTransformHint(NATIVE_WINDOW_TRANSFORM_ROT_90);
1867
1868    // Set the user buffer size.
1869    native_window_set_buffers_user_dimensions(mANW.get(), texWidth, texHeight);
1870
1871    // Do the producer side of things
1872    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1873            mProducerEglSurface, mProducerEglContext));
1874    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1875
1876    // This is needed to ensure we pick up a buffer of the correct size and the
1877    // new rotation hint.
1878    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1879
1880    glClearColor(0.6, 0.6, 0.6, 0.6);
1881    glClear(GL_COLOR_BUFFER_BIT);
1882
1883    glEnable(GL_SCISSOR_TEST);
1884    glScissor(24, 4, 1, 1);
1885    glClearColor(1.0, 0.0, 0.0, 1.0);
1886    glClear(GL_COLOR_BUFFER_BIT);
1887
1888    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1889
1890    // Do the consumer side of things
1891    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
1892            mEglContext));
1893    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1894
1895    glDisable(GL_SCISSOR_TEST);
1896
1897    // Skip the first frame, which was empty
1898    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1899    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1900
1901    glClearColor(0.2, 0.2, 0.2, 0.2);
1902    glClear(GL_COLOR_BUFFER_BIT);
1903
1904    glViewport(0, 0, texWidth, texHeight);
1905    drawTexture();
1906
1907    EXPECT_TRUE(checkPixel( 0,  0, 153, 153, 153, 153));
1908    EXPECT_TRUE(checkPixel(63,  0, 153, 153, 153, 153));
1909    EXPECT_TRUE(checkPixel(63, 15, 153, 153, 153, 153));
1910    EXPECT_TRUE(checkPixel( 0, 15, 153, 153, 153, 153));
1911
1912    EXPECT_TRUE(checkPixel(24,  4, 255,   0,   0, 255));
1913    EXPECT_TRUE(checkPixel(25,  5, 153, 153, 153, 153));
1914    EXPECT_TRUE(checkPixel(23,  3, 153, 153, 153, 153));
1915    EXPECT_TRUE(checkPixel(45, 13, 153, 153, 153, 153));
1916    EXPECT_TRUE(checkPixel(12,  8, 153, 153, 153, 153));
1917}
1918
1919TEST_F(SurfaceTextureGLToGLTest, TexturingFromPreRotatedGLFilledBuffer) {
1920    enum { texWidth = 64 };
1921    enum { texHeight = 16 };
1922
1923    // This test requires 3 buffers to complete run on a single thread.
1924    mST->setDefaultMaxBufferCount(3);
1925
1926    // Set the transform hint.
1927    mST->setTransformHint(NATIVE_WINDOW_TRANSFORM_ROT_90);
1928
1929    // Set the default buffer size.
1930    mST->setDefaultBufferSize(texWidth, texHeight);
1931
1932    // Do the producer side of things
1933    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mProducerEglSurface,
1934            mProducerEglSurface, mProducerEglContext));
1935    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1936
1937    // This is needed to ensure we pick up a buffer of the correct size and the
1938    // new rotation hint.
1939    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1940
1941    glClearColor(0.6, 0.6, 0.6, 0.6);
1942    glClear(GL_COLOR_BUFFER_BIT);
1943
1944    glEnable(GL_SCISSOR_TEST);
1945    glScissor(24, 4, 1, 1);
1946    glClearColor(1.0, 0.0, 0.0, 1.0);
1947    glClear(GL_COLOR_BUFFER_BIT);
1948
1949    eglSwapBuffers(mEglDisplay, mProducerEglSurface);
1950
1951    // Do the consumer side of things
1952    EXPECT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
1953            mEglContext));
1954    ASSERT_EQ(EGL_SUCCESS, eglGetError());
1955
1956    glDisable(GL_SCISSOR_TEST);
1957
1958    // Skip the first frame, which was empty
1959    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1960    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
1961
1962    glClearColor(0.2, 0.2, 0.2, 0.2);
1963    glClear(GL_COLOR_BUFFER_BIT);
1964
1965    glViewport(0, 0, texWidth, texHeight);
1966    drawTexture();
1967
1968    EXPECT_TRUE(checkPixel( 0,  0, 153, 153, 153, 153));
1969    EXPECT_TRUE(checkPixel(63,  0, 153, 153, 153, 153));
1970    EXPECT_TRUE(checkPixel(63, 15, 153, 153, 153, 153));
1971    EXPECT_TRUE(checkPixel( 0, 15, 153, 153, 153, 153));
1972
1973    EXPECT_TRUE(checkPixel(24,  4, 255,   0,   0, 255));
1974    EXPECT_TRUE(checkPixel(25,  5, 153, 153, 153, 153));
1975    EXPECT_TRUE(checkPixel(23,  3, 153, 153, 153, 153));
1976    EXPECT_TRUE(checkPixel(45, 13, 153, 153, 153, 153));
1977    EXPECT_TRUE(checkPixel(12,  8, 153, 153, 153, 153));
1978}
1979
1980/*
1981 * This test fixture is for testing GL -> GL texture streaming from one thread
1982 * to another.  It contains functionality to create a producer thread that will
1983 * perform GL rendering to an ANativeWindow that feeds frames to a
1984 * GLConsumer.  Additionally it supports interlocking the producer and
1985 * consumer threads so that a specific sequence of calls can be
1986 * deterministically created by the test.
1987 *
1988 * The intended usage is as follows:
1989 *
1990 * TEST_F(...) {
1991 *     class PT : public ProducerThread {
1992 *         virtual void render() {
1993 *             ...
1994 *             swapBuffers();
1995 *         }
1996 *     };
1997 *
1998 *     runProducerThread(new PT());
1999 *
2000 *     // The order of these calls will vary from test to test and may include
2001 *     // multiple frames and additional operations (e.g. GL rendering from the
2002 *     // texture).
2003 *     fc->waitForFrame();
2004 *     mST->updateTexImage();
2005 *     fc->finishFrame();
2006 * }
2007 *
2008 */
2009class SurfaceTextureGLThreadToGLTest : public SurfaceTextureGLToGLTest {
2010protected:
2011
2012    // ProducerThread is an abstract base class to simplify the creation of
2013    // OpenGL ES frame producer threads.
2014    class ProducerThread : public Thread {
2015    public:
2016        virtual ~ProducerThread() {
2017        }
2018
2019        void setEglObjects(EGLDisplay producerEglDisplay,
2020                EGLSurface producerEglSurface,
2021                EGLContext producerEglContext) {
2022            mProducerEglDisplay = producerEglDisplay;
2023            mProducerEglSurface = producerEglSurface;
2024            mProducerEglContext = producerEglContext;
2025        }
2026
2027        virtual bool threadLoop() {
2028            eglMakeCurrent(mProducerEglDisplay, mProducerEglSurface,
2029                    mProducerEglSurface, mProducerEglContext);
2030            render();
2031            eglMakeCurrent(mProducerEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
2032                    EGL_NO_CONTEXT);
2033            return false;
2034        }
2035
2036    protected:
2037        virtual void render() = 0;
2038
2039        void swapBuffers() {
2040            eglSwapBuffers(mProducerEglDisplay, mProducerEglSurface);
2041        }
2042
2043        EGLDisplay mProducerEglDisplay;
2044        EGLSurface mProducerEglSurface;
2045        EGLContext mProducerEglContext;
2046    };
2047
2048    // FrameCondition is a utility class for interlocking between the producer
2049    // and consumer threads.  The FrameCondition object should be created and
2050    // destroyed in the consumer thread only.  The consumer thread should set
2051    // the FrameCondition as the FrameAvailableListener of the GLConsumer,
2052    // and should call both waitForFrame and finishFrame once for each expected
2053    // frame.
2054    //
2055    // This interlocking relies on the fact that onFrameAvailable gets called
2056    // synchronously from GLConsumer::queueBuffer.
2057    class FrameCondition : public GLConsumer::FrameAvailableListener {
2058    public:
2059        FrameCondition():
2060                mFrameAvailable(false),
2061                mFrameFinished(false) {
2062        }
2063
2064        // waitForFrame waits for the next frame to arrive.  This should be
2065        // called from the consumer thread once for every frame expected by the
2066        // test.
2067        void waitForFrame() {
2068            Mutex::Autolock lock(mMutex);
2069            ALOGV("+waitForFrame");
2070            while (!mFrameAvailable) {
2071                mFrameAvailableCondition.wait(mMutex);
2072            }
2073            mFrameAvailable = false;
2074            ALOGV("-waitForFrame");
2075        }
2076
2077        // Allow the producer to return from its swapBuffers call and continue
2078        // on to produce the next frame.  This should be called by the consumer
2079        // thread once for every frame expected by the test.
2080        void finishFrame() {
2081            Mutex::Autolock lock(mMutex);
2082            ALOGV("+finishFrame");
2083            mFrameFinished = true;
2084            mFrameFinishCondition.signal();
2085            ALOGV("-finishFrame");
2086        }
2087
2088        // This should be called by GLConsumer on the producer thread.
2089        virtual void onFrameAvailable() {
2090            Mutex::Autolock lock(mMutex);
2091            ALOGV("+onFrameAvailable");
2092            mFrameAvailable = true;
2093            mFrameAvailableCondition.signal();
2094            while (!mFrameFinished) {
2095                mFrameFinishCondition.wait(mMutex);
2096            }
2097            mFrameFinished = false;
2098            ALOGV("-onFrameAvailable");
2099        }
2100
2101    protected:
2102        bool mFrameAvailable;
2103        bool mFrameFinished;
2104
2105        Mutex mMutex;
2106        Condition mFrameAvailableCondition;
2107        Condition mFrameFinishCondition;
2108    };
2109
2110    virtual void SetUp() {
2111        SurfaceTextureGLToGLTest::SetUp();
2112        mFC = new FrameCondition();
2113        mST->setFrameAvailableListener(mFC);
2114    }
2115
2116    virtual void TearDown() {
2117        if (mProducerThread != NULL) {
2118            mProducerThread->requestExitAndWait();
2119        }
2120        mProducerThread.clear();
2121        mFC.clear();
2122        SurfaceTextureGLToGLTest::TearDown();
2123    }
2124
2125    void runProducerThread(const sp<ProducerThread> producerThread) {
2126        ASSERT_TRUE(mProducerThread == NULL);
2127        mProducerThread = producerThread;
2128        producerThread->setEglObjects(mEglDisplay, mProducerEglSurface,
2129                mProducerEglContext);
2130        producerThread->run();
2131    }
2132
2133    sp<ProducerThread> mProducerThread;
2134    sp<FrameCondition> mFC;
2135};
2136
2137TEST_F(SurfaceTextureGLThreadToGLTest,
2138        UpdateTexImageBeforeFrameFinishedCompletes) {
2139    class PT : public ProducerThread {
2140        virtual void render() {
2141            glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
2142            glClear(GL_COLOR_BUFFER_BIT);
2143            swapBuffers();
2144        }
2145    };
2146
2147    runProducerThread(new PT());
2148
2149    mFC->waitForFrame();
2150    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2151    mFC->finishFrame();
2152
2153    // TODO: Add frame verification once RGB TEX_EXTERNAL_OES is supported!
2154}
2155
2156TEST_F(SurfaceTextureGLThreadToGLTest,
2157        UpdateTexImageAfterFrameFinishedCompletes) {
2158    class PT : public ProducerThread {
2159        virtual void render() {
2160            glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
2161            glClear(GL_COLOR_BUFFER_BIT);
2162            swapBuffers();
2163        }
2164    };
2165
2166    runProducerThread(new PT());
2167
2168    mFC->waitForFrame();
2169    mFC->finishFrame();
2170    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2171
2172    // TODO: Add frame verification once RGB TEX_EXTERNAL_OES is supported!
2173}
2174
2175TEST_F(SurfaceTextureGLThreadToGLTest,
2176        RepeatedUpdateTexImageBeforeFrameFinishedCompletes) {
2177    enum { NUM_ITERATIONS = 1024 };
2178
2179    class PT : public ProducerThread {
2180        virtual void render() {
2181            for (int i = 0; i < NUM_ITERATIONS; i++) {
2182                glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
2183                glClear(GL_COLOR_BUFFER_BIT);
2184                ALOGV("+swapBuffers");
2185                swapBuffers();
2186                ALOGV("-swapBuffers");
2187            }
2188        }
2189    };
2190
2191    runProducerThread(new PT());
2192
2193    for (int i = 0; i < NUM_ITERATIONS; i++) {
2194        mFC->waitForFrame();
2195        ALOGV("+updateTexImage");
2196        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2197        ALOGV("-updateTexImage");
2198        mFC->finishFrame();
2199
2200        // TODO: Add frame verification once RGB TEX_EXTERNAL_OES is supported!
2201    }
2202}
2203
2204TEST_F(SurfaceTextureGLThreadToGLTest,
2205        RepeatedUpdateTexImageAfterFrameFinishedCompletes) {
2206    enum { NUM_ITERATIONS = 1024 };
2207
2208    class PT : public ProducerThread {
2209        virtual void render() {
2210            for (int i = 0; i < NUM_ITERATIONS; i++) {
2211                glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
2212                glClear(GL_COLOR_BUFFER_BIT);
2213                ALOGV("+swapBuffers");
2214                swapBuffers();
2215                ALOGV("-swapBuffers");
2216            }
2217        }
2218    };
2219
2220    runProducerThread(new PT());
2221
2222    for (int i = 0; i < NUM_ITERATIONS; i++) {
2223        mFC->waitForFrame();
2224        mFC->finishFrame();
2225        ALOGV("+updateTexImage");
2226        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2227        ALOGV("-updateTexImage");
2228
2229        // TODO: Add frame verification once RGB TEX_EXTERNAL_OES is supported!
2230    }
2231}
2232
2233// XXX: This test is disabled because it is currently hanging on some devices.
2234TEST_F(SurfaceTextureGLThreadToGLTest,
2235        DISABLED_RepeatedSwapBuffersWhileDequeueStalledCompletes) {
2236    enum { NUM_ITERATIONS = 64 };
2237
2238    class PT : public ProducerThread {
2239        virtual void render() {
2240            for (int i = 0; i < NUM_ITERATIONS; i++) {
2241                glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
2242                glClear(GL_COLOR_BUFFER_BIT);
2243                ALOGV("+swapBuffers");
2244                swapBuffers();
2245                ALOGV("-swapBuffers");
2246            }
2247        }
2248    };
2249
2250    ASSERT_EQ(OK, mST->setDefaultMaxBufferCount(2));
2251
2252    runProducerThread(new PT());
2253
2254    // Allow three frames to be rendered and queued before starting the
2255    // rendering in this thread.  For the latter two frames we don't call
2256    // updateTexImage so the next dequeue from the producer thread will block
2257    // waiting for a frame to become available.
2258    mFC->waitForFrame();
2259    mFC->finishFrame();
2260
2261    // We must call updateTexImage to consume the first frame so that the
2262    // SurfaceTexture is able to reduce the buffer count to 2.  This is because
2263    // the GL driver may dequeue a buffer when the EGLSurface is created, and
2264    // that happens before we call setDefaultMaxBufferCount.  It's possible that the
2265    // driver does not dequeue a buffer at EGLSurface creation time, so we
2266    // cannot rely on this to cause the second dequeueBuffer call to block.
2267    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2268
2269    mFC->waitForFrame();
2270    mFC->finishFrame();
2271    mFC->waitForFrame();
2272    mFC->finishFrame();
2273
2274    // Sleep for 100ms to allow the producer thread's dequeueBuffer call to
2275    // block waiting for a buffer to become available.
2276    usleep(100000);
2277
2278    // Render and present a number of images.  This thread should not be blocked
2279    // by the fact that the producer thread is blocking in dequeue.
2280    for (int i = 0; i < NUM_ITERATIONS; i++) {
2281        glClear(GL_COLOR_BUFFER_BIT);
2282        eglSwapBuffers(mEglDisplay, mEglSurface);
2283    }
2284
2285    // Consume the two pending buffers to unblock the producer thread.
2286    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2287    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2288
2289    // Consume the remaining buffers from the producer thread.
2290    for (int i = 0; i < NUM_ITERATIONS-3; i++) {
2291        mFC->waitForFrame();
2292        mFC->finishFrame();
2293        ALOGV("+updateTexImage");
2294        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2295        ALOGV("-updateTexImage");
2296    }
2297}
2298
2299class SurfaceTextureFBOTest : public SurfaceTextureGLTest {
2300protected:
2301
2302    virtual void SetUp() {
2303        SurfaceTextureGLTest::SetUp();
2304
2305        glGenFramebuffers(1, &mFbo);
2306        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2307
2308        glGenTextures(1, &mFboTex);
2309        glBindTexture(GL_TEXTURE_2D, mFboTex);
2310        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getSurfaceWidth(),
2311                getSurfaceHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2312        glBindTexture(GL_TEXTURE_2D, 0);
2313        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2314
2315        glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
2316        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
2317                GL_TEXTURE_2D, mFboTex, 0);
2318        glBindFramebuffer(GL_FRAMEBUFFER, 0);
2319        ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2320    }
2321
2322    virtual void TearDown() {
2323        SurfaceTextureGLTest::TearDown();
2324
2325        glDeleteTextures(1, &mFboTex);
2326        glDeleteFramebuffers(1, &mFbo);
2327    }
2328
2329    GLuint mFbo;
2330    GLuint mFboTex;
2331};
2332
2333// This test is intended to verify that proper synchronization is done when
2334// rendering into an FBO.
2335TEST_F(SurfaceTextureFBOTest, BlitFromCpuFilledBufferToFbo) {
2336    const int texWidth = 64;
2337    const int texHeight = 64;
2338
2339    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(mANW.get(),
2340            texWidth, texHeight, HAL_PIXEL_FORMAT_RGBA_8888));
2341    ASSERT_EQ(NO_ERROR, native_window_set_usage(mANW.get(),
2342            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN));
2343
2344    android_native_buffer_t* anb;
2345    ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
2346            &anb));
2347    ASSERT_TRUE(anb != NULL);
2348
2349    sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
2350
2351    // Fill the buffer with green
2352    uint8_t* img = NULL;
2353    buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img));
2354    fillRGBA8BufferSolid(img, texWidth, texHeight, buf->getStride(), 0, 255,
2355            0, 255);
2356    buf->unlock();
2357    ASSERT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(), buf->getNativeBuffer(),
2358            -1));
2359
2360    ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2361
2362    glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
2363    drawTexture();
2364    glBindFramebuffer(GL_FRAMEBUFFER, 0);
2365
2366    for (int i = 0; i < 4; i++) {
2367        SCOPED_TRACE(String8::format("frame %d", i).string());
2368
2369        ASSERT_EQ(NO_ERROR, native_window_dequeue_buffer_and_wait(mANW.get(),
2370                &anb));
2371        ASSERT_TRUE(anb != NULL);
2372
2373        buf = new GraphicBuffer(anb, false);
2374
2375        // Fill the buffer with red
2376        ASSERT_EQ(NO_ERROR, buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN,
2377                (void**)(&img)));
2378        fillRGBA8BufferSolid(img, texWidth, texHeight, buf->getStride(), 255, 0,
2379                0, 255);
2380        ASSERT_EQ(NO_ERROR, buf->unlock());
2381        ASSERT_EQ(NO_ERROR, mANW->queueBuffer(mANW.get(),
2382                buf->getNativeBuffer(), -1));
2383
2384        ASSERT_EQ(NO_ERROR, mST->updateTexImage());
2385
2386        drawTexture();
2387
2388        EXPECT_TRUE(checkPixel( 24, 39, 255, 0, 0, 255));
2389    }
2390
2391    glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
2392
2393    EXPECT_TRUE(checkPixel( 24, 39, 0, 255, 0, 255));
2394}
2395
2396class SurfaceTextureMultiContextGLTest : public SurfaceTextureGLTest {
2397protected:
2398    enum { SECOND_TEX_ID = 123 };
2399    enum { THIRD_TEX_ID = 456 };
2400
2401    SurfaceTextureMultiContextGLTest():
2402            mSecondEglContext(EGL_NO_CONTEXT) {
2403    }
2404
2405    virtual void SetUp() {
2406        SurfaceTextureGLTest::SetUp();
2407
2408        // Set up the secondary context and texture renderer.
2409        mSecondEglContext = eglCreateContext(mEglDisplay, mGlConfig,
2410                EGL_NO_CONTEXT, getContextAttribs());
2411        ASSERT_EQ(EGL_SUCCESS, eglGetError());
2412        ASSERT_NE(EGL_NO_CONTEXT, mSecondEglContext);
2413
2414        ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2415                mSecondEglContext));
2416        ASSERT_EQ(EGL_SUCCESS, eglGetError());
2417        mSecondTextureRenderer = new TextureRenderer(SECOND_TEX_ID, mST);
2418        ASSERT_NO_FATAL_FAILURE(mSecondTextureRenderer->SetUp());
2419
2420        // Set up the tertiary context and texture renderer.
2421        mThirdEglContext = eglCreateContext(mEglDisplay, mGlConfig,
2422                EGL_NO_CONTEXT, getContextAttribs());
2423        ASSERT_EQ(EGL_SUCCESS, eglGetError());
2424        ASSERT_NE(EGL_NO_CONTEXT, mThirdEglContext);
2425
2426        ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2427                mThirdEglContext));
2428        ASSERT_EQ(EGL_SUCCESS, eglGetError());
2429        mThirdTextureRenderer = new TextureRenderer(THIRD_TEX_ID, mST);
2430        ASSERT_NO_FATAL_FAILURE(mThirdTextureRenderer->SetUp());
2431
2432        // Switch back to the primary context to start the tests.
2433        ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2434                mEglContext));
2435    }
2436
2437    virtual void TearDown() {
2438        if (mThirdEglContext != EGL_NO_CONTEXT) {
2439            eglDestroyContext(mEglDisplay, mThirdEglContext);
2440        }
2441        if (mSecondEglContext != EGL_NO_CONTEXT) {
2442            eglDestroyContext(mEglDisplay, mSecondEglContext);
2443        }
2444        SurfaceTextureGLTest::TearDown();
2445    }
2446
2447    EGLContext mSecondEglContext;
2448    sp<TextureRenderer> mSecondTextureRenderer;
2449
2450    EGLContext mThirdEglContext;
2451    sp<TextureRenderer> mThirdTextureRenderer;
2452};
2453
2454TEST_F(SurfaceTextureMultiContextGLTest, UpdateFromMultipleContextsFails) {
2455    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2456
2457    // Latch the texture contents on the primary context.
2458    mFW->waitForFrame();
2459    ASSERT_EQ(OK, mST->updateTexImage());
2460
2461    // Attempt to latch the texture on the secondary context.
2462    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2463            mSecondEglContext));
2464    ASSERT_EQ(EGL_SUCCESS, eglGetError());
2465    ASSERT_EQ(INVALID_OPERATION, mST->updateTexImage());
2466}
2467
2468TEST_F(SurfaceTextureMultiContextGLTest, DetachFromContextSucceeds) {
2469    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2470
2471    // Latch the texture contents on the primary context.
2472    mFW->waitForFrame();
2473    ASSERT_EQ(OK, mST->updateTexImage());
2474
2475    // Detach from the primary context.
2476    ASSERT_EQ(OK, mST->detachFromContext());
2477
2478    // Check that the GL texture was deleted.
2479    EXPECT_EQ(GL_FALSE, glIsTexture(TEX_ID));
2480}
2481
2482TEST_F(SurfaceTextureMultiContextGLTest,
2483        DetachFromContextSucceedsAfterProducerDisconnect) {
2484    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2485
2486    // Latch the texture contents on the primary context.
2487    mFW->waitForFrame();
2488    ASSERT_EQ(OK, mST->updateTexImage());
2489
2490    // Detach from the primary context.
2491    native_window_api_disconnect(mANW.get(), NATIVE_WINDOW_API_CPU);
2492    ASSERT_EQ(OK, mST->detachFromContext());
2493
2494    // Check that the GL texture was deleted.
2495    EXPECT_EQ(GL_FALSE, glIsTexture(TEX_ID));
2496}
2497
2498TEST_F(SurfaceTextureMultiContextGLTest, DetachFromContextFailsWhenAbandoned) {
2499    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2500
2501    // Latch the texture contents on the primary context.
2502    mFW->waitForFrame();
2503    ASSERT_EQ(OK, mST->updateTexImage());
2504
2505    // Attempt to detach from the primary context.
2506    mST->abandon();
2507    ASSERT_EQ(NO_INIT, mST->detachFromContext());
2508}
2509
2510TEST_F(SurfaceTextureMultiContextGLTest, DetachFromContextFailsWhenDetached) {
2511    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2512
2513    // Latch the texture contents on the primary context.
2514    mFW->waitForFrame();
2515    ASSERT_EQ(OK, mST->updateTexImage());
2516
2517    // Detach from the primary context.
2518    ASSERT_EQ(OK, mST->detachFromContext());
2519
2520    // Attempt to detach from the primary context again.
2521    ASSERT_EQ(INVALID_OPERATION, mST->detachFromContext());
2522}
2523
2524TEST_F(SurfaceTextureMultiContextGLTest, DetachFromContextFailsWithNoDisplay) {
2525    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2526
2527    // Latch the texture contents on the primary context.
2528    mFW->waitForFrame();
2529    ASSERT_EQ(OK, mST->updateTexImage());
2530
2531    // Make there be no current display.
2532    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
2533            EGL_NO_CONTEXT));
2534    ASSERT_EQ(EGL_SUCCESS, eglGetError());
2535
2536    // Attempt to detach from the primary context.
2537    ASSERT_EQ(INVALID_OPERATION, mST->detachFromContext());
2538}
2539
2540TEST_F(SurfaceTextureMultiContextGLTest, DetachFromContextFailsWithNoContext) {
2541    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2542
2543    // Latch the texture contents on the primary context.
2544    mFW->waitForFrame();
2545    ASSERT_EQ(OK, mST->updateTexImage());
2546
2547    // Make current context be incorrect.
2548    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2549            mSecondEglContext));
2550    ASSERT_EQ(EGL_SUCCESS, eglGetError());
2551
2552    // Attempt to detach from the primary context.
2553    ASSERT_EQ(INVALID_OPERATION, mST->detachFromContext());
2554}
2555
2556TEST_F(SurfaceTextureMultiContextGLTest, UpdateTexImageFailsWhenDetached) {
2557    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2558
2559    // Detach from the primary context.
2560    ASSERT_EQ(OK, mST->detachFromContext());
2561
2562    // Attempt to latch the texture contents on the primary context.
2563    mFW->waitForFrame();
2564    ASSERT_EQ(INVALID_OPERATION, mST->updateTexImage());
2565}
2566
2567TEST_F(SurfaceTextureMultiContextGLTest, AttachToContextSucceeds) {
2568    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2569
2570    // Latch the texture contents on the primary context.
2571    mFW->waitForFrame();
2572    ASSERT_EQ(OK, mST->updateTexImage());
2573
2574    // Detach from the primary context.
2575    ASSERT_EQ(OK, mST->detachFromContext());
2576
2577    // Attach to the secondary context.
2578    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2579            mSecondEglContext));
2580    ASSERT_EQ(OK, mST->attachToContext(SECOND_TEX_ID));
2581
2582    // Verify that the texture object was created and bound.
2583    GLint texBinding = -1;
2584    glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texBinding);
2585    EXPECT_EQ(SECOND_TEX_ID, texBinding);
2586
2587    // Try to use the texture from the secondary context.
2588    glClearColor(0.2, 0.2, 0.2, 0.2);
2589    glClear(GL_COLOR_BUFFER_BIT);
2590    glViewport(0, 0, 1, 1);
2591    mSecondTextureRenderer->drawTexture();
2592    ASSERT_TRUE(checkPixel( 0,  0,  35,  35,  35,  35));
2593    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2594}
2595
2596TEST_F(SurfaceTextureMultiContextGLTest,
2597        AttachToContextSucceedsAfterProducerDisconnect) {
2598    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2599
2600    // Latch the texture contents on the primary context.
2601    mFW->waitForFrame();
2602    ASSERT_EQ(OK, mST->updateTexImage());
2603
2604    // Detach from the primary context.
2605    native_window_api_disconnect(mANW.get(), NATIVE_WINDOW_API_CPU);
2606    ASSERT_EQ(OK, mST->detachFromContext());
2607
2608    // Attach to the secondary context.
2609    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2610            mSecondEglContext));
2611    ASSERT_EQ(OK, mST->attachToContext(SECOND_TEX_ID));
2612
2613    // Verify that the texture object was created and bound.
2614    GLint texBinding = -1;
2615    glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texBinding);
2616    EXPECT_EQ(SECOND_TEX_ID, texBinding);
2617
2618    // Try to use the texture from the secondary context.
2619    glClearColor(0.2, 0.2, 0.2, 0.2);
2620    glClear(GL_COLOR_BUFFER_BIT);
2621    glViewport(0, 0, 1, 1);
2622    mSecondTextureRenderer->drawTexture();
2623    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2624    ASSERT_TRUE(checkPixel( 0,  0,  35,  35,  35,  35));
2625}
2626
2627TEST_F(SurfaceTextureMultiContextGLTest,
2628        AttachToContextSucceedsBeforeUpdateTexImage) {
2629    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2630
2631    // Detach from the primary context.
2632    native_window_api_disconnect(mANW.get(), NATIVE_WINDOW_API_CPU);
2633    ASSERT_EQ(OK, mST->detachFromContext());
2634
2635    // Attach to the secondary context.
2636    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2637            mSecondEglContext));
2638    ASSERT_EQ(OK, mST->attachToContext(SECOND_TEX_ID));
2639
2640    // Verify that the texture object was created and bound.
2641    GLint texBinding = -1;
2642    glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texBinding);
2643    EXPECT_EQ(SECOND_TEX_ID, texBinding);
2644
2645    // Latch the texture contents on the primary context.
2646    mFW->waitForFrame();
2647    ASSERT_EQ(OK, mST->updateTexImage());
2648
2649    // Try to use the texture from the secondary context.
2650    glClearColor(0.2, 0.2, 0.2, 0.2);
2651    glClear(GL_COLOR_BUFFER_BIT);
2652    glViewport(0, 0, 1, 1);
2653    mSecondTextureRenderer->drawTexture();
2654    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2655    ASSERT_TRUE(checkPixel( 0,  0,  35,  35,  35,  35));
2656}
2657
2658TEST_F(SurfaceTextureMultiContextGLTest, AttachToContextFailsWhenAbandoned) {
2659    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2660
2661    // Latch the texture contents on the primary context.
2662    mFW->waitForFrame();
2663    ASSERT_EQ(OK, mST->updateTexImage());
2664
2665    // Detach from the primary context.
2666    ASSERT_EQ(OK, mST->detachFromContext());
2667
2668    // Attempt to attach to the secondary context.
2669    mST->abandon();
2670
2671    // Attempt to attach to the primary context.
2672    ASSERT_EQ(NO_INIT, mST->attachToContext(SECOND_TEX_ID));
2673}
2674
2675TEST_F(SurfaceTextureMultiContextGLTest, AttachToContextFailsWhenAttached) {
2676    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2677
2678    // Latch the texture contents on the primary context.
2679    mFW->waitForFrame();
2680    ASSERT_EQ(OK, mST->updateTexImage());
2681
2682    // Attempt to attach to the primary context.
2683    ASSERT_EQ(INVALID_OPERATION, mST->attachToContext(SECOND_TEX_ID));
2684}
2685
2686TEST_F(SurfaceTextureMultiContextGLTest,
2687        AttachToContextFailsWhenAttachedBeforeUpdateTexImage) {
2688    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2689
2690    // Attempt to attach to the primary context.
2691    ASSERT_EQ(INVALID_OPERATION, mST->attachToContext(SECOND_TEX_ID));
2692}
2693
2694TEST_F(SurfaceTextureMultiContextGLTest, AttachToContextFailsWithNoDisplay) {
2695    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2696
2697    // Latch the texture contents on the primary context.
2698    mFW->waitForFrame();
2699    ASSERT_EQ(OK, mST->updateTexImage());
2700
2701    // Detach from the primary context.
2702    ASSERT_EQ(OK, mST->detachFromContext());
2703
2704    // Make there be no current display.
2705    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
2706            EGL_NO_CONTEXT));
2707    ASSERT_EQ(EGL_SUCCESS, eglGetError());
2708
2709    // Attempt to attach with no context current.
2710    ASSERT_EQ(INVALID_OPERATION, mST->attachToContext(SECOND_TEX_ID));
2711}
2712
2713TEST_F(SurfaceTextureMultiContextGLTest, AttachToContextSucceedsTwice) {
2714    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2715
2716    // Latch the texture contents on the primary context.
2717    mFW->waitForFrame();
2718    ASSERT_EQ(OK, mST->updateTexImage());
2719
2720    // Detach from the primary context.
2721    ASSERT_EQ(OK, mST->detachFromContext());
2722
2723    // Attach to the secondary context.
2724    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2725            mSecondEglContext));
2726    ASSERT_EQ(OK, mST->attachToContext(SECOND_TEX_ID));
2727
2728    // Detach from the secondary context.
2729    ASSERT_EQ(OK, mST->detachFromContext());
2730
2731    // Attach to the tertiary context.
2732    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2733            mThirdEglContext));
2734    ASSERT_EQ(OK, mST->attachToContext(THIRD_TEX_ID));
2735
2736    // Verify that the texture object was created and bound.
2737    GLint texBinding = -1;
2738    glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texBinding);
2739    EXPECT_EQ(THIRD_TEX_ID, texBinding);
2740
2741    // Try to use the texture from the tertiary context.
2742    glClearColor(0.2, 0.2, 0.2, 0.2);
2743    glClear(GL_COLOR_BUFFER_BIT);
2744    glViewport(0, 0, 1, 1);
2745    mThirdTextureRenderer->drawTexture();
2746    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2747    ASSERT_TRUE(checkPixel( 0,  0,  35,  35,  35,  35));
2748}
2749
2750TEST_F(SurfaceTextureMultiContextGLTest,
2751        AttachToContextSucceedsTwiceBeforeUpdateTexImage) {
2752    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2753
2754    // Detach from the primary context.
2755    ASSERT_EQ(OK, mST->detachFromContext());
2756
2757    // Attach to the secondary context.
2758    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2759            mSecondEglContext));
2760    ASSERT_EQ(OK, mST->attachToContext(SECOND_TEX_ID));
2761
2762    // Detach from the secondary context.
2763    ASSERT_EQ(OK, mST->detachFromContext());
2764
2765    // Attach to the tertiary context.
2766    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2767            mThirdEglContext));
2768    ASSERT_EQ(OK, mST->attachToContext(THIRD_TEX_ID));
2769
2770    // Verify that the texture object was created and bound.
2771    GLint texBinding = -1;
2772    glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &texBinding);
2773    EXPECT_EQ(THIRD_TEX_ID, texBinding);
2774
2775    // Latch the texture contents on the tertiary context.
2776    mFW->waitForFrame();
2777    ASSERT_EQ(OK, mST->updateTexImage());
2778
2779    // Try to use the texture from the tertiary context.
2780    glClearColor(0.2, 0.2, 0.2, 0.2);
2781    glClear(GL_COLOR_BUFFER_BIT);
2782    glViewport(0, 0, 1, 1);
2783    mThirdTextureRenderer->drawTexture();
2784    ASSERT_EQ(GLenum(GL_NO_ERROR), glGetError());
2785    ASSERT_TRUE(checkPixel( 0,  0,  35,  35,  35,  35));
2786}
2787
2788TEST_F(SurfaceTextureMultiContextGLTest,
2789        UpdateTexImageSucceedsForBufferConsumedBeforeDetach) {
2790    ASSERT_EQ(NO_ERROR, mST->setDefaultMaxBufferCount(2));
2791
2792    // produce two frames and consume them both on the primary context
2793    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2794    mFW->waitForFrame();
2795    ASSERT_EQ(OK, mST->updateTexImage());
2796
2797    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2798    mFW->waitForFrame();
2799    ASSERT_EQ(OK, mST->updateTexImage());
2800
2801    // produce one more frame
2802    ASSERT_NO_FATAL_FAILURE(produceOneRGBA8Frame(mANW));
2803
2804    // Detach from the primary context and attach to the secondary context
2805    ASSERT_EQ(OK, mST->detachFromContext());
2806    ASSERT_TRUE(eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
2807            mSecondEglContext));
2808    ASSERT_EQ(OK, mST->attachToContext(SECOND_TEX_ID));
2809
2810    // Consume final frame on secondary context
2811    mFW->waitForFrame();
2812    ASSERT_EQ(OK, mST->updateTexImage());
2813}
2814
2815} // namespace android
2816