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