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