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