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