SurfaceFlinger.cpp revision c19c15174b1a07c5d18f45f26bee7893481ab41d
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define ATRACE_TAG ATRACE_TAG_GRAPHICS 18 19#include <stdint.h> 20#include <sys/types.h> 21#include <errno.h> 22#include <math.h> 23#include <dlfcn.h> 24 25#include <EGL/egl.h> 26#include <GLES/gl.h> 27 28#include <cutils/log.h> 29#include <cutils/properties.h> 30 31#include <binder/IPCThreadState.h> 32#include <binder/IServiceManager.h> 33#include <binder/MemoryHeapBase.h> 34#include <binder/PermissionCache.h> 35 36#include <ui/DisplayInfo.h> 37 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> 43#include <gui/GraphicBufferAlloc.h> 44 45#include <ui/GraphicBufferAllocator.h> 46#include <ui/PixelFormat.h> 47#include <ui/UiConfig.h> 48 49#include <utils/misc.h> 50#include <utils/String8.h> 51#include <utils/String16.h> 52#include <utils/StopWatch.h> 53#include <utils/Trace.h> 54 55#include <private/android_filesystem_config.h> 56 57#include "clz.h" 58#include "DdmConnection.h" 59#include "DisplayDevice.h" 60#include "Client.h" 61#include "EventThread.h" 62#include "GLExtensions.h" 63#include "Layer.h" 64#include "LayerDim.h" 65#include "LayerScreenshot.h" 66#include "SurfaceFlinger.h" 67 68#include "DisplayHardware/FramebufferSurface.h" 69#include "DisplayHardware/HWComposer.h" 70 71 72#define EGL_VERSION_HW_ANDROID 0x3143 73 74#define DISPLAY_COUNT 1 75 76namespace android { 77// --------------------------------------------------------------------------- 78 79const String16 sHardwareTest("android.permission.HARDWARE_TEST"); 80const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); 81const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER"); 82const String16 sDump("android.permission.DUMP"); 83 84// --------------------------------------------------------------------------- 85 86SurfaceFlinger::SurfaceFlinger() 87 : BnSurfaceComposer(), Thread(false), 88 mTransactionFlags(0), 89 mTransactionPending(false), 90 mAnimTransactionPending(false), 91 mLayersRemoved(false), 92 mRepaintEverything(0), 93 mBootTime(systemTime()), 94 mVisibleRegionsDirty(false), 95 mHwWorkListDirty(false), 96 mDebugRegion(0), 97 mDebugDDMS(0), 98 mDebugDisableHWC(0), 99 mDebugDisableTransformHint(0), 100 mDebugInSwapBuffers(0), 101 mLastSwapBufferTime(0), 102 mDebugInTransaction(0), 103 mLastTransactionTime(0), 104 mBootFinished(false) 105{ 106 ALOGI("SurfaceFlinger is starting"); 107 108 // debugging stuff... 109 char value[PROPERTY_VALUE_MAX]; 110 111 property_get("debug.sf.showupdates", value, "0"); 112 mDebugRegion = atoi(value); 113 114 property_get("debug.sf.ddms", value, "0"); 115 mDebugDDMS = atoi(value); 116 if (mDebugDDMS) { 117 if (!startDdmConnection()) { 118 // start failed, and DDMS debugging not enabled 119 mDebugDDMS = 0; 120 } 121 } 122 ALOGI_IF(mDebugRegion, "showupdates enabled"); 123 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); 124} 125 126void SurfaceFlinger::onFirstRef() 127{ 128 mEventQueue.init(this); 129 130 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY); 131 132 // Wait for the main thread to be done with its initialization 133 mReadyToRunBarrier.wait(); 134} 135 136 137SurfaceFlinger::~SurfaceFlinger() 138{ 139 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); 140 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 141 eglTerminate(display); 142} 143 144void SurfaceFlinger::binderDied(const wp<IBinder>& who) 145{ 146 // the window manager died on us. prepare its eulogy. 147 148 // restore initial conditions (default device unblank, etc) 149 initializeDisplays(); 150 151 // restart the boot-animation 152 startBootAnim(); 153} 154 155sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 156{ 157 sp<ISurfaceComposerClient> bclient; 158 sp<Client> client(new Client(this)); 159 status_t err = client->initCheck(); 160 if (err == NO_ERROR) { 161 bclient = client; 162 } 163 return bclient; 164} 165 166sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, 167 bool secure) 168{ 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); 176 } 177 public: 178 DisplayToken(const sp<SurfaceFlinger>& flinger) 179 : flinger(flinger) { 180 } 181 }; 182 183 sp<BBinder> token = new DisplayToken(this); 184 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); 190 191 return token; 192} 193 194void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) { 195 ALOGW_IF(mBuiltinDisplays[type], 196 "Overwriting display token for display type %d", type); 197 mBuiltinDisplays[type] = new BBinder(); 198 DisplayDeviceState info(type); 199 // All non-virtual displays are currently considered secure. 200 info.isSecure = true; 201 mCurrentState.displays.add(mBuiltinDisplays[type], info); 202} 203 204sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) { 205 if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) { 206 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id); 207 return NULL; 208 } 209 return mBuiltinDisplays[id]; 210} 211 212sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() 213{ 214 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); 215 return gba; 216} 217 218void SurfaceFlinger::bootFinished() 219{ 220 const nsecs_t now = systemTime(); 221 const nsecs_t duration = now - mBootTime; 222 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 223 mBootFinished = true; 224 225 // wait patiently for the window manager death 226 const String16 name("window"); 227 sp<IBinder> window(defaultServiceManager()->getService(name)); 228 if (window != 0) { 229 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this)); 230 } 231 232 // stop boot animation 233 // formerly we would just kill the process, but we now ask it to exit so it 234 // can choose where to stop the animation. 235 property_set("service.bootanim.exit", "1"); 236} 237 238void SurfaceFlinger::deleteTextureAsync(GLuint texture) { 239 class MessageDestroyGLTexture : public MessageBase { 240 GLuint texture; 241 public: 242 MessageDestroyGLTexture(GLuint texture) 243 : texture(texture) { 244 } 245 virtual bool handler() { 246 glDeleteTextures(1, &texture); 247 return true; 248 } 249 }; 250 postMessageAsync(new MessageDestroyGLTexture(texture)); 251} 252 253status_t SurfaceFlinger::selectConfigForAttribute( 254 EGLDisplay dpy, 255 EGLint const* attrs, 256 EGLint attribute, EGLint wanted, 257 EGLConfig* outConfig) 258{ 259 EGLConfig config = NULL; 260 EGLint numConfigs = -1, n=0; 261 eglGetConfigs(dpy, NULL, 0, &numConfigs); 262 EGLConfig* const configs = new EGLConfig[numConfigs]; 263 eglChooseConfig(dpy, attrs, configs, numConfigs, &n); 264 265 if (n) { 266 if (attribute != EGL_NONE) { 267 for (int i=0 ; i<n ; i++) { 268 EGLint value = 0; 269 eglGetConfigAttrib(dpy, configs[i], attribute, &value); 270 if (wanted == value) { 271 *outConfig = configs[i]; 272 delete [] configs; 273 return NO_ERROR; 274 } 275 } 276 } else { 277 // just pick the first one 278 *outConfig = configs[0]; 279 delete [] configs; 280 return NO_ERROR; 281 } 282 } 283 delete [] configs; 284 return NAME_NOT_FOUND; 285} 286 287class EGLAttributeVector { 288 struct Attribute; 289 class Adder; 290 friend class Adder; 291 KeyedVector<Attribute, EGLint> mList; 292 struct Attribute { 293 Attribute() {}; 294 Attribute(EGLint v) : v(v) { } 295 EGLint v; 296 bool operator < (const Attribute& other) const { 297 // this places EGL_NONE at the end 298 EGLint lhs(v); 299 EGLint rhs(other.v); 300 if (lhs == EGL_NONE) lhs = 0x7FFFFFFF; 301 if (rhs == EGL_NONE) rhs = 0x7FFFFFFF; 302 return lhs < rhs; 303 } 304 }; 305 class Adder { 306 friend class EGLAttributeVector; 307 EGLAttributeVector& v; 308 EGLint attribute; 309 Adder(EGLAttributeVector& v, EGLint attribute) 310 : v(v), attribute(attribute) { 311 } 312 public: 313 void operator = (EGLint value) { 314 if (attribute != EGL_NONE) { 315 v.mList.add(attribute, value); 316 } 317 } 318 operator EGLint () const { return v.mList[attribute]; } 319 }; 320public: 321 EGLAttributeVector() { 322 mList.add(EGL_NONE, EGL_NONE); 323 } 324 void remove(EGLint attribute) { 325 if (attribute != EGL_NONE) { 326 mList.removeItem(attribute); 327 } 328 } 329 Adder operator [] (EGLint attribute) { 330 return Adder(*this, attribute); 331 } 332 EGLint operator [] (EGLint attribute) const { 333 return mList[attribute]; 334 } 335 // cast-operator to (EGLint const*) 336 operator EGLint const* () const { return &mList.keyAt(0).v; } 337}; 338 339EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) { 340 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if 341 // it is to be used with WIFI displays 342 EGLConfig config; 343 EGLint dummy; 344 status_t err; 345 346 EGLAttributeVector attribs; 347 attribs[EGL_SURFACE_TYPE] = EGL_WINDOW_BIT; 348 attribs[EGL_RECORDABLE_ANDROID] = EGL_TRUE; 349 attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE; 350 attribs[EGL_RED_SIZE] = 8; 351 attribs[EGL_GREEN_SIZE] = 8; 352 attribs[EGL_BLUE_SIZE] = 8; 353 354 err = selectConfigForAttribute(display, attribs, EGL_NONE, EGL_NONE, &config); 355 if (!err) 356 goto success; 357 358 // maybe we failed because of EGL_FRAMEBUFFER_TARGET_ANDROID 359 ALOGW("no suitable EGLConfig found, trying without EGL_FRAMEBUFFER_TARGET_ANDROID"); 360 attribs.remove(EGL_FRAMEBUFFER_TARGET_ANDROID); 361 err = selectConfigForAttribute(display, attribs, 362 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config); 363 if (!err) 364 goto success; 365 366 // maybe we failed because of EGL_RECORDABLE_ANDROID 367 ALOGW("no suitable EGLConfig found, trying without EGL_RECORDABLE_ANDROID"); 368 attribs.remove(EGL_RECORDABLE_ANDROID); 369 err = selectConfigForAttribute(display, attribs, 370 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config); 371 if (!err) 372 goto success; 373 374 // allow less than 24-bit color; the non-gpu-accelerated emulator only 375 // supports 16-bit color 376 ALOGW("no suitable EGLConfig found, trying with 16-bit color allowed"); 377 attribs.remove(EGL_RED_SIZE); 378 attribs.remove(EGL_GREEN_SIZE); 379 attribs.remove(EGL_BLUE_SIZE); 380 err = selectConfigForAttribute(display, attribs, 381 EGL_NATIVE_VISUAL_ID, nativeVisualId, &config); 382 if (!err) 383 goto success; 384 385 // this EGL is too lame for Android 386 ALOGE("no suitable EGLConfig found, giving up"); 387 388 return 0; 389 390success: 391 if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy)) 392 ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!"); 393 return config; 394} 395 396EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) { 397 // Also create our EGLContext 398 EGLint contextAttributes[] = { 399#ifdef EGL_IMG_context_priority 400#ifdef HAS_CONTEXT_PRIORITY 401#warning "using EGL_IMG_context_priority" 402 EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG, 403#endif 404#endif 405 EGL_NONE, EGL_NONE 406 }; 407 EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes); 408 ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed"); 409 return ctxt; 410} 411 412void SurfaceFlinger::initializeGL(EGLDisplay display) { 413 GLExtensions& extensions(GLExtensions::getInstance()); 414 extensions.initWithGLStrings( 415 glGetString(GL_VENDOR), 416 glGetString(GL_RENDERER), 417 glGetString(GL_VERSION), 418 glGetString(GL_EXTENSIONS), 419 eglQueryString(display, EGL_VENDOR), 420 eglQueryString(display, EGL_VERSION), 421 eglQueryString(display, EGL_EXTENSIONS)); 422 423 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize); 424 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims); 425 426 glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 427 glPixelStorei(GL_PACK_ALIGNMENT, 4); 428 glEnableClientState(GL_VERTEX_ARRAY); 429 glShadeModel(GL_FLAT); 430 glDisable(GL_DITHER); 431 glDisable(GL_CULL_FACE); 432 433 struct pack565 { 434 inline uint16_t operator() (int r, int g, int b) const { 435 return (r<<11)|(g<<5)|b; 436 } 437 } pack565; 438 439 const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) }; 440 glGenTextures(1, &mProtectedTexName); 441 glBindTexture(GL_TEXTURE_2D, mProtectedTexName); 442 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 443 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 444 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 445 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 446 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, 447 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData); 448 449 // print some debugging info 450 EGLint r,g,b,a; 451 eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE, &r); 452 eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g); 453 eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE, &b); 454 eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a); 455 ALOGI("EGL informations:"); 456 ALOGI("vendor : %s", extensions.getEglVendor()); 457 ALOGI("version : %s", extensions.getEglVersion()); 458 ALOGI("extensions: %s", extensions.getEglExtension()); 459 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported"); 460 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig); 461 ALOGI("OpenGL ES informations:"); 462 ALOGI("vendor : %s", extensions.getVendor()); 463 ALOGI("renderer : %s", extensions.getRenderer()); 464 ALOGI("version : %s", extensions.getVersion()); 465 ALOGI("extensions: %s", extensions.getExtension()); 466 ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize); 467 ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]); 468} 469 470status_t SurfaceFlinger::readyToRun() 471{ 472 ALOGI( "SurfaceFlinger's main thread ready to run. " 473 "Initializing graphics H/W..."); 474 475 Mutex::Autolock _l(mStateLock); 476 477 // initialize EGL for the default display 478 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 479 eglInitialize(mEGLDisplay, NULL, NULL); 480 481 // Initialize the H/W composer object. There may or may not be an 482 // actual hardware composer underneath. 483 mHwc = new HWComposer(this, 484 *static_cast<HWComposer::EventHandler *>(this)); 485 486 // initialize the config and context 487 EGLint format = mHwc->getVisualID(); 488 mEGLConfig = selectEGLConfig(mEGLDisplay, format); 489 mEGLContext = createGLContext(mEGLDisplay, mEGLConfig); 490 491 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT, 492 "couldn't create EGLContext"); 493 494 // initialize our non-virtual displays 495 for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) { 496 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i); 497 // set-up the displays that are already connected 498 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) { 499 // All non-virtual displays are currently considered secure. 500 bool isSecure = true; 501 createBuiltinDisplayLocked(type); 502 wp<IBinder> token = mBuiltinDisplays[i]; 503 504 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i); 505 sp<SurfaceTextureClient> stc = new SurfaceTextureClient( 506 static_cast< sp<IGraphicBufferProducer> >(fbs->getBufferQueue())); 507 sp<DisplayDevice> hw = new DisplayDevice(this, 508 type, isSecure, token, stc, fbs, mEGLConfig); 509 if (i > DisplayDevice::DISPLAY_PRIMARY) { 510 // FIXME: currently we don't get blank/unblank requests 511 // for displays other than the main display, so we always 512 // assume a connected display is unblanked. 513 ALOGD("marking display %d as acquired/unblanked", i); 514 hw->acquireScreen(); 515 } 516 mDisplays.add(token, hw); 517 } 518 } 519 520 // we need a GL context current in a few places, when initializing 521 // OpenGL ES (see below), or creating a layer, 522 // or when a texture is (asynchronously) destroyed, and for that 523 // we need a valid surface, so it's convenient to use the main display 524 // for that. 525 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 526 527 // initialize OpenGL ES 528 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext); 529 initializeGL(mEGLDisplay); 530 531 // start the EventThread 532 mEventThread = new EventThread(this); 533 mEventQueue.setEventThread(mEventThread); 534 535 // initialize our drawing state 536 mDrawingState = mCurrentState; 537 538 539 // We're now ready to accept clients... 540 mReadyToRunBarrier.open(); 541 542 // set initial conditions (e.g. unblank default device) 543 initializeDisplays(); 544 545 // start boot animation 546 startBootAnim(); 547 548 return NO_ERROR; 549} 550 551int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) { 552 return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ? 553 type : mHwc->allocateDisplayId(); 554} 555 556void SurfaceFlinger::startBootAnim() { 557 // start boot animation 558 property_set("service.bootanim.exit", "0"); 559 property_set("ctl.start", "bootanim"); 560} 561 562uint32_t SurfaceFlinger::getMaxTextureSize() const { 563 return mMaxTextureSize; 564} 565 566uint32_t SurfaceFlinger::getMaxViewportDims() const { 567 return mMaxViewportDims[0] < mMaxViewportDims[1] ? 568 mMaxViewportDims[0] : mMaxViewportDims[1]; 569} 570 571// ---------------------------------------------------------------------------- 572 573bool SurfaceFlinger::authenticateSurfaceTexture( 574 const sp<IGraphicBufferProducer>& bufferProducer) const { 575 Mutex::Autolock _l(mStateLock); 576 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder()); 577 578 // We want to determine whether the IGraphicBufferProducer was created by 579 // SurfaceFlinger. Check to see if we can find it in the layer list. 580 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 581 size_t count = currentLayers.size(); 582 for (size_t i=0 ; i<count ; i++) { 583 const sp<LayerBase>& layer(currentLayers[i]); 584 sp<LayerBaseClient> lbc(layer->getLayerBaseClient()); 585 if (lbc != NULL) { 586 // If this is an instance of Layer (as opposed to, say, LayerDim), 587 // we will get the consumer interface of SurfaceFlingerConsumer's 588 // BufferQueue. If it's the same Binder object as the graphic 589 // buffer producer interface, return success. 590 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder(); 591 if (lbcBinder == surfaceTextureBinder) { 592 return true; 593 } 594 } 595 } 596 597 // Check the layers in the purgatory. This check is here so that if a 598 // GLConsumer gets destroyed before all the clients are done using it, 599 // the error will not be reported as "surface XYZ is not authenticated", but 600 // will instead fail later on when the client tries to use the surface, 601 // which should be reported as "surface XYZ returned an -ENODEV". The 602 // purgatorized layers are no less authentic than the visible ones, so this 603 // should not cause any harm. 604 size_t purgatorySize = mLayerPurgatory.size(); 605 for (size_t i=0 ; i<purgatorySize ; i++) { 606 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 607 sp<LayerBaseClient> lbc(layer->getLayerBaseClient()); 608 if (lbc != NULL) { 609 wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder(); 610 if (lbcBinder == surfaceTextureBinder) { 611 return true; 612 } 613 } 614 } 615 616 return false; 617} 618 619status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) { 620 int32_t type = NAME_NOT_FOUND; 621 for (int i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) { 622 if (display == mBuiltinDisplays[i]) { 623 type = i; 624 break; 625 } 626 } 627 628 if (type < 0) { 629 return type; 630 } 631 632 const HWComposer& hwc(getHwComposer()); 633 float xdpi = hwc.getDpiX(type); 634 float ydpi = hwc.getDpiY(type); 635 636 // TODO: Not sure if display density should handled by SF any longer 637 class Density { 638 static int getDensityFromProperty(char const* propName) { 639 char property[PROPERTY_VALUE_MAX]; 640 int density = 0; 641 if (property_get(propName, property, NULL) > 0) { 642 density = atoi(property); 643 } 644 return density; 645 } 646 public: 647 static int getEmuDensity() { 648 return getDensityFromProperty("qemu.sf.lcd_density"); } 649 static int getBuildDensity() { 650 return getDensityFromProperty("ro.sf.lcd_density"); } 651 }; 652 653 if (type == DisplayDevice::DISPLAY_PRIMARY) { 654 // The density of the device is provided by a build property 655 float density = Density::getBuildDensity() / 160.0f; 656 if (density == 0) { 657 // the build doesn't provide a density -- this is wrong! 658 // use xdpi instead 659 ALOGE("ro.sf.lcd_density must be defined as a build property"); 660 density = xdpi / 160.0f; 661 } 662 if (Density::getEmuDensity()) { 663 // if "qemu.sf.lcd_density" is specified, it overrides everything 664 xdpi = ydpi = density = Density::getEmuDensity(); 665 density /= 160.0f; 666 } 667 info->density = density; 668 669 // TODO: this needs to go away (currently needed only by webkit) 670 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 671 info->orientation = hw->getOrientation(); 672 getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo); 673 } else { 674 // TODO: where should this value come from? 675 static const int TV_DENSITY = 213; 676 info->density = TV_DENSITY / 160.0f; 677 info->orientation = 0; 678 } 679 680 info->w = hwc.getWidth(type); 681 info->h = hwc.getHeight(type); 682 info->xdpi = xdpi; 683 info->ydpi = ydpi; 684 info->fps = float(1e9 / hwc.getRefreshPeriod(type)); 685 686 // All non-virtual displays are currently considered secure. 687 info->secure = true; 688 689 return NO_ERROR; 690} 691 692// ---------------------------------------------------------------------------- 693 694sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() { 695 return mEventThread->createEventConnection(); 696} 697 698// ---------------------------------------------------------------------------- 699 700void SurfaceFlinger::waitForEvent() { 701 mEventQueue.waitMessage(); 702} 703 704void SurfaceFlinger::signalTransaction() { 705 mEventQueue.invalidate(); 706} 707 708void SurfaceFlinger::signalLayerUpdate() { 709 mEventQueue.invalidate(); 710} 711 712void SurfaceFlinger::signalRefresh() { 713 mEventQueue.refresh(); 714} 715 716status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 717 nsecs_t reltime, uint32_t flags) { 718 return mEventQueue.postMessage(msg, reltime); 719} 720 721status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 722 nsecs_t reltime, uint32_t flags) { 723 status_t res = mEventQueue.postMessage(msg, reltime); 724 if (res == NO_ERROR) { 725 msg->wait(); 726 } 727 return res; 728} 729 730bool SurfaceFlinger::threadLoop() { 731 waitForEvent(); 732 return true; 733} 734 735void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) { 736 if (mEventThread == NULL) { 737 // This is a temporary workaround for b/7145521. A non-null pointer 738 // does not mean EventThread has finished initializing, so this 739 // is not a correct fix. 740 ALOGW("WARNING: EventThread not started, ignoring vsync"); 741 return; 742 } 743 if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) { 744 // we should only receive DisplayDevice::DisplayType from the vsync callback 745 mEventThread->onVSyncReceived(type, timestamp); 746 } 747} 748 749void SurfaceFlinger::onHotplugReceived(int type, bool connected) { 750 if (mEventThread == NULL) { 751 // This is a temporary workaround for b/7145521. A non-null pointer 752 // does not mean EventThread has finished initializing, so this 753 // is not a correct fix. 754 ALOGW("WARNING: EventThread not started, ignoring hotplug"); 755 return; 756 } 757 758 if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) { 759 Mutex::Autolock _l(mStateLock); 760 if (connected) { 761 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type); 762 } else { 763 mCurrentState.displays.removeItem(mBuiltinDisplays[type]); 764 mBuiltinDisplays[type].clear(); 765 } 766 setTransactionFlags(eDisplayTransactionNeeded); 767 768 // Defer EventThread notification until SF has updated mDisplays. 769 } 770} 771 772void SurfaceFlinger::eventControl(int disp, int event, int enabled) { 773 getHwComposer().eventControl(disp, event, enabled); 774} 775 776void SurfaceFlinger::onMessageReceived(int32_t what) { 777 ATRACE_CALL(); 778 switch (what) { 779 case MessageQueue::INVALIDATE: 780 handleMessageTransaction(); 781 handleMessageInvalidate(); 782 signalRefresh(); 783 break; 784 case MessageQueue::REFRESH: 785 handleMessageRefresh(); 786 break; 787 } 788} 789 790void SurfaceFlinger::handleMessageTransaction() { 791 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask); 792 if (transactionFlags) { 793 handleTransaction(transactionFlags); 794 } 795} 796 797void SurfaceFlinger::handleMessageInvalidate() { 798 ATRACE_CALL(); 799 handlePageFlip(); 800} 801 802void SurfaceFlinger::handleMessageRefresh() { 803 ATRACE_CALL(); 804 preComposition(); 805 rebuildLayerStacks(); 806 setUpHWComposer(); 807 doDebugFlashRegions(); 808 doComposition(); 809 postComposition(); 810} 811 812void SurfaceFlinger::doDebugFlashRegions() 813{ 814 // is debugging enabled 815 if (CC_LIKELY(!mDebugRegion)) 816 return; 817 818 const bool repaintEverything = mRepaintEverything; 819 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 820 const sp<DisplayDevice>& hw(mDisplays[dpy]); 821 if (hw->canDraw()) { 822 // transform the dirty region into this screen's coordinate space 823 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 824 if (!dirtyRegion.isEmpty()) { 825 // redraw the whole screen 826 doComposeSurfaces(hw, Region(hw->bounds())); 827 828 // and draw the dirty region 829 glDisable(GL_TEXTURE_EXTERNAL_OES); 830 glDisable(GL_TEXTURE_2D); 831 glDisable(GL_BLEND); 832 glColor4f(1, 0, 1, 1); 833 const int32_t height = hw->getHeight(); 834 Region::const_iterator it = dirtyRegion.begin(); 835 Region::const_iterator const end = dirtyRegion.end(); 836 while (it != end) { 837 const Rect& r = *it++; 838 GLfloat vertices[][2] = { 839 { (GLfloat) r.left, (GLfloat) (height - r.top) }, 840 { (GLfloat) r.left, (GLfloat) (height - r.bottom) }, 841 { (GLfloat) r.right, (GLfloat) (height - r.bottom) }, 842 { (GLfloat) r.right, (GLfloat) (height - r.top) } 843 }; 844 glVertexPointer(2, GL_FLOAT, 0, vertices); 845 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 846 } 847 hw->compositionComplete(); 848 hw->swapBuffers(getHwComposer()); 849 } 850 } 851 } 852 853 postFramebuffer(); 854 855 if (mDebugRegion > 1) { 856 usleep(mDebugRegion * 1000); 857 } 858 859 HWComposer& hwc(getHwComposer()); 860 if (hwc.initCheck() == NO_ERROR) { 861 status_t err = hwc.prepare(); 862 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 863 } 864} 865 866void SurfaceFlinger::preComposition() 867{ 868 bool needExtraInvalidate = false; 869 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 870 const size_t count = currentLayers.size(); 871 for (size_t i=0 ; i<count ; i++) { 872 if (currentLayers[i]->onPreComposition()) { 873 needExtraInvalidate = true; 874 } 875 } 876 if (needExtraInvalidate) { 877 signalLayerUpdate(); 878 } 879} 880 881void SurfaceFlinger::postComposition() 882{ 883 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 884 const size_t count = currentLayers.size(); 885 for (size_t i=0 ; i<count ; i++) { 886 currentLayers[i]->onPostComposition(); 887 } 888} 889 890void SurfaceFlinger::rebuildLayerStacks() { 891 // rebuild the visible layer list per screen 892 if (CC_UNLIKELY(mVisibleRegionsDirty)) { 893 ATRACE_CALL(); 894 mVisibleRegionsDirty = false; 895 invalidateHwcGeometry(); 896 897 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 898 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 899 Region opaqueRegion; 900 Region dirtyRegion; 901 Vector< sp<LayerBase> > layersSortedByZ; 902 const sp<DisplayDevice>& hw(mDisplays[dpy]); 903 const Transform& tr(hw->getTransform()); 904 const Rect bounds(hw->getBounds()); 905 if (hw->canDraw()) { 906 SurfaceFlinger::computeVisibleRegions(currentLayers, 907 hw->getLayerStack(), dirtyRegion, opaqueRegion); 908 909 const size_t count = currentLayers.size(); 910 for (size_t i=0 ; i<count ; i++) { 911 const sp<LayerBase>& layer(currentLayers[i]); 912 const Layer::State& s(layer->drawingState()); 913 if (s.layerStack == hw->getLayerStack()) { 914 Region drawRegion(tr.transform( 915 layer->visibleNonTransparentRegion)); 916 drawRegion.andSelf(bounds); 917 if (!drawRegion.isEmpty()) { 918 layersSortedByZ.add(layer); 919 } 920 } 921 } 922 } 923 hw->setVisibleLayersSortedByZ(layersSortedByZ); 924 hw->undefinedRegion.set(bounds); 925 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion)); 926 hw->dirtyRegion.orSelf(dirtyRegion); 927 } 928 } 929} 930 931void SurfaceFlinger::setUpHWComposer() { 932 HWComposer& hwc(getHwComposer()); 933 if (hwc.initCheck() == NO_ERROR) { 934 // build the h/w work list 935 if (CC_UNLIKELY(mHwWorkListDirty)) { 936 mHwWorkListDirty = false; 937 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 938 sp<const DisplayDevice> hw(mDisplays[dpy]); 939 const int32_t id = hw->getHwcDisplayId(); 940 if (id >= 0) { 941 const Vector< sp<LayerBase> >& currentLayers( 942 hw->getVisibleLayersSortedByZ()); 943 const size_t count = currentLayers.size(); 944 if (hwc.createWorkList(id, count) == NO_ERROR) { 945 HWComposer::LayerListIterator cur = hwc.begin(id); 946 const HWComposer::LayerListIterator end = hwc.end(id); 947 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 948 const sp<LayerBase>& layer(currentLayers[i]); 949 layer->setGeometry(hw, *cur); 950 if (mDebugDisableHWC || mDebugRegion) { 951 cur->setSkip(true); 952 } 953 } 954 } 955 } 956 } 957 } 958 959 // set the per-frame data 960 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 961 sp<const DisplayDevice> hw(mDisplays[dpy]); 962 const int32_t id = hw->getHwcDisplayId(); 963 if (id >= 0) { 964 const Vector< sp<LayerBase> >& currentLayers( 965 hw->getVisibleLayersSortedByZ()); 966 const size_t count = currentLayers.size(); 967 HWComposer::LayerListIterator cur = hwc.begin(id); 968 const HWComposer::LayerListIterator end = hwc.end(id); 969 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 970 /* 971 * update the per-frame h/w composer data for each layer 972 * and build the transparent region of the FB 973 */ 974 const sp<LayerBase>& layer(currentLayers[i]); 975 layer->setPerFrameData(hw, *cur); 976 } 977 } 978 } 979 980 status_t err = hwc.prepare(); 981 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 982 } 983} 984 985void SurfaceFlinger::doComposition() { 986 ATRACE_CALL(); 987 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); 988 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 989 const sp<DisplayDevice>& hw(mDisplays[dpy]); 990 if (hw->canDraw()) { 991 // transform the dirty region into this screen's coordinate space 992 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 993 994 // repaint the framebuffer (if needed) 995 doDisplayComposition(hw, dirtyRegion); 996 997 hw->dirtyRegion.clear(); 998 hw->flip(hw->swapRegion); 999 hw->swapRegion.clear(); 1000 } 1001 // inform the h/w that we're done compositing 1002 hw->compositionComplete(); 1003 } 1004 postFramebuffer(); 1005} 1006 1007void SurfaceFlinger::postFramebuffer() 1008{ 1009 ATRACE_CALL(); 1010 1011 const nsecs_t now = systemTime(); 1012 mDebugInSwapBuffers = now; 1013 1014 HWComposer& hwc(getHwComposer()); 1015 if (hwc.initCheck() == NO_ERROR) { 1016 if (!hwc.supportsFramebufferTarget()) { 1017 // EGL spec says: 1018 // "surface must be bound to the calling thread's current context, 1019 // for the current rendering API." 1020 DisplayDevice::makeCurrent(mEGLDisplay, 1021 getDefaultDisplayDevice(), mEGLContext); 1022 } 1023 hwc.commit(); 1024 } 1025 1026 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1027 sp<const DisplayDevice> hw(mDisplays[dpy]); 1028 const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ()); 1029 hw->onSwapBuffersCompleted(hwc); 1030 const size_t count = currentLayers.size(); 1031 int32_t id = hw->getHwcDisplayId(); 1032 if (id >=0 && hwc.initCheck() == NO_ERROR) { 1033 HWComposer::LayerListIterator cur = hwc.begin(id); 1034 const HWComposer::LayerListIterator end = hwc.end(id); 1035 for (size_t i = 0; cur != end && i < count; ++i, ++cur) { 1036 currentLayers[i]->onLayerDisplayed(hw, &*cur); 1037 } 1038 } else { 1039 for (size_t i = 0; i < count; i++) { 1040 currentLayers[i]->onLayerDisplayed(hw, NULL); 1041 } 1042 } 1043 } 1044 1045 mLastSwapBufferTime = systemTime() - now; 1046 mDebugInSwapBuffers = 0; 1047} 1048 1049void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 1050{ 1051 ATRACE_CALL(); 1052 1053 Mutex::Autolock _l(mStateLock); 1054 const nsecs_t now = systemTime(); 1055 mDebugInTransaction = now; 1056 1057 // Here we're guaranteed that some transaction flags are set 1058 // so we can call handleTransactionLocked() unconditionally. 1059 // We call getTransactionFlags(), which will also clear the flags, 1060 // with mStateLock held to guarantee that mCurrentState won't change 1061 // until the transaction is committed. 1062 1063 transactionFlags = getTransactionFlags(eTransactionMask); 1064 handleTransactionLocked(transactionFlags); 1065 1066 mLastTransactionTime = systemTime() - now; 1067 mDebugInTransaction = 0; 1068 invalidateHwcGeometry(); 1069 // here the transaction has been committed 1070} 1071 1072void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 1073{ 1074 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 1075 const size_t count = currentLayers.size(); 1076 1077 /* 1078 * Traversal of the children 1079 * (perform the transaction for each of them if needed) 1080 */ 1081 1082 if (transactionFlags & eTraversalNeeded) { 1083 for (size_t i=0 ; i<count ; i++) { 1084 const sp<LayerBase>& layer(currentLayers[i]); 1085 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 1086 if (!trFlags) continue; 1087 1088 const uint32_t flags = layer->doTransaction(0); 1089 if (flags & Layer::eVisibleRegion) 1090 mVisibleRegionsDirty = true; 1091 } 1092 } 1093 1094 /* 1095 * Perform display own transactions if needed 1096 */ 1097 1098 if (transactionFlags & eDisplayTransactionNeeded) { 1099 // here we take advantage of Vector's copy-on-write semantics to 1100 // improve performance by skipping the transaction entirely when 1101 // know that the lists are identical 1102 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 1103 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 1104 if (!curr.isIdenticalTo(draw)) { 1105 mVisibleRegionsDirty = true; 1106 const size_t cc = curr.size(); 1107 size_t dc = draw.size(); 1108 1109 // find the displays that were removed 1110 // (ie: in drawing state but not in current state) 1111 // also handle displays that changed 1112 // (ie: displays that are in both lists) 1113 for (size_t i=0 ; i<dc ; i++) { 1114 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 1115 if (j < 0) { 1116 // in drawing state but not in current state 1117 if (!draw[i].isMainDisplay()) { 1118 // Call makeCurrent() on the primary display so we can 1119 // be sure that nothing associated with this display 1120 // is current. 1121 const sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 1122 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext); 1123 mDisplays.removeItem(draw.keyAt(i)); 1124 getHwComposer().disconnectDisplay(draw[i].type); 1125 mEventThread->onHotplugReceived(draw[i].type, false); 1126 } else { 1127 ALOGW("trying to remove the main display"); 1128 } 1129 } else { 1130 // this display is in both lists. see if something changed. 1131 const DisplayDeviceState& state(curr[j]); 1132 const wp<IBinder>& display(curr.keyAt(j)); 1133 if (state.surface->asBinder() != draw[i].surface->asBinder()) { 1134 // changing the surface is like destroying and 1135 // recreating the DisplayDevice, so we just remove it 1136 // from the drawing state, so that it get re-added 1137 // below. 1138 mDisplays.removeItem(display); 1139 mDrawingState.displays.removeItemsAt(i); 1140 dc--; i--; 1141 // at this point we must loop to the next item 1142 continue; 1143 } 1144 1145 const sp<DisplayDevice> disp(getDisplayDevice(display)); 1146 if (disp != NULL) { 1147 if (state.layerStack != draw[i].layerStack) { 1148 disp->setLayerStack(state.layerStack); 1149 } 1150 if ((state.orientation != draw[i].orientation) 1151 || (state.viewport != draw[i].viewport) 1152 || (state.frame != draw[i].frame)) 1153 { 1154 disp->setProjection(state.orientation, 1155 state.viewport, state.frame); 1156 } 1157 } 1158 } 1159 } 1160 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 1167 sp<FramebufferSurface> fbs; 1168 sp<SurfaceTextureClient> stc; 1169 if (!state.isVirtualDisplay()) { 1170 1171 ALOGE_IF(state.surface!=NULL, 1172 "adding a supported display, but rendering " 1173 "surface is provided (%p), ignoring it", 1174 state.surface.get()); 1175 1176 // for supported (by hwc) displays we provide our 1177 // own rendering surface 1178 fbs = new FramebufferSurface(*mHwc, state.type); 1179 stc = new SurfaceTextureClient( 1180 static_cast< sp<IGraphicBufferProducer> >( 1181 fbs->getBufferQueue())); 1182 } else { 1183 if (state.surface != NULL) { 1184 stc = new SurfaceTextureClient(state.surface); 1185 } 1186 } 1187 1188 const wp<IBinder>& display(curr.keyAt(i)); 1189 if (stc != NULL) { 1190 sp<DisplayDevice> hw = new DisplayDevice(this, 1191 state.type, state.isSecure, display, stc, fbs, 1192 mEGLConfig); 1193 hw->setLayerStack(state.layerStack); 1194 hw->setProjection(state.orientation, 1195 state.viewport, state.frame); 1196 hw->setDisplayName(state.displayName); 1197 mDisplays.add(display, hw); 1198 mEventThread->onHotplugReceived(state.type, true); 1199 } 1200 } 1201 } 1202 } 1203 } 1204 1205 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) { 1206 // The transform hint might have changed for some layers 1207 // (either because a display has changed, or because a layer 1208 // as changed). 1209 // 1210 // Walk through all the layers in currentLayers, 1211 // and update their transform hint. 1212 // 1213 // If a layer is visible only on a single display, then that 1214 // display is used to calculate the hint, otherwise we use the 1215 // default display. 1216 // 1217 // NOTE: we do this here, rather than in rebuildLayerStacks() so that 1218 // the hint is set before we acquire a buffer from the surface texture. 1219 // 1220 // NOTE: layer transactions have taken place already, so we use their 1221 // drawing state. However, SurfaceFlinger's own transaction has not 1222 // happened yet, so we must use the current state layer list 1223 // (soon to become the drawing state list). 1224 // 1225 sp<const DisplayDevice> disp; 1226 uint32_t currentlayerStack = 0; 1227 for (size_t i=0; i<count; i++) { 1228 // NOTE: we rely on the fact that layers are sorted by 1229 // layerStack first (so we don't have to traverse the list 1230 // of displays for every layer). 1231 const sp<LayerBase>& layerBase(currentLayers[i]); 1232 uint32_t layerStack = layerBase->drawingState().layerStack; 1233 if (i==0 || currentlayerStack != layerStack) { 1234 currentlayerStack = layerStack; 1235 // figure out if this layerstack is mirrored 1236 // (more than one display) if so, pick the default display, 1237 // if not, pick the only display it's on. 1238 disp.clear(); 1239 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1240 sp<const DisplayDevice> hw(mDisplays[dpy]); 1241 if (hw->getLayerStack() == currentlayerStack) { 1242 if (disp == NULL) { 1243 disp = hw; 1244 } else { 1245 disp = getDefaultDisplayDevice(); 1246 break; 1247 } 1248 } 1249 } 1250 } 1251 if (disp != NULL) { 1252 // presumably this means this layer is using a layerStack 1253 // that is not visible on any display 1254 layerBase->updateTransformHint(disp); 1255 } 1256 } 1257 } 1258 1259 1260 /* 1261 * Perform our own transaction if needed 1262 */ 1263 1264 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 1265 if (currentLayers.size() > previousLayers.size()) { 1266 // layers have been added 1267 mVisibleRegionsDirty = true; 1268 } 1269 1270 // some layers might have been removed, so 1271 // we need to update the regions they're exposing. 1272 if (mLayersRemoved) { 1273 mLayersRemoved = false; 1274 mVisibleRegionsDirty = true; 1275 const size_t count = previousLayers.size(); 1276 for (size_t i=0 ; i<count ; i++) { 1277 const sp<LayerBase>& layer(previousLayers[i]); 1278 if (currentLayers.indexOf(layer) < 0) { 1279 // this layer is not visible anymore 1280 // TODO: we could traverse the tree from front to back and 1281 // compute the actual visible region 1282 // TODO: we could cache the transformed region 1283 const Layer::State& s(layer->drawingState()); 1284 Region visibleReg = s.transform.transform( 1285 Region(Rect(s.active.w, s.active.h))); 1286 invalidateLayerStack(s.layerStack, visibleReg); 1287 } 1288 } 1289 } 1290 1291 commitTransaction(); 1292} 1293 1294void SurfaceFlinger::commitTransaction() 1295{ 1296 if (!mLayersPendingRemoval.isEmpty()) { 1297 // Notify removed layers now that they can't be drawn from 1298 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1299 mLayersPendingRemoval[i]->onRemoved(); 1300 } 1301 mLayersPendingRemoval.clear(); 1302 } 1303 1304 mDrawingState = mCurrentState; 1305 mTransactionPending = false; 1306 mAnimTransactionPending = false; 1307 mTransactionCV.broadcast(); 1308} 1309 1310void SurfaceFlinger::computeVisibleRegions( 1311 const LayerVector& currentLayers, uint32_t layerStack, 1312 Region& outDirtyRegion, Region& outOpaqueRegion) 1313{ 1314 ATRACE_CALL(); 1315 1316 Region aboveOpaqueLayers; 1317 Region aboveCoveredLayers; 1318 Region dirty; 1319 1320 outDirtyRegion.clear(); 1321 1322 size_t i = currentLayers.size(); 1323 while (i--) { 1324 const sp<LayerBase>& layer = currentLayers[i]; 1325 1326 // start with the whole surface at its current location 1327 const Layer::State& s(layer->drawingState()); 1328 1329 // only consider the layers on the given later stack 1330 if (s.layerStack != layerStack) 1331 continue; 1332 1333 /* 1334 * opaqueRegion: area of a surface that is fully opaque. 1335 */ 1336 Region opaqueRegion; 1337 1338 /* 1339 * visibleRegion: area of a surface that is visible on screen 1340 * and not fully transparent. This is essentially the layer's 1341 * footprint minus the opaque regions above it. 1342 * Areas covered by a translucent surface are considered visible. 1343 */ 1344 Region visibleRegion; 1345 1346 /* 1347 * coveredRegion: area of a surface that is covered by all 1348 * visible regions above it (which includes the translucent areas). 1349 */ 1350 Region coveredRegion; 1351 1352 /* 1353 * transparentRegion: area of a surface that is hinted to be completely 1354 * transparent. This is only used to tell when the layer has no visible 1355 * non-transparent regions and can be removed from the layer list. It 1356 * does not affect the visibleRegion of this layer or any layers 1357 * beneath it. The hint may not be correct if apps don't respect the 1358 * SurfaceView restrictions (which, sadly, some don't). 1359 */ 1360 Region transparentRegion; 1361 1362 1363 // handle hidden surfaces by setting the visible region to empty 1364 if (CC_LIKELY(layer->isVisible())) { 1365 const bool translucent = !layer->isOpaque(); 1366 Rect bounds(layer->computeBounds()); 1367 visibleRegion.set(bounds); 1368 if (!visibleRegion.isEmpty()) { 1369 // Remove the transparent area from the visible region 1370 if (translucent) { 1371 const Transform tr(s.transform); 1372 if (tr.transformed()) { 1373 if (tr.preserveRects()) { 1374 // transform the transparent region 1375 transparentRegion = tr.transform(s.transparentRegion); 1376 } else { 1377 // transformation too complex, can't do the 1378 // transparent region optimization. 1379 transparentRegion.clear(); 1380 } 1381 } else { 1382 transparentRegion = s.transparentRegion; 1383 } 1384 } 1385 1386 // compute the opaque region 1387 const int32_t layerOrientation = s.transform.getOrientation(); 1388 if (s.alpha==255 && !translucent && 1389 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1390 // the opaque region is the layer's footprint 1391 opaqueRegion = visibleRegion; 1392 } 1393 } 1394 } 1395 1396 // Clip the covered region to the visible region 1397 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1398 1399 // Update aboveCoveredLayers for next (lower) layer 1400 aboveCoveredLayers.orSelf(visibleRegion); 1401 1402 // subtract the opaque region covered by the layers above us 1403 visibleRegion.subtractSelf(aboveOpaqueLayers); 1404 1405 // compute this layer's dirty region 1406 if (layer->contentDirty) { 1407 // we need to invalidate the whole region 1408 dirty = visibleRegion; 1409 // as well, as the old visible region 1410 dirty.orSelf(layer->visibleRegion); 1411 layer->contentDirty = false; 1412 } else { 1413 /* compute the exposed region: 1414 * the exposed region consists of two components: 1415 * 1) what's VISIBLE now and was COVERED before 1416 * 2) what's EXPOSED now less what was EXPOSED before 1417 * 1418 * note that (1) is conservative, we start with the whole 1419 * visible region but only keep what used to be covered by 1420 * something -- which mean it may have been exposed. 1421 * 1422 * (2) handles areas that were not covered by anything but got 1423 * exposed because of a resize. 1424 */ 1425 const Region newExposed = visibleRegion - coveredRegion; 1426 const Region oldVisibleRegion = layer->visibleRegion; 1427 const Region oldCoveredRegion = layer->coveredRegion; 1428 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1429 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1430 } 1431 dirty.subtractSelf(aboveOpaqueLayers); 1432 1433 // accumulate to the screen dirty region 1434 outDirtyRegion.orSelf(dirty); 1435 1436 // Update aboveOpaqueLayers for next (lower) layer 1437 aboveOpaqueLayers.orSelf(opaqueRegion); 1438 1439 // Store the visible region in screen space 1440 layer->setVisibleRegion(visibleRegion); 1441 layer->setCoveredRegion(coveredRegion); 1442 layer->setVisibleNonTransparentRegion( 1443 visibleRegion.subtract(transparentRegion)); 1444 } 1445 1446 outOpaqueRegion = aboveOpaqueLayers; 1447} 1448 1449void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1450 const Region& dirty) { 1451 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1452 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1453 if (hw->getLayerStack() == layerStack) { 1454 hw->dirtyRegion.orSelf(dirty); 1455 } 1456 } 1457} 1458 1459void SurfaceFlinger::handlePageFlip() 1460{ 1461 Region dirtyRegion; 1462 1463 bool visibleRegions = false; 1464 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 1465 const size_t count = currentLayers.size(); 1466 for (size_t i=0 ; i<count ; i++) { 1467 const sp<LayerBase>& layer(currentLayers[i]); 1468 const Region dirty(layer->latchBuffer(visibleRegions)); 1469 const Layer::State& s(layer->drawingState()); 1470 invalidateLayerStack(s.layerStack, dirty); 1471 } 1472 1473 mVisibleRegionsDirty |= visibleRegions; 1474} 1475 1476void SurfaceFlinger::invalidateHwcGeometry() 1477{ 1478 mHwWorkListDirty = true; 1479} 1480 1481 1482void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, 1483 const Region& inDirtyRegion) 1484{ 1485 Region dirtyRegion(inDirtyRegion); 1486 1487 // compute the invalid region 1488 hw->swapRegion.orSelf(dirtyRegion); 1489 1490 uint32_t flags = hw->getFlags(); 1491 if (flags & DisplayDevice::SWAP_RECTANGLE) { 1492 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 1493 // takes a rectangle, we must make sure to update that whole 1494 // rectangle in that case 1495 dirtyRegion.set(hw->swapRegion.bounds()); 1496 } else { 1497 if (flags & DisplayDevice::PARTIAL_UPDATES) { 1498 // We need to redraw the rectangle that will be updated 1499 // (pushed to the framebuffer). 1500 // This is needed because PARTIAL_UPDATES only takes one 1501 // rectangle instead of a region (see DisplayDevice::flip()) 1502 dirtyRegion.set(hw->swapRegion.bounds()); 1503 } else { 1504 // we need to redraw everything (the whole screen) 1505 dirtyRegion.set(hw->bounds()); 1506 hw->swapRegion = dirtyRegion; 1507 } 1508 } 1509 1510 doComposeSurfaces(hw, dirtyRegion); 1511 1512 // update the swap region and clear the dirty region 1513 hw->swapRegion.orSelf(dirtyRegion); 1514 1515 // swap buffers (presentation) 1516 hw->swapBuffers(getHwComposer()); 1517} 1518 1519void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) 1520{ 1521 const int32_t id = hw->getHwcDisplayId(); 1522 HWComposer& hwc(getHwComposer()); 1523 HWComposer::LayerListIterator cur = hwc.begin(id); 1524 const HWComposer::LayerListIterator end = hwc.end(id); 1525 1526 const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end); 1527 if (hasGlesComposition) { 1528 DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext); 1529 1530 // set the frame buffer 1531 glMatrixMode(GL_MODELVIEW); 1532 glLoadIdentity(); 1533 1534 // Never touch the framebuffer if we don't have any framebuffer layers 1535 const bool hasHwcComposition = hwc.hasHwcComposition(id); 1536 if (hasHwcComposition) { 1537 // when using overlays, we assume a fully transparent framebuffer 1538 // NOTE: we could reduce how much we need to clear, for instance 1539 // remove where there are opaque FB layers. however, on some 1540 // GPUs doing a "clean slate" glClear might be more efficient. 1541 // We'll revisit later if needed. 1542 glClearColor(0, 0, 0, 0); 1543 glClear(GL_COLOR_BUFFER_BIT); 1544 } else { 1545 // we start with the whole screen area 1546 const Region bounds(hw->getBounds()); 1547 1548 // we remove the scissor part 1549 // we're left with the letterbox region 1550 // (common case is that letterbox ends-up being empty) 1551 const Region letterbox(bounds.subtract(hw->getScissor())); 1552 1553 // compute the area to clear 1554 Region region(hw->undefinedRegion.merge(letterbox)); 1555 1556 // but limit it to the dirty region 1557 region.andSelf(dirty); 1558 1559 // screen is already cleared here 1560 if (!region.isEmpty()) { 1561 // can happen with SurfaceView 1562 drawWormhole(hw, region); 1563 } 1564 } 1565 1566 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) { 1567 // just to be on the safe side, we don't set the 1568 // scissor on the main display. It should never be needed 1569 // anyways (though in theory it could since the API allows it). 1570 const Rect& bounds(hw->getBounds()); 1571 const Rect& scissor(hw->getScissor()); 1572 if (scissor != bounds) { 1573 // scissor doesn't match the screen's dimensions, so we 1574 // need to clear everything outside of it and enable 1575 // the GL scissor so we don't draw anything where we shouldn't 1576 const GLint height = hw->getHeight(); 1577 glScissor(scissor.left, height - scissor.bottom, 1578 scissor.getWidth(), scissor.getHeight()); 1579 // enable scissor for this frame 1580 glEnable(GL_SCISSOR_TEST); 1581 } 1582 } 1583 } 1584 1585 /* 1586 * and then, render the layers targeted at the framebuffer 1587 */ 1588 1589 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 1590 const size_t count = layers.size(); 1591 const Transform& tr = hw->getTransform(); 1592 if (cur != end) { 1593 // we're using h/w composer 1594 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) { 1595 const sp<LayerBase>& layer(layers[i]); 1596 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); 1597 if (!clip.isEmpty()) { 1598 switch (cur->getCompositionType()) { 1599 case HWC_OVERLAY: { 1600 if ((cur->getHints() & HWC_HINT_CLEAR_FB) 1601 && i 1602 && layer->isOpaque() 1603 && hasGlesComposition) { 1604 // never clear the very first layer since we're 1605 // guaranteed the FB is already cleared 1606 layer->clearWithOpenGL(hw, clip); 1607 } 1608 break; 1609 } 1610 case HWC_FRAMEBUFFER: { 1611 layer->draw(hw, clip); 1612 break; 1613 } 1614 case HWC_FRAMEBUFFER_TARGET: { 1615 // this should not happen as the iterator shouldn't 1616 // let us get there. 1617 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i); 1618 break; 1619 } 1620 } 1621 } 1622 layer->setAcquireFence(hw, *cur); 1623 } 1624 } else { 1625 // we're not using h/w composer 1626 for (size_t i=0 ; i<count ; ++i) { 1627 const sp<LayerBase>& layer(layers[i]); 1628 const Region clip(dirty.intersect( 1629 tr.transform(layer->visibleRegion))); 1630 if (!clip.isEmpty()) { 1631 layer->draw(hw, clip); 1632 } 1633 } 1634 } 1635 1636 // disable scissor at the end of the frame 1637 glDisable(GL_SCISSOR_TEST); 1638} 1639 1640void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, 1641 const Region& region) const 1642{ 1643 glDisable(GL_TEXTURE_EXTERNAL_OES); 1644 glDisable(GL_TEXTURE_2D); 1645 glDisable(GL_BLEND); 1646 glColor4f(0,0,0,0); 1647 1648 const int32_t height = hw->getHeight(); 1649 Region::const_iterator it = region.begin(); 1650 Region::const_iterator const end = region.end(); 1651 while (it != end) { 1652 const Rect& r = *it++; 1653 GLfloat vertices[][2] = { 1654 { (GLfloat) r.left, (GLfloat) (height - r.top) }, 1655 { (GLfloat) r.left, (GLfloat) (height - r.bottom) }, 1656 { (GLfloat) r.right, (GLfloat) (height - r.bottom) }, 1657 { (GLfloat) r.right, (GLfloat) (height - r.top) } 1658 }; 1659 glVertexPointer(2, GL_FLOAT, 0, vertices); 1660 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1661 } 1662} 1663 1664ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1665 const sp<LayerBaseClient>& lbc) 1666{ 1667 // attach this layer to the client 1668 size_t name = client->attachLayer(lbc); 1669 1670 // add this layer to the current state list 1671 Mutex::Autolock _l(mStateLock); 1672 mCurrentState.layersSortedByZ.add(lbc); 1673 1674 return ssize_t(name); 1675} 1676 1677status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1678{ 1679 Mutex::Autolock _l(mStateLock); 1680 status_t err = purgatorizeLayer_l(layer); 1681 if (err == NO_ERROR) 1682 setTransactionFlags(eTransactionNeeded); 1683 return err; 1684} 1685 1686status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1687{ 1688 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1689 if (index >= 0) { 1690 mLayersRemoved = true; 1691 return NO_ERROR; 1692 } 1693 return status_t(index); 1694} 1695 1696status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1697{ 1698 // First add the layer to the purgatory list, which makes sure it won't 1699 // go away, then remove it from the main list (through a transaction). 1700 ssize_t err = removeLayer_l(layerBase); 1701 if (err >= 0) { 1702 mLayerPurgatory.add(layerBase); 1703 } 1704 1705 mLayersPendingRemoval.push(layerBase); 1706 1707 // it's possible that we don't find a layer, because it might 1708 // have been destroyed already -- this is not technically an error 1709 // from the user because there is a race between Client::destroySurface(), 1710 // ~Client() and ~ISurface(). 1711 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1712} 1713 1714uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) 1715{ 1716 return android_atomic_release_load(&mTransactionFlags); 1717} 1718 1719uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1720{ 1721 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1722} 1723 1724uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1725{ 1726 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1727 if ((old & flags)==0) { // wake the server up 1728 signalTransaction(); 1729 } 1730 return old; 1731} 1732 1733void SurfaceFlinger::setTransactionState( 1734 const Vector<ComposerState>& state, 1735 const Vector<DisplayState>& displays, 1736 uint32_t flags) 1737{ 1738 ATRACE_CALL(); 1739 Mutex::Autolock _l(mStateLock); 1740 uint32_t transactionFlags = 0; 1741 1742 if (flags & eAnimation) { 1743 // For window updates that are part of an animation we must wait for 1744 // previous animation "frames" to be handled. 1745 while (mAnimTransactionPending) { 1746 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1747 if (CC_UNLIKELY(err != NO_ERROR)) { 1748 // just in case something goes wrong in SF, return to the 1749 // caller after a few seconds. 1750 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out " 1751 "waiting for previous animation frame"); 1752 mAnimTransactionPending = false; 1753 break; 1754 } 1755 } 1756 } 1757 1758 size_t count = displays.size(); 1759 for (size_t i=0 ; i<count ; i++) { 1760 const DisplayState& s(displays[i]); 1761 transactionFlags |= setDisplayStateLocked(s); 1762 } 1763 1764 count = state.size(); 1765 for (size_t i=0 ; i<count ; i++) { 1766 const ComposerState& s(state[i]); 1767 // Here we need to check that the interface we're given is indeed 1768 // one of our own. A malicious client could give us a NULL 1769 // IInterface, or one of its own or even one of our own but a 1770 // different type. All these situations would cause us to crash. 1771 // 1772 // NOTE: it would be better to use RTTI as we could directly check 1773 // that we have a Client*. however, RTTI is disabled in Android. 1774 if (s.client != NULL) { 1775 sp<IBinder> binder = s.client->asBinder(); 1776 if (binder != NULL) { 1777 String16 desc(binder->getInterfaceDescriptor()); 1778 if (desc == ISurfaceComposerClient::descriptor) { 1779 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1780 transactionFlags |= setClientStateLocked(client, s.state); 1781 } 1782 } 1783 } 1784 } 1785 1786 if (transactionFlags) { 1787 // this triggers the transaction 1788 setTransactionFlags(transactionFlags); 1789 1790 // if this is a synchronous transaction, wait for it to take effect 1791 // before returning. 1792 if (flags & eSynchronous) { 1793 mTransactionPending = true; 1794 } 1795 if (flags & eAnimation) { 1796 mAnimTransactionPending = true; 1797 } 1798 while (mTransactionPending) { 1799 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1800 if (CC_UNLIKELY(err != NO_ERROR)) { 1801 // just in case something goes wrong in SF, return to the 1802 // called after a few seconds. 1803 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!"); 1804 mTransactionPending = false; 1805 break; 1806 } 1807 } 1808 } 1809} 1810 1811uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 1812{ 1813 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token); 1814 if (dpyIdx < 0) 1815 return 0; 1816 1817 uint32_t flags = 0; 1818 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx)); 1819 if (disp.isValid()) { 1820 const uint32_t what = s.what; 1821 if (what & DisplayState::eSurfaceChanged) { 1822 if (disp.surface->asBinder() != s.surface->asBinder()) { 1823 disp.surface = s.surface; 1824 flags |= eDisplayTransactionNeeded; 1825 } 1826 } 1827 if (what & DisplayState::eLayerStackChanged) { 1828 if (disp.layerStack != s.layerStack) { 1829 disp.layerStack = s.layerStack; 1830 flags |= eDisplayTransactionNeeded; 1831 } 1832 } 1833 if (what & DisplayState::eDisplayProjectionChanged) { 1834 if (disp.orientation != s.orientation) { 1835 disp.orientation = s.orientation; 1836 flags |= eDisplayTransactionNeeded; 1837 } 1838 if (disp.frame != s.frame) { 1839 disp.frame = s.frame; 1840 flags |= eDisplayTransactionNeeded; 1841 } 1842 if (disp.viewport != s.viewport) { 1843 disp.viewport = s.viewport; 1844 flags |= eDisplayTransactionNeeded; 1845 } 1846 } 1847 } 1848 return flags; 1849} 1850 1851uint32_t SurfaceFlinger::setClientStateLocked( 1852 const sp<Client>& client, 1853 const layer_state_t& s) 1854{ 1855 uint32_t flags = 0; 1856 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1857 if (layer != 0) { 1858 const uint32_t what = s.what; 1859 if (what & layer_state_t::ePositionChanged) { 1860 if (layer->setPosition(s.x, s.y)) 1861 flags |= eTraversalNeeded; 1862 } 1863 if (what & layer_state_t::eLayerChanged) { 1864 // NOTE: index needs to be calculated before we update the state 1865 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1866 if (layer->setLayer(s.z)) { 1867 mCurrentState.layersSortedByZ.removeAt(idx); 1868 mCurrentState.layersSortedByZ.add(layer); 1869 // we need traversal (state changed) 1870 // AND transaction (list changed) 1871 flags |= eTransactionNeeded|eTraversalNeeded; 1872 } 1873 } 1874 if (what & layer_state_t::eSizeChanged) { 1875 if (layer->setSize(s.w, s.h)) { 1876 flags |= eTraversalNeeded; 1877 } 1878 } 1879 if (what & layer_state_t::eAlphaChanged) { 1880 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1881 flags |= eTraversalNeeded; 1882 } 1883 if (what & layer_state_t::eMatrixChanged) { 1884 if (layer->setMatrix(s.matrix)) 1885 flags |= eTraversalNeeded; 1886 } 1887 if (what & layer_state_t::eTransparentRegionChanged) { 1888 if (layer->setTransparentRegionHint(s.transparentRegion)) 1889 flags |= eTraversalNeeded; 1890 } 1891 if (what & layer_state_t::eVisibilityChanged) { 1892 if (layer->setFlags(s.flags, s.mask)) 1893 flags |= eTraversalNeeded; 1894 } 1895 if (what & layer_state_t::eCropChanged) { 1896 if (layer->setCrop(s.crop)) 1897 flags |= eTraversalNeeded; 1898 } 1899 if (what & layer_state_t::eLayerStackChanged) { 1900 // NOTE: index needs to be calculated before we update the state 1901 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1902 if (layer->setLayerStack(s.layerStack)) { 1903 mCurrentState.layersSortedByZ.removeAt(idx); 1904 mCurrentState.layersSortedByZ.add(layer); 1905 // we need traversal (state changed) 1906 // AND transaction (list changed) 1907 flags |= eTransactionNeeded|eTraversalNeeded; 1908 } 1909 } 1910 } 1911 return flags; 1912} 1913 1914sp<ISurface> SurfaceFlinger::createLayer( 1915 ISurfaceComposerClient::surface_data_t* params, 1916 const String8& name, 1917 const sp<Client>& client, 1918 uint32_t w, uint32_t h, PixelFormat format, 1919 uint32_t flags) 1920{ 1921 sp<LayerBaseClient> layer; 1922 sp<ISurface> surfaceHandle; 1923 1924 if (int32_t(w|h) < 0) { 1925 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 1926 int(w), int(h)); 1927 return surfaceHandle; 1928 } 1929 1930 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 1931 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 1932 case ISurfaceComposerClient::eFXSurfaceNormal: 1933 layer = createNormalLayer(client, w, h, flags, format); 1934 break; 1935 case ISurfaceComposerClient::eFXSurfaceBlur: 1936 case ISurfaceComposerClient::eFXSurfaceDim: 1937 layer = createDimLayer(client, w, h, flags); 1938 break; 1939 case ISurfaceComposerClient::eFXSurfaceScreenshot: 1940 layer = createScreenshotLayer(client, w, h, flags); 1941 break; 1942 } 1943 1944 if (layer != 0) { 1945 layer->initStates(w, h, flags); 1946 layer->setName(name); 1947 ssize_t token = addClientLayer(client, layer); 1948 surfaceHandle = layer->getSurface(); 1949 if (surfaceHandle != 0) { 1950 params->token = token; 1951 params->identity = layer->getIdentity(); 1952 } 1953 setTransactionFlags(eTransactionNeeded); 1954 } 1955 1956 return surfaceHandle; 1957} 1958 1959sp<Layer> SurfaceFlinger::createNormalLayer( 1960 const sp<Client>& client, 1961 uint32_t w, uint32_t h, uint32_t flags, 1962 PixelFormat& format) 1963{ 1964 // initialize the surfaces 1965 switch (format) { 1966 case PIXEL_FORMAT_TRANSPARENT: 1967 case PIXEL_FORMAT_TRANSLUCENT: 1968 format = PIXEL_FORMAT_RGBA_8888; 1969 break; 1970 case PIXEL_FORMAT_OPAQUE: 1971#ifdef NO_RGBX_8888 1972 format = PIXEL_FORMAT_RGB_565; 1973#else 1974 format = PIXEL_FORMAT_RGBX_8888; 1975#endif 1976 break; 1977 } 1978 1979#ifdef NO_RGBX_8888 1980 if (format == PIXEL_FORMAT_RGBX_8888) 1981 format = PIXEL_FORMAT_RGBA_8888; 1982#endif 1983 1984 sp<Layer> layer = new Layer(this, client); 1985 status_t err = layer->setBuffers(w, h, format, flags); 1986 if (CC_LIKELY(err != NO_ERROR)) { 1987 ALOGE("createNormalLayer() failed (%s)", strerror(-err)); 1988 layer.clear(); 1989 } 1990 return layer; 1991} 1992 1993sp<LayerDim> SurfaceFlinger::createDimLayer( 1994 const sp<Client>& client, 1995 uint32_t w, uint32_t h, uint32_t flags) 1996{ 1997 sp<LayerDim> layer = new LayerDim(this, client); 1998 return layer; 1999} 2000 2001sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer( 2002 const sp<Client>& client, 2003 uint32_t w, uint32_t h, uint32_t flags) 2004{ 2005 sp<LayerScreenshot> layer = new LayerScreenshot(this, client); 2006 return layer; 2007} 2008 2009status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid) 2010{ 2011 /* 2012 * called by the window manager, when a surface should be marked for 2013 * destruction. 2014 * 2015 * The surface is removed from the current and drawing lists, but placed 2016 * in the purgatory queue, so it's not destroyed right-away (we need 2017 * to wait for all client's references to go away first). 2018 */ 2019 2020 status_t err = NAME_NOT_FOUND; 2021 Mutex::Autolock _l(mStateLock); 2022 sp<LayerBaseClient> layer = client->getLayerUser(sid); 2023 2024 if (layer != 0) { 2025 err = purgatorizeLayer_l(layer); 2026 if (err == NO_ERROR) { 2027 setTransactionFlags(eTransactionNeeded); 2028 } 2029 } 2030 return err; 2031} 2032 2033status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer) 2034{ 2035 // called by ~ISurface() when all references are gone 2036 status_t err = NO_ERROR; 2037 sp<LayerBaseClient> l(layer.promote()); 2038 if (l != NULL) { 2039 Mutex::Autolock _l(mStateLock); 2040 err = removeLayer_l(l); 2041 if (err == NAME_NOT_FOUND) { 2042 // The surface wasn't in the current list, which means it was 2043 // removed already, which means it is in the purgatory, 2044 // and need to be removed from there. 2045 ssize_t idx = mLayerPurgatory.remove(l); 2046 ALOGE_IF(idx < 0, 2047 "layer=%p is not in the purgatory list", l.get()); 2048 } 2049 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 2050 "error removing layer=%p (%s)", l.get(), strerror(-err)); 2051 } 2052 return err; 2053} 2054 2055// --------------------------------------------------------------------------- 2056 2057void SurfaceFlinger::onInitializeDisplays() { 2058 // reset screen orientation 2059 Vector<ComposerState> state; 2060 Vector<DisplayState> displays; 2061 DisplayState d; 2062 d.what = DisplayState::eDisplayProjectionChanged; 2063 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]; 2064 d.orientation = DisplayState::eOrientationDefault; 2065 d.frame.makeInvalid(); 2066 d.viewport.makeInvalid(); 2067 displays.add(d); 2068 setTransactionState(state, displays, 0); 2069 onScreenAcquired(getDefaultDisplayDevice()); 2070} 2071 2072void SurfaceFlinger::initializeDisplays() { 2073 class MessageScreenInitialized : public MessageBase { 2074 SurfaceFlinger* flinger; 2075 public: 2076 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } 2077 virtual bool handler() { 2078 flinger->onInitializeDisplays(); 2079 return true; 2080 } 2081 }; 2082 sp<MessageBase> msg = new MessageScreenInitialized(this); 2083 postMessageAsync(msg); // we may be called from main thread, use async message 2084} 2085 2086 2087void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) { 2088 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this); 2089 if (hw->isScreenAcquired()) { 2090 // this is expected, e.g. when power manager wakes up during boot 2091 ALOGD(" screen was previously acquired"); 2092 return; 2093 } 2094 2095 hw->acquireScreen(); 2096 int32_t type = hw->getDisplayType(); 2097 if (type < DisplayDevice::NUM_DISPLAY_TYPES) { 2098 // built-in display, tell the HWC 2099 getHwComposer().acquire(type); 2100 2101 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2102 // FIXME: eventthread only knows about the main display right now 2103 mEventThread->onScreenAcquired(); 2104 } 2105 } 2106 mVisibleRegionsDirty = true; 2107 repaintEverything(); 2108} 2109 2110void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) { 2111 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this); 2112 if (!hw->isScreenAcquired()) { 2113 ALOGD(" screen was previously released"); 2114 return; 2115 } 2116 2117 hw->releaseScreen(); 2118 int32_t type = hw->getDisplayType(); 2119 if (type < DisplayDevice::NUM_DISPLAY_TYPES) { 2120 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2121 // FIXME: eventthread only knows about the main display right now 2122 mEventThread->onScreenReleased(); 2123 } 2124 2125 // built-in display, tell the HWC 2126 getHwComposer().release(type); 2127 } 2128 mVisibleRegionsDirty = true; 2129 // from this point on, SF will stop drawing on this display 2130} 2131 2132void SurfaceFlinger::unblank(const sp<IBinder>& display) { 2133 class MessageScreenAcquired : public MessageBase { 2134 SurfaceFlinger& mFlinger; 2135 sp<IBinder> mDisplay; 2136 public: 2137 MessageScreenAcquired(SurfaceFlinger& flinger, 2138 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { } 2139 virtual bool handler() { 2140 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2141 if (hw == NULL) { 2142 ALOGE("Attempt to unblank null display %p", mDisplay.get()); 2143 } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) { 2144 ALOGW("Attempt to unblank virtual display"); 2145 } else { 2146 mFlinger.onScreenAcquired(hw); 2147 } 2148 return true; 2149 } 2150 }; 2151 sp<MessageBase> msg = new MessageScreenAcquired(*this, display); 2152 postMessageSync(msg); 2153} 2154 2155void SurfaceFlinger::blank(const sp<IBinder>& display) { 2156 class MessageScreenReleased : public MessageBase { 2157 SurfaceFlinger& mFlinger; 2158 sp<IBinder> mDisplay; 2159 public: 2160 MessageScreenReleased(SurfaceFlinger& flinger, 2161 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { } 2162 virtual bool handler() { 2163 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2164 if (hw == NULL) { 2165 ALOGE("Attempt to blank null display %p", mDisplay.get()); 2166 } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) { 2167 ALOGW("Attempt to blank virtual display"); 2168 } else { 2169 mFlinger.onScreenReleased(hw); 2170 } 2171 return true; 2172 } 2173 }; 2174 sp<MessageBase> msg = new MessageScreenReleased(*this, display); 2175 postMessageSync(msg); 2176} 2177 2178// --------------------------------------------------------------------------- 2179 2180status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 2181{ 2182 const size_t SIZE = 4096; 2183 char buffer[SIZE]; 2184 String8 result; 2185 2186 if (!PermissionCache::checkCallingPermission(sDump)) { 2187 snprintf(buffer, SIZE, "Permission Denial: " 2188 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 2189 IPCThreadState::self()->getCallingPid(), 2190 IPCThreadState::self()->getCallingUid()); 2191 result.append(buffer); 2192 } else { 2193 // Try to get the main lock, but don't insist if we can't 2194 // (this would indicate SF is stuck, but we want to be able to 2195 // print something in dumpsys). 2196 int retry = 3; 2197 while (mStateLock.tryLock()<0 && --retry>=0) { 2198 usleep(1000000); 2199 } 2200 const bool locked(retry >= 0); 2201 if (!locked) { 2202 snprintf(buffer, SIZE, 2203 "SurfaceFlinger appears to be unresponsive, " 2204 "dumping anyways (no locks held)\n"); 2205 result.append(buffer); 2206 } 2207 2208 bool dumpAll = true; 2209 size_t index = 0; 2210 size_t numArgs = args.size(); 2211 if (numArgs) { 2212 if ((index < numArgs) && 2213 (args[index] == String16("--list"))) { 2214 index++; 2215 listLayersLocked(args, index, result, buffer, SIZE); 2216 dumpAll = false; 2217 } 2218 2219 if ((index < numArgs) && 2220 (args[index] == String16("--latency"))) { 2221 index++; 2222 dumpStatsLocked(args, index, result, buffer, SIZE); 2223 dumpAll = false; 2224 } 2225 2226 if ((index < numArgs) && 2227 (args[index] == String16("--latency-clear"))) { 2228 index++; 2229 clearStatsLocked(args, index, result, buffer, SIZE); 2230 dumpAll = false; 2231 } 2232 } 2233 2234 if (dumpAll) { 2235 dumpAllLocked(result, buffer, SIZE); 2236 } 2237 2238 if (locked) { 2239 mStateLock.unlock(); 2240 } 2241 } 2242 write(fd, result.string(), result.size()); 2243 return NO_ERROR; 2244} 2245 2246void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 2247 String8& result, char* buffer, size_t SIZE) const 2248{ 2249 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2250 const size_t count = currentLayers.size(); 2251 for (size_t i=0 ; i<count ; i++) { 2252 const sp<LayerBase>& layer(currentLayers[i]); 2253 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 2254 result.append(buffer); 2255 } 2256} 2257 2258void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 2259 String8& result, char* buffer, size_t SIZE) const 2260{ 2261 String8 name; 2262 if (index < args.size()) { 2263 name = String8(args[index]); 2264 index++; 2265 } 2266 2267 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2268 const size_t count = currentLayers.size(); 2269 for (size_t i=0 ; i<count ; i++) { 2270 const sp<LayerBase>& layer(currentLayers[i]); 2271 if (name.isEmpty()) { 2272 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 2273 result.append(buffer); 2274 } 2275 if (name.isEmpty() || (name == layer->getName())) { 2276 layer->dumpStats(result, buffer, SIZE); 2277 } 2278 } 2279} 2280 2281void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 2282 String8& result, char* buffer, size_t SIZE) const 2283{ 2284 String8 name; 2285 if (index < args.size()) { 2286 name = String8(args[index]); 2287 index++; 2288 } 2289 2290 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2291 const size_t count = currentLayers.size(); 2292 for (size_t i=0 ; i<count ; i++) { 2293 const sp<LayerBase>& layer(currentLayers[i]); 2294 if (name.isEmpty() || (name == layer->getName())) { 2295 layer->clearStats(); 2296 } 2297 } 2298} 2299 2300/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result) 2301{ 2302 static const char* config = 2303 " [sf" 2304#ifdef NO_RGBX_8888 2305 " NO_RGBX_8888" 2306#endif 2307#ifdef HAS_CONTEXT_PRIORITY 2308 " HAS_CONTEXT_PRIORITY" 2309#endif 2310#ifdef NEVER_DEFAULT_TO_ASYNC_MODE 2311 " NEVER_DEFAULT_TO_ASYNC_MODE" 2312#endif 2313#ifdef TARGET_DISABLE_TRIPLE_BUFFERING 2314 " TARGET_DISABLE_TRIPLE_BUFFERING" 2315#endif 2316 "]"; 2317 result.append(config); 2318} 2319 2320void SurfaceFlinger::dumpAllLocked( 2321 String8& result, char* buffer, size_t SIZE) const 2322{ 2323 // figure out if we're stuck somewhere 2324 const nsecs_t now = systemTime(); 2325 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 2326 const nsecs_t inTransaction(mDebugInTransaction); 2327 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 2328 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 2329 2330 /* 2331 * Dump library configuration. 2332 */ 2333 result.append("Build configuration:"); 2334 appendSfConfigString(result); 2335 appendUiConfigString(result); 2336 appendGuiConfigString(result); 2337 result.append("\n"); 2338 2339 /* 2340 * Dump the visible layer list 2341 */ 2342 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2343 const size_t count = currentLayers.size(); 2344 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count); 2345 result.append(buffer); 2346 for (size_t i=0 ; i<count ; i++) { 2347 const sp<LayerBase>& layer(currentLayers[i]); 2348 layer->dump(result, buffer, SIZE); 2349 } 2350 2351 /* 2352 * Dump the layers in the purgatory 2353 */ 2354 2355 const size_t purgatorySize = mLayerPurgatory.size(); 2356 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize); 2357 result.append(buffer); 2358 for (size_t i=0 ; i<purgatorySize ; i++) { 2359 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 2360 layer->shortDump(result, buffer, SIZE); 2361 } 2362 2363 /* 2364 * Dump Display state 2365 */ 2366 2367 snprintf(buffer, SIZE, "Displays (%d entries)\n", mDisplays.size()); 2368 result.append(buffer); 2369 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 2370 const sp<const DisplayDevice>& hw(mDisplays[dpy]); 2371 hw->dump(result, buffer, SIZE); 2372 } 2373 2374 /* 2375 * Dump SurfaceFlinger global state 2376 */ 2377 2378 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n"); 2379 result.append(buffer); 2380 2381 HWComposer& hwc(getHwComposer()); 2382 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2383 const GLExtensions& extensions(GLExtensions::getInstance()); 2384 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n", 2385 extensions.getVendor(), 2386 extensions.getRenderer(), 2387 extensions.getVersion()); 2388 result.append(buffer); 2389 2390 snprintf(buffer, SIZE, "EGL : %s\n", 2391 eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID)); 2392 result.append(buffer); 2393 2394 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension()); 2395 result.append(buffer); 2396 2397 hw->undefinedRegion.dump(result, "undefinedRegion"); 2398 snprintf(buffer, SIZE, 2399 " orientation=%d, canDraw=%d\n", 2400 hw->getOrientation(), hw->canDraw()); 2401 result.append(buffer); 2402 snprintf(buffer, SIZE, 2403 " last eglSwapBuffers() time: %f us\n" 2404 " last transaction time : %f us\n" 2405 " transaction-flags : %08x\n" 2406 " refresh-rate : %f fps\n" 2407 " x-dpi : %f\n" 2408 " y-dpi : %f\n", 2409 mLastSwapBufferTime/1000.0, 2410 mLastTransactionTime/1000.0, 2411 mTransactionFlags, 2412 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY), 2413 hwc.getDpiX(HWC_DISPLAY_PRIMARY), 2414 hwc.getDpiY(HWC_DISPLAY_PRIMARY)); 2415 result.append(buffer); 2416 2417 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 2418 inSwapBuffersDuration/1000.0); 2419 result.append(buffer); 2420 2421 snprintf(buffer, SIZE, " transaction time: %f us\n", 2422 inTransactionDuration/1000.0); 2423 result.append(buffer); 2424 2425 /* 2426 * VSYNC state 2427 */ 2428 mEventThread->dump(result, buffer, SIZE); 2429 2430 /* 2431 * Dump HWComposer state 2432 */ 2433 snprintf(buffer, SIZE, "h/w composer state:\n"); 2434 result.append(buffer); 2435 snprintf(buffer, SIZE, " h/w composer %s and %s\n", 2436 hwc.initCheck()==NO_ERROR ? "present" : "not present", 2437 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled"); 2438 result.append(buffer); 2439 hwc.dump(result, buffer, SIZE); 2440 2441 /* 2442 * Dump gralloc state 2443 */ 2444 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 2445 alloc.dump(result); 2446} 2447 2448const Vector< sp<LayerBase> >& 2449SurfaceFlinger::getLayerSortedByZForHwcDisplay(int disp) { 2450 // Note: mStateLock is held here 2451 return getDisplayDevice( getBuiltInDisplay(disp) )->getVisibleLayersSortedByZ(); 2452} 2453 2454bool SurfaceFlinger::startDdmConnection() 2455{ 2456 void* libddmconnection_dso = 2457 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); 2458 if (!libddmconnection_dso) { 2459 return false; 2460 } 2461 void (*DdmConnection_start)(const char* name); 2462 DdmConnection_start = 2463 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start"); 2464 if (!DdmConnection_start) { 2465 dlclose(libddmconnection_dso); 2466 return false; 2467 } 2468 (*DdmConnection_start)(getServiceName()); 2469 return true; 2470} 2471 2472status_t SurfaceFlinger::onTransact( 2473 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2474{ 2475 switch (code) { 2476 case CREATE_CONNECTION: 2477 case SET_TRANSACTION_STATE: 2478 case BOOT_FINISHED: 2479 case BLANK: 2480 case UNBLANK: 2481 { 2482 // codes that require permission check 2483 IPCThreadState* ipc = IPCThreadState::self(); 2484 const int pid = ipc->getCallingPid(); 2485 const int uid = ipc->getCallingUid(); 2486 if ((uid != AID_GRAPHICS) && 2487 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 2488 ALOGE("Permission Denial: " 2489 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2490 return PERMISSION_DENIED; 2491 } 2492 break; 2493 } 2494 case CAPTURE_SCREEN: 2495 { 2496 // codes that require permission check 2497 IPCThreadState* ipc = IPCThreadState::self(); 2498 const int pid = ipc->getCallingPid(); 2499 const int uid = ipc->getCallingUid(); 2500 if ((uid != AID_GRAPHICS) && 2501 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 2502 ALOGE("Permission Denial: " 2503 "can't read framebuffer pid=%d, uid=%d", pid, uid); 2504 return PERMISSION_DENIED; 2505 } 2506 break; 2507 } 2508 } 2509 2510 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 2511 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 2512 CHECK_INTERFACE(ISurfaceComposer, data, reply); 2513 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 2514 IPCThreadState* ipc = IPCThreadState::self(); 2515 const int pid = ipc->getCallingPid(); 2516 const int uid = ipc->getCallingUid(); 2517 ALOGE("Permission Denial: " 2518 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2519 return PERMISSION_DENIED; 2520 } 2521 int n; 2522 switch (code) { 2523 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 2524 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 2525 return NO_ERROR; 2526 case 1002: // SHOW_UPDATES 2527 n = data.readInt32(); 2528 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 2529 invalidateHwcGeometry(); 2530 repaintEverything(); 2531 return NO_ERROR; 2532 case 1004:{ // repaint everything 2533 repaintEverything(); 2534 return NO_ERROR; 2535 } 2536 case 1005:{ // force transaction 2537 setTransactionFlags( 2538 eTransactionNeeded| 2539 eDisplayTransactionNeeded| 2540 eTraversalNeeded); 2541 return NO_ERROR; 2542 } 2543 case 1006:{ // send empty update 2544 signalRefresh(); 2545 return NO_ERROR; 2546 } 2547 case 1008: // toggle use of hw composer 2548 n = data.readInt32(); 2549 mDebugDisableHWC = n ? 1 : 0; 2550 invalidateHwcGeometry(); 2551 repaintEverything(); 2552 return NO_ERROR; 2553 case 1009: // toggle use of transform hint 2554 n = data.readInt32(); 2555 mDebugDisableTransformHint = n ? 1 : 0; 2556 invalidateHwcGeometry(); 2557 repaintEverything(); 2558 return NO_ERROR; 2559 case 1010: // interrogate. 2560 reply->writeInt32(0); 2561 reply->writeInt32(0); 2562 reply->writeInt32(mDebugRegion); 2563 reply->writeInt32(0); 2564 reply->writeInt32(mDebugDisableHWC); 2565 return NO_ERROR; 2566 case 1013: { 2567 Mutex::Autolock _l(mStateLock); 2568 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2569 reply->writeInt32(hw->getPageFlipCount()); 2570 } 2571 return NO_ERROR; 2572 } 2573 } 2574 return err; 2575} 2576 2577void SurfaceFlinger::repaintEverything() { 2578 android_atomic_or(1, &mRepaintEverything); 2579 signalTransaction(); 2580} 2581 2582// --------------------------------------------------------------------------- 2583 2584status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack, 2585 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2586{ 2587 Mutex::Autolock _l(mStateLock); 2588 return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut); 2589} 2590 2591status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack, 2592 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 2593{ 2594 ATRACE_CALL(); 2595 2596 if (!GLExtensions::getInstance().haveFramebufferObject()) 2597 return INVALID_OPERATION; 2598 2599 // get screen geometry 2600 // FIXME: figure out what it means to have a screenshot texture w/ multi-display 2601 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2602 const uint32_t hw_w = hw->getWidth(); 2603 const uint32_t hw_h = hw->getHeight(); 2604 GLfloat u = 1; 2605 GLfloat v = 1; 2606 2607 // make sure to clear all GL error flags 2608 while ( glGetError() != GL_NO_ERROR ) ; 2609 2610 // create a FBO 2611 GLuint name, tname; 2612 glGenTextures(1, &tname); 2613 glBindTexture(GL_TEXTURE_2D, tname); 2614 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 2615 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 2616 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2617 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2618 if (glGetError() != GL_NO_ERROR) { 2619 while ( glGetError() != GL_NO_ERROR ) ; 2620 GLint tw = (2 << (31 - clz(hw_w))); 2621 GLint th = (2 << (31 - clz(hw_h))); 2622 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2623 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 2624 u = GLfloat(hw_w) / tw; 2625 v = GLfloat(hw_h) / th; 2626 } 2627 glGenFramebuffersOES(1, &name); 2628 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2629 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, 2630 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 2631 2632 DisplayDevice::setViewportAndProjection(hw); 2633 2634 // redraw the screen entirely... 2635 glDisable(GL_TEXTURE_EXTERNAL_OES); 2636 glDisable(GL_TEXTURE_2D); 2637 glClearColor(0,0,0,1); 2638 glClear(GL_COLOR_BUFFER_BIT); 2639 glMatrixMode(GL_MODELVIEW); 2640 glLoadIdentity(); 2641 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2642 const size_t count = layers.size(); 2643 for (size_t i=0 ; i<count ; ++i) { 2644 const sp<LayerBase>& layer(layers[i]); 2645 layer->draw(hw); 2646 } 2647 2648 hw->compositionComplete(); 2649 2650 // back to main framebuffer 2651 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2652 glDeleteFramebuffersOES(1, &name); 2653 2654 *textureName = tname; 2655 *uOut = u; 2656 *vOut = v; 2657 return NO_ERROR; 2658} 2659 2660// --------------------------------------------------------------------------- 2661 2662status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display, 2663 sp<IMemoryHeap>* heap, 2664 uint32_t* w, uint32_t* h, PixelFormat* f, 2665 uint32_t sw, uint32_t sh, 2666 uint32_t minLayerZ, uint32_t maxLayerZ) 2667{ 2668 ATRACE_CALL(); 2669 2670 status_t result = PERMISSION_DENIED; 2671 2672 if (!GLExtensions::getInstance().haveFramebufferObject()) { 2673 return INVALID_OPERATION; 2674 } 2675 2676 // get screen geometry 2677 sp<const DisplayDevice> hw(getDisplayDevice(display)); 2678 const uint32_t hw_w = hw->getWidth(); 2679 const uint32_t hw_h = hw->getHeight(); 2680 2681 // if we have secure windows on this display, never allow the screen capture 2682 if (hw->getSecureLayerVisible()) { 2683 ALOGW("FB is protected: PERMISSION_DENIED"); 2684 return PERMISSION_DENIED; 2685 } 2686 2687 if ((sw > hw_w) || (sh > hw_h)) { 2688 ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h); 2689 return BAD_VALUE; 2690 } 2691 2692 sw = (!sw) ? hw_w : sw; 2693 sh = (!sh) ? hw_h : sh; 2694 const size_t size = sw * sh * 4; 2695 const bool filtering = sw != hw_w || sh != hw_h; 2696 2697// ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", 2698// sw, sh, minLayerZ, maxLayerZ); 2699 2700 // make sure to clear all GL error flags 2701 while ( glGetError() != GL_NO_ERROR ) ; 2702 2703 // create a FBO 2704 GLuint name, tname; 2705 glGenRenderbuffersOES(1, &tname); 2706 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 2707 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 2708 2709 glGenFramebuffersOES(1, &name); 2710 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2711 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 2712 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 2713 2714 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 2715 2716 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 2717 2718 // invert everything, b/c glReadPixel() below will invert the FB 2719 GLint viewport[4]; 2720 glGetIntegerv(GL_VIEWPORT, viewport); 2721 glViewport(0, 0, sw, sh); 2722 glMatrixMode(GL_PROJECTION); 2723 glPushMatrix(); 2724 glLoadIdentity(); 2725 glOrthof(0, hw_w, hw_h, 0, 0, 1); 2726 glMatrixMode(GL_MODELVIEW); 2727 2728 // redraw the screen entirely... 2729 glClearColor(0,0,0,1); 2730 glClear(GL_COLOR_BUFFER_BIT); 2731 2732 const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ()); 2733 const size_t count = layers.size(); 2734 for (size_t i=0 ; i<count ; ++i) { 2735 const sp<LayerBase>& layer(layers[i]); 2736 const uint32_t z = layer->drawingState().z; 2737 if (z >= minLayerZ && z <= maxLayerZ) { 2738 if (filtering) layer->setFiltering(true); 2739 layer->draw(hw); 2740 if (filtering) layer->setFiltering(false); 2741 } 2742 } 2743 2744 // check for errors and return screen capture 2745 if (glGetError() != GL_NO_ERROR) { 2746 // error while rendering 2747 result = INVALID_OPERATION; 2748 } else { 2749 // allocate shared memory large enough to hold the 2750 // screen capture 2751 sp<MemoryHeapBase> base( 2752 new MemoryHeapBase(size, 0, "screen-capture") ); 2753 void* const ptr = base->getBase(); 2754 if (ptr != MAP_FAILED) { 2755 // capture the screen with glReadPixels() 2756 ScopedTrace _t(ATRACE_TAG, "glReadPixels"); 2757 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 2758 if (glGetError() == GL_NO_ERROR) { 2759 *heap = base; 2760 *w = sw; 2761 *h = sh; 2762 *f = PIXEL_FORMAT_RGBA_8888; 2763 result = NO_ERROR; 2764 } 2765 } else { 2766 result = NO_MEMORY; 2767 } 2768 } 2769 glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); 2770 glMatrixMode(GL_PROJECTION); 2771 glPopMatrix(); 2772 glMatrixMode(GL_MODELVIEW); 2773 } else { 2774 result = BAD_VALUE; 2775 } 2776 2777 // release FBO resources 2778 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2779 glDeleteRenderbuffersOES(1, &tname); 2780 glDeleteFramebuffersOES(1, &name); 2781 2782 hw->compositionComplete(); 2783 2784// ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); 2785 2786 return result; 2787} 2788 2789 2790status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, 2791 sp<IMemoryHeap>* heap, 2792 uint32_t* width, uint32_t* height, PixelFormat* format, 2793 uint32_t sw, uint32_t sh, 2794 uint32_t minLayerZ, uint32_t maxLayerZ) 2795{ 2796 if (CC_UNLIKELY(display == 0)) 2797 return BAD_VALUE; 2798 2799 if (!GLExtensions::getInstance().haveFramebufferObject()) 2800 return INVALID_OPERATION; 2801 2802 class MessageCaptureScreen : public MessageBase { 2803 SurfaceFlinger* flinger; 2804 sp<IBinder> display; 2805 sp<IMemoryHeap>* heap; 2806 uint32_t* w; 2807 uint32_t* h; 2808 PixelFormat* f; 2809 uint32_t sw; 2810 uint32_t sh; 2811 uint32_t minLayerZ; 2812 uint32_t maxLayerZ; 2813 status_t result; 2814 public: 2815 MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display, 2816 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 2817 uint32_t sw, uint32_t sh, 2818 uint32_t minLayerZ, uint32_t maxLayerZ) 2819 : flinger(flinger), display(display), 2820 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), 2821 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2822 result(PERMISSION_DENIED) 2823 { 2824 } 2825 status_t getResult() const { 2826 return result; 2827 } 2828 virtual bool handler() { 2829 Mutex::Autolock _l(flinger->mStateLock); 2830 result = flinger->captureScreenImplLocked(display, 2831 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); 2832 return true; 2833 } 2834 }; 2835 2836 sp<MessageBase> msg = new MessageCaptureScreen(this, 2837 display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ); 2838 status_t res = postMessageSync(msg); 2839 if (res == NO_ERROR) { 2840 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 2841 } 2842 return res; 2843} 2844 2845// --------------------------------------------------------------------------- 2846 2847SurfaceFlinger::LayerVector::LayerVector() { 2848} 2849 2850SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 2851 : SortedVector<sp<LayerBase> >(rhs) { 2852} 2853 2854int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 2855 const void* rhs) const 2856{ 2857 // sort layers per layer-stack, then by z-order and finally by sequence 2858 const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs)); 2859 const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs)); 2860 2861 uint32_t ls = l->currentState().layerStack; 2862 uint32_t rs = r->currentState().layerStack; 2863 if (ls != rs) 2864 return ls - rs; 2865 2866 uint32_t lz = l->currentState().z; 2867 uint32_t rz = r->currentState().z; 2868 if (lz != rz) 2869 return lz - rz; 2870 2871 return l->sequence - r->sequence; 2872} 2873 2874// --------------------------------------------------------------------------- 2875 2876SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() 2877 : type(DisplayDevice::DISPLAY_ID_INVALID) { 2878} 2879 2880SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type) 2881 : type(type), layerStack(0), orientation(0) { 2882 viewport.makeInvalid(); 2883 frame.makeInvalid(); 2884} 2885 2886// --------------------------------------------------------------------------- 2887 2888}; // namespace android 2889