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