diff options
Diffstat (limited to 'services/surfaceflinger')
29 files changed, 3409 insertions, 2965 deletions
diff --git a/services/surfaceflinger/Android.mk b/services/surfaceflinger/Android.mk index 6f7a7e1..dd0dc16 100644 --- a/services/surfaceflinger/Android.mk +++ b/services/surfaceflinger/Android.mk @@ -2,13 +2,15 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES:= \ + Client.cpp \ + DdmConnection.cpp \ + DisplayDevice.cpp \ EventThread.cpp \ Layer.cpp \ LayerBase.cpp \ LayerDim.cpp \ LayerScreenshot.cpp \ - DisplayHardware/DisplayHardware.cpp \ - DisplayHardware/DisplayHardwareBase.cpp \ + DisplayHardware/FramebufferSurface.cpp \ DisplayHardware/HWComposer.cpp \ DisplayHardware/PowerHAL.cpp \ GLExtensions.cpp \ @@ -21,23 +23,24 @@ LOCAL_SRC_FILES:= \ LOCAL_CFLAGS:= -DLOG_TAG=\"SurfaceFlinger\" LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES -ifeq ($(TARGET_BOARD_PLATFORM), omap3) +ifeq ($(TARGET_BOARD_PLATFORM),omap3) LOCAL_CFLAGS += -DNO_RGBX_8888 endif -ifeq ($(TARGET_BOARD_PLATFORM), omap4) +ifeq ($(TARGET_BOARD_PLATFORM),omap4) LOCAL_CFLAGS += -DHAS_CONTEXT_PRIORITY endif -ifeq ($(TARGET_BOARD_PLATFORM), s5pc110) +ifeq ($(TARGET_BOARD_PLATFORM),s5pc110) LOCAL_CFLAGS += -DHAS_CONTEXT_PRIORITY LOCAL_CFLAGS += -DNEVER_DEFAULT_TO_ASYNC_MODE endif -ifeq ($(TARGET_DISABLE_TRIPLE_BUFFERING), true) +ifeq ($(TARGET_DISABLE_TRIPLE_BUFFERING),true) LOCAL_CFLAGS += -DTARGET_DISABLE_TRIPLE_BUFFERING endif LOCAL_SHARED_LIBRARIES := \ libcutils \ + libdl \ libhardware \ libutils \ libEGL \ @@ -46,13 +49,6 @@ LOCAL_SHARED_LIBRARIES := \ libui \ libgui -# this is only needed for DDMS debugging -ifneq ($(TARGET_BUILD_PDK), true) - LOCAL_SHARED_LIBRARIES += libdvm libandroid_runtime - LOCAL_CLFAGS += -DDDMS_DEBUGGING - LOCAL_SRC_FILES += DdmConnection.cpp -endif - LOCAL_MODULE:= libsurfaceflinger include $(BUILD_SHARED_LIBRARY) diff --git a/services/surfaceflinger/Client.cpp b/services/surfaceflinger/Client.cpp new file mode 100644 index 0000000..d5d551e --- /dev/null +++ b/services/surfaceflinger/Client.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2012 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 <stdint.h> +#include <sys/types.h> + +#include <binder/PermissionCache.h> + +#include <private/android_filesystem_config.h> + +#include "Client.h" +#include "Layer.h" +#include "LayerBase.h" +#include "SurfaceFlinger.h" + +namespace android { + +// --------------------------------------------------------------------------- + +const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); + +// --------------------------------------------------------------------------- + +Client::Client(const sp<SurfaceFlinger>& flinger) + : mFlinger(flinger), mNameGenerator(1) +{ +} + +Client::~Client() +{ + const size_t count = mLayers.size(); + for (size_t i=0 ; i<count ; i++) { + sp<LayerBaseClient> layer(mLayers.valueAt(i).promote()); + if (layer != 0) { + mFlinger->removeLayer(layer); + } + } +} + +status_t Client::initCheck() const { + return NO_ERROR; +} + +size_t Client::attachLayer(const sp<LayerBaseClient>& layer) +{ + Mutex::Autolock _l(mLock); + size_t name = mNameGenerator++; + mLayers.add(name, layer); + return name; +} + +void Client::detachLayer(const LayerBaseClient* layer) +{ + Mutex::Autolock _l(mLock); + // we do a linear search here, because this doesn't happen often + const size_t count = mLayers.size(); + for (size_t i=0 ; i<count ; i++) { + if (mLayers.valueAt(i) == layer) { + mLayers.removeItemsAt(i, 1); + break; + } + } +} +sp<LayerBaseClient> Client::getLayerUser(int32_t i) const +{ + Mutex::Autolock _l(mLock); + sp<LayerBaseClient> lbc; + wp<LayerBaseClient> layer(mLayers.valueFor(i)); + if (layer != 0) { + lbc = layer.promote(); + ALOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i)); + } + return lbc; +} + + +status_t Client::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + // these must be checked + IPCThreadState* ipc = IPCThreadState::self(); + const int pid = ipc->getCallingPid(); + const int uid = ipc->getCallingUid(); + const int self_pid = getpid(); + if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) { + // we're called from a different process, do the real check + if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger)) + { + ALOGE("Permission Denial: " + "can't openGlobalTransaction pid=%d, uid=%d", pid, uid); + return PERMISSION_DENIED; + } + } + return BnSurfaceComposerClient::onTransact(code, data, reply, flags); +} + + +sp<ISurface> Client::createSurface( + ISurfaceComposerClient::surface_data_t* params, + const String8& name, + DisplayID display, uint32_t w, uint32_t h, PixelFormat format, + uint32_t flags) +{ + /* + * createSurface must be called from the GL thread so that it can + * have access to the GL context. + */ + + class MessageCreateLayer : public MessageBase { + sp<ISurface> result; + SurfaceFlinger* flinger; + ISurfaceComposerClient::surface_data_t* params; + Client* client; + const String8& name; + DisplayID display; + uint32_t w, h; + PixelFormat format; + uint32_t flags; + public: + MessageCreateLayer(SurfaceFlinger* flinger, + ISurfaceComposerClient::surface_data_t* params, + const String8& name, Client* client, + DisplayID display, uint32_t w, uint32_t h, PixelFormat format, + uint32_t flags) + : flinger(flinger), params(params), client(client), name(name), + display(display), w(w), h(h), format(format), flags(flags) + { + } + sp<ISurface> getResult() const { return result; } + virtual bool handler() { + result = flinger->createLayer(params, name, client, + display, w, h, format, flags); + return true; + } + }; + + sp<MessageBase> msg = new MessageCreateLayer(mFlinger.get(), + params, name, this, display, w, h, format, flags); + mFlinger->postMessageSync(msg); + return static_cast<MessageCreateLayer*>( msg.get() )->getResult(); +} +status_t Client::destroySurface(SurfaceID sid) { + return mFlinger->onLayerRemoved(this, sid); +} + +// --------------------------------------------------------------------------- +}; // namespace android diff --git a/services/surfaceflinger/Client.h b/services/surfaceflinger/Client.h new file mode 100644 index 0000000..9bfee72 --- /dev/null +++ b/services/surfaceflinger/Client.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2012 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_SF_CLIENT_H +#define ANDROID_SF_CLIENT_H + +#include <stdint.h> +#include <sys/types.h> + +#include <utils/Errors.h> +#include <utils/KeyedVector.h> +#include <utils/Mutex.h> + +#include <gui/ISurfaceComposerClient.h> + +namespace android { + +// --------------------------------------------------------------------------- + +class LayerBaseClient; +class SurfaceFlinger; + +// --------------------------------------------------------------------------- + +class Client : public BnSurfaceComposerClient +{ +public: + Client(const sp<SurfaceFlinger>& flinger); + ~Client(); + + status_t initCheck() const; + + // protected by SurfaceFlinger::mStateLock + size_t attachLayer(const sp<LayerBaseClient>& layer); + + void detachLayer(const LayerBaseClient* layer); + + sp<LayerBaseClient> getLayerUser(int32_t i) const; + +private: + // ISurfaceComposerClient interface + virtual sp<ISurface> createSurface( + surface_data_t* params, const String8& name, + DisplayID display, uint32_t w, uint32_t h,PixelFormat format, + uint32_t flags); + + virtual status_t destroySurface(SurfaceID surfaceId); + + virtual status_t onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); + + // constant + sp<SurfaceFlinger> mFlinger; + + // protected by mLock + DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers; + size_t mNameGenerator; + + // thread-safe + mutable Mutex mLock; +}; + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_SF_CLIENT_H diff --git a/services/surfaceflinger/DdmConnection.cpp b/services/surfaceflinger/DdmConnection.cpp index 467a915..433b38e 100644 --- a/services/surfaceflinger/DdmConnection.cpp +++ b/services/surfaceflinger/DdmConnection.cpp @@ -14,16 +14,16 @@ * limitations under the License. */ -#include <android_runtime/AndroidRuntime.h> +#include <dlfcn.h> + +#include <cutils/log.h> #include "jni.h" #include "DdmConnection.h" -extern "C" jint Java_com_android_internal_util_WithFramework_registerNatives( - JNIEnv* env, jclass clazz); - namespace android { + void DdmConnection::start(const char* name) { JavaVM* vm; JNIEnv* env; @@ -40,12 +40,36 @@ void DdmConnection::start(const char* name) { args.nOptions = 1; args.ignoreUnrecognized = JNI_FALSE; + + void* libdvm_dso = dlopen("libdvm.so", RTLD_NOW); + ALOGE_IF(!libdvm_dso, "DdmConnection: %s", dlerror()); + + void* libandroid_runtime_dso = dlopen("libandroid_runtime.so", RTLD_NOW); + ALOGE_IF(!libandroid_runtime_dso, "DdmConnection: %s", dlerror()); + + if (!libdvm_dso || !libandroid_runtime_dso) { + goto error; + } + + jint (*JNI_CreateJavaVM)(JavaVM** p_vm, JNIEnv** p_env, void* vm_args); + JNI_CreateJavaVM = (typeof JNI_CreateJavaVM)dlsym(libdvm_dso, "JNI_CreateJavaVM"); + ALOGE_IF(!JNI_CreateJavaVM, "DdmConnection: %s", dlerror()); + + jint (*registerNatives)(JNIEnv* env, jclass clazz); + registerNatives = (typeof registerNatives)dlsym(libandroid_runtime_dso, + "Java_com_android_internal_util_WithFramework_registerNatives"); + ALOGE_IF(!registerNatives, "DdmConnection: %s", dlerror()); + + if (!JNI_CreateJavaVM || !registerNatives) { + goto error; + } + if (JNI_CreateJavaVM(&vm, &env, &args) == 0) { jclass startClass; jmethodID startMeth; // register native code - if (Java_com_android_internal_util_WithFramework_registerNatives(env, 0) == 0) { + if (registerNatives(env, 0) == 0) { // set our name by calling DdmHandleAppName.setAppName() startClass = env->FindClass("android/ddm/DdmHandleAppName"); if (startClass) { @@ -70,6 +94,15 @@ void DdmConnection::start(const char* name) { } } } + return; + +error: + if (libandroid_runtime_dso) { + dlclose(libandroid_runtime_dso); + } + if (libdvm_dso) { + dlclose(libdvm_dso); + } } }; // namespace android diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp new file mode 100644 index 0000000..2289444 --- /dev/null +++ b/services/surfaceflinger/DisplayDevice.cpp @@ -0,0 +1,298 @@ +/* + * 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. + */ + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <math.h> + +#include <cutils/properties.h> + +#include <utils/RefBase.h> +#include <utils/Log.h> + +#include <ui/DisplayInfo.h> +#include <ui/PixelFormat.h> + +#include <gui/SurfaceTextureClient.h> + +#include <GLES/gl.h> +#include <EGL/egl.h> +#include <EGL/eglext.h> + +#include <hardware/gralloc.h> + +#include "DisplayHardware/FramebufferSurface.h" +#include "DisplayHardware/HWComposer.h" + +#include "DisplayDevice.h" +#include "GLExtensions.h" +#include "SurfaceFlinger.h" +#include "LayerBase.h" + +// ---------------------------------------------------------------------------- +using namespace android; +// ---------------------------------------------------------------------------- + +static __attribute__((noinline)) +void checkGLErrors() +{ + do { + // there could be more than one error flag + GLenum error = glGetError(); + if (error == GL_NO_ERROR) + break; + ALOGE("GL error 0x%04x", int(error)); + } while(true); +} + +// ---------------------------------------------------------------------------- + +/* + * Initialize the display to the specified values. + * + */ + +DisplayDevice::DisplayDevice( + const sp<SurfaceFlinger>& flinger, + int display, + const sp<ANativeWindow>& nativeWindow, + const sp<FramebufferSurface>& framebufferSurface, + EGLConfig config) + : mFlinger(flinger), + mId(display), + mNativeWindow(nativeWindow), + mFramebufferSurface(framebufferSurface), + mDisplay(EGL_NO_DISPLAY), + mSurface(EGL_NO_SURFACE), + mContext(EGL_NO_CONTEXT), + mDisplayWidth(), mDisplayHeight(), mFormat(), + mFlags(), + mPageFlipCount(), + mSecureLayerVisible(false), + mScreenAcquired(false), + mOrientation(), + mLayerStack(0) +{ + init(config); +} + +DisplayDevice::~DisplayDevice() { + if (mSurface != EGL_NO_SURFACE) { + eglDestroySurface(mDisplay, mSurface); + mSurface = EGL_NO_SURFACE; + } +} + +bool DisplayDevice::isValid() const { + return mFlinger != NULL; +} + +int DisplayDevice::getWidth() const { + return mDisplayWidth; +} + +int DisplayDevice::getHeight() const { + return mDisplayHeight; +} + +PixelFormat DisplayDevice::getFormat() const { + return mFormat; +} + +EGLSurface DisplayDevice::getEGLSurface() const { + return mSurface; +} + +void DisplayDevice::init(EGLConfig config) +{ + ANativeWindow* const window = mNativeWindow.get(); + + int format; + window->query(window, NATIVE_WINDOW_FORMAT, &format); + + /* + * Create our display's surface + */ + + EGLSurface surface; + EGLint w, h; + EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + surface = eglCreateWindowSurface(display, config, window, NULL); + eglQuerySurface(display, surface, EGL_WIDTH, &mDisplayWidth); + eglQuerySurface(display, surface, EGL_HEIGHT, &mDisplayHeight); + + mDisplay = display; + mSurface = surface; + mFormat = format; + mPageFlipCount = 0; + + // external displays are always considered enabled + mScreenAcquired = mId >= DisplayDevice::DISPLAY_ID_COUNT; + + // initialize the display orientation transform. + DisplayDevice::setOrientation(DisplayState::eOrientationDefault); +} + +uint32_t DisplayDevice::getPageFlipCount() const { + return mPageFlipCount; +} + +status_t DisplayDevice::compositionComplete() const { + if (mFramebufferSurface == NULL) { + return NO_ERROR; + } + return mFramebufferSurface->compositionComplete(); +} + +void DisplayDevice::flip(const Region& dirty) const +{ + checkGLErrors(); + + EGLDisplay dpy = mDisplay; + EGLSurface surface = mSurface; + +#ifdef EGL_ANDROID_swap_rectangle + if (mFlags & SWAP_RECTANGLE) { + const Region newDirty(dirty.intersect(bounds())); + const Rect b(newDirty.getBounds()); + eglSetSwapRectangleANDROID(dpy, surface, + b.left, b.top, b.width(), b.height()); + } +#endif + + mPageFlipCount++; +} + +uint32_t DisplayDevice::getFlags() const +{ + return mFlags; +} + +void DisplayDevice::dump(String8& res) const +{ + if (mFramebufferSurface != NULL) { + mFramebufferSurface->dump(res); + } +} + +void DisplayDevice::makeCurrent(const sp<const DisplayDevice>& hw, EGLContext ctx) { + EGLSurface sur = eglGetCurrentSurface(EGL_DRAW); + if (sur != hw->mSurface) { + EGLDisplay dpy = eglGetCurrentDisplay(); + eglMakeCurrent(dpy, hw->mSurface, hw->mSurface, ctx); + } +} + +// ---------------------------------------------------------------------------- + +void DisplayDevice::setVisibleLayersSortedByZ(const Vector< sp<LayerBase> >& layers) { + mVisibleLayersSortedByZ = layers; + mSecureLayerVisible = false; + size_t count = layers.size(); + for (size_t i=0 ; i<count ; i++) { + if (layers[i]->isSecure()) { + mSecureLayerVisible = true; + } + } +} + +Vector< sp<LayerBase> > DisplayDevice::getVisibleLayersSortedByZ() const { + return mVisibleLayersSortedByZ; +} + +bool DisplayDevice::getSecureLayerVisible() const { + return mSecureLayerVisible; +} + +Region DisplayDevice::getDirtyRegion(bool repaintEverything) const { + Region dirty; + const Transform& planeTransform(mGlobalTransform); + if (repaintEverything) { + dirty.set(getBounds()); + } else { + dirty = planeTransform.transform(this->dirtyRegion); + dirty.andSelf(getBounds()); + } + return dirty; +} + +// ---------------------------------------------------------------------------- + +bool DisplayDevice::canDraw() const { + return mScreenAcquired; +} + +void DisplayDevice::releaseScreen() const { + mScreenAcquired = false; +} + +void DisplayDevice::acquireScreen() const { + mScreenAcquired = true; +} + +bool DisplayDevice::isScreenAcquired() const { + return mScreenAcquired; +} + +// ---------------------------------------------------------------------------- + +void DisplayDevice::setLayerStack(uint32_t stack) { + mLayerStack = stack; + dirtyRegion.set(bounds()); +} + +// ---------------------------------------------------------------------------- + +status_t DisplayDevice::orientationToTransfrom( + int orientation, int w, int h, Transform* tr) +{ + uint32_t flags = 0; + switch (orientation) { + case DisplayState::eOrientationDefault: + flags = Transform::ROT_0; + break; + case DisplayState::eOrientation90: + flags = Transform::ROT_90; + break; + case DisplayState::eOrientation180: + flags = Transform::ROT_180; + break; + case DisplayState::eOrientation270: + flags = Transform::ROT_270; + break; + default: + return BAD_VALUE; + } + tr->set(flags, w, h); + return NO_ERROR; +} + +status_t DisplayDevice::setOrientation(int orientation) { + int w = mDisplayWidth; + int h = mDisplayHeight; + + DisplayDevice::orientationToTransfrom( + orientation, w, h, &mGlobalTransform); + if (orientation & DisplayState::eOrientationSwapMask) { + int tmp = w; + w = h; + h = tmp; + } + mOrientation = orientation; + dirtyRegion.set(bounds()); + return NO_ERROR; +} diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h new file mode 100644 index 0000000..9790699 --- /dev/null +++ b/services/surfaceflinger/DisplayDevice.h @@ -0,0 +1,178 @@ +/* + * 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_DISPLAY_DEVICE_H +#define ANDROID_DISPLAY_DEVICE_H + +#include <stdlib.h> + +#include <ui/PixelFormat.h> +#include <ui/Region.h> + +#include <EGL/egl.h> +#include <EGL/eglext.h> + +#include <utils/Mutex.h> +#include <utils/Timers.h> + +#include "Transform.h" + +struct ANativeWindow; + +namespace android { + +class DisplayInfo; +class FramebufferSurface; +class LayerBase; +class SurfaceFlinger; + +class DisplayDevice : public LightRefBase<DisplayDevice> +{ +public: + // region in layer-stack space + mutable Region dirtyRegion; + // region in screen space + mutable Region swapRegion; + // region in screen space + Region undefinedRegion; + + enum { + DISPLAY_ID_MAIN = 0, + DISPLAY_ID_HDMI = 1, + DISPLAY_ID_COUNT + }; + + enum { + PARTIAL_UPDATES = 0x00020000, // video driver feature + SWAP_RECTANGLE = 0x00080000, + }; + + DisplayDevice( + const sp<SurfaceFlinger>& flinger, + int dpy, + const sp<ANativeWindow>& nativeWindow, + const sp<FramebufferSurface>& framebufferSurface, + EGLConfig config); + + ~DisplayDevice(); + + // whether this is a valid object. An invalid DisplayDevice is returned + // when an non existing id is requested + bool isValid() const; + + // Flip the front and back buffers if the back buffer is "dirty". Might + // be instantaneous, might involve copying the frame buffer around. + void flip(const Region& dirty) const; + + int getWidth() const; + int getHeight() const; + PixelFormat getFormat() const; + uint32_t getFlags() const; + + EGLSurface getEGLSurface() const; + + void setVisibleLayersSortedByZ(const Vector< sp<LayerBase> >& layers); + Vector< sp<LayerBase> > getVisibleLayersSortedByZ() const; + bool getSecureLayerVisible() const; + Region getDirtyRegion(bool repaintEverything) const; + + status_t setOrientation(int orientation); + void setLayerStack(uint32_t stack); + + int getOrientation() const { return mOrientation; } + const Transform& getTransform() const { return mGlobalTransform; } + uint32_t getLayerStack() const { return mLayerStack; } + int32_t getDisplayId() const { return mId; } + + status_t compositionComplete() const; + + Rect getBounds() const { + return Rect(mDisplayWidth, mDisplayHeight); + } + inline Rect bounds() const { return getBounds(); } + + static void makeCurrent(const sp<const DisplayDevice>& hw, EGLContext ctx); + + /* ------------------------------------------------------------------------ + * blank / unplank management + */ + void releaseScreen() const; + void acquireScreen() const; + bool isScreenAcquired() const; + bool canDraw() const; + + /* ------------------------------------------------------------------------ + * Debugging + */ + uint32_t getPageFlipCount() const; + void dump(String8& res) const; + + inline bool operator < (const DisplayDevice& rhs) const { + return mId < rhs.mId; + } + +private: + void init(EGLConfig config); + + /* + * Constants, set during initialization + */ + sp<SurfaceFlinger> mFlinger; + int32_t mId; + + // ANativeWindow this display is rendering into + sp<ANativeWindow> mNativeWindow; + + // set if mNativeWindow is a FramebufferSurface + sp<FramebufferSurface> mFramebufferSurface; + + EGLDisplay mDisplay; + EGLSurface mSurface; + EGLContext mContext; + int mDisplayWidth; + int mDisplayHeight; + PixelFormat mFormat; + uint32_t mFlags; + mutable uint32_t mPageFlipCount; + + /* + * Can only accessed from the main thread, these members + * don't need synchronization. + */ + + // list of visible layers on that display + Vector< sp<LayerBase> > mVisibleLayersSortedByZ; + + // Whether we have a visible secure layer on this display + bool mSecureLayerVisible; + + // Whether the screen is blanked; + mutable int mScreenAcquired; + + + /* + * Transaction state + */ + static status_t orientationToTransfrom(int orientation, int w, int h, + Transform* tr); + Transform mGlobalTransform; + int mOrientation; + uint32_t mLayerStack; +}; + +}; // namespace android + +#endif // ANDROID_DISPLAY_DEVICE_H diff --git a/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp b/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp deleted file mode 100644 index bb93215..0000000 --- a/services/surfaceflinger/DisplayHardware/DisplayHardware.cpp +++ /dev/null @@ -1,481 +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. - */ - -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <math.h> - -#include <cutils/properties.h> - -#include <utils/RefBase.h> -#include <utils/Log.h> - -#include <ui/PixelFormat.h> -#include <ui/FramebufferNativeWindow.h> - -#include <GLES/gl.h> -#include <EGL/egl.h> -#include <EGL/eglext.h> - -#include "DisplayHardware/DisplayHardware.h" - -#include <hardware/gralloc.h> - -#include "DisplayHardwareBase.h" -#include "GLExtensions.h" -#include "HWComposer.h" -#include "SurfaceFlinger.h" - -using namespace android; - - -static __attribute__((noinline)) -void checkGLErrors() -{ - do { - // there could be more than one error flag - GLenum error = glGetError(); - if (error == GL_NO_ERROR) - break; - ALOGE("GL error 0x%04x", int(error)); - } while(true); -} - -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)", - token, int(error), EGLUtils::strerror(error)); - } -} - -/* - * Initialize the display to the specified values. - * - */ - -DisplayHardware::DisplayHardware( - const sp<SurfaceFlinger>& flinger, - uint32_t dpy) - : DisplayHardwareBase(flinger, dpy), - mFlinger(flinger), mFlags(0), mHwc(0) -{ - init(dpy); -} - -DisplayHardware::~DisplayHardware() -{ - fini(); -} - -float DisplayHardware::getDpiX() const { return mDpiX; } -float DisplayHardware::getDpiY() const { return mDpiY; } -float DisplayHardware::getDensity() const { return mDensity; } -float DisplayHardware::getRefreshRate() const { return mRefreshRate; } -int DisplayHardware::getWidth() const { return mWidth; } -int DisplayHardware::getHeight() const { return mHeight; } -PixelFormat DisplayHardware::getFormat() const { return mFormat; } -uint32_t DisplayHardware::getMaxTextureSize() const { return mMaxTextureSize; } - -uint32_t DisplayHardware::getMaxViewportDims() const { - return mMaxViewportDims[0] < mMaxViewportDims[1] ? - mMaxViewportDims[0] : mMaxViewportDims[1]; -} - -static status_t selectConfigForPixelFormat( - EGLDisplay dpy, - EGLint const* attrs, - PixelFormat format, - EGLConfig* outConfig) -{ - EGLConfig config = NULL; - EGLint numConfigs = -1, n=0; - eglGetConfigs(dpy, NULL, 0, &numConfigs); - EGLConfig* const configs = new EGLConfig[numConfigs]; - eglChooseConfig(dpy, attrs, configs, numConfigs, &n); - for (int i=0 ; i<n ; i++) { - EGLint nativeVisualId = 0; - eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId); - if (nativeVisualId>0 && format == nativeVisualId) { - *outConfig = configs[i]; - delete [] configs; - return NO_ERROR; - } - } - delete [] configs; - return NAME_NOT_FOUND; -} - - -void DisplayHardware::init(uint32_t dpy) -{ - mNativeWindow = new FramebufferNativeWindow(); - framebuffer_device_t const * fbDev = mNativeWindow->getDevice(); - if (!fbDev) { - ALOGE("Display subsystem failed to initialize. check logs. exiting..."); - exit(0); - } - - int format; - ANativeWindow const * const window = mNativeWindow.get(); - window->query(window, NATIVE_WINDOW_FORMAT, &format); - mDpiX = mNativeWindow->xdpi; - mDpiY = mNativeWindow->ydpi; - mRefreshRate = fbDev->fps; - - if (mDpiX == 0 || mDpiY == 0) { - ALOGE("invalid screen resolution from fb HAL (xdpi=%f, ydpi=%f), " - "defaulting to 160 dpi", mDpiX, mDpiY); - mDpiX = mDpiY = 160; - } - - class Density { - static int getDensityFromProperty(char const* propName) { - char property[PROPERTY_VALUE_MAX]; - int density = 0; - if (property_get(propName, property, NULL) > 0) { - density = atoi(property); - } - return density; - } - public: - static int getEmuDensity() { - return getDensityFromProperty("qemu.sf.lcd_density"); } - static int getBuildDensity() { - return getDensityFromProperty("ro.sf.lcd_density"); } - }; - - - // The density of the device is provided by a build property - mDensity = Density::getBuildDensity() / 160.0f; - - if (mDensity == 0) { - // the build doesn't provide a density -- this is wrong! - // use xdpi instead - ALOGE("ro.sf.lcd_density must be defined as a build property"); - mDensity = mDpiX / 160.0f; - } - - if (Density::getEmuDensity()) { - // if "qemu.sf.lcd_density" is specified, it overrides everything - mDpiX = mDpiY = mDensity = Density::getEmuDensity(); - mDensity /= 160.0f; - } - - - - /* FIXME: this is a temporary HACK until we are able to report the refresh rate - * properly from the HAL. The WindowManagerService now relies on this value. - */ -#ifndef REFRESH_RATE - mRefreshRate = fbDev->fps; -#else - mRefreshRate = REFRESH_RATE; -#warning "refresh rate set via makefile to REFRESH_RATE" -#endif - - mRefreshPeriod = nsecs_t(1e9 / mRefreshRate); - - EGLint w, h, dummy; - EGLint numConfigs=0; - EGLSurface surface; - EGLContext context; - EGLBoolean result; - status_t err; - - // initialize EGL - EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_NONE, 0, - EGL_NONE - }; - - // debug: disable h/w rendering - char property[PROPERTY_VALUE_MAX]; - if (property_get("debug.sf.hw", property, NULL) > 0) { - if (atoi(property) == 0) { - ALOGW("H/W composition disabled"); - attribs[2] = EGL_CONFIG_CAVEAT; - attribs[3] = EGL_SLOW_CONFIG; - } - } - - // TODO: all the extensions below should be queried through - // eglGetProcAddress(). - - EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - eglInitialize(display, NULL, NULL); - eglGetConfigs(display, NULL, 0, &numConfigs); - - EGLConfig config = NULL; - err = selectConfigForPixelFormat(display, attribs, format, &config); - ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format"); - - EGLint r,g,b,a; - eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r); - eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g); - eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b); - eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a); - - if (mNativeWindow->isUpdateOnDemand()) { - mFlags |= PARTIAL_UPDATES; - } - - if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) { - if (dummy == EGL_SLOW_CONFIG) - mFlags |= SLOW_CONFIG; - } - - /* - * Create our main surface - */ - - surface = eglCreateWindowSurface(display, config, mNativeWindow.get(), NULL); - eglQuerySurface(display, surface, EGL_WIDTH, &mWidth); - eglQuerySurface(display, surface, EGL_HEIGHT, &mHeight); - - if (mFlags & PARTIAL_UPDATES) { - // if we have partial updates, we definitely don't need to - // preserve the backbuffer, which may be costly. - eglSurfaceAttrib(display, surface, - EGL_SWAP_BEHAVIOR, EGL_BUFFER_DESTROYED); - } - - /* - * Create our OpenGL ES context - */ - - EGLint contextAttributes[] = { -#ifdef EGL_IMG_context_priority -#ifdef HAS_CONTEXT_PRIORITY -#warning "using EGL_IMG_context_priority" - EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG, -#endif -#endif - EGL_NONE, EGL_NONE - }; - context = eglCreateContext(display, config, NULL, contextAttributes); - - mDisplay = display; - mConfig = config; - mSurface = surface; - mContext = context; - mFormat = fbDev->format; - mPageFlipCount = 0; - - /* - * Gather OpenGL ES extensions - */ - - result = eglMakeCurrent(display, surface, surface, context); - if (!result) { - ALOGE("Couldn't create a working GLES context. check logs. exiting..."); - exit(0); - } - - GLExtensions& extensions(GLExtensions::getInstance()); - extensions.initWithGLStrings( - glGetString(GL_VENDOR), - glGetString(GL_RENDERER), - glGetString(GL_VERSION), - glGetString(GL_EXTENSIONS), - eglQueryString(display, EGL_VENDOR), - eglQueryString(display, EGL_VERSION), - eglQueryString(display, EGL_EXTENSIONS)); - - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize); - glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims); - - ALOGI("EGL informations:"); - ALOGI("# of configs : %d", numConfigs); - ALOGI("vendor : %s", extensions.getEglVendor()); - ALOGI("version : %s", extensions.getEglVersion()); - ALOGI("extensions: %s", extensions.getEglExtension()); - ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported"); - ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config); - - ALOGI("OpenGL informations:"); - ALOGI("vendor : %s", extensions.getVendor()); - ALOGI("renderer : %s", extensions.getRenderer()); - ALOGI("version : %s", extensions.getVersion()); - ALOGI("extensions: %s", extensions.getExtension()); - ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize); - ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]); - ALOGI("flags = %08x", mFlags); - - // Unbind the context from this thread - eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - - - // initialize the H/W composer - mHwc = new HWComposer(mFlinger, *this, mRefreshPeriod); - if (mHwc->initCheck() == NO_ERROR) { - mHwc->setFrameBuffer(mDisplay, mSurface); - } -} - -void DisplayHardware::setVSyncHandler(const sp<VSyncHandler>& handler) { - Mutex::Autolock _l(mLock); - mVSyncHandler = handler; -} - -void DisplayHardware::eventControl(int event, int enabled) { - if (event == EVENT_VSYNC) { - mPowerHAL.vsyncHint(enabled); - } - mHwc->eventControl(event, enabled); -} - -void DisplayHardware::onVSyncReceived(int dpy, nsecs_t timestamp) { - sp<VSyncHandler> handler; - { // scope for the lock - Mutex::Autolock _l(mLock); - mLastHwVSync = timestamp; - if (mVSyncHandler != NULL) { - handler = mVSyncHandler.promote(); - } - } - - if (handler != NULL) { - handler->onVSyncReceived(dpy, timestamp); - } -} - -HWComposer& DisplayHardware::getHwComposer() const { - return *mHwc; -} - -/* - * Clean up. Throw out our local state. - * - * (It's entirely possible we'll never get here, since this is meant - * for real hardware, which doesn't restart.) - */ - -void DisplayHardware::fini() -{ - eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - eglTerminate(mDisplay); -} - -void DisplayHardware::releaseScreen() const -{ - DisplayHardwareBase::releaseScreen(); - if (mHwc->initCheck() == NO_ERROR) { - mHwc->release(); - } -} - -void DisplayHardware::acquireScreen() const -{ - DisplayHardwareBase::acquireScreen(); -} - -uint32_t DisplayHardware::getPageFlipCount() const { - return mPageFlipCount; -} - -nsecs_t DisplayHardware::getRefreshTimestamp() const { - // this returns the last refresh timestamp. - // if the last one is not available, we estimate it based on - // the refresh period and whatever closest timestamp we have. - Mutex::Autolock _l(mLock); - nsecs_t now = systemTime(CLOCK_MONOTONIC); - return now - ((now - mLastHwVSync) % mRefreshPeriod); -} - -nsecs_t DisplayHardware::getRefreshPeriod() const { - return mRefreshPeriod; -} - -status_t DisplayHardware::compositionComplete() const { - return mNativeWindow->compositionComplete(); -} - -void DisplayHardware::flip(const Region& dirty) const -{ - checkGLErrors(); - - EGLDisplay dpy = mDisplay; - EGLSurface surface = mSurface; - -#ifdef EGL_ANDROID_swap_rectangle - if (mFlags & SWAP_RECTANGLE) { - const Region newDirty(dirty.intersect(bounds())); - const Rect b(newDirty.getBounds()); - eglSetSwapRectangleANDROID(dpy, surface, - b.left, b.top, b.width(), b.height()); - } -#endif - - if (mFlags & PARTIAL_UPDATES) { - mNativeWindow->setUpdateRectangle(dirty.getBounds()); - } - - mPageFlipCount++; - - if (mHwc->initCheck() == NO_ERROR) { - mHwc->commit(); - } else { - eglSwapBuffers(dpy, surface); - } - checkEGLErrors("eglSwapBuffers"); - - // for debugging - //glClearColor(1,0,0,0); - //glClear(GL_COLOR_BUFFER_BIT); -} - -uint32_t DisplayHardware::getFlags() const -{ - return mFlags; -} - -void DisplayHardware::makeCurrent() const -{ - eglMakeCurrent(mDisplay, mSurface, mSurface, mContext); -} - -void DisplayHardware::dump(String8& res) const -{ - mNativeWindow->dump(res); -} diff --git a/services/surfaceflinger/DisplayHardware/DisplayHardware.h b/services/surfaceflinger/DisplayHardware/DisplayHardware.h deleted file mode 100644 index 0604031..0000000 --- a/services/surfaceflinger/DisplayHardware/DisplayHardware.h +++ /dev/null @@ -1,152 +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_DISPLAY_HARDWARE_H -#define ANDROID_DISPLAY_HARDWARE_H - -#include <stdlib.h> - -#include <ui/PixelFormat.h> -#include <ui/Region.h> - -#include <GLES/gl.h> -#include <GLES/glext.h> -#include <EGL/egl.h> -#include <EGL/eglext.h> - -#include "GLExtensions.h" - -#include "DisplayHardware/DisplayHardwareBase.h" -#include "HWComposer.h" -#include "PowerHAL.h" - -namespace android { - -class FramebufferNativeWindow; - -class DisplayHardware : - public DisplayHardwareBase, - public HWComposer::EventHandler -{ -public: - - class VSyncHandler : virtual public RefBase { - friend class DisplayHardware; - virtual void onVSyncReceived(int dpy, nsecs_t timestamp) = 0; - protected: - virtual ~VSyncHandler() {} - }; - - enum { - COPY_BITS_EXTENSION = 0x00000008, - PARTIAL_UPDATES = 0x00020000, // video driver feature - SLOW_CONFIG = 0x00040000, // software - SWAP_RECTANGLE = 0x00080000, - }; - - DisplayHardware( - const sp<SurfaceFlinger>& flinger, - uint32_t displayIndex); - - virtual ~DisplayHardware(); - - void releaseScreen() const; - void acquireScreen() const; - - // Flip the front and back buffers if the back buffer is "dirty". Might - // be instantaneous, might involve copying the frame buffer around. - void flip(const Region& dirty) const; - - float getDpiX() const; - float getDpiY() const; - float getRefreshRate() const; - float getDensity() const; - int getWidth() const; - int getHeight() const; - PixelFormat getFormat() const; - uint32_t getFlags() const; - uint32_t getMaxTextureSize() const; - uint32_t getMaxViewportDims() const; - nsecs_t getRefreshPeriod() const; - nsecs_t getRefreshTimestamp() const; - void makeCurrent() const; - - - void setVSyncHandler(const sp<VSyncHandler>& handler); - - enum { - EVENT_VSYNC = HWC_EVENT_VSYNC - }; - - void eventControl(int event, int enabled); - - - uint32_t getPageFlipCount() const; - EGLDisplay getEGLDisplay() const { return mDisplay; } - - void dump(String8& res) const; - - // Hardware Composer - HWComposer& getHwComposer() const; - - status_t compositionComplete() const; - - Rect getBounds() const { - return Rect(mWidth, mHeight); - } - inline Rect bounds() const { return getBounds(); } - -private: - virtual void onVSyncReceived(int dpy, nsecs_t timestamp); - void init(uint32_t displayIndex) __attribute__((noinline)); - void fini() __attribute__((noinline)); - - sp<SurfaceFlinger> mFlinger; - EGLDisplay mDisplay; - EGLSurface mSurface; - EGLContext mContext; - EGLConfig mConfig; - float mDpiX; - float mDpiY; - float mRefreshRate; - float mDensity; - int mWidth; - int mHeight; - PixelFormat mFormat; - uint32_t mFlags; - mutable uint32_t mPageFlipCount; - GLint mMaxViewportDims[2]; - GLint mMaxTextureSize; - - nsecs_t mRefreshPeriod; - mutable nsecs_t mLastHwVSync; - - // constant once set - HWComposer* mHwc; - PowerHAL mPowerHAL; - - - mutable Mutex mLock; - - // protected by mLock - wp<VSyncHandler> mVSyncHandler; - - sp<FramebufferNativeWindow> mNativeWindow; -}; - -}; // namespace android - -#endif // ANDROID_DISPLAY_HARDWARE_H diff --git a/services/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp b/services/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp deleted file mode 100644 index d3a8bde..0000000 --- a/services/surfaceflinger/DisplayHardware/DisplayHardwareBase.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (C) 2012 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 <errno.h> -#include <stdlib.h> -#include <stdio.h> -#include <string.h> - -#include <unistd.h> -#include <fcntl.h> - -#include <utils/Log.h> - -#include "DisplayHardware/DisplayHardwareBase.h" -#include "SurfaceFlinger.h" - -// ---------------------------------------------------------------------------- -namespace android { - -static char const * const kSleepFileName = "/sys/power/wait_for_fb_sleep"; -static char const * const kWakeFileName = "/sys/power/wait_for_fb_wake"; - -// ---------------------------------------------------------------------------- - -DisplayHardwareBase::DisplayEventThread::DisplayEventThread( - const sp<SurfaceFlinger>& flinger) - : Thread(false), mFlinger(flinger) { -} - -DisplayHardwareBase::DisplayEventThread::~DisplayEventThread() { -} - -status_t DisplayHardwareBase::DisplayEventThread::initCheck() const { - return ((access(kSleepFileName, R_OK) == 0 && - access(kWakeFileName, R_OK) == 0)) ? NO_ERROR : NO_INIT; -} - -bool DisplayHardwareBase::DisplayEventThread::threadLoop() { - - if (waitForFbSleep() == NO_ERROR) { - sp<SurfaceFlinger> flinger = mFlinger.promote(); - ALOGD("About to give-up screen, flinger = %p", flinger.get()); - if (flinger != 0) { - flinger->screenReleased(); - } - if (waitForFbWake() == NO_ERROR) { - ALOGD("Screen about to return, flinger = %p", flinger.get()); - if (flinger != 0) { - flinger->screenAcquired(); - } - return true; - } - } - - // error, exit the thread - return false; -} - -status_t DisplayHardwareBase::DisplayEventThread::waitForFbSleep() { - int err = 0; - char buf; - int fd = open(kSleepFileName, O_RDONLY, 0); - // if the file doesn't exist, the error will be caught in read() below - do { - err = read(fd, &buf, 1); - } while (err < 0 && errno == EINTR); - close(fd); - ALOGE_IF(err<0, "*** ANDROID_WAIT_FOR_FB_SLEEP failed (%s)", strerror(errno)); - return err < 0 ? -errno : int(NO_ERROR); -} - -status_t DisplayHardwareBase::DisplayEventThread::waitForFbWake() { - int err = 0; - char buf; - int fd = open(kWakeFileName, O_RDONLY, 0); - // if the file doesn't exist, the error will be caught in read() below - do { - err = read(fd, &buf, 1); - } while (err < 0 && errno == EINTR); - close(fd); - ALOGE_IF(err<0, "*** ANDROID_WAIT_FOR_FB_WAKE failed (%s)", strerror(errno)); - return err < 0 ? -errno : int(NO_ERROR); -} - -// ---------------------------------------------------------------------------- - -DisplayHardwareBase::DisplayHardwareBase(const sp<SurfaceFlinger>& flinger, - uint32_t displayIndex) -{ - mScreenAcquired = true; - mDisplayEventThread = new DisplayEventThread(flinger); -} - -void DisplayHardwareBase::startSleepManagement() const { - if (mDisplayEventThread->initCheck() == NO_ERROR) { - mDisplayEventThread->run("DisplayEventThread", PRIORITY_URGENT_DISPLAY); - } else { - ALOGW("/sys/power/wait_for_fb_{wake|sleep} don't exist"); - } -} - -DisplayHardwareBase::~DisplayHardwareBase() { - // request exit - mDisplayEventThread->requestExitAndWait(); -} - -bool DisplayHardwareBase::canDraw() const { - return mScreenAcquired; -} - -void DisplayHardwareBase::releaseScreen() const { - mScreenAcquired = false; -} - -void DisplayHardwareBase::acquireScreen() const { - mScreenAcquired = true; -} - -bool DisplayHardwareBase::isScreenAcquired() const { - return mScreenAcquired; -} - -}; // namespace android diff --git a/services/surfaceflinger/DisplayHardware/DisplayHardwareBase.h b/services/surfaceflinger/DisplayHardware/DisplayHardwareBase.h deleted file mode 100644 index 6857481..0000000 --- a/services/surfaceflinger/DisplayHardware/DisplayHardwareBase.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2012 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_DISPLAY_HARDWARE_BASE_H -#define ANDROID_DISPLAY_HARDWARE_BASE_H - -#include <stdint.h> -#include <utils/RefBase.h> -#include <utils/StrongPointer.h> -#include <utils/threads.h> - -namespace android { - -class SurfaceFlinger; - -class DisplayHardwareBase -{ -public: - DisplayHardwareBase( - const sp<SurfaceFlinger>& flinger, - uint32_t displayIndex); - - ~DisplayHardwareBase(); - - void startSleepManagement() const; - - // console management - void releaseScreen() const; - void acquireScreen() const; - bool isScreenAcquired() const; - - bool canDraw() const; - - -private: - class DisplayEventThread : public Thread { - wp<SurfaceFlinger> mFlinger; - status_t waitForFbSleep(); - status_t waitForFbWake(); - public: - DisplayEventThread(const sp<SurfaceFlinger>& flinger); - virtual ~DisplayEventThread(); - virtual bool threadLoop(); - status_t initCheck() const; - }; - - sp<DisplayEventThread> mDisplayEventThread; - mutable int mScreenAcquired; -}; - -}; // namespace android - -#endif // ANDROID_DISPLAY_HARDWARE_BASE_H diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp new file mode 100644 index 0000000..6d33592 --- /dev/null +++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp @@ -0,0 +1,203 @@ +/* + ** + ** Copyright 2012 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 <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include <cutils/log.h> + +#include <utils/String8.h> + +#include <ui/Rect.h> + +#include <EGL/egl.h> + +#include <hardware/hardware.h> +#include <gui/SurfaceTextureClient.h> +#include <ui/GraphicBuffer.h> + +#include "DisplayHardware/FramebufferSurface.h" + +// ---------------------------------------------------------------------------- +namespace android { +// ---------------------------------------------------------------------------- + +sp<FramebufferSurface> FramebufferSurface::create() { + sp<FramebufferSurface> result = new FramebufferSurface(); + if (result->fbDev == NULL) { + result = NULL; + } + return result; +} + +// ---------------------------------------------------------------------------- + +class GraphicBufferAlloc : public BnGraphicBufferAlloc { +public: + GraphicBufferAlloc() { }; + virtual ~GraphicBufferAlloc() { }; + virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h, + PixelFormat format, uint32_t usage, status_t* error) { + sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage)); + return graphicBuffer; + } +}; + + +/* + * This implements the (main) framebuffer management. This class is used + * mostly by SurfaceFlinger, but also by command line GL application. + * + */ + +FramebufferSurface::FramebufferSurface(): + ConsumerBase(new BufferQueue(true, NUM_FRAME_BUFFERS, + new GraphicBufferAlloc())), + fbDev(0), + mCurrentBufferSlot(-1), + mCurrentBuffer(0) +{ + hw_module_t const* module; + + if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module) == 0) { + int stride; + int err; + int i; + err = framebuffer_open(module, &fbDev); + ALOGE_IF(err, "couldn't open framebuffer HAL (%s)", strerror(-err)); + + // bail out if we can't initialize the modules + if (!fbDev) + return; + + mName = "FramebufferSurface"; + mBufferQueue->setConsumerName(mName); + mBufferQueue->setConsumerUsageBits(GRALLOC_USAGE_HW_FB | + GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_COMPOSER); + mBufferQueue->setDefaultBufferFormat(fbDev->format); + mBufferQueue->setDefaultBufferSize(fbDev->width, fbDev->height); + mBufferQueue->setSynchronousMode(true); + mBufferQueue->setBufferCountServer(NUM_FRAME_BUFFERS); + } else { + ALOGE("Couldn't get gralloc module"); + } +} + +status_t FramebufferSurface::nextBuffer(sp<GraphicBuffer>* buffer) { + Mutex::Autolock lock(mMutex); + + BufferQueue::BufferItem item; + status_t err = acquireBufferLocked(&item); + if (err == BufferQueue::NO_BUFFER_AVAILABLE) { + if (buffer != NULL) { + *buffer = mCurrentBuffer; + } + return NO_ERROR; + } else if (err != NO_ERROR) { + ALOGE("error acquiring buffer: %s (%d)", strerror(-err), err); + return err; + } + + // If the BufferQueue has freed and reallocated a buffer in mCurrentSlot + // then we may have acquired the slot we already own. If we had released + // our current buffer before we call acquireBuffer then that release call + // would have returned STALE_BUFFER_SLOT, and we would have called + // freeBufferLocked on that slot. Because the buffer slot has already + // been overwritten with the new buffer all we have to do is skip the + // releaseBuffer call and we should be in the same state we'd be in if we + // had released the old buffer first. + if (mCurrentBufferSlot != BufferQueue::INVALID_BUFFER_SLOT && + item.mBuf != mCurrentBufferSlot) { + // Release the previous buffer. + err = releaseBufferLocked(mCurrentBufferSlot, EGL_NO_DISPLAY, + EGL_NO_SYNC_KHR, Fence::NO_FENCE); + if (err != NO_ERROR && err != BufferQueue::STALE_BUFFER_SLOT) { + ALOGE("error releasing buffer: %s (%d)", strerror(-err), err); + return err; + } + } + + mCurrentBufferSlot = item.mBuf; + mCurrentBuffer = mSlots[mCurrentBufferSlot].mGraphicBuffer; + if (item.mFence != NULL) { + item.mFence->wait(Fence::TIMEOUT_NEVER); + } + + if (buffer != NULL) { + *buffer = mCurrentBuffer; + } + + return NO_ERROR; +} + +FramebufferSurface::~FramebufferSurface() { + if (fbDev) { + framebuffer_close(fbDev); + } +} + +void FramebufferSurface::onFrameAvailable() { + // XXX: The following code is here temporarily as part of the transition + // away from the framebuffer HAL. + sp<GraphicBuffer> buf; + status_t err = nextBuffer(&buf); + if (err != NO_ERROR) { + ALOGE("error latching next FramebufferSurface buffer: %s (%d)", + strerror(-err), err); + return; + } + err = fbDev->post(fbDev, buf->handle); + if (err != NO_ERROR) { + ALOGE("error posting framebuffer: %d", err); + } +} + +void FramebufferSurface::freeBufferLocked(int slotIndex) { + ConsumerBase::freeBufferLocked(slotIndex); + if (slotIndex == mCurrentBufferSlot) { + mCurrentBufferSlot = BufferQueue::INVALID_BUFFER_SLOT; + } +} + +status_t FramebufferSurface::setUpdateRectangle(const Rect& r) +{ + return INVALID_OPERATION; +} + +status_t FramebufferSurface::compositionComplete() +{ + if (fbDev->compositionComplete) { + return fbDev->compositionComplete(fbDev); + } + return INVALID_OPERATION; +} + +void FramebufferSurface::dump(String8& result) { + if (fbDev->common.version >= 1 && fbDev->dump) { + const size_t SIZE = 4096; + char buffer[SIZE]; + fbDev->dump(fbDev, buffer, SIZE); + result.append(buffer); + } + ConsumerBase::dump(result); +} + +// ---------------------------------------------------------------------------- +}; // namespace android +// ---------------------------------------------------------------------------- diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.h b/services/surfaceflinger/DisplayHardware/FramebufferSurface.h new file mode 100644 index 0000000..bfa500b --- /dev/null +++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.h @@ -0,0 +1,83 @@ +/* + * 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_SF_FRAMEBUFFER_SURFACE_H +#define ANDROID_SF_FRAMEBUFFER_SURFACE_H + +#include <stdint.h> +#include <sys/types.h> + +#include <gui/ConsumerBase.h> + +#define NUM_FRAME_BUFFERS 2 + +// --------------------------------------------------------------------------- +namespace android { +// --------------------------------------------------------------------------- + +class Rect; +class String8; + +// --------------------------------------------------------------------------- + +class FramebufferSurface : public ConsumerBase { +public: + + static sp<FramebufferSurface> create(); + + bool isUpdateOnDemand() const { return false; } + status_t setUpdateRectangle(const Rect& updateRect); + status_t compositionComplete(); + + virtual void dump(String8& result); + + // nextBuffer waits for and then latches the next buffer from the + // BufferQueue and releases the previously latched buffer to the + // BufferQueue. The new buffer is returned in the 'buffer' argument. + status_t nextBuffer(sp<GraphicBuffer>* buffer); + + // FIXME: currently there are information we can only get from the + // FB HAL, and FB HAL can only be instantiated once on some devices. + // Eventually this functionality will have to move in HWC or somewhere else. + const framebuffer_device_t* getFbHal() const { + return fbDev; + } + +private: + FramebufferSurface(); + virtual ~FramebufferSurface(); // this class cannot be overloaded + + virtual void onFrameAvailable(); + virtual void freeBufferLocked(int slotIndex); + + framebuffer_device_t* fbDev; + + // mCurrentBufferIndex is the slot index of the current buffer or + // INVALID_BUFFER_SLOT to indicate that either there is no current buffer + // or the buffer is not associated with a slot. + int mCurrentBufferSlot; + + // mCurrentBuffer is the current buffer or NULL to indicate that there is + // no current buffer. + sp<GraphicBuffer> mCurrentBuffer; +}; + +// --------------------------------------------------------------------------- +}; // namespace android +// --------------------------------------------------------------------------- + +#endif // ANDROID_SF_FRAMEBUFFER_SURFACE_H + diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp index 65763db..a3ec352 100644 --- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp +++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp @@ -16,6 +16,9 @@ #define ATRACE_TAG ATRACE_TAG_GRAPHICS +// Uncomment this to remove support for HWC_DEVICE_API_VERSION_0_3 and older +// #define HWC_REMOVE_DEPRECATED_VERSIONS 1 + #include <stdint.h> #include <stdio.h> #include <stdlib.h> @@ -28,63 +31,227 @@ #include <utils/Trace.h> #include <utils/Vector.h> +#include <ui/GraphicBuffer.h> + #include <hardware/hardware.h> #include <hardware/hwcomposer.h> #include <cutils/log.h> #include <cutils/properties.h> -#include <EGL/egl.h> - +#include "Layer.h" // needed only for debugging #include "LayerBase.h" #include "HWComposer.h" #include "SurfaceFlinger.h" namespace android { + +// --------------------------------------------------------------------------- +// Support for HWC_DEVICE_API_VERSION_0_3 and older: +// Since v0.3 is deprecated and support will be dropped soon, as much as +// possible the code is written to target v1.0. When using a v0.3 HWC, we +// allocate v0.3 structures, but assign them to v1.0 pointers. + +#if HWC_REMOVE_DEPRECATED_VERSIONS +// We need complete types to satisfy semantic checks, even though the code +// paths that use these won't get executed at runtime (and will likely be dead- +// code-eliminated). When we remove the code to support v0.3 we can remove +// these as well. +typedef hwc_layer_1_t hwc_layer_t; +typedef hwc_display_contents_1_t hwc_layer_list_t; +typedef hwc_composer_device_1_t hwc_composer_device_t; +#endif + +// This function assumes we've already rejected HWC's with lower-than-required +// versions. Don't use it for the initial "does HWC meet requirements" check! +static bool hwcHasVersion(const hwc_composer_device_1_t* hwc, uint32_t version) { + if (HWC_REMOVE_DEPRECATED_VERSIONS && + version <= HWC_DEVICE_API_VERSION_1_0) { + return true; + } else { + return hwc->common.version >= version; + } +} + +static bool hwcHasVsyncEvent(const hwc_composer_device_1_t* hwc) { + return hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_0_3); +} + +static size_t sizeofHwcLayerList(const hwc_composer_device_1_t* hwc, + size_t numLayers) { + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + return sizeof(hwc_display_contents_1_t) + numLayers*sizeof(hwc_layer_1_t); + } else { + return sizeof(hwc_layer_list_t) + numLayers*sizeof(hwc_layer_t); + } +} + +static int hwcEventControl(hwc_composer_device_1_t* hwc, int dpy, + int event, int enabled) { + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + return hwc->methods->eventControl(hwc, dpy, event, enabled); + } else { + hwc_composer_device_t* hwc0 = reinterpret_cast<hwc_composer_device_t*>(hwc); + return hwc0->methods->eventControl(hwc0, event, enabled); + } +} + +static int hwcBlank(hwc_composer_device_1_t* hwc, int dpy, int blank) { + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + return hwc->methods->blank(hwc, dpy, blank); + } else { + if (blank) { + hwc_composer_device_t* hwc0 = reinterpret_cast<hwc_composer_device_t*>(hwc); + return hwc0->set(hwc0, NULL, NULL, NULL); + } else { + // HWC 0.x turns the screen on at the next set() + return NO_ERROR; + } + } +} + +static int hwcPrepare(hwc_composer_device_1_t* hwc, + size_t numDisplays, hwc_display_contents_1_t** displays) { + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + return hwc->prepare(hwc, numDisplays, displays); + } else { + hwc_composer_device_t* hwc0 = reinterpret_cast<hwc_composer_device_t*>(hwc); + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(displays[0]); + // In the past, SurfaceFlinger would pass a NULL list when doing full + // OpenGL ES composition. I don't know what, if any, dependencies there + // are on this behavior, so I'm playing it safe and preserving it. + if (list0->numHwLayers == 0) + return hwc0->prepare(hwc0, NULL); + else + return hwc0->prepare(hwc0, list0); + } +} + +static int hwcSet(hwc_composer_device_1_t* hwc, EGLDisplay dpy, EGLSurface sur, + size_t numDisplays, hwc_display_contents_1_t** displays) { + int err; + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + displays[0]->dpy = dpy; + displays[0]->sur = sur; + err = hwc->set(hwc, numDisplays, displays); + } else { + hwc_composer_device_t* hwc0 = reinterpret_cast<hwc_composer_device_t*>(hwc); + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(displays[0]); + err = hwc0->set(hwc0, dpy, sur, list0); + } + return err; +} + +static uint32_t& hwcFlags(hwc_composer_device_1_t* hwc, + hwc_display_contents_1_t* display) { + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + return display->flags; + } else { + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(display); + return list0->flags; + } +} + +static size_t& hwcNumHwLayers(hwc_composer_device_1_t* hwc, + hwc_display_contents_1_t* display) { + if (hwcHasVersion(hwc, HWC_DEVICE_API_VERSION_1_0)) { + return display->numHwLayers; + } else { + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(display); + return list0->numHwLayers; + } +} + +// --------------------------------------------------------------------------- + +struct HWComposer::cb_context { + struct callbacks : public hwc_procs_t { + // these are here to facilitate the transition when adding + // new callbacks (an implementation can check for NULL before + // calling a new callback). + void (*zero[4])(void); + }; + callbacks procs; + HWComposer* hwc; +}; + // --------------------------------------------------------------------------- HWComposer::HWComposer( const sp<SurfaceFlinger>& flinger, EventHandler& handler, - nsecs_t refreshPeriod) + framebuffer_device_t const* fbDev) : mFlinger(flinger), - mModule(0), mHwc(0), mList(0), mCapacity(0), + mModule(0), mHwc(0), mCapacity(0), mNumOVLayers(0), mNumFBLayers(0), - mDpy(EGL_NO_DISPLAY), mSur(EGL_NO_SURFACE), - mEventHandler(handler), - mRefreshPeriod(refreshPeriod), + mCBContext(new cb_context), + mEventHandler(handler), mRefreshPeriod(0), mVSyncCount(0), mDebugForceFakeVSync(false) { + for (size_t i = 0; i < MAX_DISPLAYS; i++) + mLists[i] = NULL; + char value[PROPERTY_VALUE_MAX]; property_get("debug.sf.no_hw_vsync", value, "0"); mDebugForceFakeVSync = atoi(value); - bool needVSyncThread = false; + bool needVSyncThread = true; int err = hw_get_module(HWC_HARDWARE_MODULE_ID, &mModule); ALOGW_IF(err, "%s module not found", HWC_HARDWARE_MODULE_ID); if (err == 0) { - err = hwc_open(mModule, &mHwc); + err = hwc_open_1(mModule, &mHwc); ALOGE_IF(err, "%s device failed to initialize (%s)", HWC_HARDWARE_COMPOSER, strerror(-err)); if (err == 0) { - if (mHwc->registerProcs) { - mCBContext.hwc = this; - mCBContext.procs.invalidate = &hook_invalidate; - mCBContext.procs.vsync = &hook_vsync; - mHwc->registerProcs(mHwc, &mCBContext.procs); - memset(mCBContext.procs.zero, 0, sizeof(mCBContext.procs.zero)); + if (HWC_REMOVE_DEPRECATED_VERSIONS && + mHwc->common.version < HWC_DEVICE_API_VERSION_1_0) { + ALOGE("%s device version %#x too old, will not be used", + HWC_HARDWARE_COMPOSER, mHwc->common.version); + hwc_close_1(mHwc); + mHwc = NULL; } - if (mHwc->common.version >= HWC_DEVICE_API_VERSION_0_3) { - if (mDebugForceFakeVSync) { - // make sure to turn h/w vsync off in "fake vsync" mode - mHwc->methods->eventControl(mHwc, HWC_EVENT_VSYNC, 0); + } + + if (mHwc) { + // always turn vsync off when we start + needVSyncThread = false; + if (hwcHasVsyncEvent(mHwc)) { + hwcEventControl(mHwc, 0, HWC_EVENT_VSYNC, 0); + + int period; + if (mHwc->query(mHwc, HWC_VSYNC_PERIOD, &period) == NO_ERROR) { + mRefreshPeriod = nsecs_t(period); } } else { needVSyncThread = true; } + + if (mHwc->registerProcs) { + mCBContext->hwc = this; + mCBContext->procs.invalidate = &hook_invalidate; + mCBContext->procs.vsync = &hook_vsync; + mHwc->registerProcs(mHwc, &mCBContext->procs); + memset(mCBContext->procs.zero, 0, sizeof(mCBContext->procs.zero)); + } + + // create initial empty display contents for display 0 + createWorkList(MAIN, 0); } - } else { - needVSyncThread = true; + } + + + if (fbDev) { + if (mRefreshPeriod == 0) { + mRefreshPeriod = nsecs_t(1e9 / fbDev->fps); + ALOGW("getting VSYNC period from fb HAL: %lld", mRefreshPeriod); + } + mDpiX = fbDev->xdpi; + mDpiY = fbDev->ydpi; + } + + if (mRefreshPeriod == 0) { + mRefreshPeriod = nsecs_t(1e9 / 60.0); + ALOGW("getting VSYNC period thin air: %lld", mRefreshPeriod); } if (needVSyncThread) { @@ -94,14 +261,16 @@ HWComposer::HWComposer( } HWComposer::~HWComposer() { - eventControl(EVENT_VSYNC, 0); - free(mList); + hwcEventControl(mHwc, 0, EVENT_VSYNC, 0); + for (size_t i = 0; i < MAX_DISPLAYS; i++) + free(mLists[i]); if (mVSyncThread != NULL) { mVSyncThread->requestExitAndWait(); } if (mHwc) { - hwc_close(mHwc); + hwc_close_1(mHwc); } + delete mCBContext; } status_t HWComposer::initCheck() const { @@ -123,13 +292,36 @@ void HWComposer::invalidate() { void HWComposer::vsync(int dpy, int64_t timestamp) { ATRACE_INT("VSYNC", ++mVSyncCount&1); mEventHandler.onVSyncReceived(dpy, timestamp); + Mutex::Autolock _l(mLock); + mLastHwVSync = timestamp; +} + +nsecs_t HWComposer::getRefreshPeriod() const { + return mRefreshPeriod; +} + +nsecs_t HWComposer::getRefreshTimestamp() const { + // this returns the last refresh timestamp. + // if the last one is not available, we estimate it based on + // the refresh period and whatever closest timestamp we have. + Mutex::Autolock _l(mLock); + nsecs_t now = systemTime(CLOCK_MONOTONIC); + return now - ((now - mLastHwVSync) % mRefreshPeriod); +} + +float HWComposer::getDpiX() const { + return mDpiX; +} + +float HWComposer::getDpiY() const { + return mDpiY; } void HWComposer::eventControl(int event, int enabled) { status_t err = NO_ERROR; if (mHwc && mHwc->common.version >= HWC_DEVICE_API_VERSION_0_3) { if (!mDebugForceFakeVSync) { - err = mHwc->methods->eventControl(mHwc, event, enabled); + err = hwcEventControl(mHwc, 0, event, enabled); // error here should not happen -- not sure what we should // do if it does. ALOGE_IF(err, "eventControl(%d, %d) failed %s", @@ -142,37 +334,65 @@ void HWComposer::eventControl(int event, int enabled) { } } -void HWComposer::setFrameBuffer(EGLDisplay dpy, EGLSurface sur) { - mDpy = (hwc_display_t)dpy; - mSur = (hwc_surface_t)sur; -} +status_t HWComposer::createWorkList(int32_t id, size_t numLayers) { + // FIXME: handle multiple displays + if (uint32_t(id) >= MAX_DISPLAYS) + return BAD_INDEX; -status_t HWComposer::createWorkList(size_t numLayers) { if (mHwc) { - if (!mList || mCapacity < numLayers) { - free(mList); - size_t size = sizeof(hwc_layer_list) + numLayers*sizeof(hwc_layer_t); - mList = (hwc_layer_list_t*)malloc(size); + // TODO: must handle multiple displays here + // mLists[0] is NULL only when this is called from the constructor + if (!mLists[0] || mCapacity < numLayers) { + free(mLists[0]); + size_t size = sizeofHwcLayerList(mHwc, numLayers); + mLists[0] = (hwc_display_contents_1_t*)malloc(size); mCapacity = numLayers; } - mList->flags = HWC_GEOMETRY_CHANGED; - mList->numHwLayers = numLayers; + hwcFlags(mHwc, mLists[0]) = HWC_GEOMETRY_CHANGED; + hwcNumHwLayers(mHwc, mLists[0]) = numLayers; + if (hwcHasVersion(mHwc, HWC_DEVICE_API_VERSION_1_0)) { + mLists[0]->flipFenceFd = -1; + } } return NO_ERROR; } status_t HWComposer::prepare() const { - int err = mHwc->prepare(mHwc, mList); + int err = hwcPrepare(mHwc, 1, + const_cast<hwc_display_contents_1_t**>(mLists)); if (err == NO_ERROR) { + + // here we're just making sure that "skip" layers are set + // to HWC_FRAMEBUFFER and we're also counting how many layers + // we have of each type. + // It would be nice if we could get rid of this entirely, which I + // think is almost possible. + + // TODO: must handle multiple displays here + size_t numOVLayers = 0; size_t numFBLayers = 0; - size_t count = mList->numHwLayers; + size_t count = getNumLayers(0); + for (size_t i=0 ; i<count ; i++) { - hwc_layer& l(mList->hwLayers[i]); - if (l.flags & HWC_SKIP_LAYER) { - l.compositionType = HWC_FRAMEBUFFER; + int compositionType; + if (hwcHasVersion(mHwc, HWC_DEVICE_API_VERSION_1_0)) { + hwc_layer_1_t* l = &mLists[0]->hwLayers[i]; + if (l->flags & HWC_SKIP_LAYER) { + l->compositionType = HWC_FRAMEBUFFER; + } + compositionType = l->compositionType; + } else { + // mList really has hwc_layer_list_t memory layout + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(mLists[0]); + hwc_layer_t* l = &list0->hwLayers[i]; + if (l->flags & HWC_SKIP_LAYER) { + l->compositionType = HWC_FRAMEBUFFER; + } + compositionType = l->compositionType; } - switch (l.compositionType) { + + switch (compositionType) { case HWC_OVERLAY: numOVLayers++; break; @@ -187,7 +407,15 @@ status_t HWComposer::prepare() const { return (status_t)err; } -size_t HWComposer::getLayerCount(int type) const { +size_t HWComposer::getLayerCount(int32_t id, int type) const { + // FIXME: handle multiple displays + if (uint32_t(id) >= MAX_DISPLAYS) { + // FIXME: in practice this is only use to know + // if we have at least one layer of type. + return (type == HWC_FRAMEBUFFER) ? 1 : 0; + } + + switch (type) { case HWC_OVERLAY: return mNumOVLayers; @@ -197,57 +425,274 @@ size_t HWComposer::getLayerCount(int type) const { return 0; } -status_t HWComposer::commit() const { - int err = mHwc->set(mHwc, mDpy, mSur, mList); - if (mList) { - mList->flags &= ~HWC_GEOMETRY_CHANGED; +status_t HWComposer::commit(void* fbDisplay, void* fbSurface) const { + int err = NO_ERROR; + if (mHwc) { + err = hwcSet(mHwc, fbDisplay, fbSurface, 1, + const_cast<hwc_display_contents_1_t**>(mLists)); + if (hwcHasVersion(mHwc, HWC_DEVICE_API_VERSION_1_0)) { + if (mLists[0]->flipFenceFd != -1) { + close(mLists[0]->flipFenceFd); + mLists[0]->flipFenceFd = -1; + } + } + hwcFlags(mHwc, mLists[0]) &= ~HWC_GEOMETRY_CHANGED; } return (status_t)err; } status_t HWComposer::release() const { if (mHwc) { - if (mHwc->common.version >= HWC_DEVICE_API_VERSION_0_3) { - mHwc->methods->eventControl(mHwc, HWC_EVENT_VSYNC, 0); + if (hwcHasVsyncEvent(mHwc)) { + hwcEventControl(mHwc, 0, HWC_EVENT_VSYNC, 0); } - int err = mHwc->set(mHwc, NULL, NULL, NULL); - return (status_t)err; + return (status_t)hwcBlank(mHwc, 0, 1); + } + return NO_ERROR; +} + +status_t HWComposer::acquire() const { + if (mHwc) { + return (status_t)hwcBlank(mHwc, 0, 0); } return NO_ERROR; } status_t HWComposer::disable() { if (mHwc) { - free(mList); - mList = NULL; - int err = mHwc->prepare(mHwc, NULL); + hwcNumHwLayers(mHwc, mLists[0]) = 0; + int err = hwcPrepare(mHwc, 1, mLists); return (status_t)err; } return NO_ERROR; } -size_t HWComposer::getNumLayers() const { - return mList ? mList->numHwLayers : 0; +size_t HWComposer::getNumLayers(int32_t id) const { // FIXME: handle multiple displays + return mHwc ? hwcNumHwLayers(mHwc, mLists[0]) : 0; +} + +/* + * Helper template to implement a concrete HWCLayer + * This holds the pointer to the concrete hwc layer type + * and implements the "iterable" side of HWCLayer. + */ +template<typename CONCRETE, typename HWCTYPE> +class Iterable : public HWComposer::HWCLayer { +protected: + HWCTYPE* const mLayerList; + HWCTYPE* mCurrentLayer; + Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { } + inline HWCTYPE const * getLayer() const { return mCurrentLayer; } + inline HWCTYPE* getLayer() { return mCurrentLayer; } + virtual ~Iterable() { } +private: + // returns a copy of ourselves + virtual HWComposer::HWCLayer* dup() { + return new CONCRETE( static_cast<const CONCRETE&>(*this) ); + } + virtual status_t setLayer(size_t index) { + mCurrentLayer = &mLayerList[index]; + return NO_ERROR; + } +}; + +// #if !HWC_REMOVE_DEPRECATED_VERSIONS +/* + * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_0_3 + * This implements the HWCLayer side of HWCIterableLayer. + */ +class HWCLayerVersion0 : public Iterable<HWCLayerVersion0, hwc_layer_t> { +public: + HWCLayerVersion0(hwc_layer_t* layer) + : Iterable<HWCLayerVersion0, hwc_layer_t>(layer) { } + + virtual int32_t getCompositionType() const { + return getLayer()->compositionType; + } + virtual uint32_t getHints() const { + return getLayer()->hints; + } + virtual int getAndResetReleaseFenceFd() { + // not supported on VERSION_03 + return -1; + } + virtual void setAcquireFenceFd(int fenceFd) { + if (fenceFd != -1) { + ALOGE("HWC 0.x can't handle acquire fences"); + close(fenceFd); + } + } + + virtual void setDefaultState() { + getLayer()->compositionType = HWC_FRAMEBUFFER; + getLayer()->hints = 0; + getLayer()->flags = HWC_SKIP_LAYER; + getLayer()->transform = 0; + getLayer()->blending = HWC_BLENDING_NONE; + getLayer()->visibleRegionScreen.numRects = 0; + getLayer()->visibleRegionScreen.rects = NULL; + } + virtual void setSkip(bool skip) { + if (skip) { + getLayer()->flags |= HWC_SKIP_LAYER; + } else { + getLayer()->flags &= ~HWC_SKIP_LAYER; + } + } + virtual void setBlending(uint32_t blending) { + getLayer()->blending = blending; + } + virtual void setTransform(uint32_t transform) { + getLayer()->transform = transform; + } + virtual void setFrame(const Rect& frame) { + reinterpret_cast<Rect&>(getLayer()->displayFrame) = frame; + } + virtual void setCrop(const Rect& crop) { + reinterpret_cast<Rect&>(getLayer()->sourceCrop) = crop; + } + virtual void setVisibleRegionScreen(const Region& reg) { + getLayer()->visibleRegionScreen.rects = + reinterpret_cast<hwc_rect_t const *>( + reg.getArray(&getLayer()->visibleRegionScreen.numRects)); + } + virtual void setBuffer(const sp<GraphicBuffer>& buffer) { + if (buffer == 0 || buffer->handle == 0) { + getLayer()->compositionType = HWC_FRAMEBUFFER; + getLayer()->flags |= HWC_SKIP_LAYER; + getLayer()->handle = 0; + } else { + getLayer()->handle = buffer->handle; + } + } +}; +// #endif // !HWC_REMOVE_DEPRECATED_VERSIONS + +/* + * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0. + * This implements the HWCLayer side of HWCIterableLayer. + */ +class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> { +public: + HWCLayerVersion1(hwc_layer_1_t* layer) + : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer) { } + + virtual int32_t getCompositionType() const { + return getLayer()->compositionType; + } + virtual uint32_t getHints() const { + return getLayer()->hints; + } + virtual int getAndResetReleaseFenceFd() { + int fd = getLayer()->releaseFenceFd; + getLayer()->releaseFenceFd = -1; + return fd; + } + virtual void setAcquireFenceFd(int fenceFd) { + getLayer()->acquireFenceFd = fenceFd; + } + + virtual void setDefaultState() { + getLayer()->compositionType = HWC_FRAMEBUFFER; + getLayer()->hints = 0; + getLayer()->flags = HWC_SKIP_LAYER; + getLayer()->transform = 0; + getLayer()->blending = HWC_BLENDING_NONE; + getLayer()->visibleRegionScreen.numRects = 0; + getLayer()->visibleRegionScreen.rects = NULL; + getLayer()->acquireFenceFd = -1; + getLayer()->releaseFenceFd = -1; + } + virtual void setSkip(bool skip) { + if (skip) { + getLayer()->flags |= HWC_SKIP_LAYER; + } else { + getLayer()->flags &= ~HWC_SKIP_LAYER; + } + } + virtual void setBlending(uint32_t blending) { + getLayer()->blending = blending; + } + virtual void setTransform(uint32_t transform) { + getLayer()->transform = transform; + } + virtual void setFrame(const Rect& frame) { + reinterpret_cast<Rect&>(getLayer()->displayFrame) = frame; + } + virtual void setCrop(const Rect& crop) { + reinterpret_cast<Rect&>(getLayer()->sourceCrop) = crop; + } + virtual void setVisibleRegionScreen(const Region& reg) { + getLayer()->visibleRegionScreen.rects = + reinterpret_cast<hwc_rect_t const *>( + reg.getArray(&getLayer()->visibleRegionScreen.numRects)); + } + virtual void setBuffer(const sp<GraphicBuffer>& buffer) { + if (buffer == 0 || buffer->handle == 0) { + getLayer()->compositionType = HWC_FRAMEBUFFER; + getLayer()->flags |= HWC_SKIP_LAYER; + getLayer()->handle = 0; + } else { + getLayer()->handle = buffer->handle; + } + } +}; + +/* + * returns an iterator initialized at a given index in the layer list + */ +HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) { + // FIXME: handle multiple displays + if (uint32_t(id) >= MAX_DISPLAYS) + return LayerListIterator(); + + if (!mHwc || index > hwcNumHwLayers(mHwc, mLists[0])) + return LayerListIterator(); + if (hwcHasVersion(mHwc, HWC_DEVICE_API_VERSION_1_0)) { + return LayerListIterator(new HWCLayerVersion1(mLists[0]->hwLayers), + index); + } else { + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(mLists[0]); + return LayerListIterator(new HWCLayerVersion0(list0->hwLayers), index); + } +} + +/* + * returns an iterator on the beginning of the layer list + */ +HWComposer::LayerListIterator HWComposer::begin(int32_t id) { + return getLayerIterator(id, 0); } -hwc_layer_t* HWComposer::getLayers() const { - return mList ? mList->hwLayers : 0; +/* + * returns an iterator on the end of the layer list + */ +HWComposer::LayerListIterator HWComposer::end(int32_t id) { + return getLayerIterator(id, getNumLayers(id)); } void HWComposer::dump(String8& result, char* buffer, size_t SIZE, const Vector< sp<LayerBase> >& visibleLayersSortedByZ) const { - if (mHwc && mList) { + if (mHwc) { + hwc_layer_list_t* list0 = reinterpret_cast<hwc_layer_list_t*>(mLists[0]); + result.append("Hardware Composer state:\n"); result.appendFormat(" mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync); result.appendFormat(" numHwLayers=%u, flags=%08x\n", - mList->numHwLayers, mList->flags); + hwcNumHwLayers(mHwc, mLists[0]), hwcFlags(mHwc, mLists[0])); result.append( " type | handle | hints | flags | tr | blend | format | source crop | frame name \n" "----------+----------+----------+----------+----+-------+----------+---------------------------+--------------------------------\n"); // " ________ | ________ | ________ | ________ | __ | _____ | ________ | [_____,_____,_____,_____] | [_____,_____,_____,_____] - for (size_t i=0 ; i<mList->numHwLayers ; i++) { - const hwc_layer_t& l(mList->hwLayers[i]); + for (size_t i=0 ; i<hwcNumHwLayers(mHwc, mLists[0]) ; i++) { + hwc_layer_1_t const* lp; + if (hwcHasVersion(mHwc, HWC_DEVICE_API_VERSION_1_0)) { + lp = &mLists[0]->hwLayers[i]; + } else { + // FIXME: here we rely on hwc_layer_1_t and hwc_layer_t having the same layout + lp = reinterpret_cast<hwc_layer_1_t const*>(&list0->hwLayers[i]); + } const sp<LayerBase> layer(visibleLayersSortedByZ[i]); int32_t format = -1; if (layer->getLayer() != NULL) { @@ -256,6 +701,7 @@ void HWComposer::dump(String8& result, char* buffer, size_t SIZE, format = buffer->getPixelFormat(); } } + const hwc_layer_1_t& l(*lp); result.appendFormat( " %8s | %08x | %08x | %08x | %02x | %05x | %08x | [%5d,%5d,%5d,%5d] | [%5d,%5d,%5d,%5d] %s\n", l.compositionType ? "OVERLAY" : "FB", @@ -265,7 +711,7 @@ void HWComposer::dump(String8& result, char* buffer, size_t SIZE, layer->getName().string()); } } - if (mHwc && mHwc->common.version >= HWC_DEVICE_API_VERSION_0_1 && mHwc->dump) { + if (mHwc && hwcHasVersion(mHwc, HWC_DEVICE_API_VERSION_0_1) && mHwc->dump) { mHwc->dump(mHwc, buffer, SIZE); result.append(buffer); } diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.h b/services/surfaceflinger/DisplayHardware/HWComposer.h index aada3cd..ac2257e 100644 --- a/services/surfaceflinger/DisplayHardware/HWComposer.h +++ b/services/surfaceflinger/DisplayHardware/HWComposer.h @@ -20,23 +20,32 @@ #include <stdint.h> #include <sys/types.h> -#include <EGL/egl.h> - -#include <hardware/hwcomposer.h> +#include <hardware/hwcomposer_defs.h> +#include <utils/Condition.h> +#include <utils/Mutex.h> #include <utils/StrongPointer.h> +#include <utils/Thread.h> +#include <utils/Timers.h> #include <utils/Vector.h> extern "C" int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *request, struct timespec *remain); +struct hwc_composer_device_1; +struct hwc_display_contents_1; +struct hwc_procs; +struct framebuffer_device_t; + namespace android { // --------------------------------------------------------------------------- +class GraphicBuffer; +class LayerBase; +class Region; class String8; class SurfaceFlinger; -class LayerBase; class HWComposer { @@ -48,17 +57,20 @@ public: virtual ~EventHandler() {} }; - HWComposer(const sp<SurfaceFlinger>& flinger, - EventHandler& handler, nsecs_t refreshPeriod); - ~HWComposer(); + enum { + MAIN = 0, + HDMI = 1, + MAX_DISPLAYS + }; - status_t initCheck() const; + HWComposer( + const sp<SurfaceFlinger>& flinger, + EventHandler& handler, + framebuffer_device_t const* fbDev); - // tells the HAL what the framebuffer is - void setFrameBuffer(EGLDisplay dpy, EGLSurface sur); + ~HWComposer(); - // create a work list for numLayers layer. sets HWC_GEOMETRY_CHANGED. - status_t createWorkList(size_t numLayers); + status_t initCheck() const; // Asks the HAL what it can do status_t prepare() const; @@ -67,18 +79,115 @@ public: status_t disable(); // commits the list - status_t commit() const; + status_t commit(void* fbDisplay, void* fbSurface) const; - // release hardware resources + // release hardware resources and blank screen status_t release() const; - // get the layer array created by createWorkList() - size_t getNumLayers() const; - hwc_layer_t* getLayers() const; + // acquire hardware resources and unblank screen + status_t acquire() const; + + // create a work list for numLayers layer. sets HWC_GEOMETRY_CHANGED. + status_t createWorkList(int32_t id, size_t numLayers); // get number of layers of the given type as updated in prepare(). // type is HWC_OVERLAY or HWC_FRAMEBUFFER - size_t getLayerCount(int type) const; + size_t getLayerCount(int32_t id, int type) const; + + // needed forward declarations + class LayerListIterator; + + /* + * Interface to hardware composer's layers functionality. + * This abstracts the HAL interface to layers which can evolve in + * incompatible ways from one release to another. + * The idea is that we could extend this interface as we add + * features to h/w composer. + */ + class HWCLayerInterface { + protected: + virtual ~HWCLayerInterface() { } + public: + virtual int32_t getCompositionType() const = 0; + virtual uint32_t getHints() const = 0; + virtual int getAndResetReleaseFenceFd() = 0; + virtual void setDefaultState() = 0; + virtual void setSkip(bool skip) = 0; + virtual void setBlending(uint32_t blending) = 0; + virtual void setTransform(uint32_t transform) = 0; + virtual void setFrame(const Rect& frame) = 0; + virtual void setCrop(const Rect& crop) = 0; + virtual void setVisibleRegionScreen(const Region& reg) = 0; + virtual void setBuffer(const sp<GraphicBuffer>& buffer) = 0; + virtual void setAcquireFenceFd(int fenceFd) = 0; + }; + + /* + * Interface used to implement an iterator to a list + * of HWCLayer. + */ + class HWCLayer : public HWCLayerInterface { + friend class LayerListIterator; + // select the layer at the given index + virtual status_t setLayer(size_t index) = 0; + virtual HWCLayer* dup() = 0; + static HWCLayer* copy(HWCLayer *rhs) { + return rhs ? rhs->dup() : NULL; + } + protected: + virtual ~HWCLayer() { } + }; + + /* + * Iterator through a HWCLayer list. + * This behaves more or less like a forward iterator. + */ + class LayerListIterator { + friend struct HWComposer; + HWCLayer* const mLayerList; + size_t mIndex; + + LayerListIterator() : mLayerList(NULL), mIndex(0) { } + + LayerListIterator(HWCLayer* layer, size_t index) + : mLayerList(layer), mIndex(index) { } + + // we don't allow assignment, because we don't need it for now + LayerListIterator& operator = (const LayerListIterator& rhs); + + public: + // copy operators + LayerListIterator(const LayerListIterator& rhs) + : mLayerList(HWCLayer::copy(rhs.mLayerList)), mIndex(rhs.mIndex) { + } + + ~LayerListIterator() { delete mLayerList; } + + // pre-increment + LayerListIterator& operator++() { + mLayerList->setLayer(++mIndex); + return *this; + } + + // dereference + HWCLayerInterface& operator * () { return *mLayerList; } + HWCLayerInterface* operator -> () { return mLayerList; } + + // comparison + bool operator == (const LayerListIterator& rhs) const { + return mIndex == rhs.mIndex; + } + bool operator != (const LayerListIterator& rhs) const { + return !operator==(rhs); + } + }; + + // Returns an iterator to the beginning of the layer list + LayerListIterator begin(int32_t id); + + // Returns an iterator to the end of the layer list + LayerListIterator end(int32_t id); + // Events handling --------------------------------------------------------- @@ -88,6 +197,11 @@ public: void eventControl(int event, int enabled); + nsecs_t getRefreshPeriod() const; + nsecs_t getRefreshTimestamp() const; + float getDpiX() const; + float getDpiY() const; + // this class is only used to fake the VSync event on systems that don't // have it. class VSyncThread : public Thread { @@ -112,17 +226,10 @@ public: private: - struct callbacks : public hwc_procs_t { - // these are here to facilitate the transition when adding - // new callbacks (an implementation can check for NULL before - // calling a new callback). - void (*zero[4])(void); - }; + LayerListIterator getLayerIterator(int32_t id, size_t index); + size_t getNumLayers(int32_t id) const; - struct cb_context { - callbacks procs; - HWComposer* hwc; - }; + struct cb_context; static void hook_invalidate(struct hwc_procs* procs); static void hook_vsync(struct hwc_procs* procs, int dpy, int64_t timestamp); @@ -130,23 +237,31 @@ private: inline void invalidate(); inline void vsync(int dpy, int64_t timestamp); - sp<SurfaceFlinger> mFlinger; - hw_module_t const* mModule; - hwc_composer_device_t* mHwc; - hwc_layer_list_t* mList; - size_t mCapacity; - mutable size_t mNumOVLayers; - mutable size_t mNumFBLayers; - hwc_display_t mDpy; - hwc_surface_t mSur; - cb_context mCBContext; - EventHandler& mEventHandler; - nsecs_t mRefreshPeriod; - size_t mVSyncCount; - sp<VSyncThread> mVSyncThread; - bool mDebugForceFakeVSync; -}; + sp<SurfaceFlinger> mFlinger; + hw_module_t const* mModule; + struct hwc_composer_device_1* mHwc; + // invariant: mLists[0] != NULL iff mHwc != NULL + // TODO: decide whether mLists[i>0] should be non-NULL when display i is + // not attached/enabled. + struct hwc_display_contents_1* mLists[MAX_DISPLAYS]; + + size_t mCapacity; + mutable size_t mNumOVLayers; + mutable size_t mNumFBLayers; + cb_context* mCBContext; + EventHandler& mEventHandler; + nsecs_t mRefreshPeriod; + float mDpiX; + float mDpiY; + size_t mVSyncCount; + sp<VSyncThread> mVSyncThread; + bool mDebugForceFakeVSync; + + // protected by mLock + mutable Mutex mLock; + mutable nsecs_t mLastHwVSync; +}; // --------------------------------------------------------------------------- }; // namespace android diff --git a/services/surfaceflinger/EventThread.cpp b/services/surfaceflinger/EventThread.cpp index 7c1aebe..9b61fa9 100644 --- a/services/surfaceflinger/EventThread.cpp +++ b/services/surfaceflinger/EventThread.cpp @@ -24,31 +24,26 @@ #include <gui/DisplayEventReceiver.h> #include <utils/Errors.h> +#include <utils/String8.h> #include <utils/Trace.h> -#include "DisplayHardware/DisplayHardware.h" #include "EventThread.h" #include "SurfaceFlinger.h" // --------------------------------------------------------------------------- - namespace android { - // --------------------------------------------------------------------------- EventThread::EventThread(const sp<SurfaceFlinger>& flinger) : mFlinger(flinger), - mHw(flinger->graphicPlane(0).editDisplayHardware()), mLastVSyncTimestamp(0), mVSyncTimestamp(0), mUseSoftwareVSync(false), mDeliveredEvents(0), - mDebugVsyncEnabled(false) -{ + mDebugVsyncEnabled(false) { } void EventThread::onFirstRef() { - mHw.setVSyncHandler(this); run("EventThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE); } @@ -254,13 +249,15 @@ bool EventThread::threadLoop() { void EventThread::enableVSyncLocked() { if (!mUseSoftwareVSync) { // never enable h/w VSYNC when screen is off - mHw.eventControl(DisplayHardware::EVENT_VSYNC, true); + mFlinger->eventControl(SurfaceFlinger::EVENT_VSYNC, true); + mPowerHAL.vsyncHint(true); } mDebugVsyncEnabled = true; } void EventThread::disableVSyncLocked() { - mHw.eventControl(DisplayHardware::EVENT_VSYNC, false); + mFlinger->eventControl(SurfaceFlinger::EVENT_VSYNC, false); + mPowerHAL.vsyncHint(false); mDebugVsyncEnabled = false; } diff --git a/services/surfaceflinger/EventThread.h b/services/surfaceflinger/EventThread.h index b42cab6..a71d985 100644 --- a/services/surfaceflinger/EventThread.h +++ b/services/surfaceflinger/EventThread.h @@ -27,19 +27,18 @@ #include <utils/threads.h> #include <utils/SortedVector.h> -#include "DisplayHardware/DisplayHardware.h" +#include "DisplayHardware/PowerHAL.h" // --------------------------------------------------------------------------- - namespace android { - // --------------------------------------------------------------------------- class SurfaceFlinger; +class String8; // --------------------------------------------------------------------------- -class EventThread : public Thread, public DisplayHardware::VSyncHandler { +class EventThread : public Thread { class Connection : public BnDisplayEventConnection { public: Connection(const sp<EventThread>& eventThread); @@ -78,13 +77,15 @@ public: // called after the screen is turned on from main thread void onScreenAcquired(); + // called when receiving a vsync event + void onVSyncReceived(int display, nsecs_t timestamp); + void dump(String8& result, char* buffer, size_t SIZE) const; private: virtual bool threadLoop(); virtual status_t readyToRun(); virtual void onFirstRef(); - virtual void onVSyncReceived(int, nsecs_t timestamp); void removeDisplayEventConnection(const wp<Connection>& connection); void enableVSyncLocked(); @@ -92,7 +93,7 @@ private: // constants sp<SurfaceFlinger> mFlinger; - DisplayHardware& mHw; + PowerHAL mPowerHAL; mutable Mutex mLock; mutable Condition mCondition; diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp index 4062340..0825ec6 100644 --- a/services/surfaceflinger/Layer.cpp +++ b/services/surfaceflinger/Layer.cpp @@ -36,13 +36,14 @@ #include <gui/Surface.h> #include "clz.h" -#include "DisplayHardware/DisplayHardware.h" -#include "DisplayHardware/HWComposer.h" +#include "DisplayDevice.h" #include "GLExtensions.h" #include "Layer.h" #include "SurfaceFlinger.h" #include "SurfaceTextureLayer.h" +#include "DisplayHardware/HWComposer.h" + #define DEBUG_RESIZE 0 namespace android { @@ -63,7 +64,6 @@ Layer::Layer(SurfaceFlinger* flinger, mFormat(PIXEL_FORMAT_NONE), mGLExtensions(GLExtensions::getInstance()), mOpaqueLayer(true), - mNeedsDithering(false), mSecure(false), mProtectedByApp(false) { @@ -71,14 +71,10 @@ Layer::Layer(SurfaceFlinger* flinger, glGenTextures(1, &mTextureName); } -void Layer::onLayerDisplayed() { - if (mFrameLatencyNeeded) { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - mFrameStats[mFrameLatencyOffset].timestamp = mSurfaceTexture->getTimestamp(); - mFrameStats[mFrameLatencyOffset].set = systemTime(); - mFrameStats[mFrameLatencyOffset].vsync = hw.getRefreshTimestamp(); - mFrameLatencyOffset = (mFrameLatencyOffset + 1) % 128; - mFrameLatencyNeeded = false; +void Layer::onLayerDisplayed(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface* layer) { + if (layer) { + mSurfaceTexture->setReleaseFence(layer->getAndResetReleaseFenceFd()); } } @@ -117,8 +113,7 @@ void Layer::onFirstRef() Layer::~Layer() { - mFlinger->postMessageAsync( - new SurfaceFlinger::MessageDestroyGLTexture(mTextureName) ); + mFlinger->deleteTextureAsync(mTextureName); } void Layer::onFrameQueued() { @@ -138,14 +133,6 @@ void Layer::setName(const String8& name) { mSurfaceTexture->setName(name); } -void Layer::validateVisibility(const Transform& globalTransform) { - LayerBase::validateVisibility(globalTransform); - - // This optimization allows the SurfaceTexture to bake in - // the rotation so hardware overlays can be used - mSurfaceTexture->setTransformHint(getTransformHint()); -} - sp<ISurface> Layer::createSurface() { class BSurface : public BnSurface, public LayerCleaner { @@ -183,10 +170,8 @@ status_t Layer::setBuffers( uint32_t w, uint32_t h, return err; } - // the display's pixel format - const DisplayHardware& hw(graphicPlane(0).displayHardware()); uint32_t const maxSurfaceDims = min( - hw.getMaxTextureSize(), hw.getMaxViewportDims()); + mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims()); // never allow a surface larger than what our underlying GL implementation // can handle. @@ -195,26 +180,17 @@ status_t Layer::setBuffers( uint32_t w, uint32_t h, return BAD_VALUE; } - PixelFormatInfo displayInfo; - getPixelFormatInfo(hw.getFormat(), &displayInfo); - const uint32_t hwFlags = hw.getFlags(); - mFormat = format; - mSecure = (flags & ISurfaceComposer::eSecure) ? true : false; - mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false; - mOpaqueLayer = (flags & ISurfaceComposer::eOpaque); + mSecure = (flags & ISurfaceComposerClient::eSecure) ? true : false; + mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false; + mOpaqueLayer = (flags & ISurfaceComposerClient::eOpaque); mCurrentOpacity = getOpacityForFormat(format); mSurfaceTexture->setDefaultBufferSize(w, h); mSurfaceTexture->setDefaultBufferFormat(format); mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0)); - // we use the red index - int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED); - int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED); - mNeedsDithering = layerRedsize > displayRedSize; - return NO_ERROR; } @@ -226,7 +202,8 @@ Rect Layer::computeBufferCrop() const { } else if (mActiveBuffer != NULL){ crop = Rect(mActiveBuffer->getWidth(), mActiveBuffer->getHeight()); } else { - crop = Rect(mTransformedBounds.width(), mTransformedBounds.height()); + crop.makeInvalid(); + return crop; } // ... then reduce that in the same proportions as the window crop reduces @@ -259,16 +236,19 @@ Rect Layer::computeBufferCrop() const { return crop; } -void Layer::setGeometry(hwc_layer_t* hwcl) +void Layer::setGeometry( + const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer) { - LayerBaseClient::setGeometry(hwcl); + LayerBaseClient::setGeometry(hw, layer); - hwcl->flags &= ~HWC_SKIP_LAYER; + // enable this layer + layer.setSkip(false); // we can't do alpha-fade with the hwc HAL const State& s(drawingState()); if (s.alpha < 0xFF) { - hwcl->flags = HWC_SKIP_LAYER; + layer.setSkip(true); } /* @@ -276,44 +256,52 @@ void Layer::setGeometry(hwc_layer_t* hwcl) * 1) buffer orientation/flip/mirror * 2) state transformation (window manager) * 3) layer orientation (screen orientation) - * mTransform is already the composition of (2) and (3) * (NOTE: the matrices are multiplied in reverse order) */ const Transform bufferOrientation(mCurrentTransform); - const Transform tr(mTransform * bufferOrientation); + const Transform tr(hw->getTransform() * s.transform * bufferOrientation); // this gives us only the "orientation" component of the transform const uint32_t finalTransform = tr.getOrientation(); // we can only handle simple transformation if (finalTransform & Transform::ROT_INVALID) { - hwcl->flags = HWC_SKIP_LAYER; + layer.setSkip(true); } else { - hwcl->transform = finalTransform; + layer.setTransform(finalTransform); } - - Rect crop = computeBufferCrop(); - hwcl->sourceCrop.left = crop.left; - hwcl->sourceCrop.top = crop.top; - hwcl->sourceCrop.right = crop.right; - hwcl->sourceCrop.bottom = crop.bottom; + layer.setCrop(computeBufferCrop()); } -void Layer::setPerFrameData(hwc_layer_t* hwcl) { +void Layer::setPerFrameData(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer) { const sp<GraphicBuffer>& buffer(mActiveBuffer); - if (buffer == NULL) { - // this can happen if the client never drew into this layer yet, - // or if we ran out of memory. In that case, don't let - // HWC handle it. - hwcl->flags |= HWC_SKIP_LAYER; - hwcl->handle = NULL; - } else { - hwcl->handle = buffer->handle; + // NOTE: buffer can be NULL if the client never drew into this + // layer yet, or if we ran out of memory + layer.setBuffer(buffer); +} + +void Layer::setAcquireFence(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer) { + int fenceFd = -1; + + // TODO: there is a possible optimization here: we only need to set the + // acquire fence the first time a new buffer is acquired on EACH display. + + if (layer.getCompositionType() == HWC_OVERLAY) { + sp<Fence> fence = mSurfaceTexture->getCurrentFence(); + if (fence.get()) { + fenceFd = fence->dup(); + if (fenceFd == -1) { + ALOGW("failed to dup layer fence, skipping sync: %d", errno); + } + } } + layer.setAcquireFenceFd(fenceFd); } -void Layer::onDraw(const Region& clip) const +void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const { ATRACE_CALL(); @@ -335,16 +323,25 @@ void Layer::onDraw(const Region& clip) const const sp<LayerBase>& layer(drawingLayers[i]); if (layer.get() == static_cast<LayerBase const*>(this)) break; - under.orSelf(layer->visibleRegionScreen); + under.orSelf( hw->getTransform().transform(layer->visibleRegion) ); } // if not everything below us is covered, we plug the holes! Region holes(clip.subtract(under)); if (!holes.isEmpty()) { - clearWithOpenGL(holes, 0, 0, 0, 1); + clearWithOpenGL(hw, holes, 0, 0, 0, 1); } return; } + // TODO: replace this with a server-side wait + sp<Fence> fence = mSurfaceTexture->getCurrentFence(); + if (fence.get()) { + status_t err = fence->wait(Fence::TIMEOUT_NEVER); + ALOGW_IF(err != OK, "Layer::onDraw: failed waiting for fence: %d", err); + // Go ahead and draw the buffer anyway; no matter what we do the screen + // is probably going to have something visibly wrong. + } + if (!isProtected()) { // TODO: we could be more subtle with isFixedSize() const bool useFiltering = getFiltering() || needsFiltering() || isFixedSize(); @@ -376,7 +373,7 @@ void Layer::onDraw(const Region& clip) const glEnable(GL_TEXTURE_2D); } - drawWithOpenGL(clip); + drawWithOpenGL(hw, clip); glDisable(GL_TEXTURE_EXTERNAL_OES); glDisable(GL_TEXTURE_2D); @@ -514,10 +511,23 @@ bool Layer::onPreComposition() { return mQueuedFrames > 0; } -void Layer::lockPageFlip(bool& recomputeVisibleRegions) +void Layer::onPostComposition() { + if (mFrameLatencyNeeded) { + const HWComposer& hwc = mFlinger->getHwComposer(); + const size_t offset = mFrameLatencyOffset; + mFrameStats[offset].timestamp = mSurfaceTexture->getTimestamp(); + mFrameStats[offset].set = systemTime(); + mFrameStats[offset].vsync = hwc.getRefreshTimestamp(); + mFrameLatencyOffset = (mFrameLatencyOffset + 1) % 128; + mFrameLatencyNeeded = false; + } +} + +Region Layer::latchBuffer(bool& recomputeVisibleRegions) { ATRACE_CALL(); + Region outDirtyRegion; if (mQueuedFrames > 0) { // if we've already called updateTexImage() without going through @@ -526,8 +536,7 @@ void Layer::lockPageFlip(bool& recomputeVisibleRegions) // compositionComplete() call. // we'll trigger an update in onPreComposition(). if (mRefreshPending) { - mPostedDirtyRegion.clear(); - return; + return outDirtyRegion; } // Capture the old state of the layer for comparisons later @@ -624,17 +633,21 @@ void Layer::lockPageFlip(bool& recomputeVisibleRegions) Reject r(mDrawingState, currentState(), recomputeVisibleRegions); + // XXX: not sure if setTransformHint belongs here + // it should only be needed when the main screen orientation changes + mSurfaceTexture->setTransformHint(getTransformHint()); + if (mSurfaceTexture->updateTexImage(&r) < NO_ERROR) { // something happened! recomputeVisibleRegions = true; - return; + return outDirtyRegion; } // update the active buffer mActiveBuffer = mSurfaceTexture->getCurrentBuffer(); if (mActiveBuffer == NULL) { // this can only happen if the very first buffer was rejected. - return; + return outDirtyRegion; } mRefreshPending = true; @@ -672,38 +685,17 @@ void Layer::lockPageFlip(bool& recomputeVisibleRegions) recomputeVisibleRegions = true; } - // FIXME: mPostedDirtyRegion = dirty & bounds - const Layer::State& front(drawingState()); - mPostedDirtyRegion.set(front.active.w, front.active.h); - glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } -} -void Layer::unlockPageFlip( - const Transform& planeTransform, Region& outDirtyRegion) -{ - ATRACE_CALL(); + // FIXME: postedRegion should be dirty & bounds + const Layer::State& front(drawingState()); + Region dirtyRegion(Rect(front.active.w, front.active.h)); - Region postedRegion(mPostedDirtyRegion); - if (!postedRegion.isEmpty()) { - mPostedDirtyRegion.clear(); - if (!visibleRegionScreen.isEmpty()) { - // The dirty region is given in the layer's coordinate space - // transform the dirty region by the surface's transformation - // and the global transformation. - const Layer::State& s(drawingState()); - const Transform tr(planeTransform * s.transform); - postedRegion = tr.transform(postedRegion); - - // At this point, the dirty region is in screen space. - // Make sure it's constrained by the visible region (which - // is in screen space as well). - postedRegion.andSelf(visibleRegionScreen); - outDirtyRegion.orSelf(postedRegion); - } + // transform the dirty region to window-manager space + outDirtyRegion = (front.transform.transform(dirtyRegion)); } + return outDirtyRegion; } void Layer::dump(String8& result, char* buffer, size_t SIZE) const @@ -736,8 +728,7 @@ void Layer::dumpStats(String8& result, char* buffer, size_t SIZE) const { LayerBaseClient::dumpStats(result, buffer, SIZE); const size_t o = mFrameLatencyOffset; - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const nsecs_t period = hw.getRefreshPeriod(); + const nsecs_t period = mFlinger->getHwComposer().getRefreshPeriod(); result.appendFormat("%lld\n", period); for (size_t i=0 ; i<128 ; i++) { const size_t index = (o+i) % 128; @@ -772,7 +763,14 @@ uint32_t Layer::getEffectiveUsage(uint32_t usage) const uint32_t Layer::getTransformHint() const { uint32_t orientation = 0; if (!mFlinger->mDebugDisableTransformHint) { - orientation = getPlaneOrientation(); + // The transform hint is used to improve performance on the main + // display -- we can only have a single transform hint, it cannot + // apply to all displays. + // This is why we use the default display here. This is not an + // oversight. + sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice()); + const Transform& planeTransform(hw->getTransform()); + orientation = planeTransform.getOrientation(); if (orientation & Transform::ROT_INVALID) { orientation = 0; } diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h index 393599f..d24013b 100644 --- a/services/surfaceflinger/Layer.h +++ b/services/surfaceflinger/Layer.h @@ -64,27 +64,30 @@ public: bool isFixedSize() const; // LayerBase interface - virtual void setGeometry(hwc_layer_t* hwcl); - virtual void setPerFrameData(hwc_layer_t* hwcl); - virtual void onDraw(const Region& clip) const; + virtual void setGeometry(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer); + virtual void setPerFrameData(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer); + virtual void setAcquireFence(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer); + virtual void onLayerDisplayed(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface* layer); + virtual bool onPreComposition(); + virtual void onPostComposition(); + + virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const; virtual uint32_t doTransaction(uint32_t transactionFlags); - virtual void lockPageFlip(bool& recomputeVisibleRegions); - virtual void unlockPageFlip(const Transform& planeTransform, Region& outDirtyRegion); + virtual Region latchBuffer(bool& recomputeVisibleRegions); virtual bool isOpaque() const; - virtual bool needsDithering() const { return mNeedsDithering; } virtual bool isSecure() const { return mSecure; } virtual bool isProtected() const; virtual void onRemoved(); virtual sp<Layer> getLayer() const { return const_cast<Layer*>(this); } virtual void setName(const String8& name); - virtual void validateVisibility(const Transform& globalTransform); // LayerBaseClient interface virtual wp<IBinder> getSurfaceTextureBinder() const; - virtual void onLayerDisplayed(); - virtual bool onPreComposition(); - // only for debugging inline const sp<GraphicBuffer>& getActiveBuffer() const { return mActiveBuffer; } @@ -137,12 +140,10 @@ private: PixelFormat mFormat; const GLExtensions& mGLExtensions; bool mOpaqueLayer; - bool mNeedsDithering; // page-flip thread (currently main thread) bool mSecure; // no screenshots bool mProtectedByApp; // application requires protected path to external sink - Region mPostedDirtyRegion; }; // --------------------------------------------------------------------------- diff --git a/services/surfaceflinger/LayerBase.cpp b/services/surfaceflinger/LayerBase.cpp index 16bac8f..2311e6d 100644 --- a/services/surfaceflinger/LayerBase.cpp +++ b/services/surfaceflinger/LayerBase.cpp @@ -29,9 +29,11 @@ #include <hardware/hardware.h> #include "clz.h" +#include "Client.h" #include "LayerBase.h" +#include "Layer.h" #include "SurfaceFlinger.h" -#include "DisplayHardware/DisplayHardware.h" +#include "DisplayDevice.h" namespace android { @@ -44,13 +46,9 @@ LayerBase::LayerBase(SurfaceFlinger* flinger, DisplayID display) sequence(uint32_t(android_atomic_inc(&sSequence))), mFlinger(flinger), mFiltering(false), mNeedsFiltering(false), - mOrientation(0), - mPlaneOrientation(0), mTransactionFlags(0), mPremultipliedAlpha(true), mName("unnamed"), mDebug(false) { - const DisplayHardware& hw(flinger->graphicPlane(0).displayHardware()); - mFlags = hw.getFlags(); } LayerBase::~LayerBase() @@ -65,23 +63,13 @@ String8 LayerBase::getName() const { return mName; } -const GraphicPlane& LayerBase::graphicPlane(int dpy) const -{ - return mFlinger->graphicPlane(dpy); -} - -GraphicPlane& LayerBase::graphicPlane(int dpy) -{ - return mFlinger->graphicPlane(dpy); -} - void LayerBase::initStates(uint32_t w, uint32_t h, uint32_t flags) { uint32_t layerFlags = 0; - if (flags & ISurfaceComposer::eHidden) - layerFlags = ISurfaceComposer::eLayerHidden; + if (flags & ISurfaceComposerClient::eHidden) + layerFlags = layer_state_t::eLayerHidden; - if (flags & ISurfaceComposer::eNonPremultiplied) + if (flags & ISurfaceComposerClient::eNonPremultiplied) mPremultipliedAlpha = false; mCurrentState.active.w = w; @@ -89,6 +77,7 @@ void LayerBase::initStates(uint32_t w, uint32_t h, uint32_t flags) mCurrentState.active.crop.makeInvalid(); mCurrentState.z = 0; mCurrentState.alpha = 0xFF; + mCurrentState.layerStack = 0; mCurrentState.flags = layerFlags; mCurrentState.sequence = 0; mCurrentState.transform.set(0, 0); @@ -181,19 +170,23 @@ bool LayerBase::setCrop(const Rect& crop) { return true; } -Rect LayerBase::visibleBounds() const -{ - return mTransformedBounds; -} +bool LayerBase::setLayerStack(uint32_t layerStack) { + if (mCurrentState.layerStack == layerStack) + return false; + mCurrentState.sequence++; + mCurrentState.layerStack = layerStack; + requestTransaction(); + return true; +} void LayerBase::setVisibleRegion(const Region& visibleRegion) { // always called from main thread - visibleRegionScreen = visibleRegion; + this->visibleRegion = visibleRegion; } void LayerBase::setCoveredRegion(const Region& coveredRegion) { // always called from main thread - coveredRegionScreen = coveredRegion; + this->coveredRegion = coveredRegion; } uint32_t LayerBase::doTransaction(uint32_t flags) @@ -230,99 +223,82 @@ uint32_t LayerBase::doTransaction(uint32_t flags) return flags; } -void LayerBase::validateVisibility(const Transform& planeTransform) +void LayerBase::computeGeometry(const sp<const DisplayDevice>& hw, LayerMesh* mesh) const { const Layer::State& s(drawingState()); - const Transform tr(planeTransform * s.transform); - const bool transformed = tr.transformed(); - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const uint32_t hw_h = hw.getHeight(); + const Transform tr(hw->getTransform() * s.transform); + const uint32_t hw_h = hw->getHeight(); const Rect& crop(s.active.crop); - Rect win(s.active.w, s.active.h); if (!crop.isEmpty()) { win.intersect(crop, &win); } - - mNumVertices = 4; - tr.transform(mVertices[0], win.left, win.top); - tr.transform(mVertices[1], win.left, win.bottom); - tr.transform(mVertices[2], win.right, win.bottom); - tr.transform(mVertices[3], win.right, win.top); - for (size_t i=0 ; i<4 ; i++) - mVertices[i][1] = hw_h - mVertices[i][1]; - - if (CC_UNLIKELY(transformed)) { - // NOTE: here we could also punt if we have too many rectangles - // in the transparent region - if (tr.preserveRects()) { - // transform the transparent region - transparentRegionScreen = tr.transform(s.transparentRegion); - } else { - // transformation too complex, can't do the transparent region - // optimization. - transparentRegionScreen.clear(); + if (mesh) { + tr.transform(mesh->mVertices[0], win.left, win.top); + tr.transform(mesh->mVertices[1], win.left, win.bottom); + tr.transform(mesh->mVertices[2], win.right, win.bottom); + tr.transform(mesh->mVertices[3], win.right, win.top); + for (size_t i=0 ; i<4 ; i++) { + mesh->mVertices[i][1] = hw_h - mesh->mVertices[i][1]; } - } else { - transparentRegionScreen = s.transparentRegion; } - - // cache a few things... - mOrientation = tr.getOrientation(); - mPlaneOrientation = planeTransform.getOrientation(); - mTransform = tr; - mTransformedBounds = tr.transform(win); } -void LayerBase::lockPageFlip(bool& recomputeVisibleRegions) { +Rect LayerBase::computeBounds() const { + const Layer::State& s(drawingState()); + const Rect& crop(s.active.crop); + Rect win(s.active.w, s.active.h); + if (!crop.isEmpty()) { + win.intersect(crop, &win); + } + return s.transform.transform(win); } -void LayerBase::unlockPageFlip( - const Transform& planeTransform, Region& outDirtyRegion) { +Region LayerBase::latchBuffer(bool& recomputeVisibleRegions) { + Region result; + return result; } -void LayerBase::setGeometry(hwc_layer_t* hwcl) +void LayerBase::setGeometry( + const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer) { - hwcl->compositionType = HWC_FRAMEBUFFER; - hwcl->hints = 0; - hwcl->flags = HWC_SKIP_LAYER; - hwcl->transform = 0; - hwcl->blending = HWC_BLENDING_NONE; + layer.setDefaultState(); // this gives us only the "orientation" component of the transform const State& s(drawingState()); const uint32_t finalTransform = s.transform.getOrientation(); // we can only handle simple transformation if (finalTransform & Transform::ROT_INVALID) { - hwcl->flags = HWC_SKIP_LAYER; + layer.setTransform(0); } else { - hwcl->transform = finalTransform; + layer.setTransform(finalTransform); } if (!isOpaque()) { - hwcl->blending = mPremultipliedAlpha ? - HWC_BLENDING_PREMULT : HWC_BLENDING_COVERAGE; + layer.setBlending(mPremultipliedAlpha ? + HWC_BLENDING_PREMULT : + HWC_BLENDING_COVERAGE); } - // scaling is already applied in mTransformedBounds - hwcl->displayFrame.left = mTransformedBounds.left; - hwcl->displayFrame.top = mTransformedBounds.top; - hwcl->displayFrame.right = mTransformedBounds.right; - hwcl->displayFrame.bottom = mTransformedBounds.bottom; - hwcl->visibleRegionScreen.rects = - reinterpret_cast<hwc_rect_t const *>( - visibleRegionScreen.getArray( - &hwcl->visibleRegionScreen.numRects)); + const Transform& tr = hw->getTransform(); + Rect transformedBounds(computeBounds()); + transformedBounds = tr.transform(transformedBounds); + + // scaling is already applied in transformedBounds + layer.setFrame(transformedBounds); + layer.setCrop(transformedBounds.getBounds()); + layer.setVisibleRegionScreen(tr.transform(visibleRegion)); +} - hwcl->sourceCrop.left = 0; - hwcl->sourceCrop.top = 0; - hwcl->sourceCrop.right = mTransformedBounds.width(); - hwcl->sourceCrop.bottom = mTransformedBounds.height(); +void LayerBase::setPerFrameData(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer) { + layer.setBuffer(0); } -void LayerBase::setPerFrameData(hwc_layer_t* hwcl) { - hwcl->compositionType = HWC_FRAMEBUFFER; - hwcl->handle = NULL; +void LayerBase::setAcquireFence(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer) { + layer.setAcquireFenceFd(-1); } void LayerBase::setFiltering(bool filtering) @@ -335,44 +311,41 @@ bool LayerBase::getFiltering() const return mFiltering; } -void LayerBase::draw(const Region& clip) const +void LayerBase::draw(const sp<const DisplayDevice>& hw, const Region& clip) const { - onDraw(clip); + onDraw(hw, clip); } -void LayerBase::drawForSreenShot() +void LayerBase::draw(const sp<const DisplayDevice>& hw) { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - setFiltering(true); - onDraw( Region(hw.bounds()) ); - setFiltering(false); + onDraw( hw, Region(hw->bounds()) ); } -void LayerBase::clearWithOpenGL(const Region& clip, GLclampf red, - GLclampf green, GLclampf blue, - GLclampf alpha) const +void LayerBase::clearWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip, + GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) const { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const uint32_t fbHeight = hw.getHeight(); + const uint32_t fbHeight = hw->getHeight(); glColor4f(red,green,blue,alpha); glDisable(GL_TEXTURE_EXTERNAL_OES); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); - glVertexPointer(2, GL_FLOAT, 0, mVertices); - glDrawArrays(GL_TRIANGLE_FAN, 0, mNumVertices); + LayerMesh mesh; + computeGeometry(hw, &mesh); + + glVertexPointer(2, GL_FLOAT, 0, mesh.getVertices()); + glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.getVertexCount()); } -void LayerBase::clearWithOpenGL(const Region& clip) const +void LayerBase::clearWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip) const { - clearWithOpenGL(clip,0,0,0,0); + clearWithOpenGL(hw, clip, 0,0,0,0); } -void LayerBase::drawWithOpenGL(const Region& clip) const +void LayerBase::drawWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip) const { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const uint32_t fbHeight = hw.getHeight(); + const uint32_t fbHeight = hw->getHeight(); const State& s(drawingState()); GLenum src = mPremultipliedAlpha ? GL_ONE : GL_SRC_ALPHA; @@ -397,6 +370,12 @@ void LayerBase::drawWithOpenGL(const Region& clip) const } } + LayerMesh mesh; + computeGeometry(hw, &mesh); + + // TODO: we probably want to generate the texture coords with the mesh + // here we assume that we only have 4 vertices + struct TexCoords { GLfloat u; GLfloat v; @@ -406,9 +385,9 @@ void LayerBase::drawWithOpenGL(const Region& clip) const if (!s.active.crop.isEmpty()) { crop = s.active.crop; } - GLfloat left = GLfloat(crop.left) / GLfloat(s.active.w); - GLfloat top = GLfloat(crop.top) / GLfloat(s.active.h); - GLfloat right = GLfloat(crop.right) / GLfloat(s.active.w); + GLfloat left = GLfloat(crop.left) / GLfloat(s.active.w); + GLfloat top = GLfloat(crop.top) / GLfloat(s.active.h); + GLfloat right = GLfloat(crop.right) / GLfloat(s.active.w); GLfloat bottom = GLfloat(crop.bottom) / GLfloat(s.active.h); TexCoords texCoords[4]; @@ -425,9 +404,9 @@ void LayerBase::drawWithOpenGL(const Region& clip) const } glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(2, GL_FLOAT, 0, mVertices); glTexCoordPointer(2, GL_FLOAT, 0, texCoords); - glDrawArrays(GL_TRIANGLE_FAN, 0, mNumVertices); + glVertexPointer(2, GL_FLOAT, 0, mesh.getVertices()); + glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.getVertexCount()); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_BLEND); @@ -443,15 +422,14 @@ void LayerBase::dump(String8& result, char* buffer, size_t SIZE) const result.append(buffer); s.transparentRegion.dump(result, "transparentRegion"); - transparentRegionScreen.dump(result, "transparentRegionScreen"); - visibleRegionScreen.dump(result, "visibleRegionScreen"); + visibleRegion.dump(result, "visibleRegion"); snprintf(buffer, SIZE, " " - "z=%9d, pos=(%g,%g), size=(%4d,%4d), crop=(%4d,%4d,%4d,%4d), " + "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), crop=(%4d,%4d,%4d,%4d), " "isOpaque=%1d, needsDithering=%1d, invalidate=%1d, " "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n", - s.z, s.transform.tx(), s.transform.ty(), s.active.w, s.active.h, + s.z, s.layerStack, s.transform.tx(), s.transform.ty(), s.active.w, s.active.h, s.active.crop.left, s.active.crop.top, s.active.crop.right, s.active.crop.bottom, isOpaque(), needsDithering(), contentDirty, @@ -471,6 +449,14 @@ void LayerBase::dumpStats(String8& result, char* scratch, size_t SIZE) const { void LayerBase::clearStats() { } +sp<LayerBaseClient> LayerBase::getLayerBaseClient() const { + return 0; +} + +sp<Layer> LayerBase::getLayer() const { + return 0; +} + // --------------------------------------------------------------------------- int32_t LayerBaseClient::sIdentity = 1; @@ -554,7 +540,7 @@ LayerBaseClient::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger, LayerBaseClient::LayerCleaner::~LayerCleaner() { // destroy client resources - mFlinger->destroySurface(mLayer); + mFlinger->onLayerDestroyed(mLayer); } // --------------------------------------------------------------------------- diff --git a/services/surfaceflinger/LayerBase.h b/services/surfaceflinger/LayerBase.h index c547a40..6394542 100644 --- a/services/surfaceflinger/LayerBase.h +++ b/services/surfaceflinger/LayerBase.h @@ -25,6 +25,7 @@ #include <GLES/gl.h> #include <utils/RefBase.h> +#include <utils/String8.h> #include <ui/Region.h> @@ -32,19 +33,16 @@ #include <private/gui/LayerState.h> -#include <hardware/hwcomposer.h> - -#include "DisplayHardware/DisplayHardware.h" #include "Transform.h" +#include "DisplayHardware/HWComposer.h" namespace android { // --------------------------------------------------------------------------- class Client; -class DisplayHardware; +class DisplayDevice; class GraphicBuffer; -class GraphicPlane; class Layer; class LayerBaseClient; class SurfaceFlinger; @@ -60,9 +58,9 @@ public: DisplayID dpy; mutable bool contentDirty; - Region visibleRegionScreen; - Region transparentRegionScreen; - Region coveredRegionScreen; + // regions below are in window-manager space + Region visibleRegion; + Region coveredRegion; int32_t sequence; struct Geometry { @@ -81,6 +79,7 @@ public: Geometry active; Geometry requested; uint32_t z; + uint32_t layerStack; uint8_t alpha; uint8_t flags; uint8_t reserved[2]; @@ -89,6 +88,20 @@ public: Region transparentRegion; }; + class LayerMesh { + friend class LayerBase; + GLfloat mVertices[4][2]; + size_t mNumVertices; + public: + LayerMesh() : mNumVertices(4) { } + GLfloat const* getVertices() const { + return &mVertices[0][0]; + } + size_t getVertexCount() const { + return mNumVertices; + } + }; + virtual void setName(const String8& name); String8 getName() const; @@ -101,24 +114,30 @@ public: bool setTransparentRegionHint(const Region& opaque); bool setFlags(uint8_t flags, uint8_t mask); bool setCrop(const Rect& crop); - + bool setLayerStack(uint32_t layerStack); + void commitTransaction(); bool requestTransaction(); void forceVisibilityTransaction(); uint32_t getTransactionFlags(uint32_t flags); uint32_t setTransactionFlags(uint32_t flags); - - Rect visibleBounds() const; - virtual sp<LayerBaseClient> getLayerBaseClient() const { return 0; } - virtual sp<Layer> getLayer() const { return 0; } + void computeGeometry(const sp<const DisplayDevice>& hw, LayerMesh* mesh) const; + Rect computeBounds() const; - virtual const char* getTypeId() const { return "LayerBase"; } - virtual void setGeometry(hwc_layer_t* hwcl); - virtual void setPerFrameData(hwc_layer_t* hwcl); + virtual sp<LayerBaseClient> getLayerBaseClient() const; + virtual sp<Layer> getLayer() const; + + virtual const char* getTypeId() const { return "LayerBase"; } + virtual void setGeometry(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer); + virtual void setPerFrameData(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer); + virtual void setAcquireFence(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface& layer); /** * draw - performs some global clipping optimizations @@ -126,13 +145,13 @@ public: * Typically this method is not overridden, instead implement onDraw() * to perform the actual drawing. */ - virtual void draw(const Region& clip) const; - virtual void drawForSreenShot(); + virtual void draw(const sp<const DisplayDevice>& hw, const Region& clip) const; + virtual void draw(const sp<const DisplayDevice>& hw); /** * onDraw - draws the surface. */ - virtual void onDraw(const Region& clip) const = 0; + virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const = 0; /** * initStates - called just after construction @@ -159,26 +178,13 @@ public: virtual void setCoveredRegion(const Region& coveredRegion); /** - * validateVisibility - cache a bunch of things - */ - virtual void validateVisibility(const Transform& globalTransform); - - /** - * lockPageFlip - called each time the screen is redrawn and returns whether + * latchBuffer - called each time the screen is redrawn and returns whether * the visible regions need to be recomputed (this is a fairly heavy * operation, so this should be set only if needed). Typically this is used * to figure out if the content or size of a surface has changed. */ - virtual void lockPageFlip(bool& recomputeVisibleRegions); - - /** - * unlockPageFlip - called each time the screen is redrawn. updates the - * final dirty region wrt the planeTransform. - * At this point, all visible regions, surface position and size, etc... are - * correct. - */ - virtual void unlockPageFlip(const Transform& planeTransform, Region& outDirtyRegion); - + virtual Region latchBuffer(bool& recomputeVisibleRegions); + /** * isOpaque - true if this surface is opaque */ @@ -212,13 +218,18 @@ public: /** called after page-flip */ - virtual void onLayerDisplayed() { } + virtual void onLayerDisplayed(const sp<const DisplayDevice>& hw, + HWComposer::HWCLayerInterface* layer) { } /** called before composition. * returns true if the layer has pending updates. */ virtual bool onPreComposition() { return false; } + /** called before composition. + */ + virtual void onPostComposition() { } + /** always call base class first */ virtual void dump(String8& result, char* scratch, size_t size) const; virtual void shortDump(String8& result, char* scratch, size_t size) const; @@ -236,43 +247,27 @@ public: inline const State& currentState() const { return mCurrentState; } inline State& currentState() { return mCurrentState; } - int32_t getOrientation() const { return mOrientation; } - int32_t getPlaneOrientation() const { return mPlaneOrientation; } + void clearWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip) const; - void clearWithOpenGL(const Region& clip) const; + void setFiltering(bool filtering); + bool getFiltering() const; protected: - const GraphicPlane& graphicPlane(int dpy) const; - GraphicPlane& graphicPlane(int dpy); - - void clearWithOpenGL(const Region& clip, GLclampf r, GLclampf g, - GLclampf b, GLclampf alpha) const; - void drawWithOpenGL(const Region& clip) const; - - void setFiltering(bool filtering); - bool getFiltering() const; + void clearWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip, + GLclampf r, GLclampf g, GLclampf b, GLclampf alpha) const; + void drawWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip) const; sp<SurfaceFlinger> mFlinger; - uint32_t mFlags; private: // accessed only in the main thread // Whether filtering is forced on or not bool mFiltering; - // cached during validateVisibility() // Whether filtering is needed b/c of the drawingstate bool mNeedsFiltering; protected: - // cached during validateVisibility() - int32_t mOrientation; - int32_t mPlaneOrientation; - Transform mTransform; - GLfloat mVertices[4][2]; - size_t mNumVertices; - Rect mTransformedBounds; - // these are protected by an external lock State mCurrentState; State mDrawingState; diff --git a/services/surfaceflinger/LayerDim.cpp b/services/surfaceflinger/LayerDim.cpp index 96a310f..087d851 100644 --- a/services/surfaceflinger/LayerDim.cpp +++ b/services/surfaceflinger/LayerDim.cpp @@ -18,6 +18,9 @@ #include <stdint.h> #include <sys/types.h> +#include <GLES/gl.h> +#include <GLES/glext.h> + #include <utils/Errors.h> #include <utils/Log.h> @@ -25,7 +28,7 @@ #include "LayerDim.h" #include "SurfaceFlinger.h" -#include "DisplayHardware/DisplayHardware.h" +#include "DisplayDevice.h" namespace android { // --------------------------------------------------------------------------- @@ -40,13 +43,12 @@ LayerDim::~LayerDim() { } -void LayerDim::onDraw(const Region& clip) const +void LayerDim::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const { const State& s(drawingState()); if (s.alpha>0) { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); const GLfloat alpha = s.alpha/255.0f; - const uint32_t fbHeight = hw.getHeight(); + const uint32_t fbHeight = hw->getHeight(); glDisable(GL_TEXTURE_EXTERNAL_OES); glDisable(GL_TEXTURE_2D); @@ -59,8 +61,11 @@ void LayerDim::onDraw(const Region& clip) const glColor4f(0, 0, 0, alpha); - glVertexPointer(2, GL_FLOAT, 0, mVertices); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + LayerMesh mesh; + computeGeometry(hw, &mesh); + + glVertexPointer(2, GL_FLOAT, 0, mesh.getVertices()); + glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.getVertexCount()); glDisable(GL_BLEND); glDisableClientState(GL_TEXTURE_COORD_ARRAY); diff --git a/services/surfaceflinger/LayerDim.h b/services/surfaceflinger/LayerDim.h index 8770e6d..fbfb2fb 100644 --- a/services/surfaceflinger/LayerDim.h +++ b/services/surfaceflinger/LayerDim.h @@ -36,7 +36,7 @@ public: const sp<Client>& client); virtual ~LayerDim(); - virtual void onDraw(const Region& clip) const; + virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const; virtual bool isOpaque() const { return false; } virtual bool isSecure() const { return false; } virtual bool isProtectedByApp() const { return false; } diff --git a/services/surfaceflinger/LayerScreenshot.cpp b/services/surfaceflinger/LayerScreenshot.cpp index b42353c..799ecdc 100644 --- a/services/surfaceflinger/LayerScreenshot.cpp +++ b/services/surfaceflinger/LayerScreenshot.cpp @@ -18,6 +18,9 @@ #include <stdint.h> #include <sys/types.h> +#include <GLES/gl.h> +#include <GLES/glext.h> + #include <utils/Errors.h> #include <utils/Log.h> @@ -25,7 +28,7 @@ #include "LayerScreenshot.h" #include "SurfaceFlinger.h" -#include "DisplayHardware/DisplayHardware.h" +#include "DisplayDevice.h" namespace android { @@ -41,8 +44,7 @@ LayerScreenshot::LayerScreenshot(SurfaceFlinger* flinger, DisplayID display, LayerScreenshot::~LayerScreenshot() { if (mTextureName) { - mFlinger->postMessageAsync( - new SurfaceFlinger::MessageDestroyGLTexture(mTextureName) ); + mFlinger->deleteTextureAsync(mTextureName); } } @@ -78,25 +80,25 @@ void LayerScreenshot::initTexture(GLfloat u, GLfloat v) { void LayerScreenshot::initStates(uint32_t w, uint32_t h, uint32_t flags) { LayerBaseClient::initStates(w, h, flags); - if (!(flags & ISurfaceComposer::eHidden)) { + if (!(flags & ISurfaceComposerClient::eHidden)) { capture(); } } uint32_t LayerScreenshot::doTransaction(uint32_t flags) { - const Layer::State& draw(drawingState()); - const Layer::State& curr(currentState()); + const LayerBase::State& draw(drawingState()); + const LayerBase::State& curr(currentState()); - if (draw.flags & ISurfaceComposer::eLayerHidden) { - if (!(curr.flags & ISurfaceComposer::eLayerHidden)) { + if (draw.flags & layer_state_t::eLayerHidden) { + if (!(curr.flags & layer_state_t::eLayerHidden)) { // we're going from hidden to visible status_t err = captureLocked(); if (err != NO_ERROR) { ALOGW("createScreenshotSurface failed (%s)", strerror(-err)); } } - } else if (curr.flags & ISurfaceComposer::eLayerHidden) { + } else if (curr.flags & layer_state_t::eLayerHidden) { // we're going from visible to hidden if (mTextureName) { glDeleteTextures(1, &mTextureName); @@ -106,13 +108,12 @@ uint32_t LayerScreenshot::doTransaction(uint32_t flags) return LayerBaseClient::doTransaction(flags); } -void LayerScreenshot::onDraw(const Region& clip) const +void LayerScreenshot::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const { const State& s(drawingState()); if (s.alpha>0) { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); const GLfloat alpha = s.alpha/255.0f; - const uint32_t fbHeight = hw.getHeight(); + const uint32_t fbHeight = hw->getHeight(); if (s.alpha == 0xFF) { glDisable(GL_BLEND); @@ -121,6 +122,9 @@ void LayerScreenshot::onDraw(const Region& clip) const glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } + LayerMesh mesh; + computeGeometry(hw, &mesh); + glColor4f(0, 0, 0, alpha); glDisable(GL_TEXTURE_EXTERNAL_OES); @@ -134,8 +138,8 @@ void LayerScreenshot::onDraw(const Region& clip) const glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, mTexCoords); - glVertexPointer(2, GL_FLOAT, 0, mVertices); - glDrawArrays(GL_TRIANGLE_FAN, 0, mNumVertices); + glVertexPointer(2, GL_FLOAT, 0, mesh.getVertices()); + glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.getVertexCount()); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); diff --git a/services/surfaceflinger/LayerScreenshot.h b/services/surfaceflinger/LayerScreenshot.h index ab90047..c06c23c 100644 --- a/services/surfaceflinger/LayerScreenshot.h +++ b/services/surfaceflinger/LayerScreenshot.h @@ -43,7 +43,7 @@ public: virtual void initStates(uint32_t w, uint32_t h, uint32_t flags); virtual uint32_t doTransaction(uint32_t flags); - virtual void onDraw(const Region& clip) const; + virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const; virtual bool isOpaque() const { return false; } virtual bool isSecure() const { return false; } virtual bool isProtectedByApp() const { return false; } diff --git a/services/surfaceflinger/MessageQueue.cpp b/services/surfaceflinger/MessageQueue.cpp index 290fff4..3f77f74 100644 --- a/services/surfaceflinger/MessageQueue.cpp +++ b/services/surfaceflinger/MessageQueue.cpp @@ -49,13 +49,13 @@ void MessageBase::handleMessage(const Message&) { // --------------------------------------------------------------------------- -void MessageQueue::Handler::signalRefresh() { +void MessageQueue::Handler::dispatchRefresh() { if ((android_atomic_or(eventMaskRefresh, &mEventMask) & eventMaskRefresh) == 0) { mQueue.mLooper->sendMessage(this, Message(MessageQueue::REFRESH)); } } -void MessageQueue::Handler::signalInvalidate() { +void MessageQueue::Handler::dispatchInvalidate() { if ((android_atomic_or(eventMaskInvalidate, &mEventMask) & eventMaskInvalidate) == 0) { mQueue.mLooper->sendMessage(this, Message(MessageQueue::INVALIDATE)); } @@ -132,13 +132,31 @@ status_t MessageQueue::postMessage( return NO_ERROR; } +/* when INVALIDATE_ON_VSYNC is set SF only processes + * buffer updates on VSYNC and performs a refresh immediately + * after. + * + * when INVALIDATE_ON_VSYNC is set to false, SF will instead + * perform the buffer updates immediately, but the refresh only + * at the next VSYNC. + * THIS MODE IS BUGGY ON GALAXY NEXUS AND WILL CAUSE HANGS + */ +#define INVALIDATE_ON_VSYNC 1 + void MessageQueue::invalidate() { -// mHandler->signalInvalidate(); +#if INVALIDATE_ON_VSYNC mEvents->requestNextVsync(); +#else + mHandler->dispatchInvalidate(); +#endif } void MessageQueue::refresh() { +#if INVALIDATE_ON_VSYNC + mHandler->dispatchRefresh(); +#else mEvents->requestNextVsync(); +#endif } int MessageQueue::cb_eventReceiver(int fd, int events, void* data) { @@ -152,7 +170,11 @@ int MessageQueue::eventReceiver(int fd, int events) { while ((n = DisplayEventReceiver::getEvents(mEventTube, buffer, 8)) > 0) { for (int i=0 ; i<n ; i++) { if (buffer[i].header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) { - mHandler->signalRefresh(); +#if INVALIDATE_ON_VSYNC + mHandler->dispatchInvalidate(); +#else + mHandler->dispatchRefresh(); +#endif break; } } diff --git a/services/surfaceflinger/MessageQueue.h b/services/surfaceflinger/MessageQueue.h index ea29e7e..710b2c2 100644 --- a/services/surfaceflinger/MessageQueue.h +++ b/services/surfaceflinger/MessageQueue.h @@ -70,8 +70,8 @@ class MessageQueue { public: Handler(MessageQueue& queue) : mQueue(queue), mEventMask(0) { } virtual void handleMessage(const Message& message); - void signalRefresh(); - void signalInvalidate(); + void dispatchRefresh(); + void dispatchInvalidate(); }; friend class Handler; diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 51fcce4..c63d0cf 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -16,17 +16,13 @@ #define ATRACE_TAG ATRACE_TAG_GRAPHICS -#include <stdlib.h> -#include <stdio.h> #include <stdint.h> -#include <unistd.h> -#include <fcntl.h> +#include <sys/types.h> #include <errno.h> #include <math.h> -#include <limits.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <sys/ioctl.h> + +#include <EGL/egl.h> +#include <GLES/gl.h> #include <cutils/log.h> #include <cutils/properties.h> @@ -36,20 +32,27 @@ #include <binder/MemoryHeapBase.h> #include <binder/PermissionCache.h> +#include <ui/DisplayInfo.h> + +#include <gui/BitTube.h> +#include <gui/BufferQueue.h> #include <gui/IDisplayEventConnection.h> +#include <gui/SurfaceTextureClient.h> + +#include <ui/GraphicBufferAllocator.h> +#include <ui/PixelFormat.h> #include <utils/String8.h> #include <utils/String16.h> #include <utils/StopWatch.h> #include <utils/Trace.h> -#include <ui/GraphicBufferAllocator.h> -#include <ui/PixelFormat.h> - -#include <GLES/gl.h> +#include <private/android_filesystem_config.h> #include "clz.h" #include "DdmConnection.h" +#include "DisplayDevice.h" +#include "Client.h" #include "EventThread.h" #include "GLExtensions.h" #include "Layer.h" @@ -57,12 +60,9 @@ #include "LayerScreenshot.h" #include "SurfaceFlinger.h" -#include "DisplayHardware/DisplayHardware.h" +#include "DisplayHardware/FramebufferSurface.h" #include "DisplayHardware/HWComposer.h" -#include <private/android_filesystem_config.h> -#include <private/gui/SharedBufferStack.h> -#include <gui/BitTube.h> #define EGL_VERSION_HW_ANDROID 0x3143 @@ -83,10 +83,10 @@ SurfaceFlinger::SurfaceFlinger() mTransactionFlags(0), mTransationPending(false), mLayersRemoved(false), + mRepaintEverything(0), mBootTime(systemTime()), mVisibleRegionsDirty(false), mHwWorkListDirty(false), - mElectronBeamAnimationMode(0), mDebugRegion(0), mDebugDDMS(0), mDebugDisableHWC(0), @@ -95,13 +95,7 @@ SurfaceFlinger::SurfaceFlinger() mLastSwapBufferTime(0), mDebugInTransaction(0), mLastTransactionTime(0), - mBootFinished(false), - mSecureFrameBuffer(0) -{ - init(); -} - -void SurfaceFlinger::init() + mBootFinished(false) { ALOGI("SurfaceFlinger is starting"); @@ -111,16 +105,14 @@ void SurfaceFlinger::init() property_get("debug.sf.showupdates", value, "0"); mDebugRegion = atoi(value); -#ifdef DDMS_DEBUGGING property_get("debug.sf.ddms", value, "0"); mDebugDDMS = atoi(value); if (mDebugDDMS) { DdmConnection::start(getServiceName()); } -#endif - ALOGI_IF(mDebugRegion, "showupdates enabled"); - ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); + ALOGI_IF(mDebugRegion, "showupdates enabled"); + ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); } void SurfaceFlinger::onFirstRef() @@ -136,7 +128,9 @@ void SurfaceFlinger::onFirstRef() SurfaceFlinger::~SurfaceFlinger() { - glDeleteTextures(1, &mWormholeTexName); + EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + eglTerminate(display); } void SurfaceFlinger::binderDied(const wp<IBinder>& who) @@ -145,17 +139,18 @@ void SurfaceFlinger::binderDied(const wp<IBinder>& who) // reset screen orientation Vector<ComposerState> state; - setTransactionState(state, eOrientationDefault, 0); + Vector<DisplayState> displays; + DisplayState d; + d.what = DisplayState::eOrientationChanged; + d.token = mDefaultDisplays[DisplayDevice::DISPLAY_ID_MAIN]; + d.orientation = DisplayState::eOrientationDefault; + displays.add(d); + setTransactionState(state, displays, 0); // restart the boot-animation startBootAnim(); } -sp<IMemoryHeap> SurfaceFlinger::getCblk() const -{ - return mServerHeap; -} - sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() { sp<ISurfaceComposerClient> bclient; @@ -167,23 +162,43 @@ sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() return bclient; } -sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() +sp<IBinder> SurfaceFlinger::createDisplay() { - sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); - return gba; + class DisplayToken : public BBinder { + sp<SurfaceFlinger> flinger; + virtual ~DisplayToken() { + // no more references, this display must be terminated + Mutex::Autolock _l(flinger->mStateLock); + flinger->mCurrentState.displays.removeItem(this); + flinger->setTransactionFlags(eDisplayTransactionNeeded); + } + public: + DisplayToken(const sp<SurfaceFlinger>& flinger) + : flinger(flinger) { + } + }; + + sp<BBinder> token = new DisplayToken(this); + + Mutex::Autolock _l(mStateLock); + DisplayDeviceState info(intptr_t(token.get())); // FIXME: we shouldn't use the address for the id + mCurrentState.displays.add(token, info); + + return token; } -const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const -{ - ALOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy); - const GraphicPlane& plane(mGraphicPlanes[dpy]); - return plane; +sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) { + if (uint32_t(id) >= DisplayDevice::DISPLAY_ID_COUNT) { + ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id); + return NULL; + } + return mDefaultDisplays[id]; } -GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) +sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() { - return const_cast<GraphicPlane&>( - const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy)); + sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); + return gba; } void SurfaceFlinger::bootFinished() @@ -197,7 +212,7 @@ void SurfaceFlinger::bootFinished() const String16 name("window"); sp<IBinder> window(defaultServiceManager()->getService(name)); if (window != 0) { - window->linkToDeath(this); + window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this)); } // stop boot animation @@ -206,60 +221,110 @@ void SurfaceFlinger::bootFinished() property_set("service.bootanim.exit", "1"); } -static inline uint16_t pack565(int r, int g, int b) { - return (r<<11)|(g<<5)|b; +void SurfaceFlinger::deleteTextureAsync(GLuint texture) { + class MessageDestroyGLTexture : public MessageBase { + GLuint texture; + public: + MessageDestroyGLTexture(GLuint texture) + : texture(texture) { + } + virtual bool handler() { + glDeleteTextures(1, &texture); + return true; + } + }; + postMessageAsync(new MessageDestroyGLTexture(texture)); +} + +status_t SurfaceFlinger::selectConfigForPixelFormat( + EGLDisplay dpy, + EGLint const* attrs, + PixelFormat format, + EGLConfig* outConfig) +{ + EGLConfig config = NULL; + EGLint numConfigs = -1, n=0; + eglGetConfigs(dpy, NULL, 0, &numConfigs); + EGLConfig* const configs = new EGLConfig[numConfigs]; + eglChooseConfig(dpy, attrs, configs, numConfigs, &n); + for (int i=0 ; i<n ; i++) { + EGLint nativeVisualId = 0; + eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId); + if (nativeVisualId>0 && format == nativeVisualId) { + *outConfig = configs[i]; + delete [] configs; + return NO_ERROR; + } + } + delete [] configs; + return NAME_NOT_FOUND; } -status_t SurfaceFlinger::readyToRun() -{ - ALOGI( "SurfaceFlinger's main thread ready to run. " - "Initializing graphics H/W..."); +EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) { + // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if + // it is to be used with WIFI displays + EGLConfig config; + EGLint dummy; + status_t err; + EGLint attribs[] = { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RECORDABLE_ANDROID, EGL_TRUE, + EGL_NONE + }; + err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config); + if (err) { + // maybe we failed because of EGL_RECORDABLE_ANDROID + ALOGW("couldn't find an EGLConfig with EGL_RECORDABLE_ANDROID"); + attribs[2] = EGL_NONE; + err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config); + } + ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format"); + if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) { + ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!"); + } + return config; +} + +EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) { + // Also create our EGLContext + EGLint contextAttributes[] = { +#ifdef EGL_IMG_context_priority +#ifdef HAS_CONTEXT_PRIORITY +#warning "using EGL_IMG_context_priority" + EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG, +#endif +#endif + EGL_NONE, EGL_NONE + }; + EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes); + ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed"); + return ctxt; +} + +void SurfaceFlinger::initializeGL(EGLDisplay display, EGLSurface surface) { + EGLBoolean result = eglMakeCurrent(display, surface, surface, mEGLContext); + if (!result) { + ALOGE("Couldn't create a working GLES context. check logs. exiting..."); + exit(0); + } + + GLExtensions& extensions(GLExtensions::getInstance()); + extensions.initWithGLStrings( + glGetString(GL_VENDOR), + glGetString(GL_RENDERER), + glGetString(GL_VERSION), + glGetString(GL_EXTENSIONS), + eglQueryString(display, EGL_VENDOR), + eglQueryString(display, EGL_VERSION), + eglQueryString(display, EGL_EXTENSIONS)); + + EGLint w, h; + eglQuerySurface(display, surface, EGL_WIDTH, &w); + eglQuerySurface(display, surface, EGL_HEIGHT, &h); + + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize); + glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims); - // we only support one display currently - int dpy = 0; - - { - // initialize the main display - GraphicPlane& plane(graphicPlane(dpy)); - DisplayHardware* const hw = new DisplayHardware(this, dpy); - plane.setDisplayHardware(hw); - } - - // create the shared control-block - mServerHeap = new MemoryHeapBase(4096, - MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap"); - ALOGE_IF(mServerHeap==0, "can't create shared memory dealer"); - - mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase()); - ALOGE_IF(mServerCblk==0, "can't get to shared control block's address"); - - new(mServerCblk) surface_flinger_cblk_t; - - // initialize primary screen - // (other display should be initialized in the same manner, but - // asynchronously, as they could come and go. None of this is supported - // yet). - const GraphicPlane& plane(graphicPlane(dpy)); - const DisplayHardware& hw = plane.displayHardware(); - const uint32_t w = hw.getWidth(); - const uint32_t h = hw.getHeight(); - const uint32_t f = hw.getFormat(); - hw.makeCurrent(); - - // initialize the shared control block - mServerCblk->connected |= 1<<dpy; - display_cblk_t* dcblk = mServerCblk->displays + dpy; - memset(dcblk, 0, sizeof(display_cblk_t)); - dcblk->w = plane.getWidth(); - dcblk->h = plane.getHeight(); - dcblk->format = f; - dcblk->orientation = ISurfaceComposer::eOrientationDefault; - dcblk->xdpi = hw.getDpiX(); - dcblk->ydpi = hw.getDpiY(); - dcblk->fps = hw.getRefreshRate(); - dcblk->density = hw.getDensity(); - - // Initialize OpenGL|ES glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glPixelStorei(GL_PACK_ALIGNMENT, 4); glEnableClientState(GL_VERTEX_ARRAY); @@ -267,17 +332,11 @@ status_t SurfaceFlinger::readyToRun() glDisable(GL_DITHER); glDisable(GL_CULL_FACE); - const uint16_t g0 = pack565(0x0F,0x1F,0x0F); - const uint16_t g1 = pack565(0x17,0x2f,0x17); - const uint16_t wormholeTexData[4] = { g0, g1, g1, g0 }; - glGenTextures(1, &mWormholeTexName); - glBindTexture(GL_TEXTURE_2D, mWormholeTexName); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, - GL_RGB, GL_UNSIGNED_SHORT_5_6_5, wormholeTexData); + struct pack565 { + inline uint16_t operator() (int r, int g, int b) const { + return (r<<11)|(g<<5)|b; + } + } pack565; const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) }; glGenTextures(1, &mProtectedTexName); @@ -295,16 +354,81 @@ status_t SurfaceFlinger::readyToRun() // put the origin in the left-bottom corner glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h + // print some debugging info + EGLint r,g,b,a; + eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE, &r); + eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g); + eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE, &b); + eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a); + ALOGI("EGL informations:"); + ALOGI("vendor : %s", extensions.getEglVendor()); + ALOGI("version : %s", extensions.getEglVersion()); + ALOGI("extensions: %s", extensions.getEglExtension()); + ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported"); + ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig); + ALOGI("OpenGL ES informations:"); + ALOGI("vendor : %s", extensions.getVendor()); + ALOGI("renderer : %s", extensions.getRenderer()); + ALOGI("version : %s", extensions.getVersion()); + ALOGI("extensions: %s", extensions.getExtension()); + ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize); + ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]); +} + +status_t SurfaceFlinger::readyToRun() +{ + ALOGI( "SurfaceFlinger's main thread ready to run. " + "Initializing graphics H/W..."); + + // initialize EGL + mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); + eglInitialize(mEGLDisplay, NULL, NULL); + + // Initialize the main display + // create native window to main display + sp<FramebufferSurface> fbs = FramebufferSurface::create(); + if (fbs == NULL) { + ALOGE("Display subsystem failed to initialize. check logs. exiting..."); + exit(0); + } + + sp<SurfaceTextureClient> stc(new SurfaceTextureClient( + static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue()))); + + // initialize the config and context + int format; + ANativeWindow* const anw = stc.get(); + anw->query(anw, NATIVE_WINDOW_FORMAT, &format); + mEGLConfig = selectEGLConfig(mEGLDisplay, format); + mEGLContext = createGLContext(mEGLDisplay, mEGLConfig); + + // initialize our main display hardware + + for (size_t i=0 ; i<DisplayDevice::DISPLAY_ID_COUNT ; i++) { + mDefaultDisplays[i] = new BBinder(); + mCurrentState.displays.add(mDefaultDisplays[i], DisplayDeviceState(i)); + } + sp<DisplayDevice> hw = new DisplayDevice(this, + DisplayDevice::DISPLAY_ID_MAIN, anw, fbs, mEGLConfig); + mDisplays.add(hw->getDisplayId(), hw); + + // initialize OpenGL ES + EGLSurface surface = hw->getEGLSurface(); + initializeGL(mEGLDisplay, surface); // start the EventThread mEventThread = new EventThread(this); mEventQueue.setEventThread(mEventThread); - hw.startSleepManagement(); - /* - * We're now ready to accept clients... - */ + // initialize the H/W composer + mHwc = new HWComposer(this, + *static_cast<HWComposer::EventHandler *>(this), + fbs->getFbHal()); + // initialize our drawing state + mDrawingState = mCurrentState; + + // We're now ready to accept clients... mReadyToRunBarrier.open(); // start boot animation @@ -319,6 +443,15 @@ void SurfaceFlinger::startBootAnim() { property_set("ctl.start", "bootanim"); } +uint32_t SurfaceFlinger::getMaxTextureSize() const { + return mMaxTextureSize; +} + +uint32_t SurfaceFlinger::getMaxViewportDims() const { + return mMaxViewportDims[0] < mMaxViewportDims[1] ? + mMaxViewportDims[0] : mMaxViewportDims[1]; +} + // ---------------------------------------------------------------------------- bool SurfaceFlinger::authenticateSurfaceTexture( @@ -362,12 +495,93 @@ bool SurfaceFlinger::authenticateSurfaceTexture( return false; } +status_t SurfaceFlinger::getDisplayInfo(DisplayID dpy, DisplayInfo* info) { + // TODO: this is here only for compatibility -- should go away eventually. + if (uint32_t(dpy) >= 1) { + return BAD_INDEX; + } + + const HWComposer& hwc(getHwComposer()); + float xdpi = hwc.getDpiX(); + float ydpi = hwc.getDpiY(); + + // TODO: Not sure if display density should handled by SF any longer + class Density { + static int getDensityFromProperty(char const* propName) { + char property[PROPERTY_VALUE_MAX]; + int density = 0; + if (property_get(propName, property, NULL) > 0) { + density = atoi(property); + } + return density; + } + public: + static int getEmuDensity() { + return getDensityFromProperty("qemu.sf.lcd_density"); } + static int getBuildDensity() { + return getDensityFromProperty("ro.sf.lcd_density"); } + }; + // The density of the device is provided by a build property + float density = Density::getBuildDensity() / 160.0f; + if (density == 0) { + // the build doesn't provide a density -- this is wrong! + // use xdpi instead + ALOGE("ro.sf.lcd_density must be defined as a build property"); + density = xdpi / 160.0f; + } + if (Density::getEmuDensity()) { + // if "qemu.sf.lcd_density" is specified, it overrides everything + xdpi = ydpi = density = Density::getEmuDensity(); + density /= 160.0f; + } + + sp<const DisplayDevice> hw(getDefaultDisplayDevice()); + info->w = hw->getWidth(); + info->h = hw->getHeight(); + info->xdpi = xdpi; + info->ydpi = ydpi; + info->fps = float(1e9 / hwc.getRefreshPeriod()); + info->density = density; + info->orientation = hw->getOrientation(); + // TODO: this needs to go away (currently needed only by webkit) + getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo); + return NO_ERROR; +} + // ---------------------------------------------------------------------------- sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() { return mEventThread->createEventConnection(); } +void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture> surface) { + + sp<IBinder> token; + { // scope for the lock + Mutex::Autolock _l(mStateLock); + token = mExtDisplayToken; + } + + if (token == 0) { + token = createDisplay(); + } + + { // scope for the lock + Mutex::Autolock _l(mStateLock); + if (surface == 0) { + // release our current display. we're guarantee to have + // a reference to it (token), while we hold the lock + mExtDisplayToken = 0; + } else { + mExtDisplayToken = token; + } + + DisplayDeviceState& info(mCurrentState.displays.editValueFor(token)); + info.surface = surface; + setTransactionFlags(eDisplayTransactionNeeded); + } +} + // ---------------------------------------------------------------------------- void SurfaceFlinger::waitForEvent() { @@ -400,83 +614,262 @@ status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, return res; } -bool SurfaceFlinger::threadLoop() -{ +bool SurfaceFlinger::threadLoop() { waitForEvent(); return true; } -void SurfaceFlinger::onMessageReceived(int32_t what) -{ +void SurfaceFlinger::onVSyncReceived(int dpy, nsecs_t timestamp) { + mEventThread->onVSyncReceived(dpy, timestamp); +} + +void SurfaceFlinger::eventControl(int event, int enabled) { + getHwComposer().eventControl(event, enabled); +} + +void SurfaceFlinger::onMessageReceived(int32_t what) { ATRACE_CALL(); switch (what) { - case MessageQueue::REFRESH: { -// case MessageQueue::INVALIDATE: { - // if we're in a global transaction, don't do anything. - const uint32_t mask = eTransactionNeeded | eTraversalNeeded; - uint32_t transactionFlags = peekTransactionFlags(mask); - if (CC_UNLIKELY(transactionFlags)) { - handleTransaction(transactionFlags); + case MessageQueue::INVALIDATE: + handleMessageTransaction(); + handleMessageInvalidate(); + signalRefresh(); + break; + case MessageQueue::REFRESH: + handleMessageRefresh(); + break; + } +} + +void SurfaceFlinger::handleMessageTransaction() { + uint32_t transactionFlags = peekTransactionFlags(eTransactionMask); + if (transactionFlags) { + handleTransaction(transactionFlags); + } +} + +void SurfaceFlinger::handleMessageInvalidate() { + ATRACE_CALL(); + handlePageFlip(); +} + +void SurfaceFlinger::handleMessageRefresh() { + ATRACE_CALL(); + preComposition(); + rebuildLayerStacks(); + setUpHWComposer(); + doDebugFlashRegions(); + doComposition(); + postComposition(); +} + +void SurfaceFlinger::doDebugFlashRegions() +{ + // is debugging enabled + if (CC_LIKELY(!mDebugRegion)) + return; + + const bool repaintEverything = mRepaintEverything; + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + const sp<DisplayDevice>& hw(mDisplays[dpy]); + if (hw->canDraw()) { + // transform the dirty region into this screen's coordinate space + const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); + if (!dirtyRegion.isEmpty()) { + // redraw the whole screen + doComposeSurfaces(hw, Region(hw->bounds())); + + // and draw the dirty region + glDisable(GL_TEXTURE_EXTERNAL_OES); + glDisable(GL_TEXTURE_2D); + glDisable(GL_BLEND); + glColor4f(1, 0, 1, 1); + const int32_t height = hw->getHeight(); + Region::const_iterator it = dirtyRegion.begin(); + Region::const_iterator const end = dirtyRegion.end(); + while (it != end) { + const Rect& r = *it++; + GLfloat vertices[][2] = { + { r.left, height - r.top }, + { r.left, height - r.bottom }, + { r.right, height - r.bottom }, + { r.right, height - r.top } + }; + glVertexPointer(2, GL_FLOAT, 0, vertices); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + } + hw->compositionComplete(); + // FIXME + if (hw->getDisplayId() >= DisplayDevice::DISPLAY_ID_COUNT) { + eglSwapBuffers(mEGLDisplay, hw->getEGLSurface()); + } } + } + } - // post surfaces (if needed) - handlePageFlip(); + postFramebuffer(); -// signalRefresh(); -// -// } break; -// -// case MessageQueue::REFRESH: { + if (mDebugRegion > 1) { + usleep(mDebugRegion * 1000); + } +} - handleRefresh(); +void SurfaceFlinger::preComposition() +{ + bool needExtraInvalidate = false; + const LayerVector& currentLayers(mDrawingState.layersSortedByZ); + const size_t count = currentLayers.size(); + for (size_t i=0 ; i<count ; i++) { + if (currentLayers[i]->onPreComposition()) { + needExtraInvalidate = true; + } + } + if (needExtraInvalidate) { + signalLayerUpdate(); + } +} - const DisplayHardware& hw(graphicPlane(0).displayHardware()); +void SurfaceFlinger::postComposition() +{ + const LayerVector& currentLayers(mDrawingState.layersSortedByZ); + const size_t count = currentLayers.size(); + for (size_t i=0 ; i<count ; i++) { + currentLayers[i]->onPostComposition(); + } +} -// if (mDirtyRegion.isEmpty()) { -// return; -// } +void SurfaceFlinger::rebuildLayerStacks() { + // rebuild the visible layer list per screen + if (CC_UNLIKELY(mVisibleRegionsDirty)) { + ATRACE_CALL(); + mVisibleRegionsDirty = false; + invalidateHwcGeometry(); + const LayerVector& currentLayers(mDrawingState.layersSortedByZ); + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + const sp<DisplayDevice>& hw(mDisplays[dpy]); + Region opaqueRegion; + Region dirtyRegion; + computeVisibleRegions(currentLayers, + hw->getLayerStack(), dirtyRegion, opaqueRegion); + hw->dirtyRegion.orSelf(dirtyRegion); - if (CC_UNLIKELY(mHwWorkListDirty)) { - // build the h/w work list - handleWorkList(); + Vector< sp<LayerBase> > layersSortedByZ; + const size_t count = currentLayers.size(); + for (size_t i=0 ; i<count ; i++) { + const Layer::State& s(currentLayers[i]->drawingState()); + if (s.layerStack == hw->getLayerStack()) { + if (!currentLayers[i]->visibleRegion.isEmpty()) { + layersSortedByZ.add(currentLayers[i]); + } + } } + hw->setVisibleLayersSortedByZ(layersSortedByZ); + hw->undefinedRegion.set(hw->getBounds()); + hw->undefinedRegion.subtractSelf( + hw->getTransform().transform(opaqueRegion)); + } + } +} - if (CC_LIKELY(hw.canDraw())) { - // repaint the framebuffer (if needed) - handleRepaint(); - // inform the h/w that we're done compositing - hw.compositionComplete(); - postFramebuffer(); - } else { - // pretend we did the post - hw.compositionComplete(); +void SurfaceFlinger::setUpHWComposer() { + HWComposer& hwc(getHwComposer()); + if (hwc.initCheck() == NO_ERROR) { + // build the h/w work list + const bool workListsDirty = mHwWorkListDirty; + mHwWorkListDirty = false; + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + sp<const DisplayDevice> hw(mDisplays[dpy]); + const Vector< sp<LayerBase> >& currentLayers( + hw->getVisibleLayersSortedByZ()); + const size_t count = currentLayers.size(); + + const int32_t id = hw->getDisplayId(); + if (hwc.createWorkList(id, count) >= 0) { + HWComposer::LayerListIterator cur = hwc.begin(id); + const HWComposer::LayerListIterator end = hwc.end(id); + for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { + const sp<LayerBase>& layer(currentLayers[i]); + + if (CC_UNLIKELY(workListsDirty)) { + layer->setGeometry(hw, *cur); + if (mDebugDisableHWC || mDebugRegion) { + cur->setSkip(true); + } + } + + /* + * update the per-frame h/w composer data for each layer + * and build the transparent region of the FB + */ + layer->setPerFrameData(hw, *cur); + } } + } + status_t err = hwc.prepare(); + ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); + } +} - } break; +void SurfaceFlinger::doComposition() { + ATRACE_CALL(); + const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + const sp<DisplayDevice>& hw(mDisplays[dpy]); + if (hw->canDraw()) { + // transform the dirty region into this screen's coordinate space + const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); + if (!dirtyRegion.isEmpty()) { + // repaint the framebuffer (if needed) + doDisplayComposition(hw, dirtyRegion); + } + hw->dirtyRegion.clear(); + hw->flip(hw->swapRegion); + hw->swapRegion.clear(); + } + // inform the h/w that we're done compositing + hw->compositionComplete(); } + postFramebuffer(); } void SurfaceFlinger::postFramebuffer() { ATRACE_CALL(); - // mSwapRegion can be empty here is some cases, for instance if a hidden - // or fully transparent window is updating. - // in that case, we need to flip anyways to not risk a deadlock with - // h/w composer. - const DisplayHardware& hw(graphicPlane(0).displayHardware()); const nsecs_t now = systemTime(); mDebugInSwapBuffers = now; - hw.flip(mSwapRegion); - size_t numLayers = mVisibleLayersSortedByZ.size(); - for (size_t i = 0; i < numLayers; i++) { - mVisibleLayersSortedByZ[i]->onLayerDisplayed(); + HWComposer& hwc(getHwComposer()); + if (hwc.initCheck() == NO_ERROR) { + // FIXME: eventually commit() won't take arguments + // FIXME: EGL spec says: + // "surface must be bound to the calling thread's current context, + // for the current rendering API." + DisplayDevice::makeCurrent( + getDisplayDevice(DisplayDevice::DISPLAY_ID_MAIN), mEGLContext); + hwc.commit(mEGLDisplay, getDefaultDisplayDevice()->getEGLSurface()); + } + + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + sp<const DisplayDevice> hw(mDisplays[dpy]); + const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); + const size_t count = currentLayers.size(); + if (hwc.initCheck() == NO_ERROR) { + int32_t id = hw->getDisplayId(); + HWComposer::LayerListIterator cur = hwc.begin(id); + const HWComposer::LayerListIterator end = hwc.end(id); + for (size_t i = 0; cur != end && i < count; ++i, ++cur) { + currentLayers[i]->onLayerDisplayed(hw, &*cur); + } + } else { + for (size_t i = 0; i < count; i++) { + currentLayers[i]->onLayerDisplayed(hw, NULL); + } + } } mLastSwapBufferTime = systemTime() - now; mDebugInSwapBuffers = 0; - mSwapRegion.clear(); } void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) @@ -493,8 +886,7 @@ void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) // with mStateLock held to guarantee that mCurrentState won't change // until the transaction is committed. - const uint32_t mask = eTransactionNeeded | eTraversalNeeded; - transactionFlags = getTransactionFlags(mask); + transactionFlags = getTransactionFlags(eTransactionMask); handleTransactionLocked(transactionFlags); mLastTransactionTime = systemTime() - now; @@ -513,8 +905,7 @@ void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) * (perform the transaction for each of them if needed) */ - const bool layersNeedTransaction = transactionFlags & eTraversalNeeded; - if (layersNeedTransaction) { + if (transactionFlags & eTraversalNeeded) { for (size_t i=0 ; i<count ; i++) { const sp<LayerBase>& layer = currentLayers[i]; uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); @@ -527,49 +918,107 @@ void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) } /* - * Perform our own transaction if needed + * Perform display own transactions if needed */ - if (transactionFlags & eTransactionNeeded) { - if (mCurrentState.orientation != mDrawingState.orientation) { - // the orientation has changed, recompute all visible regions - // and invalidate everything. - - const int dpy = 0; - const int orientation = mCurrentState.orientation; - // Currently unused: const uint32_t flags = mCurrentState.orientationFlags; - GraphicPlane& plane(graphicPlane(dpy)); - plane.setOrientation(orientation); - - // update the shared control block - const DisplayHardware& hw(plane.displayHardware()); - volatile display_cblk_t* dcblk = mServerCblk->displays + dpy; - dcblk->orientation = orientation; - dcblk->w = plane.getWidth(); - dcblk->h = plane.getHeight(); - + if (transactionFlags & eDisplayTransactionNeeded) { + // here we take advantage of Vector's copy-on-write semantics to + // improve performance by skipping the transaction entirely when + // know that the lists are identical + const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); + const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); + if (!curr.isIdenticalTo(draw)) { mVisibleRegionsDirty = true; - mDirtyRegion.set(hw.bounds()); - } + const size_t cc = curr.size(); + const size_t dc = draw.size(); + + // find the displays that were removed + // (ie: in drawing state but not in current state) + // also handle displays that changed + // (ie: displays that are in both lists) + for (size_t i=0 ; i<dc ; i++) { + const ssize_t j = curr.indexOfKey(draw.keyAt(i)); + if (j < 0) { + // in drawing state but not in current state + if (draw[i].id != DisplayDevice::DISPLAY_ID_MAIN) { + mDisplays.removeItem(draw[i].id); + } else { + ALOGW("trying to remove the main display"); + } + } else { + // this display is in both lists. see if something changed. + const DisplayDeviceState& state(curr[j]); + if (state.surface->asBinder() != draw[i].surface->asBinder()) { + // changing the surface is like destroying and + // recreating the DisplayDevice + + sp<SurfaceTextureClient> stc( + new SurfaceTextureClient(state.surface)); + + sp<DisplayDevice> disp = new DisplayDevice(this, + state.id, stc, 0, mEGLConfig); + + disp->setLayerStack(state.layerStack); + disp->setOrientation(state.orientation); + // TODO: take viewport and frame into account + mDisplays.replaceValueFor(state.id, disp); + } + if (state.layerStack != draw[i].layerStack) { + const sp<DisplayDevice>& disp(getDisplayDevice(state.id)); + disp->setLayerStack(state.layerStack); + } + if (state.orientation != draw[i].orientation || + state.viewport != draw[i].viewport || + state.frame != draw[i].frame) { + const sp<DisplayDevice>& disp(getDisplayDevice(state.id)); + disp->setOrientation(state.orientation); + // TODO: take viewport and frame into account + } + } + } - if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) { - // layers have been added - mVisibleRegionsDirty = true; + // find displays that were added + // (ie: in current state but not in drawing state) + for (size_t i=0 ; i<cc ; i++) { + if (draw.indexOfKey(curr.keyAt(i)) < 0) { + const DisplayDeviceState& state(curr[i]); + sp<SurfaceTextureClient> stc( + new SurfaceTextureClient(state.surface)); + sp<DisplayDevice> disp = new DisplayDevice(this, state.id, + stc, 0, mEGLConfig); + mDisplays.add(state.id, disp); + } + } } + } - // some layers might have been removed, so - // we need to update the regions they're exposing. - if (mLayersRemoved) { - mLayersRemoved = false; - mVisibleRegionsDirty = true; - const LayerVector& previousLayers(mDrawingState.layersSortedByZ); - const size_t count = previousLayers.size(); - for (size_t i=0 ; i<count ; i++) { - const sp<LayerBase>& layer(previousLayers[i]); - if (currentLayers.indexOf( layer ) < 0) { - // this layer is not visible anymore - mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen); - } + /* + * Perform our own transaction if needed + */ + + const LayerVector& previousLayers(mDrawingState.layersSortedByZ); + if (currentLayers.size() > previousLayers.size()) { + // layers have been added + mVisibleRegionsDirty = true; + } + + // some layers might have been removed, so + // we need to update the regions they're exposing. + if (mLayersRemoved) { + mLayersRemoved = false; + mVisibleRegionsDirty = true; + const size_t count = previousLayers.size(); + for (size_t i=0 ; i<count ; i++) { + const sp<LayerBase>& layer(previousLayers[i]); + if (currentLayers.indexOf(layer) < 0) { + // this layer is not visible anymore + // TODO: we could traverse the tree from front to back and + // compute the actual visible region + // TODO: we could cache the transformed region + Layer::State front(layer->drawingState()); + Region visibleReg = front.transform.transform( + Region(Rect(front.active.w, front.active.h))); + invalidateLayerStack(front.layerStack, visibleReg); } } } @@ -577,30 +1026,44 @@ void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) commitTransaction(); } +void SurfaceFlinger::commitTransaction() +{ + if (!mLayersPendingRemoval.isEmpty()) { + // Notify removed layers now that they can't be drawn from + for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { + mLayersPendingRemoval[i]->onRemoved(); + } + mLayersPendingRemoval.clear(); + } + + mDrawingState = mCurrentState; + mTransationPending = false; + mTransactionCV.broadcast(); +} + void SurfaceFlinger::computeVisibleRegions( - const LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion) + const LayerVector& currentLayers, uint32_t layerStack, + Region& outDirtyRegion, Region& outOpaqueRegion) { ATRACE_CALL(); - const GraphicPlane& plane(graphicPlane(0)); - const Transform& planeTransform(plane.transform()); - const DisplayHardware& hw(plane.displayHardware()); - const Region screenRegion(hw.bounds()); - Region aboveOpaqueLayers; Region aboveCoveredLayers; Region dirty; - bool secureFrameBuffer = false; + outDirtyRegion.clear(); size_t i = currentLayers.size(); while (i--) { const sp<LayerBase>& layer = currentLayers[i]; - layer->validateVisibility(planeTransform); // start with the whole surface at its current location const Layer::State& s(layer->drawingState()); + // only consider the layers on the given later stack + if (s.layerStack != layerStack) + continue; + /* * opaqueRegion: area of a surface that is fully opaque. */ @@ -622,19 +1085,32 @@ void SurfaceFlinger::computeVisibleRegions( // handle hidden surfaces by setting the visible region to empty - if (CC_LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) { + if (CC_LIKELY(!(s.flags & layer_state_t::eLayerHidden) && s.alpha)) { const bool translucent = !layer->isOpaque(); - const Rect bounds(layer->visibleBounds()); + Rect bounds(layer->computeBounds()); visibleRegion.set(bounds); - visibleRegion.andSelf(screenRegion); if (!visibleRegion.isEmpty()) { // Remove the transparent area from the visible region if (translucent) { - visibleRegion.subtractSelf(layer->transparentRegionScreen); + Region transparentRegionScreen; + const Transform tr(s.transform); + if (tr.transformed()) { + if (tr.preserveRects()) { + // transform the transparent region + transparentRegionScreen = tr.transform(s.transparentRegion); + } else { + // transformation too complex, can't do the + // transparent region optimization. + transparentRegionScreen.clear(); + } + } else { + transparentRegionScreen = s.transparentRegion; + } + visibleRegion.subtractSelf(transparentRegionScreen); } // compute the opaque region - const int32_t layerOrientation = layer->getOrientation(); + const int32_t layerOrientation = s.transform.getOrientation(); if (s.alpha==255 && !translucent && ((layerOrientation & Transform::ROT_INVALID) == false)) { // the opaque region is the layer's footprint @@ -657,7 +1133,7 @@ void SurfaceFlinger::computeVisibleRegions( // we need to invalidate the whole region dirty = visibleRegion; // as well, as the old visible region - dirty.orSelf(layer->visibleRegionScreen); + dirty.orSelf(layer->visibleRegion); layer->contentDirty = false; } else { /* compute the exposed region: @@ -673,15 +1149,15 @@ void SurfaceFlinger::computeVisibleRegions( * exposed because of a resize. */ const Region newExposed = visibleRegion - coveredRegion; - const Region oldVisibleRegion = layer->visibleRegionScreen; - const Region oldCoveredRegion = layer->coveredRegionScreen; + const Region oldVisibleRegion = layer->visibleRegion; + const Region oldCoveredRegion = layer->coveredRegion; const Region oldExposed = oldVisibleRegion - oldCoveredRegion; dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); } dirty.subtractSelf(aboveOpaqueLayers); // accumulate to the screen dirty region - dirtyRegion.orSelf(dirty); + outDirtyRegion.orSelf(dirty); // Update aboveOpaqueLayers for next (lower) layer aboveOpaqueLayers.orSelf(opaqueRegion); @@ -689,225 +1165,107 @@ void SurfaceFlinger::computeVisibleRegions( // Store the visible region is screen space layer->setVisibleRegion(visibleRegion); layer->setCoveredRegion(coveredRegion); - - // If a secure layer is partially visible, lock-down the screen! - if (layer->isSecure() && !visibleRegion.isEmpty()) { - secureFrameBuffer = true; - } } - // invalidate the areas where a layer was removed - dirtyRegion.orSelf(mDirtyRegionRemovedLayer); - mDirtyRegionRemovedLayer.clear(); - - mSecureFrameBuffer = secureFrameBuffer; - opaqueRegion = aboveOpaqueLayers; + outOpaqueRegion = aboveOpaqueLayers; } - -void SurfaceFlinger::commitTransaction() -{ - if (!mLayersPendingRemoval.isEmpty()) { - // Notify removed layers now that they can't be drawn from - for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { - mLayersPendingRemoval[i]->onRemoved(); +void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, + const Region& dirty) { + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + const sp<DisplayDevice>& hw(mDisplays[dpy]); + if (hw->getLayerStack() == layerStack) { + hw->dirtyRegion.orSelf(dirty); } - mLayersPendingRemoval.clear(); } - - mDrawingState = mCurrentState; - mTransationPending = false; - mTransactionCV.broadcast(); } void SurfaceFlinger::handlePageFlip() { - ATRACE_CALL(); - const DisplayHardware& hw = graphicPlane(0).displayHardware(); - const Region screenRegion(hw.bounds()); + Region dirtyRegion; - const LayerVector& currentLayers(mDrawingState.layersSortedByZ); - const bool visibleRegions = lockPageFlip(currentLayers); - - if (visibleRegions || mVisibleRegionsDirty) { - Region opaqueRegion; - computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion); - - /* - * rebuild the visible layer list - */ - const size_t count = currentLayers.size(); - mVisibleLayersSortedByZ.clear(); - mVisibleLayersSortedByZ.setCapacity(count); - for (size_t i=0 ; i<count ; i++) { - if (!currentLayers[i]->visibleRegionScreen.isEmpty()) - mVisibleLayersSortedByZ.add(currentLayers[i]); - } - - mWormholeRegion = screenRegion.subtract(opaqueRegion); - mVisibleRegionsDirty = false; - invalidateHwcGeometry(); - } - - unlockPageFlip(currentLayers); - - mDirtyRegion.orSelf(getAndClearInvalidateRegion()); - mDirtyRegion.andSelf(screenRegion); -} - -void SurfaceFlinger::invalidateHwcGeometry() -{ - mHwWorkListDirty = true; -} - -bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers) -{ - bool recomputeVisibleRegions = false; - size_t count = currentLayers.size(); - sp<LayerBase> const* layers = currentLayers.array(); - for (size_t i=0 ; i<count ; i++) { - const sp<LayerBase>& layer(layers[i]); - layer->lockPageFlip(recomputeVisibleRegions); - } - return recomputeVisibleRegions; -} - -void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers) -{ - const GraphicPlane& plane(graphicPlane(0)); - const Transform& planeTransform(plane.transform()); - const size_t count = currentLayers.size(); - sp<LayerBase> const* layers = currentLayers.array(); - for (size_t i=0 ; i<count ; i++) { - const sp<LayerBase>& layer(layers[i]); - layer->unlockPageFlip(planeTransform, mDirtyRegion); - } -} - -void SurfaceFlinger::handleRefresh() -{ - bool needInvalidate = false; + bool visibleRegions = false; const LayerVector& currentLayers(mDrawingState.layersSortedByZ); const size_t count = currentLayers.size(); for (size_t i=0 ; i<count ; i++) { const sp<LayerBase>& layer(currentLayers[i]); - if (layer->onPreComposition()) { - needInvalidate = true; - } - } - if (needInvalidate) { - signalLayerUpdate(); + const Region dirty(layer->latchBuffer(visibleRegions)); + Layer::State s(layer->drawingState()); + invalidateLayerStack(s.layerStack, dirty); } -} + mVisibleRegionsDirty |= visibleRegions; +} -void SurfaceFlinger::handleWorkList() +void SurfaceFlinger::invalidateHwcGeometry() { - mHwWorkListDirty = false; - HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer()); - if (hwc.initCheck() == NO_ERROR) { - const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ); - const size_t count = currentLayers.size(); - hwc.createWorkList(count); - hwc_layer_t* const cur(hwc.getLayers()); - for (size_t i=0 ; cur && i<count ; i++) { - currentLayers[i]->setGeometry(&cur[i]); - if (mDebugDisableHWC || mDebugRegion) { - cur[i].compositionType = HWC_FRAMEBUFFER; - cur[i].flags |= HWC_SKIP_LAYER; - } - } - } + mHwWorkListDirty = true; } -void SurfaceFlinger::handleRepaint() + +void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, + const Region& inDirtyRegion) { - ATRACE_CALL(); + Region dirtyRegion(inDirtyRegion); // compute the invalid region - mSwapRegion.orSelf(mDirtyRegion); + hw->swapRegion.orSelf(dirtyRegion); - if (CC_UNLIKELY(mDebugRegion)) { - debugFlashRegions(); - } - - // set the frame buffer - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - uint32_t flags = hw.getFlags(); - if (flags & DisplayHardware::SWAP_RECTANGLE) { + uint32_t flags = hw->getFlags(); + if (flags & DisplayDevice::SWAP_RECTANGLE) { // we can redraw only what's dirty, but since SWAP_RECTANGLE only // takes a rectangle, we must make sure to update that whole // rectangle in that case - mDirtyRegion.set(mSwapRegion.bounds()); + dirtyRegion.set(hw->swapRegion.bounds()); } else { - if (flags & DisplayHardware::PARTIAL_UPDATES) { + if (flags & DisplayDevice::PARTIAL_UPDATES) { // We need to redraw the rectangle that will be updated // (pushed to the framebuffer). // This is needed because PARTIAL_UPDATES only takes one - // rectangle instead of a region (see DisplayHardware::flip()) - mDirtyRegion.set(mSwapRegion.bounds()); + // rectangle instead of a region (see DisplayDevice::flip()) + dirtyRegion.set(hw->swapRegion.bounds()); } else { // we need to redraw everything (the whole screen) - mDirtyRegion.set(hw.bounds()); - mSwapRegion = mDirtyRegion; + dirtyRegion.set(hw->bounds()); + hw->swapRegion = dirtyRegion; } } - setupHardwareComposer(); - composeSurfaces(mDirtyRegion); + doComposeSurfaces(hw, dirtyRegion); + + // FIXME: we need to call eglSwapBuffers() on displays that have + // GL composition and only on those. + // however, currently hwc.commit() already does that for the main + // display and never for the other ones + if (hw->getDisplayId() >= DisplayDevice::DISPLAY_ID_COUNT) { + // FIXME: EGL spec says: + // "surface must be bound to the calling thread's current context, + // for the current rendering API." + eglSwapBuffers(mEGLDisplay, hw->getEGLSurface()); + } // update the swap region and clear the dirty region - mSwapRegion.orSelf(mDirtyRegion); - mDirtyRegion.clear(); + hw->swapRegion.orSelf(dirtyRegion); } -void SurfaceFlinger::setupHardwareComposer() +void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - HWComposer& hwc(hw.getHwComposer()); - hwc_layer_t* const cur(hwc.getLayers()); - if (!cur) { - return; - } - - const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); - size_t count = layers.size(); + HWComposer& hwc(getHwComposer()); + int32_t id = hw->getDisplayId(); + HWComposer::LayerListIterator cur = hwc.begin(id); + const HWComposer::LayerListIterator end = hwc.end(id); - ALOGE_IF(hwc.getNumLayers() != count, - "HAL number of layers (%d) doesn't match surfaceflinger (%d)", - hwc.getNumLayers(), count); - - // just to be extra-safe, use the smallest count - if (hwc.initCheck() == NO_ERROR) { - count = count < hwc.getNumLayers() ? count : hwc.getNumLayers(); - } + const size_t fbLayerCount = hwc.getLayerCount(id, HWC_FRAMEBUFFER); + if (cur==end || fbLayerCount) { - /* - * update the per-frame h/w composer data for each layer - * and build the transparent region of the FB - */ - for (size_t i=0 ; i<count ; i++) { - const sp<LayerBase>& layer(layers[i]); - layer->setPerFrameData(&cur[i]); - } - status_t err = hwc.prepare(); - ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); -} + DisplayDevice::makeCurrent(hw, mEGLContext); -void SurfaceFlinger::composeSurfaces(const Region& dirty) -{ - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - HWComposer& hwc(hw.getHwComposer()); - hwc_layer_t* const cur(hwc.getLayers()); + // set the frame buffer + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); - const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER); - if (!cur || fbLayerCount) { // Never touch the framebuffer if we don't have any framebuffer layers - - if (hwc.getLayerCount(HWC_OVERLAY)) { + if (hwc.getLayerCount(id, HWC_OVERLAY)) { // when using overlays, we assume a fully transparent framebuffer // NOTE: we could reduce how much we need to clear, for instance // remove where there are opaque FB layers. however, on some @@ -916,10 +1274,11 @@ void SurfaceFlinger::composeSurfaces(const Region& dirty) glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); } else { + const Region region(hw->undefinedRegion.intersect(dirty)); // screen is already cleared here - if (!mWormholeRegion.isEmpty()) { + if (!region.isEmpty()) { // can happen with SurfaceView - drawWormhole(); + drawWormhole(region); } } @@ -927,82 +1286,40 @@ void SurfaceFlinger::composeSurfaces(const Region& dirty) * and then, render the layers targeted at the framebuffer */ - const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); + const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); const size_t count = layers.size(); - - for (size_t i=0 ; i<count ; i++) { + const Transform& tr = hw->getTransform(); + for (size_t i=0 ; i<count ; ++i) { const sp<LayerBase>& layer(layers[i]); - const Region clip(dirty.intersect(layer->visibleRegionScreen)); - if (!clip.isEmpty()) { - if (cur && (cur[i].compositionType == HWC_OVERLAY)) { - if (i && (cur[i].hints & HWC_HINT_CLEAR_FB) - && layer->isOpaque()) { - // never clear the very first layer since we're - // guaranteed the FB is already cleared - layer->clearWithOpenGL(clip); + const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); + if (cur != end) { + // we're using h/w composer + if (!clip.isEmpty()) { + if (cur->getCompositionType() == HWC_OVERLAY) { + if (i && (cur->getHints() & HWC_HINT_CLEAR_FB) + && layer->isOpaque()) { + // never clear the very first layer since we're + // guaranteed the FB is already cleared + layer->clearWithOpenGL(hw, clip); + } + } else { + layer->draw(hw, clip); } - continue; + layer->setAcquireFence(hw, *cur); + } + ++cur; + } else { + // we're not using h/w composer + if (!clip.isEmpty()) { + layer->draw(hw, clip); } - // render the layer - layer->draw(clip); } } } } -void SurfaceFlinger::debugFlashRegions() -{ - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const uint32_t flags = hw.getFlags(); - const int32_t height = hw.getHeight(); - if (mSwapRegion.isEmpty()) { - return; - } - - if (!(flags & DisplayHardware::SWAP_RECTANGLE)) { - const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ? - mDirtyRegion.bounds() : hw.bounds()); - composeSurfaces(repaint); - } - - glDisable(GL_TEXTURE_EXTERNAL_OES); - glDisable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - - static int toggle = 0; - toggle = 1 - toggle; - if (toggle) { - glColor4f(1, 0, 1, 1); - } else { - glColor4f(1, 1, 0, 1); - } - - Region::const_iterator it = mDirtyRegion.begin(); - Region::const_iterator const end = mDirtyRegion.end(); - while (it != end) { - const Rect& r = *it++; - GLfloat vertices[][2] = { - { r.left, height - r.top }, - { r.left, height - r.bottom }, - { r.right, height - r.bottom }, - { r.right, height - r.top } - }; - glVertexPointer(2, GL_FLOAT, 0, vertices); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - } - - hw.flip(mSwapRegion); - - if (mDebugRegion > 1) - usleep(mDebugRegion * 1000); -} - -void SurfaceFlinger::drawWormhole() const +void SurfaceFlinger::drawWormhole(const Region& region) const { - const Region region(mWormholeRegion.intersect(mDirtyRegion)); - if (region.isEmpty()) - return; - glDisable(GL_TEXTURE_EXTERNAL_OES); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); @@ -1026,30 +1343,15 @@ void SurfaceFlinger::drawWormhole() const } } -status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer) -{ - Mutex::Autolock _l(mStateLock); - addLayer_l(layer); - setTransactionFlags(eTransactionNeeded|eTraversalNeeded); - return NO_ERROR; -} - -status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer) -{ - ssize_t i = mCurrentState.layersSortedByZ.add(layer); - return (i < 0) ? status_t(i) : status_t(NO_ERROR); -} - ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<LayerBaseClient>& lbc) { // attach this layer to the client size_t name = client->attachLayer(lbc); - Mutex::Autolock _l(mStateLock); - // add this layer to the current state list - addLayer_l(lbc); + Mutex::Autolock _l(mStateLock); + mCurrentState.layersSortedByZ.add(lbc); return ssize_t(name); } @@ -1065,10 +1367,6 @@ status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) { - sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient()); - if (lbc != 0) { - mLayerMap.removeItem( lbc->getSurfaceBinder() ); - } ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); if (index >= 0) { mLayersRemoved = true; @@ -1095,13 +1393,6 @@ status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; } -status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer) -{ - layer->forceVisibilityTransaction(); - setTransactionFlags(eTraversalNeeded); - return NO_ERROR; -} - uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) { return android_atomic_release_load(&mTransactionFlags); @@ -1121,23 +1412,21 @@ uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) return old; } - -void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state, - int orientation, uint32_t flags) { +void SurfaceFlinger::setTransactionState( + const Vector<ComposerState>& state, + const Vector<DisplayState>& displays, + uint32_t flags) +{ Mutex::Autolock _l(mStateLock); - uint32_t transactionFlags = 0; - if (mCurrentState.orientation != orientation) { - if (uint32_t(orientation)<=eOrientation270 || orientation==42) { - mCurrentState.orientation = orientation; - transactionFlags |= eTransactionNeeded; - } else if (orientation != eOrientationUnchanged) { - ALOGW("setTransactionState: ignoring unrecognized orientation: %d", - orientation); - } + + size_t count = displays.size(); + for (size_t i=0 ; i<count ; i++) { + const DisplayState& s(displays[i]); + transactionFlags |= setDisplayStateLocked(s); } - const size_t count = state.size(); + count = state.size(); for (size_t i=0 ; i<count ; i++) { const ComposerState& s(state[i]); sp<Client> client( static_cast<Client *>(s.client.get()) ); @@ -1166,7 +1455,110 @@ void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state, } } -sp<ISurface> SurfaceFlinger::createSurface( +uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) +{ + uint32_t flags = 0; + DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token)); + if (disp.id >= 0) { + const uint32_t what = s.what; + if (what & DisplayState::eSurfaceChanged) { + if (disp.surface->asBinder() != s.surface->asBinder()) { + disp.surface = s.surface; + flags |= eDisplayTransactionNeeded; + } + } + if (what & DisplayState::eLayerStackChanged) { + if (disp.layerStack != s.layerStack) { + disp.layerStack = s.layerStack; + flags |= eDisplayTransactionNeeded; + } + } + if (what & DisplayState::eOrientationChanged) { + if (disp.orientation != s.orientation) { + disp.orientation = s.orientation; + flags |= eDisplayTransactionNeeded; + } + } + if (what & DisplayState::eFrameChanged) { + if (disp.frame != s.frame) { + disp.frame = s.frame; + flags |= eDisplayTransactionNeeded; + } + } + if (what & DisplayState::eViewportChanged) { + if (disp.viewport != s.viewport) { + disp.viewport = s.viewport; + flags |= eDisplayTransactionNeeded; + } + } + } + return flags; +} + +uint32_t SurfaceFlinger::setClientStateLocked( + const sp<Client>& client, + const layer_state_t& s) +{ + uint32_t flags = 0; + sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); + if (layer != 0) { + const uint32_t what = s.what; + if (what & layer_state_t::ePositionChanged) { + if (layer->setPosition(s.x, s.y)) + flags |= eTraversalNeeded; + } + if (what & layer_state_t::eLayerChanged) { + // NOTE: index needs to be calculated before we update the state + ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); + if (layer->setLayer(s.z)) { + mCurrentState.layersSortedByZ.removeAt(idx); + mCurrentState.layersSortedByZ.add(layer); + // we need traversal (state changed) + // AND transaction (list changed) + flags |= eTransactionNeeded|eTraversalNeeded; + } + } + if (what & layer_state_t::eSizeChanged) { + if (layer->setSize(s.w, s.h)) { + flags |= eTraversalNeeded; + } + } + if (what & layer_state_t::eAlphaChanged) { + if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) + flags |= eTraversalNeeded; + } + if (what & layer_state_t::eMatrixChanged) { + if (layer->setMatrix(s.matrix)) + flags |= eTraversalNeeded; + } + if (what & layer_state_t::eTransparentRegionChanged) { + if (layer->setTransparentRegionHint(s.transparentRegion)) + flags |= eTraversalNeeded; + } + if (what & layer_state_t::eVisibilityChanged) { + if (layer->setFlags(s.flags, s.mask)) + flags |= eTraversalNeeded; + } + if (what & layer_state_t::eCropChanged) { + if (layer->setCrop(s.crop)) + flags |= eTraversalNeeded; + } + if (what & layer_state_t::eLayerStackChanged) { + // NOTE: index needs to be calculated before we update the state + ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); + if (layer->setLayerStack(s.layerStack)) { + mCurrentState.layersSortedByZ.removeAt(idx); + mCurrentState.layersSortedByZ.add(layer); + // we need traversal (state changed) + // AND transaction (list changed) + flags |= eTransactionNeeded|eTraversalNeeded; + } + } + } + return flags; +} + +sp<ISurface> SurfaceFlinger::createLayer( ISurfaceComposerClient::surface_data_t* params, const String8& name, const sp<Client>& client, @@ -1177,26 +1569,22 @@ sp<ISurface> SurfaceFlinger::createSurface( sp<ISurface> surfaceHandle; if (int32_t(w|h) < 0) { - ALOGE("createSurface() failed, w or h is negative (w=%d, h=%d)", + ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", int(w), int(h)); return surfaceHandle; } - //ALOGD("createSurface for (%d x %d), name=%s", w, h, name.string()); - sp<Layer> normalLayer; - switch (flags & eFXSurfaceMask) { - case eFXSurfaceNormal: - normalLayer = createNormalSurface(client, d, w, h, flags, format); - layer = normalLayer; + //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); + switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { + case ISurfaceComposerClient::eFXSurfaceNormal: + layer = createNormalLayer(client, d, w, h, flags, format); break; - case eFXSurfaceBlur: - // for now we treat Blur as Dim, until we can implement it - // efficiently. - case eFXSurfaceDim: - layer = createDimSurface(client, d, w, h, flags); + case ISurfaceComposerClient::eFXSurfaceBlur: + case ISurfaceComposerClient::eFXSurfaceDim: + layer = createDimLayer(client, d, w, h, flags); break; - case eFXSurfaceScreenshot: - layer = createScreenshotSurface(client, d, w, h, flags); + case ISurfaceComposerClient::eFXSurfaceScreenshot: + layer = createScreenshotLayer(client, d, w, h, flags); break; } @@ -1204,30 +1592,24 @@ sp<ISurface> SurfaceFlinger::createSurface( layer->initStates(w, h, flags); layer->setName(name); ssize_t token = addClientLayer(client, layer); - surfaceHandle = layer->getSurface(); if (surfaceHandle != 0) { params->token = token; params->identity = layer->getIdentity(); - if (normalLayer != 0) { - Mutex::Autolock _l(mStateLock); - mLayerMap.add(layer->getSurfaceBinder(), normalLayer); - } } - setTransactionFlags(eTransactionNeeded); } return surfaceHandle; } -sp<Layer> SurfaceFlinger::createNormalSurface( +sp<Layer> SurfaceFlinger::createNormalLayer( const sp<Client>& client, DisplayID display, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format) { // initialize the surfaces - switch (format) { // TODO: take h/w into account + switch (format) { case PIXEL_FORMAT_TRANSPARENT: case PIXEL_FORMAT_TRANSLUCENT: format = PIXEL_FORMAT_RGBA_8888; @@ -1249,13 +1631,13 @@ sp<Layer> SurfaceFlinger::createNormalSurface( sp<Layer> layer = new Layer(this, display, client); status_t err = layer->setBuffers(w, h, format, flags); if (CC_LIKELY(err != NO_ERROR)) { - ALOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err)); + ALOGE("createNormalLayer() failed (%s)", strerror(-err)); layer.clear(); } return layer; } -sp<LayerDim> SurfaceFlinger::createDimSurface( +sp<LayerDim> SurfaceFlinger::createDimLayer( const sp<Client>& client, DisplayID display, uint32_t w, uint32_t h, uint32_t flags) { @@ -1263,7 +1645,7 @@ sp<LayerDim> SurfaceFlinger::createDimSurface( return layer; } -sp<LayerScreenshot> SurfaceFlinger::createScreenshotSurface( +sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer( const sp<Client>& client, DisplayID display, uint32_t w, uint32_t h, uint32_t flags) { @@ -1271,7 +1653,7 @@ sp<LayerScreenshot> SurfaceFlinger::createScreenshotSurface( return layer; } -status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid) +status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid) { /* * called by the window manager, when a surface should be marked for @@ -1295,7 +1677,7 @@ status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid) return err; } -status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer) +status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer) { // called by ~ISurface() when all references are gone status_t err = NO_ERROR; @@ -1317,80 +1699,30 @@ status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer) return err; } -uint32_t SurfaceFlinger::setClientStateLocked( - const sp<Client>& client, - const layer_state_t& s) -{ - uint32_t flags = 0; - sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); - if (layer != 0) { - const uint32_t what = s.what; - if (what & ePositionChanged) { - if (layer->setPosition(s.x, s.y)) - flags |= eTraversalNeeded; - } - if (what & eLayerChanged) { - ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); - if (layer->setLayer(s.z)) { - mCurrentState.layersSortedByZ.removeAt(idx); - mCurrentState.layersSortedByZ.add(layer); - // we need traversal (state changed) - // AND transaction (list changed) - flags |= eTransactionNeeded|eTraversalNeeded; - } - } - if (what & eSizeChanged) { - if (layer->setSize(s.w, s.h)) { - flags |= eTraversalNeeded; - } - } - if (what & eAlphaChanged) { - if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) - flags |= eTraversalNeeded; - } - if (what & eMatrixChanged) { - if (layer->setMatrix(s.matrix)) - flags |= eTraversalNeeded; - } - if (what & eTransparentRegionChanged) { - if (layer->setTransparentRegionHint(s.transparentRegion)) - flags |= eTraversalNeeded; - } - if (what & eVisibilityChanged) { - if (layer->setFlags(s.flags, s.mask)) - flags |= eTraversalNeeded; - } - if (what & eCropChanged) { - if (layer->setCrop(s.crop)) - flags |= eTraversalNeeded; - } - } - return flags; -} - // --------------------------------------------------------------------------- void SurfaceFlinger::onScreenAcquired() { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - hw.acquireScreen(); + ALOGD("Screen about to return, flinger = %p", this); + sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice + getHwComposer().acquire(); + hw->acquireScreen(); mEventThread->onScreenAcquired(); - // this is a temporary work-around, eventually this should be called - // by the power-manager - SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode); - // from this point on, SF will process updates again + mVisibleRegionsDirty = true; repaintEverything(); } void SurfaceFlinger::onScreenReleased() { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - if (hw.isScreenAcquired()) { + ALOGD("About to give-up screen, flinger = %p", this); + sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice + if (hw->isScreenAcquired()) { mEventThread->onScreenReleased(); - hw.releaseScreen(); + hw->releaseScreen(); + getHwComposer().release(); // from this point on, SF will stop drawing } } -void SurfaceFlinger::screenAcquired() { +void SurfaceFlinger::unblank() { class MessageScreenAcquired : public MessageBase { SurfaceFlinger* flinger; public: @@ -1404,7 +1736,7 @@ void SurfaceFlinger::screenAcquired() { postMessageSync(msg); } -void SurfaceFlinger::screenReleased() { +void SurfaceFlinger::blank() { class MessageScreenReleased : public MessageBase { SurfaceFlinger* flinger; public: @@ -1575,12 +1907,34 @@ void SurfaceFlinger::dumpAllLocked( } /* + * Dump Display state + */ + + for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { + const sp<const DisplayDevice>& hw(mDisplays[dpy]); + snprintf(buffer, SIZE, + "+ DisplayDevice[%u]\n" + " id=%x, layerStack=%u, (%4dx%4d), orient=%2d, tr=%08x, " + "flips=%u, secure=%d, numLayers=%u\n", + dpy, + hw->getDisplayId(), hw->getLayerStack(), + hw->getWidth(), hw->getHeight(), + hw->getOrientation(), hw->getTransform().getType(), + hw->getPageFlipCount(), + hw->getSecureLayerVisible(), + hw->getVisibleLayersSortedByZ().size()); + result.append(buffer); + } + + /* * Dump SurfaceFlinger global state */ snprintf(buffer, SIZE, "SurfaceFlinger global state:\n"); result.append(buffer); + HWComposer& hwc(getHwComposer()); + sp<const DisplayDevice> hw(getDefaultDisplayDevice()); const GLExtensions& extensions(GLExtensions::getInstance()); snprintf(buffer, SIZE, "GLES: %s, %s, %s\n", extensions.getVendor(), @@ -1589,18 +1943,16 @@ void SurfaceFlinger::dumpAllLocked( result.append(buffer); snprintf(buffer, SIZE, "EGL : %s\n", - eglQueryString(graphicPlane(0).getEGLDisplay(), - EGL_VERSION_HW_ANDROID)); + eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID)); result.append(buffer); snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension()); result.append(buffer); - mWormholeRegion.dump(result, "WormholeRegion"); - const DisplayHardware& hw(graphicPlane(0).displayHardware()); + hw->undefinedRegion.dump(result, "undefinedRegion"); snprintf(buffer, SIZE, " orientation=%d, canDraw=%d\n", - mCurrentState.orientation, hw.canDraw()); + hw->getOrientation(), hw->canDraw()); result.append(buffer); snprintf(buffer, SIZE, " last eglSwapBuffers() time: %f us\n" @@ -1608,15 +1960,13 @@ void SurfaceFlinger::dumpAllLocked( " transaction-flags : %08x\n" " refresh-rate : %f fps\n" " x-dpi : %f\n" - " y-dpi : %f\n" - " density : %f\n", + " y-dpi : %f\n", mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0, mTransactionFlags, - hw.getRefreshRate(), - hw.getDpiX(), - hw.getDpiY(), - hw.getDensity()); + 1e9 / hwc.getRefreshPeriod(), + hwc.getDpiX(), + hwc.getDpiY()); result.append(buffer); snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", @@ -1635,21 +1985,20 @@ void SurfaceFlinger::dumpAllLocked( /* * Dump HWComposer state */ - HWComposer& hwc(hw.getHwComposer()); snprintf(buffer, SIZE, "h/w composer state:\n"); result.append(buffer); snprintf(buffer, SIZE, " h/w composer %s and %s\n", hwc.initCheck()==NO_ERROR ? "present" : "not present", (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled"); result.append(buffer); - hwc.dump(result, buffer, SIZE, mVisibleLayersSortedByZ); + hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ()); /* * Dump gralloc state */ const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); alloc.dump(result); - hw.dump(result); + hw->dump(result); } status_t SurfaceFlinger::onTransact( @@ -1658,10 +2007,9 @@ status_t SurfaceFlinger::onTransact( switch (code) { case CREATE_CONNECTION: case SET_TRANSACTION_STATE: - case SET_ORIENTATION: case BOOT_FINISHED: - case TURN_ELECTRON_BEAM_OFF: - case TURN_ELECTRON_BEAM_ON: + case BLANK: + case UNBLANK: { // codes that require permission check IPCThreadState* ipc = IPCThreadState::self(); @@ -1718,7 +2066,10 @@ status_t SurfaceFlinger::onTransact( return NO_ERROR; } case 1005:{ // force transaction - setTransactionFlags(eTransactionNeeded|eTraversalNeeded); + setTransactionFlags( + eTransactionNeeded| + eDisplayTransactionNeeded| + eTraversalNeeded); return NO_ERROR; } case 1006:{ // send empty update @@ -1746,8 +2097,8 @@ status_t SurfaceFlinger::onTransact( return NO_ERROR; case 1013: { Mutex::Autolock _l(mStateLock); - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - reply->writeInt32(hw.getPageFlipCount()); + sp<const DisplayDevice> hw(getDefaultDisplayDevice()); + reply->writeInt32(hw->getPageFlipCount()); } return NO_ERROR; } @@ -1756,24 +2107,10 @@ status_t SurfaceFlinger::onTransact( } void SurfaceFlinger::repaintEverything() { - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const Rect bounds(hw.getBounds()); - setInvalidateRegion(Region(bounds)); + android_atomic_or(1, &mRepaintEverything); signalTransaction(); } -void SurfaceFlinger::setInvalidateRegion(const Region& reg) { - Mutex::Autolock _l(mInvalidateLock); - mInvalidateRegion = reg; -} - -Region SurfaceFlinger::getAndClearInvalidateRegion() { - Mutex::Autolock _l(mInvalidateLock); - Region reg(mInvalidateRegion); - mInvalidateRegion.clear(); - return reg; -} - // --------------------------------------------------------------------------- status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy, @@ -1792,9 +2129,9 @@ status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy, return INVALID_OPERATION; // get screen geometry - const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); - const uint32_t hw_w = hw.getWidth(); - const uint32_t hw_h = hw.getHeight(); + sp<const DisplayDevice> hw(getDisplayDevice(dpy)); + const uint32_t hw_w = hw->getWidth(); + const uint32_t hw_h = hw->getHeight(); GLfloat u = 1; GLfloat v = 1; @@ -1830,14 +2167,14 @@ status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy, glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); - const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); + const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); const size_t count = layers.size(); for (size_t i=0 ; i<count ; ++i) { const sp<LayerBase>& layer(layers[i]); - layer->drawForSreenShot(); + layer->draw(hw); } - hw.compositionComplete(); + hw->compositionComplete(); // back to main framebuffer glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); @@ -1851,471 +2188,6 @@ status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy, // --------------------------------------------------------------------------- -class VSyncWaiter { - DisplayEventReceiver::Event buffer[4]; - sp<Looper> looper; - sp<IDisplayEventConnection> events; - sp<BitTube> eventTube; -public: - VSyncWaiter(const sp<EventThread>& eventThread) { - looper = new Looper(true); - events = eventThread->createEventConnection(); - eventTube = events->getDataChannel(); - looper->addFd(eventTube->getFd(), 0, ALOOPER_EVENT_INPUT, 0, 0); - events->requestNextVsync(); - } - - void wait() { - ssize_t n; - - looper->pollOnce(-1); - // we don't handle any errors here, it doesn't matter - // and we don't want to take the risk to get stuck. - - // drain the events... - while ((n = DisplayEventReceiver::getEvents( - eventTube, buffer, 4)) > 0) ; - - events->requestNextVsync(); - } -}; - -status_t SurfaceFlinger::electronBeamOffAnimationImplLocked() -{ - // get screen geometry - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const uint32_t hw_w = hw.getWidth(); - const uint32_t hw_h = hw.getHeight(); - const Region screenBounds(hw.getBounds()); - - GLfloat u, v; - GLuint tname; - status_t result = renderScreenToTextureLocked(0, &tname, &u, &v); - if (result != NO_ERROR) { - return result; - } - - GLfloat vtx[8]; - const GLfloat texCoords[4][2] = { {0,0}, {0,v}, {u,v}, {u,0} }; - glBindTexture(GL_TEXTURE_2D, tname); - glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexCoordPointer(2, GL_FLOAT, 0, texCoords); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(2, GL_FLOAT, 0, vtx); - - /* - * Texture coordinate mapping - * - * u - * 1 +----------+---+ - * | | | | image is inverted - * | V | | w.r.t. the texture - * 1-v +----------+ | coordinates - * | | - * | | - * | | - * 0 +--------------+ - * 0 1 - * - */ - - class s_curve_interpolator { - const float nbFrames, s, v; - public: - s_curve_interpolator(int nbFrames, float s) - : nbFrames(1.0f / (nbFrames-1)), s(s), - v(1.0f + expf(-s + 0.5f*s)) { - } - float operator()(int f) { - const float x = f * nbFrames; - return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; - } - }; - - class v_stretch { - const GLfloat hw_w, hw_h; - public: - v_stretch(uint32_t hw_w, uint32_t hw_h) - : hw_w(hw_w), hw_h(hw_h) { - } - void operator()(GLfloat* vtx, float v) { - const GLfloat w = hw_w + (hw_w * v); - const GLfloat h = hw_h - (hw_h * v); - const GLfloat x = (hw_w - w) * 0.5f; - const GLfloat y = (hw_h - h) * 0.5f; - vtx[0] = x; vtx[1] = y; - vtx[2] = x; vtx[3] = y + h; - vtx[4] = x + w; vtx[5] = y + h; - vtx[6] = x + w; vtx[7] = y; - } - }; - - class h_stretch { - const GLfloat hw_w, hw_h; - public: - h_stretch(uint32_t hw_w, uint32_t hw_h) - : hw_w(hw_w), hw_h(hw_h) { - } - void operator()(GLfloat* vtx, float v) { - const GLfloat w = hw_w - (hw_w * v); - const GLfloat h = 1.0f; - const GLfloat x = (hw_w - w) * 0.5f; - const GLfloat y = (hw_h - h) * 0.5f; - vtx[0] = x; vtx[1] = y; - vtx[2] = x; vtx[3] = y + h; - vtx[4] = x + w; vtx[5] = y + h; - vtx[6] = x + w; vtx[7] = y; - } - }; - - VSyncWaiter vsync(mEventThread); - - // the full animation is 24 frames - char value[PROPERTY_VALUE_MAX]; - property_get("debug.sf.electron_frames", value, "24"); - int nbFrames = (atoi(value) + 1) >> 1; - if (nbFrames <= 0) // just in case - nbFrames = 24; - - s_curve_interpolator itr(nbFrames, 7.5f); - s_curve_interpolator itg(nbFrames, 8.0f); - s_curve_interpolator itb(nbFrames, 8.5f); - - v_stretch vverts(hw_w, hw_h); - - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE); - for (int i=0 ; i<nbFrames ; i++) { - float x, y, w, h; - const float vr = itr(i); - const float vg = itg(i); - const float vb = itb(i); - - // wait for vsync - vsync.wait(); - - // clear screen - glColorMask(1,1,1,1); - glClear(GL_COLOR_BUFFER_BIT); - glEnable(GL_TEXTURE_2D); - - // draw the red plane - vverts(vtx, vr); - glColorMask(1,0,0,1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - // draw the green plane - vverts(vtx, vg); - glColorMask(0,1,0,1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - // draw the blue plane - vverts(vtx, vb); - glColorMask(0,0,1,1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - // draw the white highlight (we use the last vertices) - glDisable(GL_TEXTURE_2D); - glColorMask(1,1,1,1); - glColor4f(vg, vg, vg, 1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - hw.flip(screenBounds); - } - - h_stretch hverts(hw_w, hw_h); - glDisable(GL_BLEND); - glDisable(GL_TEXTURE_2D); - glColorMask(1,1,1,1); - for (int i=0 ; i<nbFrames ; i++) { - const float v = itg(i); - hverts(vtx, v); - - // wait for vsync - vsync.wait(); - - glClear(GL_COLOR_BUFFER_BIT); - glColor4f(1-v, 1-v, 1-v, 1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - hw.flip(screenBounds); - } - - glColorMask(1,1,1,1); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDeleteTextures(1, &tname); - glDisable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - return NO_ERROR; -} - -status_t SurfaceFlinger::electronBeamOnAnimationImplLocked() -{ - status_t result = PERMISSION_DENIED; - - if (!GLExtensions::getInstance().haveFramebufferObject()) - return INVALID_OPERATION; - - - // get screen geometry - const DisplayHardware& hw(graphicPlane(0).displayHardware()); - const uint32_t hw_w = hw.getWidth(); - const uint32_t hw_h = hw.getHeight(); - const Region screenBounds(hw.bounds()); - - GLfloat u, v; - GLuint tname; - result = renderScreenToTextureLocked(0, &tname, &u, &v); - if (result != NO_ERROR) { - return result; - } - - GLfloat vtx[8]; - const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} }; - glBindTexture(GL_TEXTURE_2D, tname); - glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexCoordPointer(2, GL_FLOAT, 0, texCoords); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glVertexPointer(2, GL_FLOAT, 0, vtx); - - class s_curve_interpolator { - const float nbFrames, s, v; - public: - s_curve_interpolator(int nbFrames, float s) - : nbFrames(1.0f / (nbFrames-1)), s(s), - v(1.0f + expf(-s + 0.5f*s)) { - } - float operator()(int f) { - const float x = f * nbFrames; - return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; - } - }; - - class v_stretch { - const GLfloat hw_w, hw_h; - public: - v_stretch(uint32_t hw_w, uint32_t hw_h) - : hw_w(hw_w), hw_h(hw_h) { - } - void operator()(GLfloat* vtx, float v) { - const GLfloat w = hw_w + (hw_w * v); - const GLfloat h = hw_h - (hw_h * v); - const GLfloat x = (hw_w - w) * 0.5f; - const GLfloat y = (hw_h - h) * 0.5f; - vtx[0] = x; vtx[1] = y; - vtx[2] = x; vtx[3] = y + h; - vtx[4] = x + w; vtx[5] = y + h; - vtx[6] = x + w; vtx[7] = y; - } - }; - - class h_stretch { - const GLfloat hw_w, hw_h; - public: - h_stretch(uint32_t hw_w, uint32_t hw_h) - : hw_w(hw_w), hw_h(hw_h) { - } - void operator()(GLfloat* vtx, float v) { - const GLfloat w = hw_w - (hw_w * v); - const GLfloat h = 1.0f; - const GLfloat x = (hw_w - w) * 0.5f; - const GLfloat y = (hw_h - h) * 0.5f; - vtx[0] = x; vtx[1] = y; - vtx[2] = x; vtx[3] = y + h; - vtx[4] = x + w; vtx[5] = y + h; - vtx[6] = x + w; vtx[7] = y; - } - }; - - VSyncWaiter vsync(mEventThread); - - // the full animation is 12 frames - int nbFrames = 8; - s_curve_interpolator itr(nbFrames, 7.5f); - s_curve_interpolator itg(nbFrames, 8.0f); - s_curve_interpolator itb(nbFrames, 8.5f); - - h_stretch hverts(hw_w, hw_h); - glDisable(GL_BLEND); - glDisable(GL_TEXTURE_2D); - glColorMask(1,1,1,1); - for (int i=nbFrames-1 ; i>=0 ; i--) { - const float v = itg(i); - hverts(vtx, v); - - // wait for vsync - vsync.wait(); - - glClear(GL_COLOR_BUFFER_BIT); - glColor4f(1-v, 1-v, 1-v, 1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - hw.flip(screenBounds); - } - - nbFrames = 4; - v_stretch vverts(hw_w, hw_h); - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE); - for (int i=nbFrames-1 ; i>=0 ; i--) { - float x, y, w, h; - const float vr = itr(i); - const float vg = itg(i); - const float vb = itb(i); - - // wait for vsync - vsync.wait(); - - // clear screen - glColorMask(1,1,1,1); - glClear(GL_COLOR_BUFFER_BIT); - glEnable(GL_TEXTURE_2D); - - // draw the red plane - vverts(vtx, vr); - glColorMask(1,0,0,1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - // draw the green plane - vverts(vtx, vg); - glColorMask(0,1,0,1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - // draw the blue plane - vverts(vtx, vb); - glColorMask(0,0,1,1); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - hw.flip(screenBounds); - } - - glColorMask(1,1,1,1); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDeleteTextures(1, &tname); - glDisable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - - return NO_ERROR; -} - -// --------------------------------------------------------------------------- - -status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode) -{ - ATRACE_CALL(); - - DisplayHardware& hw(graphicPlane(0).editDisplayHardware()); - if (!hw.canDraw()) { - // we're already off - return NO_ERROR; - } - - // turn off hwc while we're doing the animation - hw.getHwComposer().disable(); - // and make sure to turn it back on (if needed) next time we compose - invalidateHwcGeometry(); - - if (mode & ISurfaceComposer::eElectronBeamAnimationOff) { - electronBeamOffAnimationImplLocked(); - } - - // always clear the whole screen at the end of the animation - glClearColor(0,0,0,1); - glClear(GL_COLOR_BUFFER_BIT); - hw.flip( Region(hw.bounds()) ); - - return NO_ERROR; -} - -status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode) -{ - class MessageTurnElectronBeamOff : public MessageBase { - SurfaceFlinger* flinger; - int32_t mode; - status_t result; - public: - MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode) - : flinger(flinger), mode(mode), result(PERMISSION_DENIED) { - } - status_t getResult() const { - return result; - } - virtual bool handler() { - Mutex::Autolock _l(flinger->mStateLock); - result = flinger->turnElectronBeamOffImplLocked(mode); - return true; - } - }; - - sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode); - status_t res = postMessageSync(msg); - if (res == NO_ERROR) { - res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult(); - - // work-around: when the power-manager calls us we activate the - // animation. eventually, the "on" animation will be called - // by the power-manager itself - mElectronBeamAnimationMode = mode; - } - return res; -} - -// --------------------------------------------------------------------------- - -status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode) -{ - DisplayHardware& hw(graphicPlane(0).editDisplayHardware()); - if (hw.canDraw()) { - // we're already on - return NO_ERROR; - } - if (mode & ISurfaceComposer::eElectronBeamAnimationOn) { - electronBeamOnAnimationImplLocked(); - } - - // make sure to redraw the whole screen when the animation is done - mDirtyRegion.set(hw.bounds()); - signalTransaction(); - - return NO_ERROR; -} - -status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode) -{ - class MessageTurnElectronBeamOn : public MessageBase { - SurfaceFlinger* flinger; - int32_t mode; - status_t result; - public: - MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode) - : flinger(flinger), mode(mode), result(PERMISSION_DENIED) { - } - status_t getResult() const { - return result; - } - virtual bool handler() { - Mutex::Autolock _l(flinger->mStateLock); - result = flinger->turnElectronBeamOnImplLocked(mode); - return true; - } - }; - - postMessageAsync( new MessageTurnElectronBeamOn(this, mode) ); - return NO_ERROR; -} - -// --------------------------------------------------------------------------- - status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, @@ -2327,26 +2199,38 @@ status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, status_t result = PERMISSION_DENIED; // only one display supported for now - if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) + if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) { + ALOGE("invalid display %d", dpy); return BAD_VALUE; + } - if (!GLExtensions::getInstance().haveFramebufferObject()) + if (!GLExtensions::getInstance().haveFramebufferObject()) { return INVALID_OPERATION; + } // get screen geometry - const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); - const uint32_t hw_w = hw.getWidth(); - const uint32_t hw_h = hw.getHeight(); + sp<const DisplayDevice> hw(getDisplayDevice(dpy)); + const uint32_t hw_w = hw->getWidth(); + const uint32_t hw_h = hw->getHeight(); + + // if we have secure windows on this display, never allow the screen capture + if (hw->getSecureLayerVisible()) { + ALOGW("FB is protected: PERMISSION_DENIED"); + return PERMISSION_DENIED; + } - if ((sw > hw_w) || (sh > hw_h)) + if ((sw > hw_w) || (sh > hw_h)) { + ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h); return BAD_VALUE; + } sw = (!sw) ? hw_w : sw; sh = (!sh) ? hw_h : sh; const size_t size = sw * sh * 4; + const bool filtering = sw != hw_w || sh != hw_h; - //ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", - // sw, sh, minLayerZ, maxLayerZ); +// ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", +// sw, sh, minLayerZ, maxLayerZ); // make sure to clear all GL error flags while ( glGetError() != GL_NO_ERROR ) ; @@ -2383,10 +2267,12 @@ status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, for (size_t i=0 ; i<count ; ++i) { const sp<LayerBase>& layer(layers[i]); const uint32_t flags = layer->drawingState().flags; - if (!(flags & ISurfaceComposer::eLayerHidden)) { + if (!(flags & layer_state_t::eLayerHidden)) { const uint32_t z = layer->drawingState().z; if (z >= minLayerZ && z <= maxLayerZ) { - layer->drawForSreenShot(); + if (filtering) layer->setFiltering(true); + layer->draw(hw); + if (filtering) layer->setFiltering(false); } } } @@ -2429,9 +2315,9 @@ status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, glDeleteRenderbuffersOES(1, &tname); glDeleteFramebuffersOES(1, &name); - hw.compositionComplete(); + hw->compositionComplete(); - // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); +// ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); return result; } @@ -2478,14 +2364,8 @@ status_t SurfaceFlinger::captureScreen(DisplayID dpy, } virtual bool handler() { Mutex::Autolock _l(flinger->mStateLock); - - // if we have secure windows, never allow the screen capture - if (flinger->mSecureFrameBuffer) - return true; - result = flinger->captureScreenImplLocked(dpy, heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); - return true; } }; @@ -2501,136 +2381,40 @@ status_t SurfaceFlinger::captureScreen(DisplayID dpy, // --------------------------------------------------------------------------- -sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const -{ - sp<Layer> result; - Mutex::Autolock _l(mStateLock); - result = mLayerMap.valueFor( sur->asBinder() ).promote(); - return result; +SurfaceFlinger::LayerVector::LayerVector() { } -// --------------------------------------------------------------------------- - -Client::Client(const sp<SurfaceFlinger>& flinger) - : mFlinger(flinger), mNameGenerator(1) -{ +SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) + : SortedVector<sp<LayerBase> >(rhs) { } -Client::~Client() +int SurfaceFlinger::LayerVector::do_compare(const void* lhs, + const void* rhs) const { - const size_t count = mLayers.size(); - for (size_t i=0 ; i<count ; i++) { - sp<LayerBaseClient> layer(mLayers.valueAt(i).promote()); - if (layer != 0) { - mFlinger->removeLayer(layer); - } - } -} + // sort layers per layer-stack, then by z-order and finally by sequence + const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs)); + const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs)); -status_t Client::initCheck() const { - return NO_ERROR; -} + uint32_t ls = l->currentState().layerStack; + uint32_t rs = r->currentState().layerStack; + if (ls != rs) + return ls - rs; -size_t Client::attachLayer(const sp<LayerBaseClient>& layer) -{ - Mutex::Autolock _l(mLock); - size_t name = mNameGenerator++; - mLayers.add(name, layer); - return name; -} + uint32_t lz = l->currentState().z; + uint32_t rz = r->currentState().z; + if (lz != rz) + return lz - rz; -void Client::detachLayer(const LayerBaseClient* layer) -{ - Mutex::Autolock _l(mLock); - // we do a linear search here, because this doesn't happen often - const size_t count = mLayers.size(); - for (size_t i=0 ; i<count ; i++) { - if (mLayers.valueAt(i) == layer) { - mLayers.removeItemsAt(i, 1); - break; - } - } -} -sp<LayerBaseClient> Client::getLayerUser(int32_t i) const -{ - Mutex::Autolock _l(mLock); - sp<LayerBaseClient> lbc; - wp<LayerBaseClient> layer(mLayers.valueFor(i)); - if (layer != 0) { - lbc = layer.promote(); - ALOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i)); - } - return lbc; + return l->sequence - r->sequence; } +// --------------------------------------------------------------------------- -status_t Client::onTransact( - uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) -{ - // these must be checked - IPCThreadState* ipc = IPCThreadState::self(); - const int pid = ipc->getCallingPid(); - const int uid = ipc->getCallingUid(); - const int self_pid = getpid(); - if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) { - // we're called from a different process, do the real check - if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger)) - { - ALOGE("Permission Denial: " - "can't openGlobalTransaction pid=%d, uid=%d", pid, uid); - return PERMISSION_DENIED; - } - } - return BnSurfaceComposerClient::onTransact(code, data, reply, flags); +SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() : id(-1) { } - -sp<ISurface> Client::createSurface( - ISurfaceComposerClient::surface_data_t* params, - const String8& name, - DisplayID display, uint32_t w, uint32_t h, PixelFormat format, - uint32_t flags) -{ - /* - * createSurface must be called from the GL thread so that it can - * have access to the GL context. - */ - - class MessageCreateSurface : public MessageBase { - sp<ISurface> result; - SurfaceFlinger* flinger; - ISurfaceComposerClient::surface_data_t* params; - Client* client; - const String8& name; - DisplayID display; - uint32_t w, h; - PixelFormat format; - uint32_t flags; - public: - MessageCreateSurface(SurfaceFlinger* flinger, - ISurfaceComposerClient::surface_data_t* params, - const String8& name, Client* client, - DisplayID display, uint32_t w, uint32_t h, PixelFormat format, - uint32_t flags) - : flinger(flinger), params(params), client(client), name(name), - display(display), w(w), h(h), format(format), flags(flags) - { - } - sp<ISurface> getResult() const { return result; } - virtual bool handler() { - result = flinger->createSurface(params, name, client, - display, w, h, format, flags); - return true; - } - }; - - sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(), - params, name, this, display, w, h, format, flags); - mFlinger->postMessageSync(msg); - return static_cast<MessageCreateSurface*>( msg.get() )->getResult(); -} -status_t Client::destroySurface(SurfaceID sid) { - return mFlinger->removeSurface(this, sid); +SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(int32_t id) + : id(id), layerStack(0), orientation(0) { } // --------------------------------------------------------------------------- @@ -2658,126 +2442,4 @@ sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h // --------------------------------------------------------------------------- -GraphicPlane::GraphicPlane() - : mHw(0) -{ -} - -GraphicPlane::~GraphicPlane() { - delete mHw; -} - -bool GraphicPlane::initialized() const { - return mHw ? true : false; -} - -int GraphicPlane::getWidth() const { - return mWidth; -} - -int GraphicPlane::getHeight() const { - return mHeight; -} - -void GraphicPlane::setDisplayHardware(DisplayHardware *hw) -{ - mHw = hw; - - // initialize the display orientation transform. - // it's a constant that should come from the display driver. - int displayOrientation = ISurfaceComposer::eOrientationDefault; - char property[PROPERTY_VALUE_MAX]; - if (property_get("ro.sf.hwrotation", property, NULL) > 0) { - //displayOrientation - switch (atoi(property)) { - case 90: - displayOrientation = ISurfaceComposer::eOrientation90; - break; - case 270: - displayOrientation = ISurfaceComposer::eOrientation270; - break; - } - } - - const float w = hw->getWidth(); - const float h = hw->getHeight(); - GraphicPlane::orientationToTransfrom(displayOrientation, w, h, - &mDisplayTransform); - if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) { - mDisplayWidth = h; - mDisplayHeight = w; - } else { - mDisplayWidth = w; - mDisplayHeight = h; - } - - setOrientation(ISurfaceComposer::eOrientationDefault); -} - -status_t GraphicPlane::orientationToTransfrom( - int orientation, int w, int h, Transform* tr) -{ - uint32_t flags = 0; - switch (orientation) { - case ISurfaceComposer::eOrientationDefault: - flags = Transform::ROT_0; - break; - case ISurfaceComposer::eOrientation90: - flags = Transform::ROT_90; - break; - case ISurfaceComposer::eOrientation180: - flags = Transform::ROT_180; - break; - case ISurfaceComposer::eOrientation270: - flags = Transform::ROT_270; - break; - default: - return BAD_VALUE; - } - tr->set(flags, w, h); - return NO_ERROR; -} - -status_t GraphicPlane::setOrientation(int orientation) -{ - // If the rotation can be handled in hardware, this is where - // the magic should happen. - - const DisplayHardware& hw(displayHardware()); - const float w = mDisplayWidth; - const float h = mDisplayHeight; - mWidth = int(w); - mHeight = int(h); - - Transform orientationTransform; - GraphicPlane::orientationToTransfrom(orientation, w, h, - &orientationTransform); - if (orientation & ISurfaceComposer::eOrientationSwapMask) { - mWidth = int(h); - mHeight = int(w); - } - - mOrientation = orientation; - mGlobalTransform = mDisplayTransform * orientationTransform; - return NO_ERROR; -} - -const DisplayHardware& GraphicPlane::displayHardware() const { - return *mHw; -} - -DisplayHardware& GraphicPlane::editDisplayHardware() { - return *mHw; -} - -const Transform& GraphicPlane::transform() const { - return mGlobalTransform; -} - -EGLDisplay GraphicPlane::getEGLDisplay() const { - return mHw->getEGLDisplay(); -} - -// --------------------------------------------------------------------------- - }; // namespace android diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index b20973b..1f79906 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -20,6 +20,9 @@ #include <stdint.h> #include <sys/types.h> +#include <EGL/egl.h> +#include <GLES/gl.h> + #include <cutils/compiler.h> #include <utils/Atomic.h> @@ -33,66 +36,38 @@ #include <binder/IMemory.h> #include <ui/PixelFormat.h> + #include <gui/IGraphicBufferAlloc.h> #include <gui/ISurfaceComposer.h> #include <gui/ISurfaceComposerClient.h> -#include "Barrier.h" -#include "Layer.h" +#include <hardware/hwcomposer_defs.h> + +#include <private/gui/LayerState.h> +#include "Barrier.h" #include "MessageQueue.h" +#include "DisplayDevice.h" + +#include "DisplayHardware/HWComposer.h" namespace android { // --------------------------------------------------------------------------- class Client; -class DisplayHardware; class DisplayEventConnection; class EventThread; class Layer; +class LayerBase; +class LayerBaseClient; class LayerDim; class LayerScreenshot; -struct surface_flinger_cblk_t; +class SurfaceTextureClient; // --------------------------------------------------------------------------- -class Client : public BnSurfaceComposerClient -{ -public: - Client(const sp<SurfaceFlinger>& flinger); - ~Client(); - - status_t initCheck() const; - - // protected by SurfaceFlinger::mStateLock - size_t attachLayer(const sp<LayerBaseClient>& layer); - void detachLayer(const LayerBaseClient* layer); - sp<LayerBaseClient> getLayerUser(int32_t i) const; - -private: - // ISurfaceComposerClient interface - virtual sp<ISurface> createSurface( - surface_data_t* params, const String8& name, - DisplayID display, uint32_t w, uint32_t h,PixelFormat format, - uint32_t flags); - virtual status_t destroySurface(SurfaceID surfaceId); - virtual status_t onTransact( - uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); - - // constant - sp<SurfaceFlinger> mFlinger; - - // protected by mLock - DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers; - size_t mNameGenerator; - - // thread-safe - mutable Mutex mLock; -}; - -class GraphicBufferAlloc : public BnGraphicBufferAlloc -{ +class GraphicBufferAlloc : public BnGraphicBufferAlloc { public: GraphicBufferAlloc(); virtual ~GraphicBufferAlloc(); @@ -102,135 +77,66 @@ public: // --------------------------------------------------------------------------- -class GraphicPlane -{ -public: - static status_t orientationToTransfrom(int orientation, int w, int h, - Transform* tr); - - GraphicPlane(); - ~GraphicPlane(); - - bool initialized() const; - - void setDisplayHardware(DisplayHardware *); - status_t setOrientation(int orientation); - int getOrientation() const { return mOrientation; } - int getWidth() const; - int getHeight() const; - - const DisplayHardware& displayHardware() const; - DisplayHardware& editDisplayHardware(); - const Transform& transform() const; - EGLDisplay getEGLDisplay() const; - -private: - GraphicPlane(const GraphicPlane&); - GraphicPlane operator = (const GraphicPlane&); - - DisplayHardware* mHw; - Transform mGlobalTransform; - Transform mDisplayTransform; - int mOrientation; - float mDisplayWidth; - float mDisplayHeight; - int mWidth; - int mHeight; -}; - -// --------------------------------------------------------------------------- - enum { - eTransactionNeeded = 0x01, - eTraversalNeeded = 0x02 + eTransactionNeeded = 0x01, + eTraversalNeeded = 0x02, + eDisplayTransactionNeeded = 0x04, + eTransactionMask = 0x07 }; -class SurfaceFlinger : - public BinderService<SurfaceFlinger>, - public BnSurfaceComposer, - public IBinder::DeathRecipient, - protected Thread +class SurfaceFlinger : public BinderService<SurfaceFlinger>, + public BnSurfaceComposer, + private IBinder::DeathRecipient, + private Thread, + private HWComposer::EventHandler { public: - static char const* getServiceName() { return "SurfaceFlinger"; } - - SurfaceFlinger(); - virtual ~SurfaceFlinger(); - void init(); + static char const* getServiceName() { + return "SurfaceFlinger"; + } - virtual status_t onTransact( - uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); + SurfaceFlinger(); - virtual status_t dump(int fd, const Vector<String16>& args); - - // ISurfaceComposer interface - virtual sp<ISurfaceComposerClient> createConnection(); - virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc(); - virtual sp<IMemoryHeap> getCblk() const; - virtual void bootFinished(); - virtual void setTransactionState(const Vector<ComposerState>& state, - int orientation, uint32_t flags); - virtual bool authenticateSurfaceTexture(const sp<ISurfaceTexture>& surface) const; - virtual sp<IDisplayEventConnection> createDisplayEventConnection(); - - virtual status_t captureScreen(DisplayID dpy, - sp<IMemoryHeap>* heap, - uint32_t* width, uint32_t* height, - PixelFormat* format, uint32_t reqWidth, uint32_t reqHeight, - uint32_t minLayerZ, uint32_t maxLayerZ); - - virtual status_t turnElectronBeamOff(int32_t mode); - virtual status_t turnElectronBeamOn(int32_t mode); - - - // called when screen needs to turn off - void screenReleased(); - // called when screen is turning back on - void screenAcquired(); - - // called on the main thread in response to screenReleased() - void onScreenReleased(); - // called on the main thread in response to screenAcquired() - void onScreenAcquired(); + enum { + EVENT_VSYNC = HWC_EVENT_VSYNC + }; + // post an asynchronous message to the main thread + status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, + uint32_t flags = 0); - status_t renderScreenToTexture(DisplayID dpy, - GLuint* textureName, GLfloat* uOut, GLfloat* vOut); - status_t renderScreenToTextureLocked(DisplayID dpy, - GLuint* textureName, GLfloat* uOut, GLfloat* vOut); + // post a synchronous message to the main thread + status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, + uint32_t flags = 0); - void onMessageReceived(int32_t what); + // force full composition on all displays + void repaintEverything(); - status_t postMessageAsync(const sp<MessageBase>& msg, - nsecs_t reltime=0, uint32_t flags = 0); + // renders content on given display to a texture. thread-safe version. + status_t renderScreenToTexture(DisplayID dpy, GLuint* textureName, + GLfloat* uOut, GLfloat* vOut); - status_t postMessageSync(const sp<MessageBase>& msg, - nsecs_t reltime=0, uint32_t flags = 0); + // renders content on given display to a texture, w/o acquiring main lock + status_t renderScreenToTextureLocked(DisplayID dpy, GLuint* textureName, + GLfloat* uOut, GLfloat* vOut); - status_t removeLayer(const sp<LayerBase>& layer); - status_t addLayer(const sp<LayerBase>& layer); - status_t invalidateLayerVisibility(const sp<LayerBase>& layer); - void invalidateHwcGeometry(); + // returns the default Display + sp<const DisplayDevice> getDefaultDisplayDevice() const { + return getDisplayDevice(DisplayDevice::DISPLAY_ID_MAIN); + } - sp<Layer> getLayer(const sp<ISurface>& sur) const; + // utility function to delete a texture on the main thread + void deleteTextureAsync(GLuint texture); - GLuint getProtectedTexName() const { return mProtectedTexName; } + // enable/disable h/w composer event + // TODO: this should be made accessible only to EventThread + void eventControl(int event, int enabled); - class MessageDestroyGLTexture : public MessageBase { - GLuint texture; - public: - MessageDestroyGLTexture(GLuint texture) : texture(texture) { } - virtual bool handler() { - glDeleteTextures(1, &texture); - return true; - } - }; - - -private: - // DeathRecipient interface - virtual void binderDied(const wp<IBinder>& who); + // called on the main thread by MessageQueue when an internal message + // is received + // TODO: this should be made accessible only to MessageQueue + void onMessageReceived(int32_t what); private: friend class Client; @@ -239,190 +145,297 @@ private: friend class LayerBaseClient; friend class Layer; - sp<ISurface> createSurface( - ISurfaceComposerClient::surface_data_t* params, - const String8& name, - const sp<Client>& client, - DisplayID display, uint32_t w, uint32_t h, PixelFormat format, - uint32_t flags); - - sp<Layer> createNormalSurface( - const sp<Client>& client, DisplayID display, - uint32_t w, uint32_t h, uint32_t flags, - PixelFormat& format); - - sp<LayerDim> createDimSurface( - const sp<Client>& client, DisplayID display, - uint32_t w, uint32_t h, uint32_t flags); + // We're reference counted, never destroy SurfaceFlinger directly + virtual ~SurfaceFlinger(); - sp<LayerScreenshot> createScreenshotSurface( - const sp<Client>& client, DisplayID display, - uint32_t w, uint32_t h, uint32_t flags); + /* ------------------------------------------------------------------------ + * Internal data structures + */ - status_t removeSurface(const sp<Client>& client, SurfaceID sid); - status_t destroySurface(const wp<LayerBaseClient>& layer); - uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s); - - class LayerVector : public SortedVector< sp<LayerBase> > { + class LayerVector : public SortedVector<sp<LayerBase> > { public: - LayerVector() { } - LayerVector(const LayerVector& rhs) : SortedVector< sp<LayerBase> >(rhs) { } - virtual int do_compare(const void* lhs, const void* rhs) const { - const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs)); - const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs)); - // sort layers by Z order - uint32_t lz = l->currentState().z; - uint32_t rz = r->currentState().z; - // then by sequence, so we get a stable ordering - return (lz != rz) ? (lz - rz) : (l->sequence - r->sequence); - } + LayerVector(); + LayerVector(const LayerVector& rhs); + virtual int do_compare(const void* lhs, const void* rhs) const; + }; + + struct DisplayDeviceState { + DisplayDeviceState(); + DisplayDeviceState(int32_t id); + int32_t id; + sp<ISurfaceTexture> surface; + uint32_t layerStack; + Rect viewport; + Rect frame; + uint8_t orientation; }; struct State { - State() - : orientation(ISurfaceComposer::eOrientationDefault), - orientationFlags(0) { - } - LayerVector layersSortedByZ; - uint8_t orientation; - uint8_t orientationFlags; + LayerVector layersSortedByZ; + DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays; }; - virtual bool threadLoop(); - virtual status_t readyToRun(); - virtual void onFirstRef(); + /* ------------------------------------------------------------------------ + * IBinder interface + */ + virtual status_t onTransact(uint32_t code, const Parcel& data, + Parcel* reply, uint32_t flags); + virtual status_t dump(int fd, const Vector<String16>& args); -public: // hack to work around gcc 4.0.3 bug - const GraphicPlane& graphicPlane(int dpy) const; - GraphicPlane& graphicPlane(int dpy); + /* ------------------------------------------------------------------------ + * ISurfaceComposer interface + */ + virtual sp<ISurfaceComposerClient> createConnection(); + virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc(); + virtual sp<IBinder> createDisplay(); + virtual sp<IBinder> getBuiltInDisplay(int32_t id); + virtual void setTransactionState(const Vector<ComposerState>& state, + const Vector<DisplayState>& displays, uint32_t flags); + virtual void bootFinished(); + virtual bool authenticateSurfaceTexture( + const sp<ISurfaceTexture>& surface) const; + virtual sp<IDisplayEventConnection> createDisplayEventConnection(); + virtual status_t captureScreen(DisplayID dpy, sp<IMemoryHeap>* heap, + uint32_t* width, uint32_t* height, PixelFormat* format, + uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ, + uint32_t maxLayerZ); + // called when screen needs to turn off + virtual void blank(); + // called when screen is turning back on + virtual void unblank(); + virtual status_t getDisplayInfo(DisplayID dpy, DisplayInfo* info); + virtual void connectDisplay(const sp<ISurfaceTexture> display); + + /* ------------------------------------------------------------------------ + * DeathRecipient interface + */ + virtual void binderDied(const wp<IBinder>& who); - void signalTransaction(); - void signalLayerUpdate(); - void signalRefresh(); - void repaintEverything(); + /* ------------------------------------------------------------------------ + * Thread interface + */ + virtual bool threadLoop(); + virtual status_t readyToRun(); + virtual void onFirstRef(); + + /* ------------------------------------------------------------------------ + * HWComposer::EventHandler interface + */ + virtual void onVSyncReceived(int dpy, nsecs_t timestamp); + + /* ------------------------------------------------------------------------ + * Message handling + */ + void waitForEvent(); + void signalTransaction(); + void signalLayerUpdate(); + void signalRefresh(); + + // called on the main thread in response to screenReleased() + void onScreenReleased(); + // called on the main thread in response to screenAcquired() + void onScreenAcquired(); + + void handleMessageTransaction(); + void handleMessageInvalidate(); + void handleMessageRefresh(); + + void handleTransaction(uint32_t transactionFlags); + void handleTransactionLocked(uint32_t transactionFlags); + + /* handlePageFilp: this is were we latch a new buffer + * if available and compute the dirty region. + */ + void handlePageFlip(); + + /* ------------------------------------------------------------------------ + * Transactions + */ + uint32_t getTransactionFlags(uint32_t flags); + uint32_t peekTransactionFlags(uint32_t flags); + uint32_t setTransactionFlags(uint32_t flags); + void commitTransaction(); + uint32_t setClientStateLocked(const sp<Client>& client, + const layer_state_t& s); + uint32_t setDisplayStateLocked(const DisplayState& s); + + /* ------------------------------------------------------------------------ + * Layer management + */ + sp<ISurface> createLayer(ISurfaceComposerClient::surface_data_t* params, + const String8& name, const sp<Client>& client, DisplayID display, + uint32_t w, uint32_t h, PixelFormat format, uint32_t flags); + + sp<Layer> createNormalLayer(const sp<Client>& client, DisplayID display, + uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format); + + sp<LayerDim> createDimLayer(const sp<Client>& client, DisplayID display, + uint32_t w, uint32_t h, uint32_t flags); + + sp<LayerScreenshot> createScreenshotLayer(const sp<Client>& client, + DisplayID display, uint32_t w, uint32_t h, uint32_t flags); + + // called in response to the window-manager calling + // ISurfaceComposerClient::destroySurface() + // The specified layer is first placed in a purgatory list + // until all references from the client are released. + status_t onLayerRemoved(const sp<Client>& client, SurfaceID sid); + + // called when all clients have released all their references to + // this layer meaning it is entirely safe to destroy all + // resources associated to this layer. + status_t onLayerDestroyed(const wp<LayerBaseClient>& layer); + + // remove a layer from SurfaceFlinger immediately + status_t removeLayer(const sp<LayerBase>& layer); -private: - void waitForEvent(); - void handleTransaction(uint32_t transactionFlags); - void handleTransactionLocked(uint32_t transactionFlags); - - void computeVisibleRegions( - const LayerVector& currentLayers, - Region& dirtyRegion, - Region& wormholeRegion); - - void handlePageFlip(); - bool lockPageFlip(const LayerVector& currentLayers); - void unlockPageFlip(const LayerVector& currentLayers); - void handleRefresh(); - void handleWorkList(); - void handleRepaint(); - void postFramebuffer(); - void setupHardwareComposer(); - void composeSurfaces(const Region& dirty); - - - void setInvalidateRegion(const Region& reg); - Region getAndClearInvalidateRegion(); - - ssize_t addClientLayer(const sp<Client>& client, - const sp<LayerBaseClient>& lbc); - status_t addLayer_l(const sp<LayerBase>& layer); - status_t removeLayer_l(const sp<LayerBase>& layer); - status_t purgatorizeLayer_l(const sp<LayerBase>& layer); - - uint32_t getTransactionFlags(uint32_t flags); - uint32_t peekTransactionFlags(uint32_t flags); - uint32_t setTransactionFlags(uint32_t flags); - void commitTransaction(); - - - status_t captureScreenImplLocked(DisplayID dpy, - sp<IMemoryHeap>* heap, - uint32_t* width, uint32_t* height, PixelFormat* format, - uint32_t reqWidth, uint32_t reqHeight, - uint32_t minLayerZ, uint32_t maxLayerZ); - - status_t turnElectronBeamOffImplLocked(int32_t mode); - status_t turnElectronBeamOnImplLocked(int32_t mode); - status_t electronBeamOffAnimationImplLocked(); - status_t electronBeamOnAnimationImplLocked(); - - void debugFlashRegions(); - void drawWormhole() const; - - void startBootAnim(); - - void listLayersLocked(const Vector<String16>& args, size_t& index, - String8& result, char* buffer, size_t SIZE) const; - void dumpStatsLocked(const Vector<String16>& args, size_t& index, - String8& result, char* buffer, size_t SIZE) const; - void clearStatsLocked(const Vector<String16>& args, size_t& index, - String8& result, char* buffer, size_t SIZE) const; - void dumpAllLocked(String8& result, char* buffer, size_t SIZE) const; - - mutable MessageQueue mEventQueue; - - // access must be protected by mStateLock - mutable Mutex mStateLock; - State mCurrentState; - volatile int32_t mTransactionFlags; - Condition mTransactionCV; - SortedVector< sp<LayerBase> > mLayerPurgatory; - bool mTransationPending; - Vector< sp<LayerBase> > mLayersPendingRemoval; - - // protected by mStateLock (but we could use another lock) - GraphicPlane mGraphicPlanes[1]; - bool mLayersRemoved; - DefaultKeyedVector< wp<IBinder>, wp<Layer> > mLayerMap; - - // access must be protected by mInvalidateLock - mutable Mutex mInvalidateLock; - Region mInvalidateRegion; - - // constant members (no synchronization needed for access) - sp<IMemoryHeap> mServerHeap; - surface_flinger_cblk_t* mServerCblk; - GLuint mWormholeTexName; - GLuint mProtectedTexName; - nsecs_t mBootTime; - sp<EventThread> mEventThread; - - // Can only accessed from the main thread, these members - // don't need synchronization - State mDrawingState; - Region mDirtyRegion; - Region mDirtyRegionRemovedLayer; - Region mSwapRegion; - Region mWormholeRegion; - bool mVisibleRegionsDirty; - bool mHwWorkListDirty; - int32_t mElectronBeamAnimationMode; - Vector< sp<LayerBase> > mVisibleLayersSortedByZ; - - - // don't use a lock for these, we don't care - int mDebugRegion; - int mDebugDDMS; - int mDebugDisableHWC; - int mDebugDisableTransformHint; - volatile nsecs_t mDebugInSwapBuffers; - nsecs_t mLastSwapBufferTime; - volatile nsecs_t mDebugInTransaction; - nsecs_t mLastTransactionTime; - bool mBootFinished; - - // these are thread safe - mutable Barrier mReadyToRunBarrier; - - - // protected by mDestroyedLayerLock; - mutable Mutex mDestroyedLayerLock; - Vector<LayerBase const *> mDestroyedLayers; - - // only written in the main thread, only read in other threads - volatile int32_t mSecureFrameBuffer; + // add a layer to SurfaceFlinger + ssize_t addClientLayer(const sp<Client>& client, + const sp<LayerBaseClient>& lbc); + + status_t removeLayer_l(const sp<LayerBase>& layer); + status_t purgatorizeLayer_l(const sp<LayerBase>& layer); + + /* ------------------------------------------------------------------------ + * Boot animation, on/off animations and screen capture + */ + + void startBootAnim(); + + status_t captureScreenImplLocked(DisplayID dpy, sp<IMemoryHeap>* heap, + uint32_t* width, uint32_t* height, PixelFormat* format, + uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ, + uint32_t maxLayerZ); + + /* ------------------------------------------------------------------------ + * EGL + */ + static status_t selectConfigForPixelFormat(EGLDisplay dpy, + EGLint const* attrs, PixelFormat format, EGLConfig* outConfig); + static EGLConfig selectEGLConfig(EGLDisplay disp, EGLint visualId); + static EGLContext createGLContext(EGLDisplay disp, EGLConfig config); + void initializeGL(EGLDisplay display, EGLSurface surface); + uint32_t getMaxTextureSize() const; + uint32_t getMaxViewportDims() const; + + /* ------------------------------------------------------------------------ + * Display and layer stack management + */ + sp<const DisplayDevice> getDisplayDevice(DisplayID dpy) const { + return mDisplays.valueFor(dpy); + } + const sp<DisplayDevice>& getDisplayDevice(DisplayID dpy) { + return mDisplays.valueFor(dpy); + } + + // mark a region of a layer stack dirty. this updates the dirty + // region of all screens presenting this layer stack. + void invalidateLayerStack(uint32_t layerStack, const Region& dirty); + + /* ------------------------------------------------------------------------ + * H/W composer + */ + + HWComposer& getHwComposer() const { return *mHwc; } + + /* ------------------------------------------------------------------------ + * Compositing + */ + void invalidateHwcGeometry(); + void computeVisibleRegions(const LayerVector& currentLayers, + uint32_t layerStack, + Region& dirtyRegion, Region& opaqueRegion); + + void preComposition(); + void postComposition(); + void rebuildLayerStacks(); + void setUpHWComposer(); + void doComposition(); + void doDebugFlashRegions(); + void doDisplayComposition(const sp<const DisplayDevice>& hw, + const Region& dirtyRegion); + void doComposeSurfaces(const sp<const DisplayDevice>& hw, + const Region& dirty); + + void postFramebuffer(); + void drawWormhole(const Region& region) const; + GLuint getProtectedTexName() const { + return mProtectedTexName; + } + + /* ------------------------------------------------------------------------ + * Debugging & dumpsys + */ + void listLayersLocked(const Vector<String16>& args, size_t& index, + String8& result, char* buffer, size_t SIZE) const; + void dumpStatsLocked(const Vector<String16>& args, size_t& index, + String8& result, char* buffer, size_t SIZE) const; + void clearStatsLocked(const Vector<String16>& args, size_t& index, + String8& result, char* buffer, size_t SIZE) const; + void dumpAllLocked(String8& result, char* buffer, size_t SIZE) const; + + /* ------------------------------------------------------------------------ + * Attributes + */ + + // access must be protected by mStateLock + mutable Mutex mStateLock; + State mCurrentState; + volatile int32_t mTransactionFlags; + Condition mTransactionCV; + SortedVector<sp<LayerBase> > mLayerPurgatory; + bool mTransationPending; + Vector<sp<LayerBase> > mLayersPendingRemoval; + + // protected by mStateLock (but we could use another lock) + bool mLayersRemoved; + + // access must be protected by mInvalidateLock + volatile int32_t mRepaintEverything; + + // constant members (no synchronization needed for access) + HWComposer* mHwc; + GLuint mProtectedTexName; + nsecs_t mBootTime; + sp<EventThread> mEventThread; + GLint mMaxViewportDims[2]; + GLint mMaxTextureSize; + EGLContext mEGLContext; + EGLConfig mEGLConfig; + EGLDisplay mEGLDisplay; + sp<IBinder> mDefaultDisplays[DisplayDevice::DISPLAY_ID_COUNT]; + + // Can only accessed from the main thread, these members + // don't need synchronization + State mDrawingState; + bool mVisibleRegionsDirty; + bool mHwWorkListDirty; + DefaultKeyedVector<int32_t, sp<DisplayDevice> > mDisplays; + + // don't use a lock for these, we don't care + int mDebugRegion; + int mDebugDDMS; + int mDebugDisableHWC; + int mDebugDisableTransformHint; + volatile nsecs_t mDebugInSwapBuffers; + nsecs_t mLastSwapBufferTime; + volatile nsecs_t mDebugInTransaction; + nsecs_t mLastTransactionTime; + bool mBootFinished; + + // these are thread safe + mutable MessageQueue mEventQueue; + mutable Barrier mReadyToRunBarrier; + + // protected by mDestroyedLayerLock; + mutable Mutex mDestroyedLayerLock; + Vector<LayerBase const *> mDestroyedLayers; + + /* ------------------------------------------------------------------------ + * Feature prototyping + */ + + sp<IBinder> mExtDisplayToken; }; // --------------------------------------------------------------------------- diff --git a/services/surfaceflinger/tests/Transaction_test.cpp b/services/surfaceflinger/tests/Transaction_test.cpp index 84ae0d9..e3a98ff 100644 --- a/services/surfaceflinger/tests/Transaction_test.cpp +++ b/services/surfaceflinger/tests/Transaction_test.cpp @@ -24,6 +24,7 @@ #include <private/gui/ComposerService.h> #include <utils/String8.h> +#include <ui/DisplayInfo.h> namespace android { @@ -92,8 +93,11 @@ protected: mComposerClient = new SurfaceComposerClient; ASSERT_EQ(NO_ERROR, mComposerClient->initCheck()); - ssize_t displayWidth = mComposerClient->getDisplayWidth(0); - ssize_t displayHeight = mComposerClient->getDisplayHeight(0); + DisplayInfo info; + SurfaceComposerClient::getDisplayInfo(0, &info); + + ssize_t displayWidth = info.w; + ssize_t displayHeight = info.h; // Background surface mBGSurfaceControl = mComposerClient->createSurface( |