Merge "gltrace: Make code 64-bit safe."
diff --git a/include/gui/BufferQueue.h b/include/gui/BufferQueue.h
index ae99160..039e7b0 100644
--- a/include/gui/BufferQueue.h
+++ b/include/gui/BufferQueue.h
@@ -40,6 +40,7 @@
     };
     enum { NUM_BUFFER_SLOTS = 32 };
     enum { NO_CONNECTED_API = 0 };
+    enum { INVALID_BUFFER_SLOT = -1 };
 
     struct FrameAvailableListener : public virtual RefBase {
         // onFrameAvailable() is called from queueBuffer() each time an
@@ -119,8 +120,91 @@
     // connected to the specified client API.
     virtual status_t disconnect(int api);
 
-protected:
+    // dump our state in a String
+    virtual void dump(String8& result) const;
+    virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
 
+    // public facing structure for BufferSlot
+    struct BufferItem {
+
+        BufferItem()
+         :
+           mTransform(0),
+           mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
+           mTimestamp(0),
+           mFrameNumber(0),
+           mBuf(INVALID_BUFFER_SLOT) {
+             mCrop.makeInvalid();
+         }
+        // mGraphicBuffer points to the buffer allocated for this slot or is NULL
+        // if no buffer has been allocated.
+        sp<GraphicBuffer> mGraphicBuffer;
+
+        // mCrop is the current crop rectangle for this buffer slot. This gets
+        // set to mNextCrop each time queueBuffer gets called for this buffer.
+        Rect mCrop;
+
+        // mTransform is the current transform flags for this buffer slot. This
+        // gets set to mNextTransform each time queueBuffer gets called for this
+        // slot.
+        uint32_t mTransform;
+
+        // mScalingMode is the current scaling mode for this buffer slot. This
+        // gets set to mNextScalingMode each time queueBuffer gets called for
+        // this slot.
+        uint32_t mScalingMode;
+
+        // mTimestamp is the current timestamp for this buffer slot. This gets
+        // to set by queueBuffer each time this slot is queued.
+        int64_t mTimestamp;
+
+        // mFrameNumber is the number of the queued frame for this slot.
+        uint64_t mFrameNumber;
+
+        // buf is the slot index of this buffer
+        int mBuf;
+
+    };
+
+    // The following public functions is the consumer facing interface
+
+    // acquire consumes a buffer by transferring its ownership to a consumer.
+    // buffer contains the GraphicBuffer and its corresponding information.
+    // buffer.mGraphicsBuffer will be NULL when the buffer has been already
+    // acquired by the consumer.
+
+    status_t acquire(BufferItem *buffer);
+
+    // releaseBuffer releases a buffer slot from the consumer back to the
+    // BufferQueue pending a fence sync.
+    status_t releaseBuffer(int buf, EGLDisplay display, EGLSyncKHR fence);
+
+    // consumerDisconnect disconnects a consumer from the BufferQueue. All
+    // buffers will be freed.
+    status_t consumerDisconnect();
+
+    // setDefaultBufferSize is used to set the size of buffers returned by
+    // requestBuffers when a with and height of zero is requested.
+    status_t setDefaultBufferSize(uint32_t w, uint32_t h);
+
+    // setBufferCountServer set the buffer count. If the client has requested
+    // a buffer count using setBufferCount, the server-buffer count will
+    // take effect once the client sets the count back to zero.
+    status_t setBufferCountServer(int bufferCount);
+
+    // isSynchronousMode returns whether the SurfaceTexture is currently in
+    // synchronous mode.
+    bool isSynchronousMode() const;
+
+    // setConsumerName sets the name used in logging
+    void setConsumerName(const String8& name);
+
+    // setFrameAvailableListener sets the listener object that will be notified
+    // when a new frame becomes available.
+    void setFrameAvailableListener(const sp<FrameAvailableListener>& listener);
+
+
+private:
     // freeBufferLocked frees the resources (both GraphicBuffer and EGLImage)
     // for the given slot.
     void freeBufferLocked(int index);
@@ -145,20 +229,18 @@
 
     status_t setBufferCountServerLocked(int bufferCount);
 
-    enum { INVALID_BUFFER_SLOT = -1 };
-
     struct BufferSlot {
 
         BufferSlot()
-        : mEglImage(EGL_NO_IMAGE_KHR),
-          mEglDisplay(EGL_NO_DISPLAY),
+        : mEglDisplay(EGL_NO_DISPLAY),
           mBufferState(BufferSlot::FREE),
           mRequestBufferCalled(false),
           mTransform(0),
           mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
           mTimestamp(0),
           mFrameNumber(0),
-          mFence(EGL_NO_SYNC_KHR) {
+          mFence(EGL_NO_SYNC_KHR),
+          mAcquireCalled(false) {
             mCrop.makeInvalid();
         }
 
@@ -166,9 +248,6 @@
         // if no buffer has been allocated.
         sp<GraphicBuffer> mGraphicBuffer;
 
-        // mEglImage is the EGLImage created from mGraphicBuffer.
-        EGLImageKHR mEglImage;
-
         // mEglDisplay is the EGLDisplay used to create mEglImage.
         EGLDisplay mEglDisplay;
 
@@ -178,6 +257,7 @@
             // FREE indicates that the buffer is not currently being used and
             // will not be used in the future until it gets dequeued and
             // subsequently queued by the client.
+            // aka "owned by BufferQueue, ready to be dequeued"
             FREE = 0,
 
             // DEQUEUED indicates that the buffer has been dequeued by the
@@ -190,6 +270,7 @@
             // dequeued by the client.  That means that the current buffer can
             // be in either the DEQUEUED or QUEUED state.  In asynchronous mode,
             // however, the current buffer is always in the QUEUED state.
+            // aka "owned by producer, ready to be queued"
             DEQUEUED = 1,
 
             // QUEUED indicates that the buffer has been queued by the client,
@@ -199,7 +280,11 @@
             // the current buffer may be dequeued by the client under some
             // circumstances. See the note about the current buffer in the
             // documentation for DEQUEUED.
+            // aka "owned by BufferQueue, ready to be acquired"
             QUEUED = 2,
+
+            // aka "owned by consumer, ready to be released"
+            ACQUIRED = 3
         };
 
         // mBufferState is the current state of this buffer slot.
@@ -236,6 +321,9 @@
         // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
         // on a compile-time option) set to a new sync object in updateTexImage.
         EGLSyncKHR mFence;
+
+        // Indicates whether this buffer has been seen by a consumer yet
+        bool mAcquireCalled;
     };
 
     // mSlots is the array of buffer slots that must be mirrored on the client
@@ -245,7 +333,6 @@
     // for a slot when requestBuffer is called with that slot's index.
     BufferSlot mSlots[NUM_BUFFER_SLOTS];
 
-
     // mDefaultWidth holds the default width of allocated buffers. It is used
     // in requestBuffers() if a width and height of zero is specified.
     uint32_t mDefaultWidth;
@@ -271,14 +358,6 @@
     // mServerBufferCount buffer count requested by the server-side
     int mServerBufferCount;
 
-    // mCurrentTexture is the buffer slot index of the buffer that is currently
-    // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
-    // indicating that no buffer slot is currently bound to the texture. Note,
-    // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
-    // that no buffer is bound to the texture. A call to setBufferCount will
-    // reset mCurrentTexture to INVALID_BUFFER_SLOT.
-    int mCurrentTexture;
-
     // mNextCrop is the crop rectangle that will be used for the next buffer
     // that gets queued. It is set by calling setCrop.
     Rect mNextCrop;
@@ -327,7 +406,7 @@
 
     // mName is a string used to identify the BufferQueue in log messages.
     // It is set by the setName method.
-    String8 mName;
+    String8 mConsumerName;
 
     // mMutex is the mutex used to prevent concurrent access to the member
     // variables of BufferQueue objects. It must be locked whenever the
@@ -337,6 +416,8 @@
     // mFrameCounter is the free running counter, incremented for every buffer queued
     // with the surface Texture.
     uint64_t mFrameCounter;
+
+    bool mBufferHasBeenQueued;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h
index dcab049..5531e53 100644
--- a/include/gui/SurfaceTexture.h
+++ b/include/gui/SurfaceTexture.h
@@ -153,8 +153,8 @@
     void setName(const String8& name);
 
     // dump our state in a String
-    void dump(String8& result) const;
-    void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
+    virtual void dump(String8& result) const;
+    virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
 
 protected:
 
@@ -217,6 +217,56 @@
     // browser's tile cache exceeds.
     const GLenum mTexTarget;
 
+    // SurfaceTexture maintains EGL information about GraphicBuffers that corresponds
+    // directly with BufferQueue's buffers
+    struct EGLSlot {
+        EGLSlot()
+        : mEglImage(EGL_NO_IMAGE_KHR),
+          mEglDisplay(EGL_NO_DISPLAY),
+          mFence(EGL_NO_SYNC_KHR) {
+        }
+
+        sp<GraphicBuffer> mGraphicBuffer;
+
+        // mEglImage is the EGLImage created from mGraphicBuffer.
+        EGLImageKHR mEglImage;
+
+        // mEglDisplay is the EGLDisplay used to create mEglImage.
+        EGLDisplay mEglDisplay;
+
+        // mFence is the EGL sync object that must signal before the buffer
+        // associated with this buffer slot may be dequeued. It is initialized
+        // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
+        // on a compile-time option) set to a new sync object in updateTexImage.
+        EGLSyncKHR mFence;
+    };
+
+    EGLSlot mEGLSlots[NUM_BUFFER_SLOTS];
+
+    // mAbandoned indicates that the BufferQueue will no longer be used to
+    // consume images buffers pushed to it using the ISurfaceTexture interface.
+    // It is initialized to false, and set to true in the abandon method.  A
+    // BufferQueue that has been abandoned will return the NO_INIT error from
+    // all ISurfaceTexture methods capable of returning an error.
+    bool mAbandoned;
+
+    // mName is a string used to identify the SurfaceTexture in log messages.
+    // It can be set by the setName method.
+    String8 mName;
+
+    // mMutex is the mutex used to prevent concurrent access to the member
+    // variables of SurfaceTexture objects. It must be locked whenever the
+    // member variables are accessed.
+    mutable Mutex mMutex;
+
+    // mCurrentTexture is the buffer slot index of the buffer that is currently
+    // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
+    // indicating that no buffer slot is currently bound to the texture. Note,
+    // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
+    // that no buffer is bound to the texture. A call to setBufferCount will
+    // reset mCurrentTexture to INVALID_BUFFER_SLOT.
+    int mCurrentTexture;
+
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/SurfaceTextureClient.h b/include/gui/SurfaceTextureClient.h
index 971a1b8..aa7fe48 100644
--- a/include/gui/SurfaceTextureClient.h
+++ b/include/gui/SurfaceTextureClient.h
@@ -20,7 +20,7 @@
 #include <gui/ISurfaceTexture.h>
 #include <gui/SurfaceTexture.h>
 
-#include <ui/egl/android_natives.h>
+#include <ui/ANativeObjectBase.h>
 #include <ui/Region.h>
 
 #include <utils/RefBase.h>
@@ -31,7 +31,7 @@
 class Surface;
 
 class SurfaceTextureClient
-    : public EGLNativeBase<ANativeWindow, SurfaceTextureClient, RefBase>
+    : public ANativeObjectBase<ANativeWindow, SurfaceTextureClient, RefBase>
 {
 public:
     SurfaceTextureClient(const sp<ISurfaceTexture>& surfaceTexture);
diff --git a/include/private/ui/android_natives_priv.h b/include/private/ui/android_natives_priv.h
deleted file mode 100644
index 6b9f524..0000000
--- a/include/private/ui/android_natives_priv.h
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <ui/android_native_buffer.h>
diff --git a/include/surfaceflinger/Surface.h b/include/surfaceflinger/Surface.h
index 0460bbd..06eff8a 100644
--- a/include/surfaceflinger/Surface.h
+++ b/include/surfaceflinger/Surface.h
@@ -26,7 +26,6 @@
 
 #include <ui/PixelFormat.h>
 #include <ui/Region.h>
-#include <ui/egl/android_natives.h>
 
 #include <gui/SurfaceTextureClient.h>
 
diff --git a/include/ui/egl/android_natives.h b/include/ui/ANativeObjectBase.h
similarity index 84%
rename from include/ui/egl/android_natives.h
rename to include/ui/ANativeObjectBase.h
index 9ac50a5..76e850f 100644
--- a/include/ui/egl/android_natives.h
+++ b/include/ui/ANativeObjectBase.h
@@ -22,8 +22,7 @@
 
 #include <hardware/gralloc.h>
 #include <system/window.h>
-// FIXME: remove this header, it's for legacy use.  native_window is pulled from frameworks/base/native/include/android/
-#include <android/native_window.h>
+
 // ---------------------------------------------------------------------------
 
 /* FIXME: this is legacy for pixmaps */
@@ -52,11 +51,11 @@
 namespace android {
 
 /*
- * This helper class turns an EGL android_native_xxx type into a C++
+ * This helper class turns a ANativeXXX object type into a C++
  * reference-counted object; with proper type conversions.
  */
 template <typename NATIVE_TYPE, typename TYPE, typename REF>
-class EGLNativeBase : public NATIVE_TYPE, public REF
+class ANativeObjectBase : public NATIVE_TYPE, public REF
 {
 public:
     // Disambiguate between the incStrong in REF and NATIVE_TYPE
@@ -68,8 +67,8 @@
     }
 
 protected:
-    typedef EGLNativeBase<NATIVE_TYPE, TYPE, REF> BASE;
-    EGLNativeBase() : NATIVE_TYPE(), REF() {
+    typedef ANativeObjectBase<NATIVE_TYPE, TYPE, REF> BASE;
+    ANativeObjectBase() : NATIVE_TYPE(), REF() {
         NATIVE_TYPE::common.incRef = incRef;
         NATIVE_TYPE::common.decRef = decRef;
     }
@@ -86,11 +85,11 @@
         return getSelf(reinterpret_cast<NATIVE_TYPE const*>(base));
     }
     static void incRef(android_native_base_t* base) {
-        EGLNativeBase* self = getSelf(base);
+        ANativeObjectBase* self = getSelf(base);
         self->incStrong(self);
     }
     static void decRef(android_native_base_t* base) {
-        EGLNativeBase* self = getSelf(base);
+        ANativeObjectBase* self = getSelf(base);
         self->decStrong(self);
     }
 };
diff --git a/include/ui/EGLNativeSurface.h b/include/ui/EGLNativeSurface.h
deleted file mode 100644
index 7964e7c..0000000
--- a/include/ui/EGLNativeSurface.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_EGL_NATIVE_SURFACE_H
-#define ANDROID_EGL_NATIVE_SURFACE_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cutils/atomic.h>
-#include <utils/RefBase.h>
-
-#include <EGL/eglnatives.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-template <class TYPE>
-class EGLNativeSurface : public egl_native_window_t, public LightRefBase<TYPE>
-{
-public:
-    EGLNativeSurface() { 
-        memset(egl_native_window_t::reserved, 0, 
-                sizeof(egl_native_window_t::reserved));
-        memset(egl_native_window_t::reserved_proc, 0, 
-                sizeof(egl_native_window_t::reserved_proc));
-        memset(egl_native_window_t::oem, 0, 
-                sizeof(egl_native_window_t::oem));
-    }
-protected:
-    EGLNativeSurface& operator = (const EGLNativeSurface& rhs);
-    EGLNativeSurface(const EGLNativeSurface& rhs);
-    inline ~EGLNativeSurface() { };
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_EGL_SURFACE_H
-
diff --git a/include/ui/EGLUtils.h b/include/ui/EGLUtils.h
deleted file mode 100644
index a5bff81..0000000
--- a/include/ui/EGLUtils.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-#ifndef ANDROID_UI_EGLUTILS_H
-#define ANDROID_UI_EGLUTILS_H
-
-#include <utils/Errors.h>
-#include <ui/PixelFormat.h>
-#include <EGL/egl.h>
-
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-class EGLUtils
-{
-public:
-
-    static const char *strerror(EGLint err);
-
-    static status_t selectConfigForPixelFormat(
-            EGLDisplay dpy,
-            EGLint const* attrs,
-            PixelFormat format,
-            EGLConfig* outConfig);
-
-    static status_t selectConfigForNativeWindow(
-            EGLDisplay dpy,
-            EGLint const* attrs,
-            EGLNativeWindowType window,
-            EGLConfig* outConfig);
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
-
-#endif /* ANDROID_UI_EGLUTILS_H */
diff --git a/include/ui/FramebufferNativeWindow.h b/include/ui/FramebufferNativeWindow.h
index 302d012..b202b95 100644
--- a/include/ui/FramebufferNativeWindow.h
+++ b/include/ui/FramebufferNativeWindow.h
@@ -24,12 +24,10 @@
 
 #include <utils/threads.h>
 #include <utils/String8.h>
+
+#include <ui/ANativeObjectBase.h>
 #include <ui/Rect.h>
 
-#include <pixelflinger/pixelflinger.h>
-
-#include <ui/egl/android_natives.h>
-
 #define NUM_FRAME_BUFFERS  2
 
 extern "C" EGLNativeWindowType android_createDisplaySurface(void);
@@ -44,7 +42,7 @@
 // ---------------------------------------------------------------------------
 
 class FramebufferNativeWindow 
-    : public EGLNativeBase<
+    : public ANativeObjectBase<
         ANativeWindow, 
         FramebufferNativeWindow, 
         LightRefBase<FramebufferNativeWindow> >
diff --git a/include/ui/GraphicBuffer.h b/include/ui/GraphicBuffer.h
index 6ab01f4..f318cd8 100644
--- a/include/ui/GraphicBuffer.h
+++ b/include/ui/GraphicBuffer.h
@@ -20,11 +20,11 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <ui/android_native_buffer.h>
+#include <ui/ANativeObjectBase.h>
 #include <ui/PixelFormat.h>
 #include <ui/Rect.h>
 #include <utils/Flattenable.h>
-#include <pixelflinger/pixelflinger.h>
+
 
 struct ANativeWindowBuffer;
 
@@ -37,7 +37,7 @@
 // ===========================================================================
 
 class GraphicBuffer
-    : public EGLNativeBase<
+    : public ANativeObjectBase<
         ANativeWindowBuffer,
         GraphicBuffer, 
         LightRefBase<GraphicBuffer> >, public Flattenable
@@ -93,7 +93,6 @@
 
     status_t lock(uint32_t usage, void** vaddr);
     status_t lock(uint32_t usage, const Rect& rect, void** vaddr);
-    status_t lock(GGLSurface* surface, uint32_t usage);
     status_t unlock();
 
     ANativeWindowBuffer* getNativeBuffer() const;
diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h
index fc260c4..9f3e267 100644
--- a/include/ui/PixelFormat.h
+++ b/include/ui/PixelFormat.h
@@ -64,9 +64,6 @@
     PIXEL_FORMAT_RGBA_5551   = HAL_PIXEL_FORMAT_RGBA_5551,  // 16-bit ARGB
     PIXEL_FORMAT_RGBA_4444   = HAL_PIXEL_FORMAT_RGBA_4444,  // 16-bit ARGB
     PIXEL_FORMAT_A_8         = 8,                           // 8-bit A
-
-    // New formats can be added if they're also defined in
-    // pixelflinger/format.h
 };
 
 typedef int32_t PixelFormat;
@@ -80,10 +77,12 @@
     };
 
     enum { // components
-        ALPHA               = 1,
-        RGB                 = 2,
-        RGBA                = 3,
-        OTHER               = 0xFF
+        ALPHA   = 1,
+        RGB     = 2,
+        RGBA    = 3,
+        L       = 4,
+        LA      = 5,
+        OTHER   = 0xFF
     };
 
     struct szinfo {
diff --git a/include/ui/android_native_buffer.h b/include/ui/android_native_buffer.h
deleted file mode 100644
index b6e1db4..0000000
--- a/include/ui/android_native_buffer.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_ANDROID_NATIVES_PRIV_H
-#define ANDROID_ANDROID_NATIVES_PRIV_H
-
-#include <ui/egl/android_natives.h>
-
-#endif /* ANDROID_ANDROID_NATIVES_PRIV_H */
diff --git a/libs/gui/BufferQueue.cpp b/libs/gui/BufferQueue.cpp
index 0791de2..f4214c7 100644
--- a/libs/gui/BufferQueue.cpp
+++ b/libs/gui/BufferQueue.cpp
@@ -15,6 +15,7 @@
  */
 
 #define LOG_TAG "BufferQueue"
+//#define LOG_NDEBUG 0
 
 #define GL_GLEXT_PROTOTYPES
 #define EGL_EGLEXT_PROTOTYPES
@@ -27,6 +28,7 @@
 #include <surfaceflinger/ISurfaceComposer.h>
 
 #include <utils/Log.h>
+#include <gui/SurfaceTexture.h>
 
 // This compile option causes SurfaceTexture to return the buffer that is currently
 // attached to the GL texture from dequeueBuffer when no other buffers are
@@ -42,11 +44,11 @@
 #endif
 
 // Macros for including the BufferQueue name in log messages
-#define ST_LOGV(x, ...) ALOGV("[%s] "x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGD(x, ...) ALOGD("[%s] "x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGI(x, ...) ALOGI("[%s] "x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGW(x, ...) ALOGW("[%s] "x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGE(x, ...) ALOGE("[%s] "x, mName.string(), ##__VA_ARGS__)
+#define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
+#define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
+#define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
+#define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
+#define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
 
 namespace android {
 
@@ -63,17 +65,17 @@
     mBufferCount(MIN_ASYNC_BUFFER_SLOTS),
     mClientBufferCount(0),
     mServerBufferCount(MIN_ASYNC_BUFFER_SLOTS),
-    mCurrentTexture(INVALID_BUFFER_SLOT),
     mNextTransform(0),
     mNextScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
     mSynchronousMode(false),
     mAllowSynchronousMode(allowSynchronousMode),
     mConnectedApi(NO_CONNECTED_API),
     mAbandoned(false),
-    mFrameCounter(0)
+    mFrameCounter(0),
+    mBufferHasBeenQueued(false)
 {
     // Choose a name using the PID and a process-unique ID.
-    mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
+    mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
 
     ST_LOGV("BufferQueue");
     sp<ISurfaceComposer> composer(ComposerService::getComposerService());
@@ -119,6 +121,23 @@
     return OK;
 }
 
+bool BufferQueue::isSynchronousMode() const {
+    Mutex::Autolock lock(mMutex);
+    return mSynchronousMode;
+}
+
+void BufferQueue::setConsumerName(const String8& name) {
+    Mutex::Autolock lock(mMutex);
+    mConsumerName = name;
+}
+
+void BufferQueue::setFrameAvailableListener(
+        const sp<FrameAvailableListener>& listener) {
+    ST_LOGV("setFrameAvailableListener");
+    Mutex::Autolock lock(mMutex);
+    mFrameAvailableListener = listener;
+}
+
 status_t BufferQueue::setBufferCount(int bufferCount) {
     ST_LOGV("setBufferCount: count=%d", bufferCount);
     Mutex::Autolock lock(mMutex);
@@ -160,7 +179,7 @@
     freeAllBuffersLocked();
     mBufferCount = bufferCount;
     mClientBufferCount = bufferCount;
-    mCurrentTexture = INVALID_BUFFER_SLOT;
+    mBufferHasBeenQueued = false;
     mQueue.clear();
     mDequeueCondition.signal();
     return OK;
@@ -276,7 +295,7 @@
                 mBufferCount = mServerBufferCount;
                 if (mBufferCount < minBufferCountNeeded)
                     mBufferCount = minBufferCountNeeded;
-                mCurrentTexture = INVALID_BUFFER_SLOT;
+                mBufferHasBeenQueued = false;
                 returnFlags |= ISurfaceTexture::RELEASE_ALL_BUFFERS;
             }
 
@@ -290,19 +309,10 @@
                     dequeuedCount++;
                 }
 
-                // if buffer is FREE it CANNOT be current
-                ALOGW_IF((state == BufferSlot::FREE) && (mCurrentTexture==i),
-                        "dequeueBuffer: buffer %d is both FREE and current!",
-                        i);
-
                 if (FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER) {
-                    if (state == BufferSlot::FREE || i == mCurrentTexture) {
-                        foundSync = i;
-                        if (i != mCurrentTexture) {
-                            found = i;
-                            break;
-                        }
-                    }
+                    // This functionality has been temporarily removed so
+                    // BufferQueue and SurfaceTexture can be refactored into
+                    // separate objects
                 } else {
                     if (state == BufferSlot::FREE) {
                         /* We return the oldest of the free buffers to avoid
@@ -331,8 +341,7 @@
             // See whether a buffer has been queued since the last
             // setBufferCount so we know whether to perform the
             // MIN_UNDEQUEUED_BUFFERS check below.
-            bool bufferHasBeenQueued = mCurrentTexture != INVALID_BUFFER_SLOT;
-            if (bufferHasBeenQueued) {
+            if (mBufferHasBeenQueued) {
                 // make sure the client is not trying to dequeue more buffers
                 // than allowed.
                 const int avail = mBufferCount - (dequeuedCount+1);
@@ -404,27 +413,23 @@
             if (updateFormat) {
                 mPixelFormat = format;
             }
+
+            mSlots[buf].mAcquireCalled = false;
             mSlots[buf].mGraphicBuffer = graphicBuffer;
             mSlots[buf].mRequestBufferCalled = false;
             mSlots[buf].mFence = EGL_NO_SYNC_KHR;
-            if (mSlots[buf].mEglImage != EGL_NO_IMAGE_KHR) {
-                eglDestroyImageKHR(mSlots[buf].mEglDisplay,
-                        mSlots[buf].mEglImage);
-                mSlots[buf].mEglImage = EGL_NO_IMAGE_KHR;
-                mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
-            }
-            if (mCurrentTexture == buf) {
-                // The current texture no longer references the buffer in this slot
-                // since we just allocated a new buffer.
-                mCurrentTexture = INVALID_BUFFER_SLOT;
-            }
+            mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
+
+
+
+
             returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION;
         }
 
         dpy = mSlots[buf].mEglDisplay;
         fence = mSlots[buf].mFence;
         mSlots[buf].mFence = EGL_NO_SYNC_KHR;
-    }
+    }  // end lock scope
 
     if (fence != EGL_NO_SYNC_KHR) {
         EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
@@ -437,6 +442,7 @@
             ALOGE("dequeueBuffer: timeout waiting for fence");
         }
         eglDestroySyncKHR(dpy, fence);
+
     }
 
     ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf,
@@ -496,9 +502,6 @@
             ST_LOGE("queueBuffer: slot %d is not owned by the client "
                     "(state=%d)", buf, mSlots[buf].mBufferState);
             return -EINVAL;
-        } else if (buf == mCurrentTexture) {
-            ST_LOGE("queueBuffer: slot %d is current!", buf);
-            return -EINVAL;
         } else if (!mSlots[buf].mRequestBufferCalled) {
             ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
                     "buffer", buf);
@@ -538,6 +541,7 @@
         mFrameCounter++;
         mSlots[buf].mFrameNumber = mFrameCounter;
 
+        mBufferHasBeenQueued = true;
         mDequeueCondition.signal();
 
         *outWidth = mDefaultWidth;
@@ -647,6 +651,9 @@
             err = -EINVAL;
             break;
     }
+
+    mBufferHasBeenQueued = false;
+
     return err;
 }
 
@@ -687,26 +694,185 @@
     return err;
 }
 
+void BufferQueue::dump(String8& result) const
+{
+    char buffer[1024];
+    BufferQueue::dump(result, "", buffer, 1024);
+}
+
+void BufferQueue::dump(String8& result, const char* prefix,
+        char* buffer, size_t SIZE) const
+{
+    Mutex::Autolock _l(mMutex);
+    snprintf(buffer, SIZE,
+            "%snext   : {crop=[%d,%d,%d,%d], transform=0x%02x}\n"
+            ,prefix, mNextCrop.left, mNextCrop.top, mNextCrop.right,
+            mNextCrop.bottom, mNextTransform
+    );
+    result.append(buffer);
+
+    String8 fifo;
+    int fifoSize = 0;
+    Fifo::const_iterator i(mQueue.begin());
+    while (i != mQueue.end()) {
+       snprintf(buffer, SIZE, "%02d ", *i++);
+       fifoSize++;
+       fifo.append(buffer);
+    }
+
+    snprintf(buffer, SIZE,
+            "%s-BufferQueue mBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
+            "mPixelFormat=%d, FIFO(%d)={%s}\n",
+            prefix, mBufferCount, mSynchronousMode, mDefaultWidth,
+            mDefaultHeight, mPixelFormat, fifoSize, fifo.string());
+    result.append(buffer);
+
+
+    struct {
+        const char * operator()(int state) const {
+            switch (state) {
+                case BufferSlot::DEQUEUED: return "DEQUEUED";
+                case BufferSlot::QUEUED: return "QUEUED";
+                case BufferSlot::FREE: return "FREE";
+                case BufferSlot::ACQUIRED: return "ACQUIRED";
+                default: return "Unknown";
+            }
+        }
+    } stateName;
+
+    for (int i=0 ; i<mBufferCount ; i++) {
+        const BufferSlot& slot(mSlots[i]);
+        snprintf(buffer, SIZE,
+                "%s%s[%02d] "
+                "state=%-8s, crop=[%d,%d,%d,%d], "
+                "transform=0x%02x, timestamp=%lld",
+                prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i,
+                stateName(slot.mBufferState),
+                slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
+                slot.mCrop.bottom, slot.mTransform, slot.mTimestamp
+        );
+        result.append(buffer);
+
+        const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
+        if (buf != NULL) {
+            snprintf(buffer, SIZE,
+                    ", %p [%4ux%4u:%4u,%3X]",
+                    buf->handle, buf->width, buf->height, buf->stride,
+                    buf->format);
+            result.append(buffer);
+        }
+        result.append("\n");
+    }
+}
+
 void BufferQueue::freeBufferLocked(int i) {
     mSlots[i].mGraphicBuffer = 0;
     mSlots[i].mBufferState = BufferSlot::FREE;
     mSlots[i].mFrameNumber = 0;
-    if (mSlots[i].mEglImage != EGL_NO_IMAGE_KHR) {
-        eglDestroyImageKHR(mSlots[i].mEglDisplay, mSlots[i].mEglImage);
-        mSlots[i].mEglImage = EGL_NO_IMAGE_KHR;
-        mSlots[i].mEglDisplay = EGL_NO_DISPLAY;
+    mSlots[i].mAcquireCalled = false;
+
+    // destroy fence as BufferQueue now takes ownership
+    if (mSlots[i].mFence != EGL_NO_SYNC_KHR) {
+        eglDestroySyncKHR(mSlots[i].mEglDisplay, mSlots[i].mFence);
+        mSlots[i].mFence = EGL_NO_SYNC_KHR;
     }
 }
 
 void BufferQueue::freeAllBuffersLocked() {
     ALOGW_IF(!mQueue.isEmpty(),
             "freeAllBuffersLocked called but mQueue is not empty");
-    mCurrentTexture = INVALID_BUFFER_SLOT;
+    mQueue.clear();
+    mBufferHasBeenQueued = false;
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         freeBufferLocked(i);
     }
 }
 
+status_t BufferQueue::acquire(BufferItem *buffer) {
+    Mutex::Autolock _l(mMutex);
+    // check if queue is empty
+    // In asynchronous mode the list is guaranteed to be one buffer
+    // deep, while in synchronous mode we use the oldest buffer.
+    if (!mQueue.empty()) {
+        Fifo::iterator front(mQueue.begin());
+        int buf = *front;
+
+        if (mSlots[buf].mAcquireCalled) {
+            buffer->mGraphicBuffer = NULL;
+        }
+        else {
+            buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
+        }
+        buffer->mCrop = mSlots[buf].mCrop;
+        buffer->mTransform = mSlots[buf].mTransform;
+        buffer->mScalingMode = mSlots[buf].mScalingMode;
+        buffer->mFrameNumber = mSlots[buf].mFrameNumber;
+        buffer->mBuf = buf;
+        mSlots[buf].mAcquireCalled = true;
+
+        mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
+        mQueue.erase(front);
+    }
+    else {
+        return -EINVAL; //should be a better return code
+    }
+
+    return OK;
+}
+
+status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display,
+        EGLSyncKHR fence) {
+    Mutex::Autolock _l(mMutex);
+
+    if (buf == INVALID_BUFFER_SLOT) {
+        return -EINVAL;
+    }
+
+    mSlots[buf].mEglDisplay = display;
+    mSlots[buf].mFence = fence;
+
+    // The current buffer becomes FREE if it was still in the queued
+    // state. If it has already been given to the client
+    // (synchronous mode), then it stays in DEQUEUED state.
+    if (mSlots[buf].mBufferState == BufferSlot::QUEUED
+            || mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
+        mSlots[buf].mBufferState = BufferSlot::FREE;
+    }
+    mDequeueCondition.signal();
+
+    return OK;
+}
+
+status_t BufferQueue::consumerDisconnect() {
+    Mutex::Autolock lock(mMutex);
+    // Once the SurfaceTexture disconnects, the BufferQueue
+    // is considered abandoned
+    mAbandoned = true;
+    freeAllBuffersLocked();
+    mDequeueCondition.signal();
+    return OK;
+}
+
+status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
+{
+    ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
+    if (!w || !h) {
+        ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
+                w, h);
+        return BAD_VALUE;
+    }
+
+    Mutex::Autolock lock(mMutex);
+    mDefaultWidth = w;
+    mDefaultHeight = h;
+    return OK;
+}
+
+status_t BufferQueue::setBufferCountServer(int bufferCount) {
+    Mutex::Autolock lock(mMutex);
+    return setBufferCountServerLocked(bufferCount);
+}
+
 void BufferQueue::freeAllBuffersExceptHeadLocked() {
     ALOGW_IF(!mQueue.isEmpty(),
             "freeAllBuffersExceptCurrentLocked called but mQueue is not empty");
@@ -715,7 +881,7 @@
         Fifo::iterator front(mQueue.begin());
         head = *front;
     }
-    mCurrentTexture = INVALID_BUFFER_SLOT;
+    mBufferHasBeenQueued = false;
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         if (i != head) {
             freeBufferLocked(i);
diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp
index a7bfc61..ee5deb3 100644
--- a/libs/gui/SurfaceTexture.cpp
+++ b/libs/gui/SurfaceTexture.cpp
@@ -97,6 +97,11 @@
 
 static void mtxMul(float out[16], const float a[16], const float b[16]);
 
+// Get an ID that's unique within this process.
+static int32_t createProcessUniqueId() {
+    static volatile int32_t globalCounter = 0;
+    return android_atomic_inc(&globalCounter);
+}
 
 SurfaceTexture::SurfaceTexture(GLuint tex, bool allowSynchronousMode,
         GLenum texTarget, bool useFenceSync) :
@@ -109,8 +114,13 @@
 #else
     mUseFenceSync(false),
 #endif
-    mTexTarget(texTarget)
+    mTexTarget(texTarget),
+    mAbandoned(false),
+    mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT)
 {
+    // Choose a name using the PID and a process-unique ID.
+    mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
+    BufferQueue::setConsumerName(mName);
 
     ST_LOGV("SurfaceTexture");
     memcpy(mCurrentTransformMatrix, mtxIdentity,
@@ -119,28 +129,18 @@
 
 SurfaceTexture::~SurfaceTexture() {
     ST_LOGV("~SurfaceTexture");
-    freeAllBuffersLocked();
+    abandon();
 }
 
 status_t SurfaceTexture::setBufferCountServer(int bufferCount) {
     Mutex::Autolock lock(mMutex);
-    return setBufferCountServerLocked(bufferCount);
+    return BufferQueue::setBufferCountServer(bufferCount);
 }
 
 
 status_t SurfaceTexture::setDefaultBufferSize(uint32_t w, uint32_t h)
 {
-    ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
-    if (!w || !h) {
-        ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
-                w, h);
-        return BAD_VALUE;
-    }
-
-    Mutex::Autolock lock(mMutex);
-    mDefaultWidth = w;
-    mDefaultHeight = h;
-    return OK;
+    return BufferQueue::setDefaultBufferSize(w, h);
 }
 
 status_t SurfaceTexture::updateTexImage() {
@@ -152,23 +152,35 @@
         return NO_INIT;
     }
 
+    BufferItem item;
+
     // In asynchronous mode the list is guaranteed to be one buffer
     // deep, while in synchronous mode we use the oldest buffer.
-    if (!mQueue.empty()) {
-        Fifo::iterator front(mQueue.begin());
-        int buf = *front;
+    if (acquire(&item) == NO_ERROR) {
+        int buf = item.mBuf;
+        // This buffer was newly allocated, so we need to clean up on our side
+        if (item.mGraphicBuffer != NULL) {
+            mEGLSlots[buf].mGraphicBuffer = 0;
+            if (mEGLSlots[buf].mEglImage != EGL_NO_IMAGE_KHR) {
+                eglDestroyImageKHR(mEGLSlots[buf].mEglDisplay,
+                        mEGLSlots[buf].mEglImage);
+                mEGLSlots[buf].mEglImage = EGL_NO_IMAGE_KHR;
+                mEGLSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
+            }
+            mEGLSlots[buf].mGraphicBuffer = item.mGraphicBuffer;
+        }
 
         // Update the GL texture object.
-        EGLImageKHR image = mSlots[buf].mEglImage;
+        EGLImageKHR image = mEGLSlots[buf].mEglImage;
         EGLDisplay dpy = eglGetCurrentDisplay();
         if (image == EGL_NO_IMAGE_KHR) {
-            if (mSlots[buf].mGraphicBuffer == 0) {
+            if (item.mGraphicBuffer == 0) {
                 ST_LOGE("buffer at slot %d is null", buf);
                 return BAD_VALUE;
             }
-            image = createImage(dpy, mSlots[buf].mGraphicBuffer);
-            mSlots[buf].mEglImage = image;
-            mSlots[buf].mEglDisplay = dpy;
+            image = createImage(dpy, item.mGraphicBuffer);
+            mEGLSlots[buf].mEglImage = image;
+            mEGLSlots[buf].mEglDisplay = dpy;
             if (image == EGL_NO_IMAGE_KHR) {
                 // NOTE: if dpy was invalid, createImage() is guaranteed to
                 // fail. so we'd end up here.
@@ -191,6 +203,8 @@
             failed = true;
         }
         if (failed) {
+            releaseBuffer(buf, mEGLSlots[buf].mEglDisplay,
+                    mEGLSlots[buf].mFence);
             return -EINVAL;
         }
 
@@ -201,40 +215,37 @@
                 if (fence == EGL_NO_SYNC_KHR) {
                     ALOGE("updateTexImage: error creating fence: %#x",
                             eglGetError());
+                    releaseBuffer(buf, mEGLSlots[buf].mEglDisplay,
+                            mEGLSlots[buf].mFence);
                     return -EINVAL;
                 }
                 glFlush();
-                mSlots[mCurrentTexture].mFence = fence;
+                mEGLSlots[mCurrentTexture].mFence = fence;
             }
         }
 
         ST_LOGV("updateTexImage: (slot=%d buf=%p) -> (slot=%d buf=%p)",
                 mCurrentTexture,
                 mCurrentTextureBuf != NULL ? mCurrentTextureBuf->handle : 0,
-                buf, mSlots[buf].mGraphicBuffer->handle);
+                buf, item.mGraphicBuffer->handle);
 
-        if (mCurrentTexture != INVALID_BUFFER_SLOT) {
-            // The current buffer becomes FREE if it was still in the queued
-            // state. If it has already been given to the client
-            // (synchronous mode), then it stays in DEQUEUED state.
-            if (mSlots[mCurrentTexture].mBufferState == BufferSlot::QUEUED) {
-                mSlots[mCurrentTexture].mBufferState = BufferSlot::FREE;
-            }
-        }
+        // release old buffer
+        releaseBuffer(mCurrentTexture,
+                mEGLSlots[mCurrentTexture].mEglDisplay,
+                mEGLSlots[mCurrentTexture].mFence);
 
         // Update the SurfaceTexture state.
         mCurrentTexture = buf;
-        mCurrentTextureBuf = mSlots[buf].mGraphicBuffer;
-        mCurrentCrop = mSlots[buf].mCrop;
-        mCurrentTransform = mSlots[buf].mTransform;
-        mCurrentScalingMode = mSlots[buf].mScalingMode;
-        mCurrentTimestamp = mSlots[buf].mTimestamp;
+        mCurrentTextureBuf = mEGLSlots[buf].mGraphicBuffer;
+        mCurrentCrop = item.mCrop;
+        mCurrentTransform = item.mTransform;
+        mCurrentScalingMode = item.mScalingMode;
+        mCurrentTimestamp = item.mTimestamp;
         computeCurrentTransformMatrix();
 
         // Now that we've passed the point at which failures can happen,
         // it's safe to remove the buffer from the front of the queue.
-        mQueue.erase(front);
-        mDequeueCondition.signal();
+
     } else {
         // We always bind the texture even if we don't update its contents.
         glBindTexture(mTexTarget, mTexName);
@@ -300,7 +311,7 @@
         }
     }
 
-    sp<GraphicBuffer>& buf(mSlots[mCurrentTexture].mGraphicBuffer);
+    sp<GraphicBuffer>& buf(mCurrentTextureBuf);
     float tx, ty, sx, sy;
     if (!mCurrentCrop.isEmpty()) {
         // In order to prevent bilinear sampling at the of the crop rectangle we
@@ -372,7 +383,7 @@
         const sp<FrameAvailableListener>& listener) {
     ST_LOGV("setFrameAvailableListener");
     Mutex::Autolock lock(mMutex);
-    mFrameAvailableListener = listener;
+    BufferQueue::setFrameAvailableListener(listener);
 }
 
 EGLImageKHR SurfaceTexture::createImage(EGLDisplay dpy,
@@ -413,22 +424,33 @@
 
 bool SurfaceTexture::isSynchronousMode() const {
     Mutex::Autolock lock(mMutex);
-    return mSynchronousMode;
+    return BufferQueue::isSynchronousMode();
 }
 
-
-
 void SurfaceTexture::abandon() {
     Mutex::Autolock lock(mMutex);
-    mQueue.clear();
     mAbandoned = true;
     mCurrentTextureBuf.clear();
-    freeAllBuffersLocked();
-    mDequeueCondition.signal();
+
+    // destroy all egl buffers
+    for (int i =0; i < NUM_BUFFER_SLOTS; i++) {
+        mEGLSlots[i].mGraphicBuffer = 0;
+        if (mEGLSlots[i].mEglImage != EGL_NO_IMAGE_KHR) {
+            eglDestroyImageKHR(mEGLSlots[i].mEglDisplay,
+                    mEGLSlots[i].mEglImage);
+            mEGLSlots[i].mEglImage = EGL_NO_IMAGE_KHR;
+            mEGLSlots[i].mEglDisplay = EGL_NO_DISPLAY;
+        }
+    }
+
+    // disconnect from the BufferQueue
+    BufferQueue::consumerDisconnect();
 }
 
 void SurfaceTexture::setName(const String8& name) {
+    Mutex::Autolock _l(mMutex);
     mName = name;
+    BufferQueue::setConsumerName(name);
 }
 
 void SurfaceTexture::dump(String8& result) const
@@ -441,68 +463,19 @@
         char* buffer, size_t SIZE) const
 {
     Mutex::Autolock _l(mMutex);
-    snprintf(buffer, SIZE,
-            "%smBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
-            "mPixelFormat=%d, mTexName=%d\n",
-            prefix, mBufferCount, mSynchronousMode, mDefaultWidth,
-            mDefaultHeight, mPixelFormat, mTexName);
+    snprintf(buffer, SIZE, "%smTexName=%d\n", prefix, mTexName);
     result.append(buffer);
 
-    String8 fifo;
-    int fifoSize = 0;
-    Fifo::const_iterator i(mQueue.begin());
-    while (i != mQueue.end()) {
-        snprintf(buffer, SIZE, "%02d ", *i++);
-        fifoSize++;
-        fifo.append(buffer);
-    }
-
     snprintf(buffer, SIZE,
-            "%scurrent: {crop=[%d,%d,%d,%d], transform=0x%02x, current=%d}\n"
-            "%snext   : {crop=[%d,%d,%d,%d], transform=0x%02x, FIFO(%d)={%s}}\n"
-            ,
-            prefix, mCurrentCrop.left,
+            "%snext   : {crop=[%d,%d,%d,%d], transform=0x%02x, current=%d}\n"
+            ,prefix, mCurrentCrop.left,
             mCurrentCrop.top, mCurrentCrop.right, mCurrentCrop.bottom,
-            mCurrentTransform, mCurrentTexture,
-            prefix, mNextCrop.left, mNextCrop.top, mNextCrop.right,
-            mNextCrop.bottom, mNextTransform, fifoSize, fifo.string()
+            mCurrentTransform, mCurrentTexture
     );
     result.append(buffer);
 
-    struct {
-        const char * operator()(int state) const {
-            switch (state) {
-                case BufferSlot::DEQUEUED: return "DEQUEUED";
-                case BufferSlot::QUEUED: return "QUEUED";
-                case BufferSlot::FREE: return "FREE";
-                default: return "Unknown";
-            }
-        }
-    } stateName;
 
-    for (int i=0 ; i<mBufferCount ; i++) {
-        const BufferSlot& slot(mSlots[i]);
-        snprintf(buffer, SIZE,
-                "%s%s[%02d] "
-                "state=%-8s, crop=[%d,%d,%d,%d], "
-                "transform=0x%02x, timestamp=%lld",
-                prefix, (i==mCurrentTexture)?">":" ", i,
-                stateName(slot.mBufferState),
-                slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
-                slot.mCrop.bottom, slot.mTransform, slot.mTimestamp
-        );
-        result.append(buffer);
-
-        const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
-        if (buf != NULL) {
-            snprintf(buffer, SIZE,
-                    ", %p [%4ux%4u:%4u,%3X]",
-                    buf->handle, buf->width, buf->height, buf->stride,
-                    buf->format);
-            result.append(buffer);
-        }
-        result.append("\n");
-    }
+    BufferQueue::dump(result, prefix, buffer, SIZE);
 }
 
 static void mtxMul(float out[16], const float a[16], const float b[16]) {
diff --git a/libs/ui/Android.mk b/libs/ui/Android.mk
index c029291..5aff7a4 100644
--- a/libs/ui/Android.mk
+++ b/libs/ui/Android.mk
@@ -16,7 +16,6 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	EGLUtils.cpp \
 	FramebufferNativeWindow.cpp \
 	GraphicBuffer.cpp \
 	GraphicBufferAllocator.cpp \
@@ -28,7 +27,6 @@
 LOCAL_SHARED_LIBRARIES := \
 	libcutils \
 	libutils \
-	libEGL \
 	libhardware
 
 ifneq ($(BOARD_FRAMEBUFFER_FORCE_FORMAT),)
diff --git a/libs/ui/FramebufferNativeWindow.cpp b/libs/ui/FramebufferNativeWindow.cpp
index 26d4823..dec99b6 100644
--- a/libs/ui/FramebufferNativeWindow.cpp
+++ b/libs/ui/FramebufferNativeWindow.cpp
@@ -27,25 +27,21 @@
 #include <utils/threads.h>
 #include <utils/RefBase.h>
 
-#include <ui/Rect.h>
+#include <ui/ANativeObjectBase.h>
 #include <ui/FramebufferNativeWindow.h>
+#include <ui/Rect.h>
 
 #include <EGL/egl.h>
 
-#include <pixelflinger/format.h>
-#include <pixelflinger/pixelflinger.h>
-
 #include <hardware/hardware.h>
 #include <hardware/gralloc.h>
 
-#include <private/ui/android_natives_priv.h>
-
 // ----------------------------------------------------------------------------
 namespace android {
 // ----------------------------------------------------------------------------
 
 class NativeBuffer 
-    : public EGLNativeBase<
+    : public ANativeObjectBase<
         ANativeWindowBuffer, 
         NativeBuffer, 
         LightRefBase<NativeBuffer> >
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index f549a37..57063e5 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -28,8 +28,6 @@
 #include <ui/GraphicBufferMapper.h>
 #include <ui/PixelFormat.h>
 
-#include <pixelflinger/pixelflinger.h>
-
 namespace android {
 
 // ===========================================================================
@@ -182,21 +180,6 @@
     return res;
 }
 
-status_t GraphicBuffer::lock(GGLSurface* sur, uint32_t usage) 
-{
-    void* vaddr;
-    status_t res = GraphicBuffer::lock(usage, &vaddr);
-    if (res == NO_ERROR && sur) {
-        sur->version = sizeof(GGLSurface);
-        sur->width = width;
-        sur->height = height;
-        sur->stride = stride;
-        sur->format = format;
-        sur->data = static_cast<GGLubyte*>(vaddr);
-    }
-    return res;
-}
-
 size_t GraphicBuffer::getFlattenedSize() const {
     return (8 + (handle ? handle->numInts : 0))*sizeof(int);
 }
diff --git a/libs/ui/PixelFormat.cpp b/libs/ui/PixelFormat.cpp
index 6993dac..fc1d3c2 100644
--- a/libs/ui/PixelFormat.cpp
+++ b/libs/ui/PixelFormat.cpp
@@ -48,7 +48,10 @@
         { 4, 32, {32,24,  24,16,  16, 8,   8, 0 }, PixelFormatInfo::RGBA },
         { 2, 16, { 1, 0,  16,11,  11, 6,   6, 1 }, PixelFormatInfo::RGBA },
         { 2, 16, { 4, 0,  16,12,  12, 8,   8, 4 }, PixelFormatInfo::RGBA },
-        { 1,  8, { 8, 0,   0, 0,   0, 0,   0, 0 }, PixelFormatInfo::ALPHA}
+        { 1,  8, { 8, 0,   0, 0,   0, 0,   0, 0 }, PixelFormatInfo::ALPHA},
+        { 1,  8, { 0, 0,   8, 0,   8, 0,   8, 0 }, PixelFormatInfo::L    },
+        { 2, 16, {16, 8,   8, 0,   8, 0,   8, 0 }, PixelFormatInfo::LA   },
+        { 1,  8, { 0, 0,   8, 5,   5, 2,   2, 0 }, PixelFormatInfo::RGB  },
 };
 
 static const Info* gGetPixelFormatTable(size_t* numEntries) {
diff --git a/opengl/libagl/TextureObjectManager.cpp b/opengl/libagl/TextureObjectManager.cpp
index 6a006aa..06d45cc 100644
--- a/opengl/libagl/TextureObjectManager.cpp
+++ b/opengl/libagl/TextureObjectManager.cpp
@@ -19,8 +19,6 @@
 #include "context.h"
 #include "TextureObjectManager.h"
 
-#include <private/ui/android_natives_priv.h>
-
 namespace android {
 // ----------------------------------------------------------------------------
 
diff --git a/opengl/libagl/egl.cpp b/opengl/libagl/egl.cpp
index eb55bee..92d32a2 100644
--- a/opengl/libagl/egl.cpp
+++ b/opengl/libagl/egl.cpp
@@ -30,6 +30,7 @@
 #include <cutils/atomic.h>
 
 #include <utils/threads.h>
+#include <ui/ANativeObjectBase.h>
 
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
@@ -39,8 +40,6 @@
 #include <pixelflinger/format.h>
 #include <pixelflinger/pixelflinger.h>
 
-#include <private/ui/android_natives_priv.h>
-
 #include "context.h"
 #include "state.h"
 #include "texture.h"
@@ -49,13 +48,14 @@
 #undef NELEM
 #define NELEM(x) (sizeof(x)/sizeof(*(x)))
 
+// ----------------------------------------------------------------------------
 
 EGLBoolean EGLAPI eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
         EGLint left, EGLint top, EGLint width, EGLint height);
 
-
 // ----------------------------------------------------------------------------
 namespace android {
+
 // ----------------------------------------------------------------------------
 
 const unsigned int NUM_DISPLAYS = 1;
diff --git a/opengl/libagl/texture.cpp b/opengl/libagl/texture.cpp
index 88e8651..08536df 100644
--- a/opengl/libagl/texture.cpp
+++ b/opengl/libagl/texture.cpp
@@ -23,7 +23,6 @@
 #include "texture.h"
 #include "TextureObjectManager.h"
 
-#include <private/ui/android_natives_priv.h>
 #include <ETC1/etc1.h>
 
 namespace android {
diff --git a/opengl/tests/angeles/Android.mk b/opengl/tests/angeles/Android.mk
index d0c3221..84b754b 100644
--- a/opengl/tests/angeles/Android.mk
+++ b/opengl/tests/angeles/Android.mk
@@ -4,14 +4,7 @@
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES:= app-linux.cpp demo.c.arm
 LOCAL_SHARED_LIBRARIES := libEGL libGLESv1_CM libui
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
 LOCAL_MODULE:= angeles
 LOCAL_MODULE_TAGS := optional
 include $(BUILD_EXECUTABLE)
-
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= gpustate.c
-LOCAL_SHARED_LIBRARIES := libEGL libGLESv1_CM
-LOCAL_MODULE:= gpustate
-LOCAL_MODULE_TAGS := optional
-include $(BUILD_EXECUTABLE)
diff --git a/opengl/tests/angeles/app-linux.cpp b/opengl/tests/angeles/app-linux.cpp
index 4d10ee5..6ac68a2 100644
--- a/opengl/tests/angeles/app-linux.cpp
+++ b/opengl/tests/angeles/app-linux.cpp
@@ -53,7 +53,7 @@
 #include <GLES/gl.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/angeles/gpustate.c b/opengl/tests/angeles/gpustate.c
deleted file mode 100644
index 3c540c9..0000000
--- a/opengl/tests/angeles/gpustate.c
+++ /dev/null
@@ -1,39 +0,0 @@
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <unistd.h>
-#include <fcntl.h>
-
-static void *map_memory(const char *fn, unsigned base, unsigned size)
-{
-    int fd;
-    void *ptr;
-    
-    fd = open(fn, O_RDWR | O_SYNC);
-    if(fd < 0) {
-        perror("cannot open %s for mapping");
-        return MAP_FAILED;
-    }
-
-    ptr = mmap(0, size, PROT_READ | PROT_WRITE,
-               MAP_SHARED, fd, base);
-    close(fd);
-    
-    if(ptr == MAP_FAILED) {
-        fprintf(stderr,"cannot map %s (@%08x,%08x)\n", fn, base, size);
-    }
-    return ptr;    
-}
-
-
-int main(int argc, char** argv)
-{
-    void *grp_regs = map_memory("/dev/hw3d", 0, 1024 * 1024);
-    printf("GPU base mapped at %p\n", grp_regs);
-    int state_offset = 0x10140;
-    printf("GPU state = %08lx\n",
-            *((long*)((char*)grp_regs + state_offset))  );
-
-    return 0;
-}
diff --git a/opengl/tests/fillrate/Android.mk b/opengl/tests/fillrate/Android.mk
index 191c59b..835f858 100644
--- a/opengl/tests/fillrate/Android.mk
+++ b/opengl/tests/fillrate/Android.mk
@@ -11,6 +11,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-fillrate
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/fillrate/fillrate.cpp b/opengl/tests/fillrate/fillrate.cpp
index 911d354..a708647 100644
--- a/opengl/tests/fillrate/fillrate.cpp
+++ b/opengl/tests/fillrate/fillrate.cpp
@@ -26,7 +26,7 @@
 
 #include <utils/StopWatch.h>
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/filter/Android.mk b/opengl/tests/filter/Android.mk
index a254127..d780362 100644
--- a/opengl/tests/filter/Android.mk
+++ b/opengl/tests/filter/Android.mk
@@ -10,6 +10,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-filter
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/filter/filter.cpp b/opengl/tests/filter/filter.cpp
index 2351909..0067327 100644
--- a/opengl/tests/filter/filter.cpp
+++ b/opengl/tests/filter/filter.cpp
@@ -6,7 +6,7 @@
 #include <GLES/glext.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/finish/Android.mk b/opengl/tests/finish/Android.mk
index aa607c6..8f4f9c3 100644
--- a/opengl/tests/finish/Android.mk
+++ b/opengl/tests/finish/Android.mk
@@ -11,6 +11,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-finish
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/finish/finish.cpp b/opengl/tests/finish/finish.cpp
index 91f5c45..11f0c22 100644
--- a/opengl/tests/finish/finish.cpp
+++ b/opengl/tests/finish/finish.cpp
@@ -27,7 +27,7 @@
 #include <utils/Timers.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/gl2_basic/Android.mk b/opengl/tests/gl2_basic/Android.mk
index a642eaf..07469a0 100644
--- a/opengl/tests/gl2_basic/Android.mk
+++ b/opengl/tests/gl2_basic/Android.mk
@@ -10,6 +10,8 @@
     libGLESv2 \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-gl2_basic
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/gl2_basic/gl2_basic.cpp b/opengl/tests/gl2_basic/gl2_basic.cpp
index f274c7c..7007871 100644
--- a/opengl/tests/gl2_basic/gl2_basic.cpp
+++ b/opengl/tests/gl2_basic/gl2_basic.cpp
@@ -27,7 +27,7 @@
 #include <utils/Timers.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/gl2_copyTexImage/Android.mk b/opengl/tests/gl2_copyTexImage/Android.mk
index bef1f90..b616428 100644
--- a/opengl/tests/gl2_copyTexImage/Android.mk
+++ b/opengl/tests/gl2_copyTexImage/Android.mk
@@ -10,6 +10,8 @@
     libGLESv2 \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-gl2_copyTexImage
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/gl2_copyTexImage/gl2_copyTexImage.cpp b/opengl/tests/gl2_copyTexImage/gl2_copyTexImage.cpp
index c2bfdec..988d7ac 100644
--- a/opengl/tests/gl2_copyTexImage/gl2_copyTexImage.cpp
+++ b/opengl/tests/gl2_copyTexImage/gl2_copyTexImage.cpp
@@ -27,7 +27,7 @@
 #include <utils/Timers.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/gl2_yuvtex/Android.mk b/opengl/tests/gl2_yuvtex/Android.mk
index 6304700..e36f319 100644
--- a/opengl/tests/gl2_yuvtex/Android.mk
+++ b/opengl/tests/gl2_yuvtex/Android.mk
@@ -10,6 +10,8 @@
     libGLESv2 \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-gl2_yuvtex
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/gl2_yuvtex/gl2_yuvtex.cpp b/opengl/tests/gl2_yuvtex/gl2_yuvtex.cpp
index f0b8d12..d3e4932 100644
--- a/opengl/tests/gl2_yuvtex/gl2_yuvtex.cpp
+++ b/opengl/tests/gl2_yuvtex/gl2_yuvtex.cpp
@@ -29,7 +29,7 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/gl_basic/Android.mk b/opengl/tests/gl_basic/Android.mk
index 6b6341f..2ba327b 100644
--- a/opengl/tests/gl_basic/Android.mk
+++ b/opengl/tests/gl_basic/Android.mk
@@ -10,6 +10,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-gl_basic
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/gl_basic/gl_basic.cpp b/opengl/tests/gl_basic/gl_basic.cpp
index 0cc8398..23ce934 100644
--- a/opengl/tests/gl_basic/gl_basic.cpp
+++ b/opengl/tests/gl_basic/gl_basic.cpp
@@ -6,7 +6,7 @@
 #include <GLES/glext.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 #include <stdio.h>
 
diff --git a/opengl/tests/gl_perf/Android.mk b/opengl/tests/gl_perf/Android.mk
index 37647ca..f32abd3 100644
--- a/opengl/tests/gl_perf/Android.mk
+++ b/opengl/tests/gl_perf/Android.mk
@@ -11,6 +11,8 @@
     libGLESv2 \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-gl2_perf
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/gl_perf/gl2_perf.cpp b/opengl/tests/gl_perf/gl2_perf.cpp
index 9dfcf1c..224acaf 100644
--- a/opengl/tests/gl_perf/gl2_perf.cpp
+++ b/opengl/tests/gl_perf/gl2_perf.cpp
@@ -27,7 +27,7 @@
 #include <utils/Timers.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/gl_yuvtex/Android.mk b/opengl/tests/gl_yuvtex/Android.mk
index a78db25..5b87f2e 100644
--- a/opengl/tests/gl_yuvtex/Android.mk
+++ b/opengl/tests/gl_yuvtex/Android.mk
@@ -10,6 +10,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-gl_yuvtex
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/gl_yuvtex/gl_yuvtex.cpp b/opengl/tests/gl_yuvtex/gl_yuvtex.cpp
index fbe65f1..7a00f76 100644
--- a/opengl/tests/gl_yuvtex/gl_yuvtex.cpp
+++ b/opengl/tests/gl_yuvtex/gl_yuvtex.cpp
@@ -29,7 +29,7 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/hwc/hwcColorEquiv.cpp b/opengl/tests/hwc/hwcColorEquiv.cpp
index 1d03948..bb305dc 100644
--- a/opengl/tests/hwc/hwcColorEquiv.cpp
+++ b/opengl/tests/hwc/hwcColorEquiv.cpp
@@ -87,7 +87,6 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
 
 #define LOG_TAG "hwcColorEquivTest"
 #include <utils/Log.h>
diff --git a/opengl/tests/hwc/hwcCommit.cpp b/opengl/tests/hwc/hwcCommit.cpp
index 66ccdae..685dc5d 100644
--- a/opengl/tests/hwc/hwcCommit.cpp
+++ b/opengl/tests/hwc/hwcCommit.cpp
@@ -98,7 +98,6 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
 
 #define LOG_TAG "hwcCommitTest"
 #include <utils/Log.h>
diff --git a/opengl/tests/hwc/hwcRects.cpp b/opengl/tests/hwc/hwcRects.cpp
index 523e3de..80cde23 100644
--- a/opengl/tests/hwc/hwcRects.cpp
+++ b/opengl/tests/hwc/hwcRects.cpp
@@ -106,7 +106,6 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
 
 #define LOG_TAG "hwcRectsTest"
 #include <utils/Log.h>
diff --git a/opengl/tests/hwc/hwcStress.cpp b/opengl/tests/hwc/hwcStress.cpp
index 1cefb4b..7d7bc1f 100644
--- a/opengl/tests/hwc/hwcStress.cpp
+++ b/opengl/tests/hwc/hwcStress.cpp
@@ -103,7 +103,6 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
 
 #define LOG_TAG "hwcStressTest"
 #include <utils/Log.h>
diff --git a/opengl/tests/hwc/hwcTestLib.cpp b/opengl/tests/hwc/hwcTestLib.cpp
index 925405e..63f42ba 100644
--- a/opengl/tests/hwc/hwcTestLib.cpp
+++ b/opengl/tests/hwc/hwcTestLib.cpp
@@ -27,6 +27,8 @@
 
 #include <hwc/hwcTestLib.h>
 
+#include "EGLUtils.h"
+
 // Defines
 #define NUMA(a) (sizeof(a) / sizeof(a [0]))
 
diff --git a/opengl/tests/hwc/hwcTestLib.h b/opengl/tests/hwc/hwcTestLib.h
index 99ee608..b0c3012 100644
--- a/opengl/tests/hwc/hwcTestLib.h
+++ b/opengl/tests/hwc/hwcTestLib.h
@@ -29,7 +29,6 @@
 
 #include <ui/FramebufferNativeWindow.h>
 #include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
 
 #include <utils/Log.h>
 #include <testUtil.h>
diff --git a/libs/ui/EGLUtils.cpp b/opengl/tests/include/EGLUtils.h
similarity index 82%
rename from libs/ui/EGLUtils.cpp
rename to opengl/tests/include/EGLUtils.h
index f24a71d..014c261 100644
--- a/libs/ui/EGLUtils.cpp
+++ b/opengl/tests/include/EGLUtils.h
@@ -15,21 +15,42 @@
  */
 
 
-#define LOG_TAG "EGLUtils"
+#ifndef ANDROID_UI_EGLUTILS_H
+#define ANDROID_UI_EGLUTILS_H
 
-#include <cutils/log.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#include <system/window.h>
 #include <utils/Errors.h>
-
-#include <ui/EGLUtils.h>
-
 #include <EGL/egl.h>
 
-#include <private/ui/android_natives_priv.h>
 
 // ----------------------------------------------------------------------------
 namespace android {
 // ----------------------------------------------------------------------------
 
+class EGLUtils
+{
+public:
+
+    static inline const char *strerror(EGLint err);
+
+    static inline status_t selectConfigForPixelFormat(
+            EGLDisplay dpy,
+            EGLint const* attrs,
+            int32_t format,
+            EGLConfig* outConfig);
+
+    static inline status_t selectConfigForNativeWindow(
+            EGLDisplay dpy,
+            EGLint const* attrs,
+            EGLNativeWindowType window,
+            EGLConfig* outConfig);
+};
+
+// ----------------------------------------------------------------------------
+
 const char *EGLUtils::strerror(EGLint err)
 {
     switch (err){
@@ -55,7 +76,7 @@
 status_t EGLUtils::selectConfigForPixelFormat(
         EGLDisplay dpy,
         EGLint const* attrs,
-        PixelFormat format,
+        int32_t format,
         EGLConfig* outConfig)
 {
     EGLint numConfigs = -1, n=0;
@@ -65,7 +86,7 @@
 
     if (outConfig == NULL)
         return BAD_VALUE;
-    
+
     // Get all the "potential match" configs...
     if (eglGetConfigs(dpy, NULL, 0, &numConfigs) == EGL_FALSE)
         return BAD_VALUE;
@@ -75,7 +96,7 @@
         free(configs);
         return BAD_VALUE;
     }
-    
+
     int i;
     EGLConfig config = NULL;
     for (i=0 ; i<n ; i++) {
@@ -88,7 +109,7 @@
     }
 
     free(configs);
-    
+
     if (i<n) {
         *outConfig = config;
         return NO_ERROR;
@@ -105,10 +126,10 @@
 {
     int err;
     int format;
-    
+
     if (!window)
         return BAD_VALUE;
-    
+
     if ((err = window->query(window, NATIVE_WINDOW_FORMAT, &format)) < 0) {
         return err;
     }
@@ -119,3 +140,5 @@
 // ----------------------------------------------------------------------------
 }; // namespace android
 // ----------------------------------------------------------------------------
+
+#endif /* ANDROID_UI_EGLUTILS_H */
diff --git a/opengl/tests/include/glTestLib.h b/opengl/tests/include/glTestLib.h
index 06fbf5d..c91c594 100644
--- a/opengl/tests/include/glTestLib.h
+++ b/opengl/tests/include/glTestLib.h
@@ -24,9 +24,7 @@
 #include <GLES2/gl2.h>
 #include <GLES2/gl2ext.h>
 
-//#include <ui/FramebufferNativeWindow.h>
-//#include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 void glTestPrintGLString(const char *name, GLenum s);
 void glTestCheckEglError(const char* op, EGLBoolean returnVal = EGL_TRUE);
diff --git a/opengl/tests/lib/glTestLib.cpp b/opengl/tests/lib/glTestLib.cpp
index 052cbd7..b434fc7 100644
--- a/opengl/tests/lib/glTestLib.cpp
+++ b/opengl/tests/lib/glTestLib.cpp
@@ -26,7 +26,7 @@
 #include <GLES2/gl2.h>
 #include <GLES2/gl2ext.h>
 
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 #include <utils/Log.h>
 #include <testUtil.h>
diff --git a/opengl/tests/linetex/Android.mk b/opengl/tests/linetex/Android.mk
index 6ff248d..261940e 100644
--- a/opengl/tests/linetex/Android.mk
+++ b/opengl/tests/linetex/Android.mk
@@ -10,6 +10,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-linetex
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/linetex/linetex.cpp b/opengl/tests/linetex/linetex.cpp
index 6842940..8669492 100644
--- a/opengl/tests/linetex/linetex.cpp
+++ b/opengl/tests/linetex/linetex.cpp
@@ -27,7 +27,7 @@
 
 #include <utils/StopWatch.h>
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/swapinterval/Android.mk b/opengl/tests/swapinterval/Android.mk
index 9a4145e..d014cc9 100644
--- a/opengl/tests/swapinterval/Android.mk
+++ b/opengl/tests/swapinterval/Android.mk
@@ -11,6 +11,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-swapinterval
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/swapinterval/swapinterval.cpp b/opengl/tests/swapinterval/swapinterval.cpp
index 8ca031b..a0f4bc4 100644
--- a/opengl/tests/swapinterval/swapinterval.cpp
+++ b/opengl/tests/swapinterval/swapinterval.cpp
@@ -24,7 +24,7 @@
 
 #include <utils/StopWatch.h>
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/textures/Android.mk b/opengl/tests/textures/Android.mk
index b2fa185..fe9f43c 100644
--- a/opengl/tests/textures/Android.mk
+++ b/opengl/tests/textures/Android.mk
@@ -10,6 +10,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-textures
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/textures/textures.cpp b/opengl/tests/textures/textures.cpp
index cbe8ffd..5d3d94e 100644
--- a/opengl/tests/textures/textures.cpp
+++ b/opengl/tests/textures/textures.cpp
@@ -23,7 +23,7 @@
 #include <GLES/glext.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 using namespace android;
 
diff --git a/opengl/tests/tritex/Android.mk b/opengl/tests/tritex/Android.mk
index 6db3f49..fc544e4 100644
--- a/opengl/tests/tritex/Android.mk
+++ b/opengl/tests/tritex/Android.mk
@@ -10,6 +10,8 @@
     libGLESv1_CM \
     libui
 
+LOCAL_C_INCLUDES += frameworks/base/opengl/tests/include
+
 LOCAL_MODULE:= test-opengl-tritex
 
 LOCAL_MODULE_TAGS := optional
diff --git a/opengl/tests/tritex/tritex.cpp b/opengl/tests/tritex/tritex.cpp
index 3365ab4..f183483 100644
--- a/opengl/tests/tritex/tritex.cpp
+++ b/opengl/tests/tritex/tritex.cpp
@@ -9,7 +9,7 @@
 #include <GLES/glext.h>
 
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
+#include "EGLUtils.h"
 
 #include <stdio.h>

 #include <stdlib.h>
diff --git a/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp b/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp
index 986aec5..cea17f8 100644
--- a/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp
+++ b/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp
@@ -26,7 +26,6 @@
 
 #include <ui/PixelFormat.h>
 #include <ui/FramebufferNativeWindow.h>
-#include <ui/EGLUtils.h>
 
 #include <GLES/gl.h>
 #include <EGL/egl.h>
@@ -60,6 +59,29 @@
 static __attribute__((noinline))
 void checkEGLErrors(const char* token)
 {
+    struct EGLUtils {
+        static const char *strerror(EGLint err) {
+            switch (err){
+                case EGL_SUCCESS:           return "EGL_SUCCESS";
+                case EGL_NOT_INITIALIZED:   return "EGL_NOT_INITIALIZED";
+                case EGL_BAD_ACCESS:        return "EGL_BAD_ACCESS";
+                case EGL_BAD_ALLOC:         return "EGL_BAD_ALLOC";
+                case EGL_BAD_ATTRIBUTE:     return "EGL_BAD_ATTRIBUTE";
+                case EGL_BAD_CONFIG:        return "EGL_BAD_CONFIG";
+                case EGL_BAD_CONTEXT:       return "EGL_BAD_CONTEXT";
+                case EGL_BAD_CURRENT_SURFACE: return "EGL_BAD_CURRENT_SURFACE";
+                case EGL_BAD_DISPLAY:       return "EGL_BAD_DISPLAY";
+                case EGL_BAD_MATCH:         return "EGL_BAD_MATCH";
+                case EGL_BAD_NATIVE_PIXMAP: return "EGL_BAD_NATIVE_PIXMAP";
+                case EGL_BAD_NATIVE_WINDOW: return "EGL_BAD_NATIVE_WINDOW";
+                case EGL_BAD_PARAMETER:     return "EGL_BAD_PARAMETER";
+                case EGL_BAD_SURFACE:       return "EGL_BAD_SURFACE";
+                case EGL_CONTEXT_LOST:      return "EGL_CONTEXT_LOST";
+                default: return "UNKNOWN";
+            }
+        }
+    };
+
     EGLint error = eglGetError();
     if (error && error != EGL_SUCCESS) {
         ALOGE("%s: EGL error 0x%04x (%s)",
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 4ee6953..efcdd87 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -160,7 +160,10 @@
     // this surfaces pixel format
     PixelFormatInfo info;
     status_t err = getPixelFormatInfo(format, &info);
-    if (err) return err;
+    if (err) {
+        ALOGE("unsupported pixelformat %d", format);
+        return err;
+    }
 
     // the display's pixel format
     const DisplayHardware& hw(graphicPlane(0).displayHardware());
@@ -170,6 +173,7 @@
     // never allow a surface larger than what our underlying GL implementation
     // can handle.
     if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
+        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
         return BAD_VALUE;
     }
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 9d821dc..05b5bf5 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -1285,7 +1285,7 @@
         return surfaceHandle;
     }
 
-    //ALOGD("createSurface for pid %d (%d x %d)", pid, w, h);
+    //ALOGD("createSurface for (%d x %d), name=%s", w, h, name.string());
     sp<Layer> normalLayer;
     switch (flags & eFXSurfaceMask) {
         case eFXSurfaceNormal: