2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #include <sys/types.h>
28 #include <cutils/log.h>
29 #include <cutils/properties.h>
31 #include <binder/IPCThreadState.h>
32 #include <binder/IServiceManager.h>
33 #include <binder/MemoryHeapBase.h>
34 #include <binder/PermissionCache.h>
36 #include <ui/DisplayInfo.h>
38 #include <gui/BitTube.h>
39 #include <gui/BufferQueue.h>
40 #include <gui/GuiConfig.h>
41 #include <gui/IDisplayEventConnection.h>
42 #include <gui/SurfaceTextureClient.h>
44 #include <ui/GraphicBufferAllocator.h>
45 #include <ui/PixelFormat.h>
46 #include <ui/UiConfig.h>
48 #include <utils/misc.h>
49 #include <utils/String8.h>
50 #include <utils/String16.h>
51 #include <utils/StopWatch.h>
52 #include <utils/Trace.h>
54 #include <private/android_filesystem_config.h>
57 #include "DdmConnection.h"
58 #include "DisplayDevice.h"
60 #include "EventThread.h"
61 #include "GLExtensions.h"
64 #include "LayerScreenshot.h"
65 #include "SurfaceFlinger.h"
67 #include "DisplayHardware/FramebufferSurface.h"
68 #include "DisplayHardware/GraphicBufferAlloc.h"
69 #include "DisplayHardware/HWComposer.h"
72 #define EGL_VERSION_HW_ANDROID 0x3143
74 #define DISPLAY_COUNT 1
77 // ---------------------------------------------------------------------------
79 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
80 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
81 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
82 const String16 sDump("android.permission.DUMP");
84 // ---------------------------------------------------------------------------
86 SurfaceFlinger::SurfaceFlinger()
87 : BnSurfaceComposer(), Thread(false),
89 mTransactionPending(false),
90 mAnimTransactionPending(false),
91 mLayersRemoved(false),
92 mRepaintEverything(0),
93 mBootTime(systemTime()),
94 mVisibleRegionsDirty(false),
95 mHwWorkListDirty(false),
99 mDebugDisableTransformHint(0),
100 mDebugInSwapBuffers(0),
101 mLastSwapBufferTime(0),
102 mDebugInTransaction(0),
103 mLastTransactionTime(0),
106 ALOGI("SurfaceFlinger is starting");
108 // debugging stuff...
109 char value[PROPERTY_VALUE_MAX];
111 property_get("debug.sf.showupdates", value, "0");
112 mDebugRegion = atoi(value);
114 property_get("debug.sf.ddms", value, "0");
115 mDebugDDMS = atoi(value);
117 if (!startDdmConnection()) {
118 // start failed, and DDMS debugging not enabled
122 ALOGI_IF(mDebugRegion, "showupdates enabled");
123 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
126 void SurfaceFlinger::onFirstRef()
128 mEventQueue.init(this);
130 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
132 // Wait for the main thread to be done with its initialization
133 mReadyToRunBarrier.wait();
137 SurfaceFlinger::~SurfaceFlinger()
139 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
140 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
141 eglTerminate(display);
144 void SurfaceFlinger::binderDied(const wp<IBinder>& who)
146 // the window manager died on us. prepare its eulogy.
148 // restore initial conditions (default device unblank, etc)
149 initializeDisplays();
151 // restart the boot-animation
155 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
157 sp<ISurfaceComposerClient> bclient;
158 sp<Client> client(new Client(this));
159 status_t err = client->initCheck();
160 if (err == NO_ERROR) {
166 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
169 class DisplayToken : public BBinder {
170 sp<SurfaceFlinger> flinger;
171 virtual ~DisplayToken() {
172 // no more references, this display must be terminated
173 Mutex::Autolock _l(flinger->mStateLock);
174 flinger->mCurrentState.displays.removeItem(this);
175 flinger->setTransactionFlags(eDisplayTransactionNeeded);
178 DisplayToken(const sp<SurfaceFlinger>& flinger)
183 sp<BBinder> token = new DisplayToken(this);
185 Mutex::Autolock _l(mStateLock);
186 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
187 info.displayName = displayName;
188 info.isSecure = secure;
189 mCurrentState.displays.add(token, info);
194 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
195 if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
196 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
199 return mDefaultDisplays[id];
202 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
204 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
208 void SurfaceFlinger::bootFinished()
210 const nsecs_t now = systemTime();
211 const nsecs_t duration = now - mBootTime;
212 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
213 mBootFinished = true;
215 // wait patiently for the window manager death
216 const String16 name("window");
217 sp<IBinder> window(defaultServiceManager()->getService(name));
219 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
222 // stop boot animation
223 // formerly we would just kill the process, but we now ask it to exit so it
224 // can choose where to stop the animation.
225 property_set("service.bootanim.exit", "1");
228 void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
229 class MessageDestroyGLTexture : public MessageBase {
232 MessageDestroyGLTexture(GLuint texture)
235 virtual bool handler() {
236 glDeleteTextures(1, &texture);
240 postMessageAsync(new MessageDestroyGLTexture(texture));
243 status_t SurfaceFlinger::selectConfigForAttribute(
246 EGLint attribute, EGLint wanted,
247 EGLConfig* outConfig)
249 EGLConfig config = NULL;
250 EGLint numConfigs = -1, n=0;
251 eglGetConfigs(dpy, NULL, 0, &numConfigs);
252 EGLConfig* const configs = new EGLConfig[numConfigs];
253 eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
256 if (attribute != EGL_NONE) {
257 for (int i=0 ; i<n ; i++) {
259 eglGetConfigAttrib(dpy, configs[i], attribute, &value);
260 if (wanted == value) {
261 *outConfig = configs[i];
267 // just pick the first one
268 *outConfig = configs[0];
274 return NAME_NOT_FOUND;
277 class EGLAttributeVector {
281 KeyedVector<Attribute, EGLint> mList;
284 Attribute(EGLint v) : v(v) { }
286 bool operator < (const Attribute& other) const {
287 // this places EGL_NONE at the end
290 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
291 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
296 friend class EGLAttributeVector;
297 EGLAttributeVector& v;
299 Adder(EGLAttributeVector& v, EGLint attribute)
300 : v(v), attribute(attribute) {
303 void operator = (EGLint value) {
304 if (attribute != EGL_NONE) {
305 v.mList.add(attribute, value);
308 operator EGLint () const { return v.mList[attribute]; }
311 EGLAttributeVector() {
312 mList.add(EGL_NONE, EGL_NONE);
314 void remove(EGLint attribute) {
315 if (attribute != EGL_NONE) {
316 mList.removeItem(attribute);
319 Adder operator [] (EGLint attribute) {
320 return Adder(*this, attribute);
322 EGLint operator [] (EGLint attribute) const {
323 return mList[attribute];
325 // cast-operator to (EGLint const*)
326 operator EGLint const* () const { return &mList.keyAt(0).v; }
329 EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
330 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
331 // it is to be used with WIFI displays
336 EGLAttributeVector attribs;
337 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT;
338 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE;
339 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
340 attribs[EGL_RED_SIZE] = 8;
341 attribs[EGL_GREEN_SIZE] = 8;
342 attribs[EGL_BLUE_SIZE] = 8;
344 err = selectConfigForAttribute(display, attribs, EGL_NONE, EGL_NONE, &config);
348 // maybe we failed because of EGL_FRAMEBUFFER_TARGET_ANDROID
349 ALOGW("no suitable EGLConfig found, trying without EGL_FRAMEBUFFER_TARGET_ANDROID");
350 attribs.remove(EGL_FRAMEBUFFER_TARGET_ANDROID);
351 err = selectConfigForAttribute(display, attribs,
352 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
356 // maybe we failed because of EGL_RECORDABLE_ANDROID
357 ALOGW("no suitable EGLConfig found, trying without EGL_RECORDABLE_ANDROID");
358 attribs.remove(EGL_RECORDABLE_ANDROID);
359 err = selectConfigForAttribute(display, attribs,
360 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
364 // allow less than 24-bit color; the non-gpu-accelerated emulator only
365 // supports 16-bit color
366 ALOGW("no suitable EGLConfig found, trying with 16-bit color allowed");
367 attribs.remove(EGL_RED_SIZE);
368 attribs.remove(EGL_GREEN_SIZE);
369 attribs.remove(EGL_BLUE_SIZE);
370 err = selectConfigForAttribute(display, attribs,
371 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
375 // this EGL is too lame for Android
376 ALOGE("no suitable EGLConfig found, giving up");
381 if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy))
382 ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
386 EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
387 // Also create our EGLContext
388 EGLint contextAttributes[] = {
389 #ifdef EGL_IMG_context_priority
390 #ifdef HAS_CONTEXT_PRIORITY
391 #warning "using EGL_IMG_context_priority"
392 EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
397 EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
398 ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
402 void SurfaceFlinger::initializeGL(EGLDisplay display) {
403 GLExtensions& extensions(GLExtensions::getInstance());
404 extensions.initWithGLStrings(
405 glGetString(GL_VENDOR),
406 glGetString(GL_RENDERER),
407 glGetString(GL_VERSION),
408 glGetString(GL_EXTENSIONS),
409 eglQueryString(display, EGL_VENDOR),
410 eglQueryString(display, EGL_VERSION),
411 eglQueryString(display, EGL_EXTENSIONS));
413 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
414 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
416 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
417 glPixelStorei(GL_PACK_ALIGNMENT, 4);
418 glEnableClientState(GL_VERTEX_ARRAY);
419 glShadeModel(GL_FLAT);
420 glDisable(GL_DITHER);
421 glDisable(GL_CULL_FACE);
424 inline uint16_t operator() (int r, int g, int b) const {
425 return (r<<11)|(g<<5)|b;
429 const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
430 glGenTextures(1, &mProtectedTexName);
431 glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
432 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
433 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
434 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
435 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
436 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
437 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
439 // print some debugging info
441 eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE, &r);
442 eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
443 eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE, &b);
444 eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
445 ALOGI("EGL informations:");
446 ALOGI("vendor : %s", extensions.getEglVendor());
447 ALOGI("version : %s", extensions.getEglVersion());
448 ALOGI("extensions: %s", extensions.getEglExtension());
449 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
450 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
451 ALOGI("OpenGL ES informations:");
452 ALOGI("vendor : %s", extensions.getVendor());
453 ALOGI("renderer : %s", extensions.getRenderer());
454 ALOGI("version : %s", extensions.getVersion());
455 ALOGI("extensions: %s", extensions.getExtension());
456 ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
457 ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
460 status_t SurfaceFlinger::readyToRun()
462 ALOGI( "SurfaceFlinger's main thread ready to run. "
463 "Initializing graphics H/W...");
465 // initialize EGL for the default display
466 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
467 eglInitialize(mEGLDisplay, NULL, NULL);
469 // Initialize the H/W composer object. There may or may not be an
470 // actual hardware composer underneath.
471 mHwc = new HWComposer(this,
472 *static_cast<HWComposer::EventHandler *>(this));
474 // initialize the config and context
475 EGLint format = mHwc->getVisualID();
476 mEGLConfig = selectEGLConfig(mEGLDisplay, format);
477 mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
479 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
480 "couldn't create EGLContext");
482 // initialize our non-virtual displays
483 for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
484 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
485 mDefaultDisplays[i] = new BBinder();
486 wp<IBinder> token = mDefaultDisplays[i];
488 // set-up the displays that are already connected
489 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
490 // All non-virtual displays are currently considered secure.
491 bool isSecure = true;
492 mCurrentState.displays.add(token, DisplayDeviceState(type));
493 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i);
494 sp<SurfaceTextureClient> stc = new SurfaceTextureClient(
495 static_cast< sp<ISurfaceTexture> >(fbs->getBufferQueue()));
496 sp<DisplayDevice> hw = new DisplayDevice(this,
497 type, isSecure, token, stc, fbs, mEGLConfig);
498 if (i > DisplayDevice::DISPLAY_PRIMARY) {
499 // FIXME: currently we don't get blank/unblank requests
500 // for displays other than the main display, so we always
501 // assume a connected display is unblanked.
502 ALOGD("marking display %d as acquired/unblanked", i);
505 mDisplays.add(token, hw);
509 // we need a GL context current in a few places, when initializing
510 // OpenGL ES (see below), or creating a layer,
511 // or when a texture is (asynchronously) destroyed, and for that
512 // we need a valid surface, so it's convenient to use the main display
514 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
516 // initialize OpenGL ES
517 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
518 initializeGL(mEGLDisplay);
520 // start the EventThread
521 mEventThread = new EventThread(this);
522 mEventQueue.setEventThread(mEventThread);
524 // initialize our drawing state
525 mDrawingState = mCurrentState;
528 // We're now ready to accept clients...
529 mReadyToRunBarrier.open();
531 // set initial conditions (e.g. unblank default device)
532 initializeDisplays();
534 // start boot animation
540 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
541 return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
542 type : mHwc->allocateDisplayId();
545 void SurfaceFlinger::startBootAnim() {
546 // start boot animation
547 property_set("service.bootanim.exit", "0");
548 property_set("ctl.start", "bootanim");
551 uint32_t SurfaceFlinger::getMaxTextureSize() const {
552 return mMaxTextureSize;
555 uint32_t SurfaceFlinger::getMaxViewportDims() const {
556 return mMaxViewportDims[0] < mMaxViewportDims[1] ?
557 mMaxViewportDims[0] : mMaxViewportDims[1];
560 // ----------------------------------------------------------------------------
562 bool SurfaceFlinger::authenticateSurfaceTexture(
563 const sp<ISurfaceTexture>& surfaceTexture) const {
564 Mutex::Autolock _l(mStateLock);
565 sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
567 // Check the visible layer list for the ISurface
568 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
569 size_t count = currentLayers.size();
570 for (size_t i=0 ; i<count ; i++) {
571 const sp<LayerBase>& layer(currentLayers[i]);
572 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
574 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
575 if (lbcBinder == surfaceTextureBinder) {
581 // Check the layers in the purgatory. This check is here so that if a
582 // SurfaceTexture gets destroyed before all the clients are done using it,
583 // the error will not be reported as "surface XYZ is not authenticated", but
584 // will instead fail later on when the client tries to use the surface,
585 // which should be reported as "surface XYZ returned an -ENODEV". The
586 // purgatorized layers are no less authentic than the visible ones, so this
587 // should not cause any harm.
588 size_t purgatorySize = mLayerPurgatory.size();
589 for (size_t i=0 ; i<purgatorySize ; i++) {
590 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
591 sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
593 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
594 if (lbcBinder == surfaceTextureBinder) {
603 status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
604 int32_t type = BAD_VALUE;
605 for (int i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
606 if (display == mDefaultDisplays[i]) {
616 const HWComposer& hwc(getHwComposer());
617 if (!hwc.isConnected(type)) {
618 return NAME_NOT_FOUND;
621 float xdpi = hwc.getDpiX(type);
622 float ydpi = hwc.getDpiY(type);
624 // TODO: Not sure if display density should handled by SF any longer
626 static int getDensityFromProperty(char const* propName) {
627 char property[PROPERTY_VALUE_MAX];
629 if (property_get(propName, property, NULL) > 0) {
630 density = atoi(property);
635 static int getEmuDensity() {
636 return getDensityFromProperty("qemu.sf.lcd_density"); }
637 static int getBuildDensity() {
638 return getDensityFromProperty("ro.sf.lcd_density"); }
641 if (type == DisplayDevice::DISPLAY_PRIMARY) {
642 // The density of the device is provided by a build property
643 float density = Density::getBuildDensity() / 160.0f;
645 // the build doesn't provide a density -- this is wrong!
647 ALOGE("ro.sf.lcd_density must be defined as a build property");
648 density = xdpi / 160.0f;
650 if (Density::getEmuDensity()) {
651 // if "qemu.sf.lcd_density" is specified, it overrides everything
652 xdpi = ydpi = density = Density::getEmuDensity();
655 info->density = density;
657 // TODO: this needs to go away (currently needed only by webkit)
658 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
659 info->orientation = hw->getOrientation();
660 getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
662 // TODO: where should this value come from?
663 static const int TV_DENSITY = 213;
664 info->density = TV_DENSITY / 160.0f;
665 info->orientation = 0;
668 info->w = hwc.getWidth(type);
669 info->h = hwc.getHeight(type);
672 info->fps = float(1e9 / hwc.getRefreshPeriod(type));
674 // All non-virtual displays are currently considered secure.
680 // ----------------------------------------------------------------------------
682 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
683 return mEventThread->createEventConnection();
686 // ----------------------------------------------------------------------------
688 void SurfaceFlinger::waitForEvent() {
689 mEventQueue.waitMessage();
692 void SurfaceFlinger::signalTransaction() {
693 mEventQueue.invalidate();
696 void SurfaceFlinger::signalLayerUpdate() {
697 mEventQueue.invalidate();
700 void SurfaceFlinger::signalRefresh() {
701 mEventQueue.refresh();
704 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
705 nsecs_t reltime, uint32_t flags) {
706 return mEventQueue.postMessage(msg, reltime);
709 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
710 nsecs_t reltime, uint32_t flags) {
711 status_t res = mEventQueue.postMessage(msg, reltime);
712 if (res == NO_ERROR) {
718 bool SurfaceFlinger::threadLoop() {
723 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
724 if (mEventThread == NULL) {
725 // This is a temporary workaround for b/7145521. A non-null pointer
726 // does not mean EventThread has finished initializing, so this
727 // is not a correct fix.
728 ALOGW("WARNING: EventThread not started, ignoring vsync");
731 if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
732 // we should only receive DisplayDevice::DisplayType from the vsync callback
733 mEventThread->onVSyncReceived(type, timestamp);
737 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
738 if (mEventThread == NULL) {
739 // This is a temporary workaround for b/7145521. A non-null pointer
740 // does not mean EventThread has finished initializing, so this
741 // is not a correct fix.
742 ALOGW("WARNING: EventThread not started, ignoring hotplug");
746 if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
747 Mutex::Autolock _l(mStateLock);
748 if (connected == false) {
749 mCurrentState.displays.removeItem(mDefaultDisplays[type]);
751 DisplayDeviceState info((DisplayDevice::DisplayType)type);
752 mCurrentState.displays.add(mDefaultDisplays[type], info);
754 setTransactionFlags(eDisplayTransactionNeeded);
756 // Defer EventThread notification until SF has updated mDisplays.
760 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
761 getHwComposer().eventControl(disp, event, enabled);
764 void SurfaceFlinger::onMessageReceived(int32_t what) {
767 case MessageQueue::INVALIDATE:
768 handleMessageTransaction();
769 handleMessageInvalidate();
772 case MessageQueue::REFRESH:
773 handleMessageRefresh();
778 void SurfaceFlinger::handleMessageTransaction() {
779 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
780 if (transactionFlags) {
781 handleTransaction(transactionFlags);
785 void SurfaceFlinger::handleMessageInvalidate() {
790 void SurfaceFlinger::handleMessageRefresh() {
793 rebuildLayerStacks();
795 doDebugFlashRegions();
800 void SurfaceFlinger::doDebugFlashRegions()
802 // is debugging enabled
803 if (CC_LIKELY(!mDebugRegion))
806 const bool repaintEverything = mRepaintEverything;
807 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
808 const sp<DisplayDevice>& hw(mDisplays[dpy]);
810 // transform the dirty region into this screen's coordinate space
811 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
812 if (!dirtyRegion.isEmpty()) {
813 // redraw the whole screen
814 doComposeSurfaces(hw, Region(hw->bounds()));
816 // and draw the dirty region
817 glDisable(GL_TEXTURE_EXTERNAL_OES);
818 glDisable(GL_TEXTURE_2D);
820 glColor4f(1, 0, 1, 1);
821 const int32_t height = hw->getHeight();
822 Region::const_iterator it = dirtyRegion.begin();
823 Region::const_iterator const end = dirtyRegion.end();
825 const Rect& r = *it++;
826 GLfloat vertices[][2] = {
827 { r.left, height - r.top },
828 { r.left, height - r.bottom },
829 { r.right, height - r.bottom },
830 { r.right, height - r.top }
832 glVertexPointer(2, GL_FLOAT, 0, vertices);
833 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
835 hw->compositionComplete();
836 hw->swapBuffers(getHwComposer());
843 if (mDebugRegion > 1) {
844 usleep(mDebugRegion * 1000);
847 HWComposer& hwc(getHwComposer());
848 if (hwc.initCheck() == NO_ERROR) {
849 status_t err = hwc.prepare();
850 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
854 void SurfaceFlinger::preComposition()
856 bool needExtraInvalidate = false;
857 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
858 const size_t count = currentLayers.size();
859 for (size_t i=0 ; i<count ; i++) {
860 if (currentLayers[i]->onPreComposition()) {
861 needExtraInvalidate = true;
864 if (needExtraInvalidate) {
869 void SurfaceFlinger::postComposition()
871 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
872 const size_t count = currentLayers.size();
873 for (size_t i=0 ; i<count ; i++) {
874 currentLayers[i]->onPostComposition();
878 void SurfaceFlinger::rebuildLayerStacks() {
879 // rebuild the visible layer list per screen
880 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
882 mVisibleRegionsDirty = false;
883 invalidateHwcGeometry();
885 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
886 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
889 Vector< sp<LayerBase> > layersSortedByZ;
890 const sp<DisplayDevice>& hw(mDisplays[dpy]);
891 const Transform& tr(hw->getTransform());
892 const Rect bounds(hw->getBounds());
894 SurfaceFlinger::computeVisibleRegions(currentLayers,
895 hw->getLayerStack(), dirtyRegion, opaqueRegion);
897 const size_t count = currentLayers.size();
898 for (size_t i=0 ; i<count ; i++) {
899 const sp<LayerBase>& layer(currentLayers[i]);
900 const Layer::State& s(layer->drawingState());
901 if (s.layerStack == hw->getLayerStack()) {
902 Region drawRegion(tr.transform(
903 layer->visibleNonTransparentRegion));
904 drawRegion.andSelf(bounds);
905 if (!drawRegion.isEmpty()) {
906 layersSortedByZ.add(layer);
911 hw->setVisibleLayersSortedByZ(layersSortedByZ);
912 hw->undefinedRegion.set(bounds);
913 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
914 hw->dirtyRegion.orSelf(dirtyRegion);
919 void SurfaceFlinger::setUpHWComposer() {
920 HWComposer& hwc(getHwComposer());
921 if (hwc.initCheck() == NO_ERROR) {
922 // build the h/w work list
923 if (CC_UNLIKELY(mHwWorkListDirty)) {
924 mHwWorkListDirty = false;
925 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
926 sp<const DisplayDevice> hw(mDisplays[dpy]);
927 const int32_t id = hw->getHwcDisplayId();
929 const Vector< sp<LayerBase> >& currentLayers(
930 hw->getVisibleLayersSortedByZ());
931 const size_t count = currentLayers.size();
932 if (hwc.createWorkList(id, count) == NO_ERROR) {
933 HWComposer::LayerListIterator cur = hwc.begin(id);
934 const HWComposer::LayerListIterator end = hwc.end(id);
935 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
936 const sp<LayerBase>& layer(currentLayers[i]);
937 layer->setGeometry(hw, *cur);
938 if (mDebugDisableHWC || mDebugRegion) {
947 // set the per-frame data
948 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
949 sp<const DisplayDevice> hw(mDisplays[dpy]);
950 const int32_t id = hw->getHwcDisplayId();
952 const Vector< sp<LayerBase> >& currentLayers(
953 hw->getVisibleLayersSortedByZ());
954 const size_t count = currentLayers.size();
955 HWComposer::LayerListIterator cur = hwc.begin(id);
956 const HWComposer::LayerListIterator end = hwc.end(id);
957 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
959 * update the per-frame h/w composer data for each layer
960 * and build the transparent region of the FB
962 const sp<LayerBase>& layer(currentLayers[i]);
963 layer->setPerFrameData(hw, *cur);
968 status_t err = hwc.prepare();
969 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
973 void SurfaceFlinger::doComposition() {
975 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
976 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
977 const sp<DisplayDevice>& hw(mDisplays[dpy]);
979 // transform the dirty region into this screen's coordinate space
980 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
981 if (!dirtyRegion.isEmpty()) {
982 // repaint the framebuffer (if needed)
983 doDisplayComposition(hw, dirtyRegion);
985 hw->dirtyRegion.clear();
986 hw->flip(hw->swapRegion);
987 hw->swapRegion.clear();
989 // inform the h/w that we're done compositing
990 hw->compositionComplete();
995 void SurfaceFlinger::postFramebuffer()
999 const nsecs_t now = systemTime();
1000 mDebugInSwapBuffers = now;
1002 HWComposer& hwc(getHwComposer());
1003 if (hwc.initCheck() == NO_ERROR) {
1004 if (!hwc.supportsFramebufferTarget()) {
1006 // "surface must be bound to the calling thread's current context,
1007 // for the current rendering API."
1008 DisplayDevice::makeCurrent(mEGLDisplay,
1009 getDefaultDisplayDevice(), mEGLContext);
1014 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1015 sp<const DisplayDevice> hw(mDisplays[dpy]);
1016 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
1017 hw->onSwapBuffersCompleted(hwc);
1018 const size_t count = currentLayers.size();
1019 int32_t id = hw->getHwcDisplayId();
1020 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1021 HWComposer::LayerListIterator cur = hwc.begin(id);
1022 const HWComposer::LayerListIterator end = hwc.end(id);
1023 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1024 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1027 for (size_t i = 0; i < count; i++) {
1028 currentLayers[i]->onLayerDisplayed(hw, NULL);
1033 mLastSwapBufferTime = systemTime() - now;
1034 mDebugInSwapBuffers = 0;
1037 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1041 Mutex::Autolock _l(mStateLock);
1042 const nsecs_t now = systemTime();
1043 mDebugInTransaction = now;
1045 // Here we're guaranteed that some transaction flags are set
1046 // so we can call handleTransactionLocked() unconditionally.
1047 // We call getTransactionFlags(), which will also clear the flags,
1048 // with mStateLock held to guarantee that mCurrentState won't change
1049 // until the transaction is committed.
1051 transactionFlags = getTransactionFlags(eTransactionMask);
1052 handleTransactionLocked(transactionFlags);
1054 mLastTransactionTime = systemTime() - now;
1055 mDebugInTransaction = 0;
1056 invalidateHwcGeometry();
1057 // here the transaction has been committed
1060 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1062 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1063 const size_t count = currentLayers.size();
1066 * Traversal of the children
1067 * (perform the transaction for each of them if needed)
1070 if (transactionFlags & eTraversalNeeded) {
1071 for (size_t i=0 ; i<count ; i++) {
1072 const sp<LayerBase>& layer = currentLayers[i];
1073 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1074 if (!trFlags) continue;
1076 const uint32_t flags = layer->doTransaction(0);
1077 if (flags & Layer::eVisibleRegion)
1078 mVisibleRegionsDirty = true;
1083 * Perform display own transactions if needed
1086 if (transactionFlags & eDisplayTransactionNeeded) {
1087 // here we take advantage of Vector's copy-on-write semantics to
1088 // improve performance by skipping the transaction entirely when
1089 // know that the lists are identical
1090 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1091 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1092 if (!curr.isIdenticalTo(draw)) {
1093 mVisibleRegionsDirty = true;
1094 const size_t cc = curr.size();
1095 size_t dc = draw.size();
1097 // find the displays that were removed
1098 // (ie: in drawing state but not in current state)
1099 // also handle displays that changed
1100 // (ie: displays that are in both lists)
1101 for (size_t i=0 ; i<dc ; i++) {
1102 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1104 // in drawing state but not in current state
1105 if (!draw[i].isMainDisplay()) {
1106 // Call makeCurrent() on the primary display so we can
1107 // be sure that nothing associated with this display
1109 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1110 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1111 mDisplays.removeItem(draw.keyAt(i));
1112 getHwComposer().disconnectDisplay(draw[i].type);
1113 mEventThread->onHotplugReceived(draw[i].type, false);
1115 ALOGW("trying to remove the main display");
1118 // this display is in both lists. see if something changed.
1119 const DisplayDeviceState& state(curr[j]);
1120 const wp<IBinder>& display(curr.keyAt(j));
1121 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1122 // changing the surface is like destroying and
1123 // recreating the DisplayDevice, so we just remove it
1124 // from the drawing state, so that it get re-added
1126 mDisplays.removeItem(display);
1127 mDrawingState.displays.removeItemsAt(i);
1129 // at this point we must loop to the next item
1133 const sp<DisplayDevice> disp(getDisplayDevice(display));
1135 if (state.layerStack != draw[i].layerStack) {
1136 disp->setLayerStack(state.layerStack);
1138 if ((state.orientation != draw[i].orientation)
1139 || (state.viewport != draw[i].viewport)
1140 || (state.frame != draw[i].frame))
1142 disp->setProjection(state.orientation,
1143 state.viewport, state.frame);
1146 // Walk through all the layers in currentLayers,
1147 // and update their transform hint.
1149 // TODO: we could be much more clever about which
1150 // layers we touch and how often we do these updates
1151 // (e.g. only touch the layers associated with this
1152 // display, and only on a rotation).
1153 for (size_t i = 0; i < count; i++) {
1154 const sp<LayerBase>& layerBase = currentLayers[i];
1155 layerBase->updateTransformHint();
1161 // find displays that were added
1162 // (ie: in current state but not in drawing state)
1163 for (size_t i=0 ; i<cc ; i++) {
1164 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1165 const DisplayDeviceState& state(curr[i]);
1166 bool isSecure = false;
1168 sp<FramebufferSurface> fbs;
1169 sp<SurfaceTextureClient> stc;
1170 if (!state.isVirtualDisplay()) {
1172 ALOGE_IF(state.surface!=NULL,
1173 "adding a supported display, but rendering "
1174 "surface is provided (%p), ignoring it",
1175 state.surface.get());
1177 // All non-virtual displays are currently considered
1181 // for supported (by hwc) displays we provide our
1182 // own rendering surface
1183 fbs = new FramebufferSurface(*mHwc, state.type);
1184 stc = new SurfaceTextureClient(
1185 static_cast< sp<ISurfaceTexture> >(
1186 fbs->getBufferQueue()));
1188 if (state.surface != NULL) {
1189 stc = new SurfaceTextureClient(state.surface);
1191 isSecure = state.isSecure;
1194 const wp<IBinder>& display(curr.keyAt(i));
1196 sp<DisplayDevice> hw = new DisplayDevice(this,
1197 state.type, isSecure, display, stc, fbs,
1199 hw->setLayerStack(state.layerStack);
1200 hw->setProjection(state.orientation,
1201 state.viewport, state.frame);
1202 hw->setDisplayName(state.displayName);
1203 mDisplays.add(display, hw);
1204 mEventThread->onHotplugReceived(state.type, true);
1212 * Perform our own transaction if needed
1215 const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1216 if (currentLayers.size() > previousLayers.size()) {
1217 // layers have been added
1218 mVisibleRegionsDirty = true;
1221 // some layers might have been removed, so
1222 // we need to update the regions they're exposing.
1223 if (mLayersRemoved) {
1224 mLayersRemoved = false;
1225 mVisibleRegionsDirty = true;
1226 const size_t count = previousLayers.size();
1227 for (size_t i=0 ; i<count ; i++) {
1228 const sp<LayerBase>& layer(previousLayers[i]);
1229 if (currentLayers.indexOf(layer) < 0) {
1230 // this layer is not visible anymore
1231 // TODO: we could traverse the tree from front to back and
1232 // compute the actual visible region
1233 // TODO: we could cache the transformed region
1234 const Layer::State& s(layer->drawingState());
1235 Region visibleReg = s.transform.transform(
1236 Region(Rect(s.active.w, s.active.h)));
1237 invalidateLayerStack(s.layerStack, visibleReg);
1242 commitTransaction();
1245 void SurfaceFlinger::commitTransaction()
1247 if (!mLayersPendingRemoval.isEmpty()) {
1248 // Notify removed layers now that they can't be drawn from
1249 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1250 mLayersPendingRemoval[i]->onRemoved();
1252 mLayersPendingRemoval.clear();
1255 mDrawingState = mCurrentState;
1256 mTransactionPending = false;
1257 mAnimTransactionPending = false;
1258 mTransactionCV.broadcast();
1261 void SurfaceFlinger::computeVisibleRegions(
1262 const LayerVector& currentLayers, uint32_t layerStack,
1263 Region& outDirtyRegion, Region& outOpaqueRegion)
1267 Region aboveOpaqueLayers;
1268 Region aboveCoveredLayers;
1271 outDirtyRegion.clear();
1273 size_t i = currentLayers.size();
1275 const sp<LayerBase>& layer = currentLayers[i];
1277 // start with the whole surface at its current location
1278 const Layer::State& s(layer->drawingState());
1280 // only consider the layers on the given later stack
1281 if (s.layerStack != layerStack)
1285 * opaqueRegion: area of a surface that is fully opaque.
1287 Region opaqueRegion;
1290 * visibleRegion: area of a surface that is visible on screen
1291 * and not fully transparent. This is essentially the layer's
1292 * footprint minus the opaque regions above it.
1293 * Areas covered by a translucent surface are considered visible.
1295 Region visibleRegion;
1298 * coveredRegion: area of a surface that is covered by all
1299 * visible regions above it (which includes the translucent areas).
1301 Region coveredRegion;
1304 * transparentRegion: area of a surface that is hinted to be completely
1305 * transparent. This is only used to tell when the layer has no visible
1306 * non-transparent regions and can be removed from the layer list. It
1307 * does not affect the visibleRegion of this layer or any layers
1308 * beneath it. The hint may not be correct if apps don't respect the
1309 * SurfaceView restrictions (which, sadly, some don't).
1311 Region transparentRegion;
1314 // handle hidden surfaces by setting the visible region to empty
1315 if (CC_LIKELY(layer->isVisible())) {
1316 const bool translucent = !layer->isOpaque();
1317 Rect bounds(layer->computeBounds());
1318 visibleRegion.set(bounds);
1319 if (!visibleRegion.isEmpty()) {
1320 // Remove the transparent area from the visible region
1322 const Transform tr(s.transform);
1323 if (tr.transformed()) {
1324 if (tr.preserveRects()) {
1325 // transform the transparent region
1326 transparentRegion = tr.transform(s.transparentRegion);
1328 // transformation too complex, can't do the
1329 // transparent region optimization.
1330 transparentRegion.clear();
1333 transparentRegion = s.transparentRegion;
1337 // compute the opaque region
1338 const int32_t layerOrientation = s.transform.getOrientation();
1339 if (s.alpha==255 && !translucent &&
1340 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1341 // the opaque region is the layer's footprint
1342 opaqueRegion = visibleRegion;
1347 // Clip the covered region to the visible region
1348 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1350 // Update aboveCoveredLayers for next (lower) layer
1351 aboveCoveredLayers.orSelf(visibleRegion);
1353 // subtract the opaque region covered by the layers above us
1354 visibleRegion.subtractSelf(aboveOpaqueLayers);
1356 // compute this layer's dirty region
1357 if (layer->contentDirty) {
1358 // we need to invalidate the whole region
1359 dirty = visibleRegion;
1360 // as well, as the old visible region
1361 dirty.orSelf(layer->visibleRegion);
1362 layer->contentDirty = false;
1364 /* compute the exposed region:
1365 * the exposed region consists of two components:
1366 * 1) what's VISIBLE now and was COVERED before
1367 * 2) what's EXPOSED now less what was EXPOSED before
1369 * note that (1) is conservative, we start with the whole
1370 * visible region but only keep what used to be covered by
1371 * something -- which mean it may have been exposed.
1373 * (2) handles areas that were not covered by anything but got
1374 * exposed because of a resize.
1376 const Region newExposed = visibleRegion - coveredRegion;
1377 const Region oldVisibleRegion = layer->visibleRegion;
1378 const Region oldCoveredRegion = layer->coveredRegion;
1379 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1380 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1382 dirty.subtractSelf(aboveOpaqueLayers);
1384 // accumulate to the screen dirty region
1385 outDirtyRegion.orSelf(dirty);
1387 // Update aboveOpaqueLayers for next (lower) layer
1388 aboveOpaqueLayers.orSelf(opaqueRegion);
1390 // Store the visible region in screen space
1391 layer->setVisibleRegion(visibleRegion);
1392 layer->setCoveredRegion(coveredRegion);
1393 layer->setVisibleNonTransparentRegion(
1394 visibleRegion.subtract(transparentRegion));
1397 outOpaqueRegion = aboveOpaqueLayers;
1400 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1401 const Region& dirty) {
1402 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1403 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1404 if (hw->getLayerStack() == layerStack) {
1405 hw->dirtyRegion.orSelf(dirty);
1410 void SurfaceFlinger::handlePageFlip()
1414 bool visibleRegions = false;
1415 const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1416 const size_t count = currentLayers.size();
1417 for (size_t i=0 ; i<count ; i++) {
1418 const sp<LayerBase>& layer(currentLayers[i]);
1419 const Region dirty(layer->latchBuffer(visibleRegions));
1420 const Layer::State& s(layer->drawingState());
1421 invalidateLayerStack(s.layerStack, dirty);
1424 mVisibleRegionsDirty |= visibleRegions;
1427 void SurfaceFlinger::invalidateHwcGeometry()
1429 mHwWorkListDirty = true;
1433 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1434 const Region& inDirtyRegion)
1436 Region dirtyRegion(inDirtyRegion);
1438 // compute the invalid region
1439 hw->swapRegion.orSelf(dirtyRegion);
1441 uint32_t flags = hw->getFlags();
1442 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1443 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1444 // takes a rectangle, we must make sure to update that whole
1445 // rectangle in that case
1446 dirtyRegion.set(hw->swapRegion.bounds());
1448 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1449 // We need to redraw the rectangle that will be updated
1450 // (pushed to the framebuffer).
1451 // This is needed because PARTIAL_UPDATES only takes one
1452 // rectangle instead of a region (see DisplayDevice::flip())
1453 dirtyRegion.set(hw->swapRegion.bounds());
1455 // we need to redraw everything (the whole screen)
1456 dirtyRegion.set(hw->bounds());
1457 hw->swapRegion = dirtyRegion;
1461 doComposeSurfaces(hw, dirtyRegion);
1463 // update the swap region and clear the dirty region
1464 hw->swapRegion.orSelf(dirtyRegion);
1466 // swap buffers (presentation)
1467 hw->swapBuffers(getHwComposer());
1470 void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1472 const int32_t id = hw->getHwcDisplayId();
1473 HWComposer& hwc(getHwComposer());
1474 HWComposer::LayerListIterator cur = hwc.begin(id);
1475 const HWComposer::LayerListIterator end = hwc.end(id);
1477 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1478 if (hasGlesComposition) {
1479 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1481 // set the frame buffer
1482 glMatrixMode(GL_MODELVIEW);
1485 // Never touch the framebuffer if we don't have any framebuffer layers
1486 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1487 if (hasHwcComposition) {
1488 // when using overlays, we assume a fully transparent framebuffer
1489 // NOTE: we could reduce how much we need to clear, for instance
1490 // remove where there are opaque FB layers. however, on some
1491 // GPUs doing a "clean slate" glClear might be more efficient.
1492 // We'll revisit later if needed.
1493 glClearColor(0, 0, 0, 0);
1494 glClear(GL_COLOR_BUFFER_BIT);
1496 const Region region(hw->undefinedRegion.intersect(dirty));
1497 // screen is already cleared here
1498 if (!region.isEmpty()) {
1499 // can happen with SurfaceView
1500 drawWormhole(hw, region);
1506 * and then, render the layers targeted at the framebuffer
1509 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1510 const size_t count = layers.size();
1511 const Transform& tr = hw->getTransform();
1513 // we're using h/w composer
1514 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1515 const sp<LayerBase>& layer(layers[i]);
1516 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1517 if (!clip.isEmpty()) {
1518 switch (cur->getCompositionType()) {
1520 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1522 && layer->isOpaque()
1523 && hasGlesComposition) {
1524 // never clear the very first layer since we're
1525 // guaranteed the FB is already cleared
1526 layer->clearWithOpenGL(hw, clip);
1530 case HWC_FRAMEBUFFER: {
1531 layer->draw(hw, clip);
1534 case HWC_FRAMEBUFFER_TARGET: {
1535 // this should not happen as the iterator shouldn't
1536 // let us get there.
1537 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1542 layer->setAcquireFence(hw, *cur);
1545 // we're not using h/w composer
1546 for (size_t i=0 ; i<count ; ++i) {
1547 const sp<LayerBase>& layer(layers[i]);
1548 const Region clip(dirty.intersect(
1549 tr.transform(layer->visibleRegion)));
1550 if (!clip.isEmpty()) {
1551 layer->draw(hw, clip);
1557 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1558 const Region& region) const
1560 glDisable(GL_TEXTURE_EXTERNAL_OES);
1561 glDisable(GL_TEXTURE_2D);
1562 glDisable(GL_BLEND);
1565 const int32_t height = hw->getHeight();
1566 Region::const_iterator it = region.begin();
1567 Region::const_iterator const end = region.end();
1569 const Rect& r = *it++;
1570 GLfloat vertices[][2] = {
1571 { r.left, height - r.top },
1572 { r.left, height - r.bottom },
1573 { r.right, height - r.bottom },
1574 { r.right, height - r.top }
1576 glVertexPointer(2, GL_FLOAT, 0, vertices);
1577 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1581 ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1582 const sp<LayerBaseClient>& lbc)
1584 // attach this layer to the client
1585 size_t name = client->attachLayer(lbc);
1587 // add this layer to the current state list
1588 Mutex::Autolock _l(mStateLock);
1589 mCurrentState.layersSortedByZ.add(lbc);
1591 return ssize_t(name);
1594 status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1596 Mutex::Autolock _l(mStateLock);
1597 status_t err = purgatorizeLayer_l(layer);
1598 if (err == NO_ERROR)
1599 setTransactionFlags(eTransactionNeeded);
1603 status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1605 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1607 mLayersRemoved = true;
1610 return status_t(index);
1613 status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1615 // First add the layer to the purgatory list, which makes sure it won't
1616 // go away, then remove it from the main list (through a transaction).
1617 ssize_t err = removeLayer_l(layerBase);
1619 mLayerPurgatory.add(layerBase);
1622 mLayersPendingRemoval.push(layerBase);
1624 // it's possible that we don't find a layer, because it might
1625 // have been destroyed already -- this is not technically an error
1626 // from the user because there is a race between Client::destroySurface(),
1627 // ~Client() and ~ISurface().
1628 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1631 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1633 return android_atomic_release_load(&mTransactionFlags);
1636 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1638 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1641 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1643 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1644 if ((old & flags)==0) { // wake the server up
1645 signalTransaction();
1650 void SurfaceFlinger::setTransactionState(
1651 const Vector<ComposerState>& state,
1652 const Vector<DisplayState>& displays,
1656 Mutex::Autolock _l(mStateLock);
1657 uint32_t transactionFlags = 0;
1659 if (flags & eAnimation) {
1660 // For window updates that are part of an animation we must wait for
1661 // previous animation "frames" to be handled.
1662 while (mAnimTransactionPending) {
1663 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1664 if (CC_UNLIKELY(err != NO_ERROR)) {
1665 // just in case something goes wrong in SF, return to the
1666 // caller after a few seconds.
1667 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1668 "waiting for previous animation frame");
1669 mAnimTransactionPending = false;
1675 size_t count = displays.size();
1676 for (size_t i=0 ; i<count ; i++) {
1677 const DisplayState& s(displays[i]);
1678 transactionFlags |= setDisplayStateLocked(s);
1681 count = state.size();
1682 for (size_t i=0 ; i<count ; i++) {
1683 const ComposerState& s(state[i]);
1684 sp<Client> client( static_cast<Client *>(s.client.get()) );
1685 transactionFlags |= setClientStateLocked(client, s.state);
1688 if (transactionFlags) {
1689 // this triggers the transaction
1690 setTransactionFlags(transactionFlags);
1692 // if this is a synchronous transaction, wait for it to take effect
1693 // before returning.
1694 if (flags & eSynchronous) {
1695 mTransactionPending = true;
1697 if (flags & eAnimation) {
1698 mAnimTransactionPending = true;
1700 while (mTransactionPending) {
1701 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1702 if (CC_UNLIKELY(err != NO_ERROR)) {
1703 // just in case something goes wrong in SF, return to the
1704 // called after a few seconds.
1705 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1706 mTransactionPending = false;
1713 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1715 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1720 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1721 if (disp.isValid()) {
1722 const uint32_t what = s.what;
1723 if (what & DisplayState::eSurfaceChanged) {
1724 if (disp.surface->asBinder() != s.surface->asBinder()) {
1725 disp.surface = s.surface;
1726 flags |= eDisplayTransactionNeeded;
1729 if (what & DisplayState::eLayerStackChanged) {
1730 if (disp.layerStack != s.layerStack) {
1731 disp.layerStack = s.layerStack;
1732 flags |= eDisplayTransactionNeeded;
1735 if (what & DisplayState::eDisplayProjectionChanged) {
1736 if (disp.orientation != s.orientation) {
1737 disp.orientation = s.orientation;
1738 flags |= eDisplayTransactionNeeded;
1740 if (disp.frame != s.frame) {
1741 disp.frame = s.frame;
1742 flags |= eDisplayTransactionNeeded;
1744 if (disp.viewport != s.viewport) {
1745 disp.viewport = s.viewport;
1746 flags |= eDisplayTransactionNeeded;
1753 uint32_t SurfaceFlinger::setClientStateLocked(
1754 const sp<Client>& client,
1755 const layer_state_t& s)
1758 sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1760 const uint32_t what = s.what;
1761 if (what & layer_state_t::ePositionChanged) {
1762 if (layer->setPosition(s.x, s.y))
1763 flags |= eTraversalNeeded;
1765 if (what & layer_state_t::eLayerChanged) {
1766 // NOTE: index needs to be calculated before we update the state
1767 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1768 if (layer->setLayer(s.z)) {
1769 mCurrentState.layersSortedByZ.removeAt(idx);
1770 mCurrentState.layersSortedByZ.add(layer);
1771 // we need traversal (state changed)
1772 // AND transaction (list changed)
1773 flags |= eTransactionNeeded|eTraversalNeeded;
1776 if (what & layer_state_t::eSizeChanged) {
1777 if (layer->setSize(s.w, s.h)) {
1778 flags |= eTraversalNeeded;
1781 if (what & layer_state_t::eAlphaChanged) {
1782 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1783 flags |= eTraversalNeeded;
1785 if (what & layer_state_t::eMatrixChanged) {
1786 if (layer->setMatrix(s.matrix))
1787 flags |= eTraversalNeeded;
1789 if (what & layer_state_t::eTransparentRegionChanged) {
1790 if (layer->setTransparentRegionHint(s.transparentRegion))
1791 flags |= eTraversalNeeded;
1793 if (what & layer_state_t::eVisibilityChanged) {
1794 if (layer->setFlags(s.flags, s.mask))
1795 flags |= eTraversalNeeded;
1797 if (what & layer_state_t::eCropChanged) {
1798 if (layer->setCrop(s.crop))
1799 flags |= eTraversalNeeded;
1801 if (what & layer_state_t::eLayerStackChanged) {
1802 // NOTE: index needs to be calculated before we update the state
1803 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1804 if (layer->setLayerStack(s.layerStack)) {
1805 mCurrentState.layersSortedByZ.removeAt(idx);
1806 mCurrentState.layersSortedByZ.add(layer);
1807 // we need traversal (state changed)
1808 // AND transaction (list changed)
1809 flags |= eTransactionNeeded|eTraversalNeeded;
1816 sp<ISurface> SurfaceFlinger::createLayer(
1817 ISurfaceComposerClient::surface_data_t* params,
1818 const String8& name,
1819 const sp<Client>& client,
1820 uint32_t w, uint32_t h, PixelFormat format,
1823 sp<LayerBaseClient> layer;
1824 sp<ISurface> surfaceHandle;
1826 if (int32_t(w|h) < 0) {
1827 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1829 return surfaceHandle;
1832 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1833 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1834 case ISurfaceComposerClient::eFXSurfaceNormal:
1835 layer = createNormalLayer(client, w, h, flags, format);
1837 case ISurfaceComposerClient::eFXSurfaceBlur:
1838 case ISurfaceComposerClient::eFXSurfaceDim:
1839 layer = createDimLayer(client, w, h, flags);
1841 case ISurfaceComposerClient::eFXSurfaceScreenshot:
1842 layer = createScreenshotLayer(client, w, h, flags);
1847 layer->initStates(w, h, flags);
1848 layer->setName(name);
1849 ssize_t token = addClientLayer(client, layer);
1850 surfaceHandle = layer->getSurface();
1851 if (surfaceHandle != 0) {
1852 params->token = token;
1853 params->identity = layer->getIdentity();
1855 setTransactionFlags(eTransactionNeeded);
1858 return surfaceHandle;
1861 sp<Layer> SurfaceFlinger::createNormalLayer(
1862 const sp<Client>& client,
1863 uint32_t w, uint32_t h, uint32_t flags,
1864 PixelFormat& format)
1866 // initialize the surfaces
1868 case PIXEL_FORMAT_TRANSPARENT:
1869 case PIXEL_FORMAT_TRANSLUCENT:
1870 format = PIXEL_FORMAT_RGBA_8888;
1872 case PIXEL_FORMAT_OPAQUE:
1874 format = PIXEL_FORMAT_RGB_565;
1876 format = PIXEL_FORMAT_RGBX_8888;
1882 if (format == PIXEL_FORMAT_RGBX_8888)
1883 format = PIXEL_FORMAT_RGBA_8888;
1886 sp<Layer> layer = new Layer(this, client);
1887 status_t err = layer->setBuffers(w, h, format, flags);
1888 if (CC_LIKELY(err != NO_ERROR)) {
1889 ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1895 sp<LayerDim> SurfaceFlinger::createDimLayer(
1896 const sp<Client>& client,
1897 uint32_t w, uint32_t h, uint32_t flags)
1899 sp<LayerDim> layer = new LayerDim(this, client);
1903 sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1904 const sp<Client>& client,
1905 uint32_t w, uint32_t h, uint32_t flags)
1907 sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1911 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1914 * called by the window manager, when a surface should be marked for
1917 * The surface is removed from the current and drawing lists, but placed
1918 * in the purgatory queue, so it's not destroyed right-away (we need
1919 * to wait for all client's references to go away first).
1922 status_t err = NAME_NOT_FOUND;
1923 Mutex::Autolock _l(mStateLock);
1924 sp<LayerBaseClient> layer = client->getLayerUser(sid);
1927 err = purgatorizeLayer_l(layer);
1928 if (err == NO_ERROR) {
1929 setTransactionFlags(eTransactionNeeded);
1935 status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1937 // called by ~ISurface() when all references are gone
1938 status_t err = NO_ERROR;
1939 sp<LayerBaseClient> l(layer.promote());
1941 Mutex::Autolock _l(mStateLock);
1942 err = removeLayer_l(l);
1943 if (err == NAME_NOT_FOUND) {
1944 // The surface wasn't in the current list, which means it was
1945 // removed already, which means it is in the purgatory,
1946 // and need to be removed from there.
1947 ssize_t idx = mLayerPurgatory.remove(l);
1949 "layer=%p is not in the purgatory list", l.get());
1951 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1952 "error removing layer=%p (%s)", l.get(), strerror(-err));
1957 // ---------------------------------------------------------------------------
1959 void SurfaceFlinger::onInitializeDisplays() {
1960 // reset screen orientation
1961 Vector<ComposerState> state;
1962 Vector<DisplayState> displays;
1964 d.what = DisplayState::eDisplayProjectionChanged;
1965 d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1966 d.orientation = DisplayState::eOrientationDefault;
1967 d.frame.makeInvalid();
1968 d.viewport.makeInvalid();
1970 setTransactionState(state, displays, 0);
1971 onScreenAcquired(getDefaultDisplayDevice());
1974 void SurfaceFlinger::initializeDisplays() {
1975 class MessageScreenInitialized : public MessageBase {
1976 SurfaceFlinger* flinger;
1978 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1979 virtual bool handler() {
1980 flinger->onInitializeDisplays();
1984 sp<MessageBase> msg = new MessageScreenInitialized(this);
1985 postMessageAsync(msg); // we may be called from main thread, use async message
1989 void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
1990 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
1991 if (hw->isScreenAcquired()) {
1992 // this is expected, e.g. when power manager wakes up during boot
1993 ALOGD(" screen was previously acquired");
1997 hw->acquireScreen();
1998 int32_t type = hw->getDisplayType();
1999 if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2000 // built-in display, tell the HWC
2001 getHwComposer().acquire(type);
2003 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2004 // FIXME: eventthread only knows about the main display right now
2005 mEventThread->onScreenAcquired();
2008 mVisibleRegionsDirty = true;
2009 repaintEverything();
2012 void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2013 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2014 if (!hw->isScreenAcquired()) {
2015 ALOGD(" screen was previously released");
2019 hw->releaseScreen();
2020 int32_t type = hw->getDisplayType();
2021 if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2022 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2023 // FIXME: eventthread only knows about the main display right now
2024 mEventThread->onScreenReleased();
2027 // built-in display, tell the HWC
2028 getHwComposer().release(type);
2030 mVisibleRegionsDirty = true;
2031 // from this point on, SF will stop drawing on this display
2034 void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2035 class MessageScreenAcquired : public MessageBase {
2036 SurfaceFlinger& mFlinger;
2037 sp<IBinder> mDisplay;
2039 MessageScreenAcquired(SurfaceFlinger& flinger,
2040 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2041 virtual bool handler() {
2042 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2044 ALOGE("Attempt to unblank null display %p", mDisplay.get());
2045 } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2046 ALOGW("Attempt to unblank virtual display");
2048 mFlinger.onScreenAcquired(hw);
2053 sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2054 postMessageSync(msg);
2057 void SurfaceFlinger::blank(const sp<IBinder>& display) {
2058 class MessageScreenReleased : public MessageBase {
2059 SurfaceFlinger& mFlinger;
2060 sp<IBinder> mDisplay;
2062 MessageScreenReleased(SurfaceFlinger& flinger,
2063 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2064 virtual bool handler() {
2065 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2067 ALOGE("Attempt to blank null display %p", mDisplay.get());
2068 } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2069 ALOGW("Attempt to blank virtual display");
2071 mFlinger.onScreenReleased(hw);
2076 sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2077 postMessageSync(msg);
2080 // ---------------------------------------------------------------------------
2082 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2084 const size_t SIZE = 4096;
2088 if (!PermissionCache::checkCallingPermission(sDump)) {
2089 snprintf(buffer, SIZE, "Permission Denial: "
2090 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
2091 IPCThreadState::self()->getCallingPid(),
2092 IPCThreadState::self()->getCallingUid());
2093 result.append(buffer);
2095 // Try to get the main lock, but don't insist if we can't
2096 // (this would indicate SF is stuck, but we want to be able to
2097 // print something in dumpsys).
2099 while (mStateLock.tryLock()<0 && --retry>=0) {
2102 const bool locked(retry >= 0);
2104 snprintf(buffer, SIZE,
2105 "SurfaceFlinger appears to be unresponsive, "
2106 "dumping anyways (no locks held)\n");
2107 result.append(buffer);
2110 bool dumpAll = true;
2112 size_t numArgs = args.size();
2114 if ((index < numArgs) &&
2115 (args[index] == String16("--list"))) {
2117 listLayersLocked(args, index, result, buffer, SIZE);
2121 if ((index < numArgs) &&
2122 (args[index] == String16("--latency"))) {
2124 dumpStatsLocked(args, index, result, buffer, SIZE);
2128 if ((index < numArgs) &&
2129 (args[index] == String16("--latency-clear"))) {
2131 clearStatsLocked(args, index, result, buffer, SIZE);
2137 dumpAllLocked(result, buffer, SIZE);
2141 mStateLock.unlock();
2144 write(fd, result.string(), result.size());
2148 void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2149 String8& result, char* buffer, size_t SIZE) const
2151 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2152 const size_t count = currentLayers.size();
2153 for (size_t i=0 ; i<count ; i++) {
2154 const sp<LayerBase>& layer(currentLayers[i]);
2155 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2156 result.append(buffer);
2160 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2161 String8& result, char* buffer, size_t SIZE) const
2164 if (index < args.size()) {
2165 name = String8(args[index]);
2169 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2170 const size_t count = currentLayers.size();
2171 for (size_t i=0 ; i<count ; i++) {
2172 const sp<LayerBase>& layer(currentLayers[i]);
2173 if (name.isEmpty()) {
2174 snprintf(buffer, SIZE, "%s\n", layer->getName().string());
2175 result.append(buffer);
2177 if (name.isEmpty() || (name == layer->getName())) {
2178 layer->dumpStats(result, buffer, SIZE);
2183 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2184 String8& result, char* buffer, size_t SIZE) const
2187 if (index < args.size()) {
2188 name = String8(args[index]);
2192 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2193 const size_t count = currentLayers.size();
2194 for (size_t i=0 ; i<count ; i++) {
2195 const sp<LayerBase>& layer(currentLayers[i]);
2196 if (name.isEmpty() || (name == layer->getName())) {
2197 layer->clearStats();
2202 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2204 static const char* config =
2209 #ifdef HAS_CONTEXT_PRIORITY
2210 " HAS_CONTEXT_PRIORITY"
2212 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2213 " NEVER_DEFAULT_TO_ASYNC_MODE"
2215 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2216 " TARGET_DISABLE_TRIPLE_BUFFERING"
2219 result.append(config);
2222 void SurfaceFlinger::dumpAllLocked(
2223 String8& result, char* buffer, size_t SIZE) const
2225 // figure out if we're stuck somewhere
2226 const nsecs_t now = systemTime();
2227 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2228 const nsecs_t inTransaction(mDebugInTransaction);
2229 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2230 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2233 * Dump library configuration.
2235 result.append("Build configuration:");
2236 appendSfConfigString(result);
2237 appendUiConfigString(result);
2238 appendGuiConfigString(result);
2239 result.append("\n");
2242 * Dump the visible layer list
2244 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2245 const size_t count = currentLayers.size();
2246 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
2247 result.append(buffer);
2248 for (size_t i=0 ; i<count ; i++) {
2249 const sp<LayerBase>& layer(currentLayers[i]);
2250 layer->dump(result, buffer, SIZE);
2254 * Dump the layers in the purgatory
2257 const size_t purgatorySize = mLayerPurgatory.size();
2258 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
2259 result.append(buffer);
2260 for (size_t i=0 ; i<purgatorySize ; i++) {
2261 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
2262 layer->shortDump(result, buffer, SIZE);
2266 * Dump Display state
2269 snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size());
2270 result.append(buffer);
2271 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2272 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2273 hw->dump(result, buffer, SIZE);
2277 * Dump SurfaceFlinger global state
2280 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
2281 result.append(buffer);
2283 HWComposer& hwc(getHwComposer());
2284 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2285 const GLExtensions& extensions(GLExtensions::getInstance());
2286 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
2287 extensions.getVendor(),
2288 extensions.getRenderer(),
2289 extensions.getVersion());
2290 result.append(buffer);
2292 snprintf(buffer, SIZE, "EGL : %s\n",
2293 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2294 result.append(buffer);
2296 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2297 result.append(buffer);
2299 hw->undefinedRegion.dump(result, "undefinedRegion");
2300 snprintf(buffer, SIZE,
2301 " orientation=%d, canDraw=%d\n",
2302 hw->getOrientation(), hw->canDraw());
2303 result.append(buffer);
2304 snprintf(buffer, SIZE,
2305 " last eglSwapBuffers() time: %f us\n"
2306 " last transaction time : %f us\n"
2307 " transaction-flags : %08x\n"
2308 " refresh-rate : %f fps\n"
2311 mLastSwapBufferTime/1000.0,
2312 mLastTransactionTime/1000.0,
2314 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2315 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2316 hwc.getDpiY(HWC_DISPLAY_PRIMARY));
2317 result.append(buffer);
2319 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n",
2320 inSwapBuffersDuration/1000.0);
2321 result.append(buffer);
2323 snprintf(buffer, SIZE, " transaction time: %f us\n",
2324 inTransactionDuration/1000.0);
2325 result.append(buffer);
2330 mEventThread->dump(result, buffer, SIZE);
2333 * Dump HWComposer state
2335 snprintf(buffer, SIZE, "h/w composer state:\n");
2336 result.append(buffer);
2337 snprintf(buffer, SIZE, " h/w composer %s and %s\n",
2338 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2339 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2340 result.append(buffer);
2341 hwc.dump(result, buffer, SIZE);
2344 * Dump gralloc state
2346 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2350 const Vector< sp<LayerBase> >&
2351 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int disp) {
2352 // Note: mStateLock is held here
2353 return getDisplayDevice( getBuiltInDisplay(disp) )->getVisibleLayersSortedByZ();
2356 bool SurfaceFlinger::startDdmConnection()
2358 void* libddmconnection_dso =
2359 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2360 if (!libddmconnection_dso) {
2363 void (*DdmConnection_start)(const char* name);
2364 DdmConnection_start =
2365 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2366 if (!DdmConnection_start) {
2367 dlclose(libddmconnection_dso);
2370 (*DdmConnection_start)(getServiceName());
2374 status_t SurfaceFlinger::onTransact(
2375 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2378 case CREATE_CONNECTION:
2379 case SET_TRANSACTION_STATE:
2384 // codes that require permission check
2385 IPCThreadState* ipc = IPCThreadState::self();
2386 const int pid = ipc->getCallingPid();
2387 const int uid = ipc->getCallingUid();
2388 if ((uid != AID_GRAPHICS) &&
2389 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2390 ALOGE("Permission Denial: "
2391 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2392 return PERMISSION_DENIED;
2396 case CAPTURE_SCREEN:
2398 // codes that require permission check
2399 IPCThreadState* ipc = IPCThreadState::self();
2400 const int pid = ipc->getCallingPid();
2401 const int uid = ipc->getCallingUid();
2402 if ((uid != AID_GRAPHICS) &&
2403 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2404 ALOGE("Permission Denial: "
2405 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2406 return PERMISSION_DENIED;
2412 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2413 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2414 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2415 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2416 IPCThreadState* ipc = IPCThreadState::self();
2417 const int pid = ipc->getCallingPid();
2418 const int uid = ipc->getCallingUid();
2419 ALOGE("Permission Denial: "
2420 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2421 return PERMISSION_DENIED;
2425 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2426 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2428 case 1002: // SHOW_UPDATES
2429 n = data.readInt32();
2430 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2431 invalidateHwcGeometry();
2432 repaintEverything();
2434 case 1004:{ // repaint everything
2435 repaintEverything();
2438 case 1005:{ // force transaction
2439 setTransactionFlags(
2441 eDisplayTransactionNeeded|
2445 case 1006:{ // send empty update
2449 case 1008: // toggle use of hw composer
2450 n = data.readInt32();
2451 mDebugDisableHWC = n ? 1 : 0;
2452 invalidateHwcGeometry();
2453 repaintEverything();
2455 case 1009: // toggle use of transform hint
2456 n = data.readInt32();
2457 mDebugDisableTransformHint = n ? 1 : 0;
2458 invalidateHwcGeometry();
2459 repaintEverything();
2461 case 1010: // interrogate.
2462 reply->writeInt32(0);
2463 reply->writeInt32(0);
2464 reply->writeInt32(mDebugRegion);
2465 reply->writeInt32(0);
2466 reply->writeInt32(mDebugDisableHWC);
2469 Mutex::Autolock _l(mStateLock);
2470 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2471 reply->writeInt32(hw->getPageFlipCount());
2479 void SurfaceFlinger::repaintEverything() {
2480 android_atomic_or(1, &mRepaintEverything);
2481 signalTransaction();
2484 // ---------------------------------------------------------------------------
2486 status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2487 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2489 Mutex::Autolock _l(mStateLock);
2490 return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2493 status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2494 GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2498 if (!GLExtensions::getInstance().haveFramebufferObject())
2499 return INVALID_OPERATION;
2501 // get screen geometry
2502 // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2503 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2504 const uint32_t hw_w = hw->getWidth();
2505 const uint32_t hw_h = hw->getHeight();
2509 // make sure to clear all GL error flags
2510 while ( glGetError() != GL_NO_ERROR ) ;
2514 glGenTextures(1, &tname);
2515 glBindTexture(GL_TEXTURE_2D, tname);
2516 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2517 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2518 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2519 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2520 if (glGetError() != GL_NO_ERROR) {
2521 while ( glGetError() != GL_NO_ERROR ) ;
2522 GLint tw = (2 << (31 - clz(hw_w)));
2523 GLint th = (2 << (31 - clz(hw_h)));
2524 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2525 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2526 u = GLfloat(hw_w) / tw;
2527 v = GLfloat(hw_h) / th;
2529 glGenFramebuffersOES(1, &name);
2530 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2531 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2532 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2534 DisplayDevice::setViewportAndProjection(hw);
2536 // redraw the screen entirely...
2537 glDisable(GL_TEXTURE_EXTERNAL_OES);
2538 glDisable(GL_TEXTURE_2D);
2539 glClearColor(0,0,0,1);
2540 glClear(GL_COLOR_BUFFER_BIT);
2541 glMatrixMode(GL_MODELVIEW);
2543 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2544 const size_t count = layers.size();
2545 for (size_t i=0 ; i<count ; ++i) {
2546 const sp<LayerBase>& layer(layers[i]);
2550 hw->compositionComplete();
2552 // back to main framebuffer
2553 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2554 glDeleteFramebuffersOES(1, &name);
2556 *textureName = tname;
2562 // ---------------------------------------------------------------------------
2564 status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2565 sp<IMemoryHeap>* heap,
2566 uint32_t* w, uint32_t* h, PixelFormat* f,
2567 uint32_t sw, uint32_t sh,
2568 uint32_t minLayerZ, uint32_t maxLayerZ)
2572 status_t result = PERMISSION_DENIED;
2574 if (!GLExtensions::getInstance().haveFramebufferObject()) {
2575 return INVALID_OPERATION;
2578 // get screen geometry
2579 sp<const DisplayDevice> hw(getDisplayDevice(display));
2580 const uint32_t hw_w = hw->getWidth();
2581 const uint32_t hw_h = hw->getHeight();
2583 // if we have secure windows on this display, never allow the screen capture
2584 if (hw->getSecureLayerVisible()) {
2585 ALOGW("FB is protected: PERMISSION_DENIED");
2586 return PERMISSION_DENIED;
2589 if ((sw > hw_w) || (sh > hw_h)) {
2590 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2594 sw = (!sw) ? hw_w : sw;
2595 sh = (!sh) ? hw_h : sh;
2596 const size_t size = sw * sh * 4;
2597 const bool filtering = sw != hw_w || sh != hw_h;
2599 // ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2600 // sw, sh, minLayerZ, maxLayerZ);
2602 // make sure to clear all GL error flags
2603 while ( glGetError() != GL_NO_ERROR ) ;
2607 glGenRenderbuffersOES(1, &tname);
2608 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2609 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2611 glGenFramebuffersOES(1, &name);
2612 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2613 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2614 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2616 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2618 if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2620 // invert everything, b/c glReadPixel() below will invert the FB
2622 glGetIntegerv(GL_VIEWPORT, viewport);
2623 glViewport(0, 0, sw, sh);
2624 glMatrixMode(GL_PROJECTION);
2627 glOrthof(0, hw_w, hw_h, 0, 0, 1);
2628 glMatrixMode(GL_MODELVIEW);
2630 // redraw the screen entirely...
2631 glClearColor(0,0,0,1);
2632 glClear(GL_COLOR_BUFFER_BIT);
2634 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2635 const size_t count = layers.size();
2636 for (size_t i=0 ; i<count ; ++i) {
2637 const sp<LayerBase>& layer(layers[i]);
2638 const uint32_t z = layer->drawingState().z;
2639 if (z >= minLayerZ && z <= maxLayerZ) {
2640 if (filtering) layer->setFiltering(true);
2642 if (filtering) layer->setFiltering(false);
2646 // check for errors and return screen capture
2647 if (glGetError() != GL_NO_ERROR) {
2648 // error while rendering
2649 result = INVALID_OPERATION;
2651 // allocate shared memory large enough to hold the
2653 sp<MemoryHeapBase> base(
2654 new MemoryHeapBase(size, 0, "screen-capture") );
2655 void* const ptr = base->getBase();
2656 if (ptr != MAP_FAILED) {
2657 // capture the screen with glReadPixels()
2658 ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2659 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2660 if (glGetError() == GL_NO_ERROR) {
2664 *f = PIXEL_FORMAT_RGBA_8888;
2671 glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
2672 glMatrixMode(GL_PROJECTION);
2674 glMatrixMode(GL_MODELVIEW);
2679 // release FBO resources
2680 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2681 glDeleteRenderbuffersOES(1, &tname);
2682 glDeleteFramebuffersOES(1, &name);
2684 hw->compositionComplete();
2686 // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2692 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2693 sp<IMemoryHeap>* heap,
2694 uint32_t* width, uint32_t* height, PixelFormat* format,
2695 uint32_t sw, uint32_t sh,
2696 uint32_t minLayerZ, uint32_t maxLayerZ)
2698 if (CC_UNLIKELY(display == 0))
2701 if (!GLExtensions::getInstance().haveFramebufferObject())
2702 return INVALID_OPERATION;
2704 class MessageCaptureScreen : public MessageBase {
2705 SurfaceFlinger* flinger;
2706 sp<IBinder> display;
2707 sp<IMemoryHeap>* heap;
2717 MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2718 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2719 uint32_t sw, uint32_t sh,
2720 uint32_t minLayerZ, uint32_t maxLayerZ)
2721 : flinger(flinger), display(display),
2722 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2723 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2724 result(PERMISSION_DENIED)
2727 status_t getResult() const {
2730 virtual bool handler() {
2731 Mutex::Autolock _l(flinger->mStateLock);
2732 result = flinger->captureScreenImplLocked(display,
2733 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2738 sp<MessageBase> msg = new MessageCaptureScreen(this,
2739 display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2740 status_t res = postMessageSync(msg);
2741 if (res == NO_ERROR) {
2742 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2747 // ---------------------------------------------------------------------------
2749 SurfaceFlinger::LayerVector::LayerVector() {
2752 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2753 : SortedVector<sp<LayerBase> >(rhs) {
2756 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2757 const void* rhs) const
2759 // sort layers per layer-stack, then by z-order and finally by sequence
2760 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2761 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2763 uint32_t ls = l->currentState().layerStack;
2764 uint32_t rs = r->currentState().layerStack;
2768 uint32_t lz = l->currentState().z;
2769 uint32_t rz = r->currentState().z;
2773 return l->sequence - r->sequence;
2776 // ---------------------------------------------------------------------------
2778 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2779 : type(DisplayDevice::DISPLAY_ID_INVALID) {
2782 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2783 : type(type), layerStack(0), orientation(0) {
2784 viewport.makeInvalid();
2785 frame.makeInvalid();
2788 // ---------------------------------------------------------------------------
2790 }; // namespace android