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