SurfaceFlinger.cpp revision c2633ce19bdbca4cbf8d6a225ede68a0afd693b9
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define ATRACE_TAG ATRACE_TAG_GRAPHICS 18 19#include <stdint.h> 20#include <sys/types.h> 21#include <errno.h> 22#include <math.h> 23#include <dlfcn.h> 24#include <inttypes.h> 25 26#include <EGL/egl.h> 27 28#include <cutils/log.h> 29#include <cutils/properties.h> 30 31#include <binder/IPCThreadState.h> 32#include <binder/IServiceManager.h> 33#include <binder/MemoryHeapBase.h> 34#include <binder/PermissionCache.h> 35 36#include <ui/DisplayInfo.h> 37 38#include <gui/BitTube.h> 39#include <gui/BufferQueue.h> 40#include <gui/GuiConfig.h> 41#include <gui/IDisplayEventConnection.h> 42#include <gui/Surface.h> 43#include <gui/GraphicBufferAlloc.h> 44 45#include <ui/GraphicBufferAllocator.h> 46#include <ui/PixelFormat.h> 47#include <ui/UiConfig.h> 48 49#include <utils/misc.h> 50#include <utils/String8.h> 51#include <utils/String16.h> 52#include <utils/StopWatch.h> 53#include <utils/Trace.h> 54 55#include <private/android_filesystem_config.h> 56#include <private/gui/SyncFeatures.h> 57 58#include "Client.h" 59#include "clz.h" 60#include "Colorizer.h" 61#include "DdmConnection.h" 62#include "DisplayDevice.h" 63#include "DispSync.h" 64#include "EventControlThread.h" 65#include "EventThread.h" 66#include "Layer.h" 67#include "LayerDim.h" 68#include "SurfaceFlinger.h" 69 70#include "DisplayHardware/FramebufferSurface.h" 71#include "DisplayHardware/HWComposer.h" 72#include "DisplayHardware/VirtualDisplaySurface.h" 73 74#include "Effects/Daltonizer.h" 75 76#include "RenderEngine/RenderEngine.h" 77#include <cutils/compiler.h> 78 79#define DISPLAY_COUNT 1 80 81/* 82 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all 83 * black pixels. 84 */ 85#define DEBUG_SCREENSHOTS false 86 87EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name); 88 89namespace android { 90 91// This works around the lack of support for the sync framework on some 92// devices. 93#ifdef RUNNING_WITHOUT_SYNC_FRAMEWORK 94static const bool runningWithoutSyncFramework = true; 95#else 96static const bool runningWithoutSyncFramework = false; 97#endif 98 99// This is the phase offset in nanoseconds of the software vsync event 100// relative to the vsync event reported by HWComposer. The software vsync 101// event is when SurfaceFlinger and Choreographer-based applications run each 102// frame. 103// 104// This phase offset allows adjustment of the minimum latency from application 105// wake-up (by Choregographer) time to the time at which the resulting window 106// image is displayed. This value may be either positive (after the HW vsync) 107// or negative (before the HW vsync). Setting it to 0 will result in a 108// minimum latency of two vsync periods because the app and SurfaceFlinger 109// will run just after the HW vsync. Setting it to a positive number will 110// result in the minimum latency being: 111// 112// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD)) 113// 114// Note that reducing this latency makes it more likely for the applications 115// to not have their window content image ready in time. When this happens 116// the latency will end up being an additional vsync period, and animations 117// will hiccup. Therefore, this latency should be tuned somewhat 118// conservatively (or at least with awareness of the trade-off being made). 119static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS; 120 121// This is the phase offset at which SurfaceFlinger's composition runs. 122static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS; 123 124// --------------------------------------------------------------------------- 125 126const String16 sHardwareTest("android.permission.HARDWARE_TEST"); 127const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); 128const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER"); 129const String16 sDump("android.permission.DUMP"); 130 131// --------------------------------------------------------------------------- 132 133SurfaceFlinger::SurfaceFlinger() 134 : BnSurfaceComposer(), 135 mTransactionFlags(0), 136 mTransactionPending(false), 137 mAnimTransactionPending(false), 138 mLayersRemoved(false), 139 mRepaintEverything(0), 140 mRenderEngine(NULL), 141 mBootTime(systemTime()), 142 mVisibleRegionsDirty(false), 143 mHwWorkListDirty(false), 144 mAnimCompositionPending(false), 145 mDebugRegion(0), 146 mDebugDDMS(0), 147 mDebugDisableHWC(0), 148 mDebugDisableTransformHint(0), 149 mDebugInSwapBuffers(0), 150 mLastSwapBufferTime(0), 151 mDebugInTransaction(0), 152 mLastTransactionTime(0), 153 mBootFinished(false), 154 mPrimaryHWVsyncEnabled(false), 155 mHWVsyncAvailable(false), 156 mDaltonize(false) 157{ 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 %zu 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 mDisplays[dpy]->beginFrame(); 886 } 887 888 HWComposer& hwc(getHwComposer()); 889 if (hwc.initCheck() == NO_ERROR) { 890 // build the h/w work list 891 if (CC_UNLIKELY(mHwWorkListDirty)) { 892 mHwWorkListDirty = false; 893 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 894 sp<const DisplayDevice> hw(mDisplays[dpy]); 895 const int32_t id = hw->getHwcDisplayId(); 896 if (id >= 0) { 897 const Vector< sp<Layer> >& currentLayers( 898 hw->getVisibleLayersSortedByZ()); 899 const size_t count = currentLayers.size(); 900 if (hwc.createWorkList(id, count) == NO_ERROR) { 901 HWComposer::LayerListIterator cur = hwc.begin(id); 902 const HWComposer::LayerListIterator end = hwc.end(id); 903 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 904 const sp<Layer>& layer(currentLayers[i]); 905 layer->setGeometry(hw, *cur); 906 if (mDebugDisableHWC || mDebugRegion || mDaltonize) { 907 cur->setSkip(true); 908 } 909 } 910 } 911 } 912 } 913 } 914 915 // set the per-frame data 916 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 917 sp<const DisplayDevice> hw(mDisplays[dpy]); 918 const int32_t id = hw->getHwcDisplayId(); 919 if (id >= 0) { 920 const Vector< sp<Layer> >& currentLayers( 921 hw->getVisibleLayersSortedByZ()); 922 const size_t count = currentLayers.size(); 923 HWComposer::LayerListIterator cur = hwc.begin(id); 924 const HWComposer::LayerListIterator end = hwc.end(id); 925 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) { 926 /* 927 * update the per-frame h/w composer data for each layer 928 * and build the transparent region of the FB 929 */ 930 const sp<Layer>& layer(currentLayers[i]); 931 layer->setPerFrameData(hw, *cur); 932 } 933 } 934 } 935 936 status_t err = hwc.prepare(); 937 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 938 939 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 940 sp<const DisplayDevice> hw(mDisplays[dpy]); 941 hw->prepareFrame(hwc); 942 } 943 } 944} 945 946void SurfaceFlinger::doComposition() { 947 ATRACE_CALL(); 948 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); 949 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 950 const sp<DisplayDevice>& hw(mDisplays[dpy]); 951 if (hw->canDraw()) { 952 // transform the dirty region into this screen's coordinate space 953 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 954 955 // repaint the framebuffer (if needed) 956 doDisplayComposition(hw, dirtyRegion); 957 958 hw->dirtyRegion.clear(); 959 hw->flip(hw->swapRegion); 960 hw->swapRegion.clear(); 961 } 962 // inform the h/w that we're done compositing 963 hw->compositionComplete(); 964 } 965 postFramebuffer(); 966} 967 968void SurfaceFlinger::postFramebuffer() 969{ 970 ATRACE_CALL(); 971 972 const nsecs_t now = systemTime(); 973 mDebugInSwapBuffers = now; 974 975 HWComposer& hwc(getHwComposer()); 976 if (hwc.initCheck() == NO_ERROR) { 977 if (!hwc.supportsFramebufferTarget()) { 978 // EGL spec says: 979 // "surface must be bound to the calling thread's current context, 980 // for the current rendering API." 981 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); 982 } 983 hwc.commit(); 984 } 985 986 // make the default display current because the VirtualDisplayDevice code cannot 987 // deal with dequeueBuffer() being called outside of the composition loop; however 988 // the code below can call glFlush() which is allowed (and does in some case) call 989 // dequeueBuffer(). 990 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); 991 992 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 993 sp<const DisplayDevice> hw(mDisplays[dpy]); 994 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ()); 995 hw->onSwapBuffersCompleted(hwc); 996 const size_t count = currentLayers.size(); 997 int32_t id = hw->getHwcDisplayId(); 998 if (id >=0 && hwc.initCheck() == NO_ERROR) { 999 HWComposer::LayerListIterator cur = hwc.begin(id); 1000 const HWComposer::LayerListIterator end = hwc.end(id); 1001 for (size_t i = 0; cur != end && i < count; ++i, ++cur) { 1002 currentLayers[i]->onLayerDisplayed(hw, &*cur); 1003 } 1004 } else { 1005 for (size_t i = 0; i < count; i++) { 1006 currentLayers[i]->onLayerDisplayed(hw, NULL); 1007 } 1008 } 1009 } 1010 1011 mLastSwapBufferTime = systemTime() - now; 1012 mDebugInSwapBuffers = 0; 1013 1014 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount(); 1015 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) { 1016 logFrameStats(); 1017 } 1018} 1019 1020void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 1021{ 1022 ATRACE_CALL(); 1023 1024 // here we keep a copy of the drawing state (that is the state that's 1025 // going to be overwritten by handleTransactionLocked()) outside of 1026 // mStateLock so that the side-effects of the State assignment 1027 // don't happen with mStateLock held (which can cause deadlocks). 1028 State drawingState(mDrawingState); 1029 1030 Mutex::Autolock _l(mStateLock); 1031 const nsecs_t now = systemTime(); 1032 mDebugInTransaction = now; 1033 1034 // Here we're guaranteed that some transaction flags are set 1035 // so we can call handleTransactionLocked() unconditionally. 1036 // We call getTransactionFlags(), which will also clear the flags, 1037 // with mStateLock held to guarantee that mCurrentState won't change 1038 // until the transaction is committed. 1039 1040 transactionFlags = getTransactionFlags(eTransactionMask); 1041 handleTransactionLocked(transactionFlags); 1042 1043 mLastTransactionTime = systemTime() - now; 1044 mDebugInTransaction = 0; 1045 invalidateHwcGeometry(); 1046 // here the transaction has been committed 1047} 1048 1049void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 1050{ 1051 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 1052 const size_t count = currentLayers.size(); 1053 1054 /* 1055 * Traversal of the children 1056 * (perform the transaction for each of them if needed) 1057 */ 1058 1059 if (transactionFlags & eTraversalNeeded) { 1060 for (size_t i=0 ; i<count ; i++) { 1061 const sp<Layer>& layer(currentLayers[i]); 1062 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 1063 if (!trFlags) continue; 1064 1065 const uint32_t flags = layer->doTransaction(0); 1066 if (flags & Layer::eVisibleRegion) 1067 mVisibleRegionsDirty = true; 1068 } 1069 } 1070 1071 /* 1072 * Perform display own transactions if needed 1073 */ 1074 1075 if (transactionFlags & eDisplayTransactionNeeded) { 1076 // here we take advantage of Vector's copy-on-write semantics to 1077 // improve performance by skipping the transaction entirely when 1078 // know that the lists are identical 1079 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 1080 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 1081 if (!curr.isIdenticalTo(draw)) { 1082 mVisibleRegionsDirty = true; 1083 const size_t cc = curr.size(); 1084 size_t dc = draw.size(); 1085 1086 // find the displays that were removed 1087 // (ie: in drawing state but not in current state) 1088 // also handle displays that changed 1089 // (ie: displays that are in both lists) 1090 for (size_t i=0 ; i<dc ; i++) { 1091 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 1092 if (j < 0) { 1093 // in drawing state but not in current state 1094 if (!draw[i].isMainDisplay()) { 1095 // Call makeCurrent() on the primary display so we can 1096 // be sure that nothing associated with this display 1097 // is current. 1098 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice()); 1099 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext); 1100 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i))); 1101 if (hw != NULL) 1102 hw->disconnect(getHwComposer()); 1103 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) 1104 mEventThread->onHotplugReceived(draw[i].type, false); 1105 mDisplays.removeItem(draw.keyAt(i)); 1106 } else { 1107 ALOGW("trying to remove the main display"); 1108 } 1109 } else { 1110 // this display is in both lists. see if something changed. 1111 const DisplayDeviceState& state(curr[j]); 1112 const wp<IBinder>& display(curr.keyAt(j)); 1113 if (state.surface->asBinder() != draw[i].surface->asBinder()) { 1114 // changing the surface is like destroying and 1115 // recreating the DisplayDevice, so we just remove it 1116 // from the drawing state, so that it get re-added 1117 // below. 1118 sp<DisplayDevice> hw(getDisplayDevice(display)); 1119 if (hw != NULL) 1120 hw->disconnect(getHwComposer()); 1121 mDisplays.removeItem(display); 1122 mDrawingState.displays.removeItemsAt(i); 1123 dc--; i--; 1124 // at this point we must loop to the next item 1125 continue; 1126 } 1127 1128 const sp<DisplayDevice> disp(getDisplayDevice(display)); 1129 if (disp != NULL) { 1130 if (state.layerStack != draw[i].layerStack) { 1131 disp->setLayerStack(state.layerStack); 1132 } 1133 if ((state.orientation != draw[i].orientation) 1134 || (state.viewport != draw[i].viewport) 1135 || (state.frame != draw[i].frame)) 1136 { 1137 disp->setProjection(state.orientation, 1138 state.viewport, state.frame); 1139 } 1140 } 1141 } 1142 } 1143 1144 // find displays that were added 1145 // (ie: in current state but not in drawing state) 1146 for (size_t i=0 ; i<cc ; i++) { 1147 if (draw.indexOfKey(curr.keyAt(i)) < 0) { 1148 const DisplayDeviceState& state(curr[i]); 1149 1150 sp<DisplaySurface> dispSurface; 1151 sp<IGraphicBufferProducer> producer; 1152 sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc()); 1153 1154 int32_t hwcDisplayId = -1; 1155 if (state.isVirtualDisplay()) { 1156 // Virtual displays without a surface are dormant: 1157 // they have external state (layer stack, projection, 1158 // etc.) but no internal state (i.e. a DisplayDevice). 1159 if (state.surface != NULL) { 1160 1161 hwcDisplayId = allocateHwcDisplayId(state.type); 1162 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface( 1163 *mHwc, hwcDisplayId, state.surface, bq, 1164 state.displayName); 1165 1166 dispSurface = vds; 1167 if (hwcDisplayId >= 0) { 1168 producer = vds; 1169 } else { 1170 // There won't be any interaction with HWC for this virtual display, 1171 // so the GLES driver can pass buffers directly to the sink. 1172 producer = state.surface; 1173 } 1174 } 1175 } else { 1176 ALOGE_IF(state.surface!=NULL, 1177 "adding a supported display, but rendering " 1178 "surface is provided (%p), ignoring it", 1179 state.surface.get()); 1180 hwcDisplayId = allocateHwcDisplayId(state.type); 1181 // for supported (by hwc) displays we provide our 1182 // own rendering surface 1183 dispSurface = new FramebufferSurface(*mHwc, state.type, bq); 1184 producer = bq; 1185 } 1186 1187 const wp<IBinder>& display(curr.keyAt(i)); 1188 if (dispSurface != NULL) { 1189 sp<DisplayDevice> hw = new DisplayDevice(this, 1190 state.type, hwcDisplayId, 1191 mHwc->getFormat(hwcDisplayId), state.isSecure, 1192 display, dispSurface, producer, 1193 mRenderEngine->getEGLConfig()); 1194 hw->setLayerStack(state.layerStack); 1195 hw->setProjection(state.orientation, 1196 state.viewport, state.frame); 1197 hw->setDisplayName(state.displayName); 1198 mDisplays.add(display, hw); 1199 if (state.isVirtualDisplay()) { 1200 if (hwcDisplayId >= 0) { 1201 mHwc->setVirtualDisplayProperties(hwcDisplayId, 1202 hw->getWidth(), hw->getHeight(), 1203 hw->getFormat()); 1204 } 1205 } else { 1206 mEventThread->onHotplugReceived(state.type, true); 1207 } 1208 } 1209 } 1210 } 1211 } 1212 } 1213 1214 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) { 1215 // The transform hint might have changed for some layers 1216 // (either because a display has changed, or because a layer 1217 // as changed). 1218 // 1219 // Walk through all the layers in currentLayers, 1220 // and update their transform hint. 1221 // 1222 // If a layer is visible only on a single display, then that 1223 // display is used to calculate the hint, otherwise we use the 1224 // default display. 1225 // 1226 // NOTE: we do this here, rather than in rebuildLayerStacks() so that 1227 // the hint is set before we acquire a buffer from the surface texture. 1228 // 1229 // NOTE: layer transactions have taken place already, so we use their 1230 // drawing state. However, SurfaceFlinger's own transaction has not 1231 // happened yet, so we must use the current state layer list 1232 // (soon to become the drawing state list). 1233 // 1234 sp<const DisplayDevice> disp; 1235 uint32_t currentlayerStack = 0; 1236 for (size_t i=0; i<count; i++) { 1237 // NOTE: we rely on the fact that layers are sorted by 1238 // layerStack first (so we don't have to traverse the list 1239 // of displays for every layer). 1240 const sp<Layer>& layer(currentLayers[i]); 1241 uint32_t layerStack = layer->getDrawingState().layerStack; 1242 if (i==0 || currentlayerStack != layerStack) { 1243 currentlayerStack = layerStack; 1244 // figure out if this layerstack is mirrored 1245 // (more than one display) if so, pick the default display, 1246 // if not, pick the only display it's on. 1247 disp.clear(); 1248 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1249 sp<const DisplayDevice> hw(mDisplays[dpy]); 1250 if (hw->getLayerStack() == currentlayerStack) { 1251 if (disp == NULL) { 1252 disp = hw; 1253 } else { 1254 disp = NULL; 1255 break; 1256 } 1257 } 1258 } 1259 } 1260 if (disp == NULL) { 1261 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to 1262 // redraw after transform hint changes. See bug 8508397. 1263 1264 // could be null when this layer is using a layerStack 1265 // that is not visible on any display. Also can occur at 1266 // screen off/on times. 1267 disp = getDefaultDisplayDevice(); 1268 } 1269 layer->updateTransformHint(disp); 1270 } 1271 } 1272 1273 1274 /* 1275 * Perform our own transaction if needed 1276 */ 1277 1278 const LayerVector& layers(mDrawingState.layersSortedByZ); 1279 if (currentLayers.size() > layers.size()) { 1280 // layers have been added 1281 mVisibleRegionsDirty = true; 1282 } 1283 1284 // some layers might have been removed, so 1285 // we need to update the regions they're exposing. 1286 if (mLayersRemoved) { 1287 mLayersRemoved = false; 1288 mVisibleRegionsDirty = true; 1289 const size_t count = layers.size(); 1290 for (size_t i=0 ; i<count ; i++) { 1291 const sp<Layer>& layer(layers[i]); 1292 if (currentLayers.indexOf(layer) < 0) { 1293 // this layer is not visible anymore 1294 // TODO: we could traverse the tree from front to back and 1295 // compute the actual visible region 1296 // TODO: we could cache the transformed region 1297 const Layer::State& s(layer->getDrawingState()); 1298 Region visibleReg = s.transform.transform( 1299 Region(Rect(s.active.w, s.active.h))); 1300 invalidateLayerStack(s.layerStack, visibleReg); 1301 } 1302 } 1303 } 1304 1305 commitTransaction(); 1306} 1307 1308void SurfaceFlinger::commitTransaction() 1309{ 1310 if (!mLayersPendingRemoval.isEmpty()) { 1311 // Notify removed layers now that they can't be drawn from 1312 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1313 mLayersPendingRemoval[i]->onRemoved(); 1314 } 1315 mLayersPendingRemoval.clear(); 1316 } 1317 1318 // If this transaction is part of a window animation then the next frame 1319 // we composite should be considered an animation as well. 1320 mAnimCompositionPending = mAnimTransactionPending; 1321 1322 mDrawingState = mCurrentState; 1323 mTransactionPending = false; 1324 mAnimTransactionPending = false; 1325 mTransactionCV.broadcast(); 1326} 1327 1328void SurfaceFlinger::computeVisibleRegions( 1329 const LayerVector& currentLayers, uint32_t layerStack, 1330 Region& outDirtyRegion, Region& outOpaqueRegion) 1331{ 1332 ATRACE_CALL(); 1333 1334 Region aboveOpaqueLayers; 1335 Region aboveCoveredLayers; 1336 Region dirty; 1337 1338 outDirtyRegion.clear(); 1339 1340 size_t i = currentLayers.size(); 1341 while (i--) { 1342 const sp<Layer>& layer = currentLayers[i]; 1343 1344 // start with the whole surface at its current location 1345 const Layer::State& s(layer->getDrawingState()); 1346 1347 // only consider the layers on the given layer stack 1348 if (s.layerStack != layerStack) 1349 continue; 1350 1351 /* 1352 * opaqueRegion: area of a surface that is fully opaque. 1353 */ 1354 Region opaqueRegion; 1355 1356 /* 1357 * visibleRegion: area of a surface that is visible on screen 1358 * and not fully transparent. This is essentially the layer's 1359 * footprint minus the opaque regions above it. 1360 * Areas covered by a translucent surface are considered visible. 1361 */ 1362 Region visibleRegion; 1363 1364 /* 1365 * coveredRegion: area of a surface that is covered by all 1366 * visible regions above it (which includes the translucent areas). 1367 */ 1368 Region coveredRegion; 1369 1370 /* 1371 * transparentRegion: area of a surface that is hinted to be completely 1372 * transparent. This is only used to tell when the layer has no visible 1373 * non-transparent regions and can be removed from the layer list. It 1374 * does not affect the visibleRegion of this layer or any layers 1375 * beneath it. The hint may not be correct if apps don't respect the 1376 * SurfaceView restrictions (which, sadly, some don't). 1377 */ 1378 Region transparentRegion; 1379 1380 1381 // handle hidden surfaces by setting the visible region to empty 1382 if (CC_LIKELY(layer->isVisible())) { 1383 const bool translucent = !layer->isOpaque(); 1384 Rect bounds(s.transform.transform(layer->computeBounds())); 1385 visibleRegion.set(bounds); 1386 if (!visibleRegion.isEmpty()) { 1387 // Remove the transparent area from the visible region 1388 if (translucent) { 1389 const Transform tr(s.transform); 1390 if (tr.transformed()) { 1391 if (tr.preserveRects()) { 1392 // transform the transparent region 1393 transparentRegion = tr.transform(s.activeTransparentRegion); 1394 } else { 1395 // transformation too complex, can't do the 1396 // transparent region optimization. 1397 transparentRegion.clear(); 1398 } 1399 } else { 1400 transparentRegion = s.activeTransparentRegion; 1401 } 1402 } 1403 1404 // compute the opaque region 1405 const int32_t layerOrientation = s.transform.getOrientation(); 1406 if (s.alpha==255 && !translucent && 1407 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1408 // the opaque region is the layer's footprint 1409 opaqueRegion = visibleRegion; 1410 } 1411 } 1412 } 1413 1414 // Clip the covered region to the visible region 1415 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1416 1417 // Update aboveCoveredLayers for next (lower) layer 1418 aboveCoveredLayers.orSelf(visibleRegion); 1419 1420 // subtract the opaque region covered by the layers above us 1421 visibleRegion.subtractSelf(aboveOpaqueLayers); 1422 1423 // compute this layer's dirty region 1424 if (layer->contentDirty) { 1425 // we need to invalidate the whole region 1426 dirty = visibleRegion; 1427 // as well, as the old visible region 1428 dirty.orSelf(layer->visibleRegion); 1429 layer->contentDirty = false; 1430 } else { 1431 /* compute the exposed region: 1432 * the exposed region consists of two components: 1433 * 1) what's VISIBLE now and was COVERED before 1434 * 2) what's EXPOSED now less what was EXPOSED before 1435 * 1436 * note that (1) is conservative, we start with the whole 1437 * visible region but only keep what used to be covered by 1438 * something -- which mean it may have been exposed. 1439 * 1440 * (2) handles areas that were not covered by anything but got 1441 * exposed because of a resize. 1442 */ 1443 const Region newExposed = visibleRegion - coveredRegion; 1444 const Region oldVisibleRegion = layer->visibleRegion; 1445 const Region oldCoveredRegion = layer->coveredRegion; 1446 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1447 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1448 } 1449 dirty.subtractSelf(aboveOpaqueLayers); 1450 1451 // accumulate to the screen dirty region 1452 outDirtyRegion.orSelf(dirty); 1453 1454 // Update aboveOpaqueLayers for next (lower) layer 1455 aboveOpaqueLayers.orSelf(opaqueRegion); 1456 1457 // Store the visible region in screen space 1458 layer->setVisibleRegion(visibleRegion); 1459 layer->setCoveredRegion(coveredRegion); 1460 layer->setVisibleNonTransparentRegion( 1461 visibleRegion.subtract(transparentRegion)); 1462 } 1463 1464 outOpaqueRegion = aboveOpaqueLayers; 1465} 1466 1467void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1468 const Region& dirty) { 1469 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1470 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1471 if (hw->getLayerStack() == layerStack) { 1472 hw->dirtyRegion.orSelf(dirty); 1473 } 1474 } 1475} 1476 1477void SurfaceFlinger::handlePageFlip() 1478{ 1479 Region dirtyRegion; 1480 1481 bool visibleRegions = false; 1482 const LayerVector& layers(mDrawingState.layersSortedByZ); 1483 const size_t count = layers.size(); 1484 for (size_t i=0 ; i<count ; i++) { 1485 const sp<Layer>& layer(layers[i]); 1486 const Region dirty(layer->latchBuffer(visibleRegions)); 1487 const Layer::State& s(layer->getDrawingState()); 1488 invalidateLayerStack(s.layerStack, dirty); 1489 } 1490 1491 mVisibleRegionsDirty |= visibleRegions; 1492} 1493 1494void SurfaceFlinger::invalidateHwcGeometry() 1495{ 1496 mHwWorkListDirty = true; 1497} 1498 1499 1500void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, 1501 const Region& inDirtyRegion) 1502{ 1503 Region dirtyRegion(inDirtyRegion); 1504 1505 // compute the invalid region 1506 hw->swapRegion.orSelf(dirtyRegion); 1507 1508 uint32_t flags = hw->getFlags(); 1509 if (flags & DisplayDevice::SWAP_RECTANGLE) { 1510 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 1511 // takes a rectangle, we must make sure to update that whole 1512 // rectangle in that case 1513 dirtyRegion.set(hw->swapRegion.bounds()); 1514 } else { 1515 if (flags & DisplayDevice::PARTIAL_UPDATES) { 1516 // We need to redraw the rectangle that will be updated 1517 // (pushed to the framebuffer). 1518 // This is needed because PARTIAL_UPDATES only takes one 1519 // rectangle instead of a region (see DisplayDevice::flip()) 1520 dirtyRegion.set(hw->swapRegion.bounds()); 1521 } else { 1522 // we need to redraw everything (the whole screen) 1523 dirtyRegion.set(hw->bounds()); 1524 hw->swapRegion = dirtyRegion; 1525 } 1526 } 1527 1528 if (CC_LIKELY(!mDaltonize)) { 1529 doComposeSurfaces(hw, dirtyRegion); 1530 } else { 1531 RenderEngine& engine(getRenderEngine()); 1532 engine.beginGroup(mDaltonizer()); 1533 doComposeSurfaces(hw, dirtyRegion); 1534 engine.endGroup(); 1535 } 1536 1537 // update the swap region and clear the dirty region 1538 hw->swapRegion.orSelf(dirtyRegion); 1539 1540 // swap buffers (presentation) 1541 hw->swapBuffers(getHwComposer()); 1542} 1543 1544void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty) 1545{ 1546 RenderEngine& engine(getRenderEngine()); 1547 const int32_t id = hw->getHwcDisplayId(); 1548 HWComposer& hwc(getHwComposer()); 1549 HWComposer::LayerListIterator cur = hwc.begin(id); 1550 const HWComposer::LayerListIterator end = hwc.end(id); 1551 1552 bool hasGlesComposition = hwc.hasGlesComposition(id); 1553 if (hasGlesComposition) { 1554 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) { 1555 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s", 1556 hw->getDisplayName().string()); 1557 return; 1558 } 1559 1560 // Never touch the framebuffer if we don't have any framebuffer layers 1561 const bool hasHwcComposition = hwc.hasHwcComposition(id); 1562 if (hasHwcComposition) { 1563 // when using overlays, we assume a fully transparent framebuffer 1564 // NOTE: we could reduce how much we need to clear, for instance 1565 // remove where there are opaque FB layers. however, on some 1566 // GPUs doing a "clean slate" clear might be more efficient. 1567 // We'll revisit later if needed. 1568 engine.clearWithColor(0, 0, 0, 0); 1569 } else { 1570 // we start with the whole screen area 1571 const Region bounds(hw->getBounds()); 1572 1573 // we remove the scissor part 1574 // we're left with the letterbox region 1575 // (common case is that letterbox ends-up being empty) 1576 const Region letterbox(bounds.subtract(hw->getScissor())); 1577 1578 // compute the area to clear 1579 Region region(hw->undefinedRegion.merge(letterbox)); 1580 1581 // but limit it to the dirty region 1582 region.andSelf(dirty); 1583 1584 // screen is already cleared here 1585 if (!region.isEmpty()) { 1586 // can happen with SurfaceView 1587 drawWormhole(hw, region); 1588 } 1589 } 1590 1591 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) { 1592 // just to be on the safe side, we don't set the 1593 // scissor on the main display. It should never be needed 1594 // anyways (though in theory it could since the API allows it). 1595 const Rect& bounds(hw->getBounds()); 1596 const Rect& scissor(hw->getScissor()); 1597 if (scissor != bounds) { 1598 // scissor doesn't match the screen's dimensions, so we 1599 // need to clear everything outside of it and enable 1600 // the GL scissor so we don't draw anything where we shouldn't 1601 1602 // enable scissor for this frame 1603 const uint32_t height = hw->getHeight(); 1604 engine.setScissor(scissor.left, height - scissor.bottom, 1605 scissor.getWidth(), scissor.getHeight()); 1606 } 1607 } 1608 } 1609 1610 /* 1611 * and then, render the layers targeted at the framebuffer 1612 */ 1613 1614 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ()); 1615 const size_t count = layers.size(); 1616 const Transform& tr = hw->getTransform(); 1617 if (cur != end) { 1618 // we're using h/w composer 1619 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) { 1620 const sp<Layer>& layer(layers[i]); 1621 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion))); 1622 if (!clip.isEmpty()) { 1623 switch (cur->getCompositionType()) { 1624 case HWC_OVERLAY: { 1625 const Layer::State& state(layer->getDrawingState()); 1626 if ((cur->getHints() & HWC_HINT_CLEAR_FB) 1627 && i 1628 && layer->isOpaque() && (state.alpha == 0xFF) 1629 && hasGlesComposition) { 1630 // never clear the very first layer since we're 1631 // guaranteed the FB is already cleared 1632 layer->clearWithOpenGL(hw, clip); 1633 } 1634 break; 1635 } 1636 case HWC_FRAMEBUFFER: { 1637 layer->draw(hw, clip); 1638 break; 1639 } 1640 case HWC_FRAMEBUFFER_TARGET: { 1641 // this should not happen as the iterator shouldn't 1642 // let us get there. 1643 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i); 1644 break; 1645 } 1646 } 1647 } 1648 layer->setAcquireFence(hw, *cur); 1649 } 1650 } else { 1651 // we're not using h/w composer 1652 for (size_t i=0 ; i<count ; ++i) { 1653 const sp<Layer>& layer(layers[i]); 1654 const Region clip(dirty.intersect( 1655 tr.transform(layer->visibleRegion))); 1656 if (!clip.isEmpty()) { 1657 layer->draw(hw, clip); 1658 } 1659 } 1660 } 1661 1662 // disable scissor at the end of the frame 1663 engine.disableScissor(); 1664} 1665 1666void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const { 1667 const int32_t height = hw->getHeight(); 1668 RenderEngine& engine(getRenderEngine()); 1669 engine.fillRegionWithColor(region, height, 0, 0, 0, 0); 1670} 1671 1672void SurfaceFlinger::addClientLayer(const sp<Client>& client, 1673 const sp<IBinder>& handle, 1674 const sp<IGraphicBufferProducer>& gbc, 1675 const sp<Layer>& lbc) 1676{ 1677 // attach this layer to the client 1678 client->attachLayer(handle, lbc); 1679 1680 // add this layer to the current state list 1681 Mutex::Autolock _l(mStateLock); 1682 mCurrentState.layersSortedByZ.add(lbc); 1683 mGraphicBufferProducerList.add(gbc->asBinder()); 1684} 1685 1686status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) { 1687 Mutex::Autolock _l(mStateLock); 1688 ssize_t index = mCurrentState.layersSortedByZ.remove(layer); 1689 if (index >= 0) { 1690 mLayersPendingRemoval.push(layer); 1691 mLayersRemoved = true; 1692 setTransactionFlags(eTransactionNeeded); 1693 return NO_ERROR; 1694 } 1695 return status_t(index); 1696} 1697 1698uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) { 1699 return android_atomic_release_load(&mTransactionFlags); 1700} 1701 1702uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) { 1703 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1704} 1705 1706uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) { 1707 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1708 if ((old & flags)==0) { // wake the server up 1709 signalTransaction(); 1710 } 1711 return old; 1712} 1713 1714void SurfaceFlinger::setTransactionState( 1715 const Vector<ComposerState>& state, 1716 const Vector<DisplayState>& displays, 1717 uint32_t flags) 1718{ 1719 ATRACE_CALL(); 1720 Mutex::Autolock _l(mStateLock); 1721 uint32_t transactionFlags = 0; 1722 1723 if (flags & eAnimation) { 1724 // For window updates that are part of an animation we must wait for 1725 // previous animation "frames" to be handled. 1726 while (mAnimTransactionPending) { 1727 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1728 if (CC_UNLIKELY(err != NO_ERROR)) { 1729 // just in case something goes wrong in SF, return to the 1730 // caller after a few seconds. 1731 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out " 1732 "waiting for previous animation frame"); 1733 mAnimTransactionPending = false; 1734 break; 1735 } 1736 } 1737 } 1738 1739 size_t count = displays.size(); 1740 for (size_t i=0 ; i<count ; i++) { 1741 const DisplayState& s(displays[i]); 1742 transactionFlags |= setDisplayStateLocked(s); 1743 } 1744 1745 count = state.size(); 1746 for (size_t i=0 ; i<count ; i++) { 1747 const ComposerState& s(state[i]); 1748 // Here we need to check that the interface we're given is indeed 1749 // one of our own. A malicious client could give us a NULL 1750 // IInterface, or one of its own or even one of our own but a 1751 // different type. All these situations would cause us to crash. 1752 // 1753 // NOTE: it would be better to use RTTI as we could directly check 1754 // that we have a Client*. however, RTTI is disabled in Android. 1755 if (s.client != NULL) { 1756 sp<IBinder> binder = s.client->asBinder(); 1757 if (binder != NULL) { 1758 String16 desc(binder->getInterfaceDescriptor()); 1759 if (desc == ISurfaceComposerClient::descriptor) { 1760 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1761 transactionFlags |= setClientStateLocked(client, s.state); 1762 } 1763 } 1764 } 1765 } 1766 1767 if (transactionFlags) { 1768 // this triggers the transaction 1769 setTransactionFlags(transactionFlags); 1770 1771 // if this is a synchronous transaction, wait for it to take effect 1772 // before returning. 1773 if (flags & eSynchronous) { 1774 mTransactionPending = true; 1775 } 1776 if (flags & eAnimation) { 1777 mAnimTransactionPending = true; 1778 } 1779 while (mTransactionPending) { 1780 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1781 if (CC_UNLIKELY(err != NO_ERROR)) { 1782 // just in case something goes wrong in SF, return to the 1783 // called after a few seconds. 1784 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!"); 1785 mTransactionPending = false; 1786 break; 1787 } 1788 } 1789 } 1790} 1791 1792uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 1793{ 1794 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token); 1795 if (dpyIdx < 0) 1796 return 0; 1797 1798 uint32_t flags = 0; 1799 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx)); 1800 if (disp.isValid()) { 1801 const uint32_t what = s.what; 1802 if (what & DisplayState::eSurfaceChanged) { 1803 if (disp.surface->asBinder() != s.surface->asBinder()) { 1804 disp.surface = s.surface; 1805 flags |= eDisplayTransactionNeeded; 1806 } 1807 } 1808 if (what & DisplayState::eLayerStackChanged) { 1809 if (disp.layerStack != s.layerStack) { 1810 disp.layerStack = s.layerStack; 1811 flags |= eDisplayTransactionNeeded; 1812 } 1813 } 1814 if (what & DisplayState::eDisplayProjectionChanged) { 1815 if (disp.orientation != s.orientation) { 1816 disp.orientation = s.orientation; 1817 flags |= eDisplayTransactionNeeded; 1818 } 1819 if (disp.frame != s.frame) { 1820 disp.frame = s.frame; 1821 flags |= eDisplayTransactionNeeded; 1822 } 1823 if (disp.viewport != s.viewport) { 1824 disp.viewport = s.viewport; 1825 flags |= eDisplayTransactionNeeded; 1826 } 1827 } 1828 } 1829 return flags; 1830} 1831 1832uint32_t SurfaceFlinger::setClientStateLocked( 1833 const sp<Client>& client, 1834 const layer_state_t& s) 1835{ 1836 uint32_t flags = 0; 1837 sp<Layer> layer(client->getLayerUser(s.surface)); 1838 if (layer != 0) { 1839 const uint32_t what = s.what; 1840 if (what & layer_state_t::ePositionChanged) { 1841 if (layer->setPosition(s.x, s.y)) 1842 flags |= eTraversalNeeded; 1843 } 1844 if (what & layer_state_t::eLayerChanged) { 1845 // NOTE: index needs to be calculated before we update the state 1846 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1847 if (layer->setLayer(s.z)) { 1848 mCurrentState.layersSortedByZ.removeAt(idx); 1849 mCurrentState.layersSortedByZ.add(layer); 1850 // we need traversal (state changed) 1851 // AND transaction (list changed) 1852 flags |= eTransactionNeeded|eTraversalNeeded; 1853 } 1854 } 1855 if (what & layer_state_t::eSizeChanged) { 1856 if (layer->setSize(s.w, s.h)) { 1857 flags |= eTraversalNeeded; 1858 } 1859 } 1860 if (what & layer_state_t::eAlphaChanged) { 1861 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1862 flags |= eTraversalNeeded; 1863 } 1864 if (what & layer_state_t::eMatrixChanged) { 1865 if (layer->setMatrix(s.matrix)) 1866 flags |= eTraversalNeeded; 1867 } 1868 if (what & layer_state_t::eTransparentRegionChanged) { 1869 if (layer->setTransparentRegionHint(s.transparentRegion)) 1870 flags |= eTraversalNeeded; 1871 } 1872 if (what & layer_state_t::eVisibilityChanged) { 1873 if (layer->setFlags(s.flags, s.mask)) 1874 flags |= eTraversalNeeded; 1875 } 1876 if (what & layer_state_t::eCropChanged) { 1877 if (layer->setCrop(s.crop)) 1878 flags |= eTraversalNeeded; 1879 } 1880 if (what & layer_state_t::eLayerStackChanged) { 1881 // NOTE: index needs to be calculated before we update the state 1882 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1883 if (layer->setLayerStack(s.layerStack)) { 1884 mCurrentState.layersSortedByZ.removeAt(idx); 1885 mCurrentState.layersSortedByZ.add(layer); 1886 // we need traversal (state changed) 1887 // AND transaction (list changed) 1888 flags |= eTransactionNeeded|eTraversalNeeded; 1889 } 1890 } 1891 } 1892 return flags; 1893} 1894 1895status_t SurfaceFlinger::createLayer( 1896 const String8& name, 1897 const sp<Client>& client, 1898 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, 1899 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp) 1900{ 1901 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 1902 if (int32_t(w|h) < 0) { 1903 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 1904 int(w), int(h)); 1905 return BAD_VALUE; 1906 } 1907 1908 status_t result = NO_ERROR; 1909 1910 sp<Layer> layer; 1911 1912 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 1913 case ISurfaceComposerClient::eFXSurfaceNormal: 1914 result = createNormalLayer(client, 1915 name, w, h, flags, format, 1916 handle, gbp, &layer); 1917 break; 1918 case ISurfaceComposerClient::eFXSurfaceDim: 1919 result = createDimLayer(client, 1920 name, w, h, flags, 1921 handle, gbp, &layer); 1922 break; 1923 default: 1924 result = BAD_VALUE; 1925 break; 1926 } 1927 1928 if (result == NO_ERROR) { 1929 addClientLayer(client, *handle, *gbp, layer); 1930 setTransactionFlags(eTransactionNeeded); 1931 } 1932 return result; 1933} 1934 1935status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client, 1936 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format, 1937 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) 1938{ 1939 // initialize the surfaces 1940 switch (format) { 1941 case PIXEL_FORMAT_TRANSPARENT: 1942 case PIXEL_FORMAT_TRANSLUCENT: 1943 format = PIXEL_FORMAT_RGBA_8888; 1944 break; 1945 case PIXEL_FORMAT_OPAQUE: 1946#ifdef NO_RGBX_8888 1947 format = PIXEL_FORMAT_RGB_565; 1948#else 1949 format = PIXEL_FORMAT_RGBX_8888; 1950#endif 1951 break; 1952 } 1953 1954#ifdef NO_RGBX_8888 1955 if (format == PIXEL_FORMAT_RGBX_8888) 1956 format = PIXEL_FORMAT_RGBA_8888; 1957#endif 1958 1959 *outLayer = new Layer(this, client, name, w, h, flags); 1960 status_t err = (*outLayer)->setBuffers(w, h, format, flags); 1961 if (err == NO_ERROR) { 1962 *handle = (*outLayer)->getHandle(); 1963 *gbp = (*outLayer)->getBufferQueue(); 1964 } 1965 1966 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err)); 1967 return err; 1968} 1969 1970status_t SurfaceFlinger::createDimLayer(const sp<Client>& client, 1971 const String8& name, uint32_t w, uint32_t h, uint32_t flags, 1972 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) 1973{ 1974 *outLayer = new LayerDim(this, client, name, w, h, flags); 1975 *handle = (*outLayer)->getHandle(); 1976 *gbp = (*outLayer)->getBufferQueue(); 1977 return NO_ERROR; 1978} 1979 1980status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle) 1981{ 1982 // called by the window manager when it wants to remove a Layer 1983 status_t err = NO_ERROR; 1984 sp<Layer> l(client->getLayerUser(handle)); 1985 if (l != NULL) { 1986 err = removeLayer(l); 1987 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1988 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1989 } 1990 return err; 1991} 1992 1993status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer) 1994{ 1995 // called by ~LayerCleaner() when all references to the IBinder (handle) 1996 // are gone 1997 status_t err = NO_ERROR; 1998 sp<Layer> l(layer.promote()); 1999 if (l != NULL) { 2000 err = removeLayer(l); 2001 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 2002 "error removing layer=%p (%s)", l.get(), strerror(-err)); 2003 } 2004 return err; 2005} 2006 2007// --------------------------------------------------------------------------- 2008 2009void SurfaceFlinger::onInitializeDisplays() { 2010 // reset screen orientation and use primary layer stack 2011 Vector<ComposerState> state; 2012 Vector<DisplayState> displays; 2013 DisplayState d; 2014 d.what = DisplayState::eDisplayProjectionChanged | 2015 DisplayState::eLayerStackChanged; 2016 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]; 2017 d.layerStack = 0; 2018 d.orientation = DisplayState::eOrientationDefault; 2019 d.frame.makeInvalid(); 2020 d.viewport.makeInvalid(); 2021 displays.add(d); 2022 setTransactionState(state, displays, 0); 2023 onScreenAcquired(getDefaultDisplayDevice()); 2024 2025 const nsecs_t period = 2026 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); 2027 mAnimFrameTracker.setDisplayRefreshPeriod(period); 2028} 2029 2030void SurfaceFlinger::initializeDisplays() { 2031 class MessageScreenInitialized : public MessageBase { 2032 SurfaceFlinger* flinger; 2033 public: 2034 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } 2035 virtual bool handler() { 2036 flinger->onInitializeDisplays(); 2037 return true; 2038 } 2039 }; 2040 sp<MessageBase> msg = new MessageScreenInitialized(this); 2041 postMessageAsync(msg); // we may be called from main thread, use async message 2042} 2043 2044 2045void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) { 2046 ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this); 2047 if (hw->isScreenAcquired()) { 2048 // this is expected, e.g. when power manager wakes up during boot 2049 ALOGD(" screen was previously acquired"); 2050 return; 2051 } 2052 2053 hw->acquireScreen(); 2054 int32_t type = hw->getDisplayType(); 2055 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 2056 // built-in display, tell the HWC 2057 getHwComposer().acquire(type); 2058 2059 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2060 // FIXME: eventthread only knows about the main display right now 2061 mEventThread->onScreenAcquired(); 2062 2063 resyncToHardwareVsync(true); 2064 } 2065 } 2066 mVisibleRegionsDirty = true; 2067 repaintEverything(); 2068} 2069 2070void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) { 2071 ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this); 2072 if (!hw->isScreenAcquired()) { 2073 ALOGD(" screen was previously released"); 2074 return; 2075 } 2076 2077 hw->releaseScreen(); 2078 int32_t type = hw->getDisplayType(); 2079 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 2080 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2081 disableHardwareVsync(true); // also cancels any in-progress resync 2082 2083 // FIXME: eventthread only knows about the main display right now 2084 mEventThread->onScreenReleased(); 2085 } 2086 2087 // built-in display, tell the HWC 2088 getHwComposer().release(type); 2089 } 2090 mVisibleRegionsDirty = true; 2091 // from this point on, SF will stop drawing on this display 2092} 2093 2094void SurfaceFlinger::unblank(const sp<IBinder>& display) { 2095 class MessageScreenAcquired : public MessageBase { 2096 SurfaceFlinger& mFlinger; 2097 sp<IBinder> mDisplay; 2098 public: 2099 MessageScreenAcquired(SurfaceFlinger& flinger, 2100 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { } 2101 virtual bool handler() { 2102 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2103 if (hw == NULL) { 2104 ALOGE("Attempt to unblank null display %p", mDisplay.get()); 2105 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 2106 ALOGW("Attempt to unblank virtual display"); 2107 } else { 2108 mFlinger.onScreenAcquired(hw); 2109 } 2110 return true; 2111 } 2112 }; 2113 sp<MessageBase> msg = new MessageScreenAcquired(*this, display); 2114 postMessageSync(msg); 2115} 2116 2117void SurfaceFlinger::blank(const sp<IBinder>& display) { 2118 class MessageScreenReleased : public MessageBase { 2119 SurfaceFlinger& mFlinger; 2120 sp<IBinder> mDisplay; 2121 public: 2122 MessageScreenReleased(SurfaceFlinger& flinger, 2123 const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { } 2124 virtual bool handler() { 2125 const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2126 if (hw == NULL) { 2127 ALOGE("Attempt to blank null display %p", mDisplay.get()); 2128 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 2129 ALOGW("Attempt to blank virtual display"); 2130 } else { 2131 mFlinger.onScreenReleased(hw); 2132 } 2133 return true; 2134 } 2135 }; 2136 sp<MessageBase> msg = new MessageScreenReleased(*this, display); 2137 postMessageSync(msg); 2138} 2139 2140// --------------------------------------------------------------------------- 2141 2142status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 2143{ 2144 String8 result; 2145 2146 IPCThreadState* ipc = IPCThreadState::self(); 2147 const int pid = ipc->getCallingPid(); 2148 const int uid = ipc->getCallingUid(); 2149 if ((uid != AID_SHELL) && 2150 !PermissionCache::checkPermission(sDump, pid, uid)) { 2151 result.appendFormat("Permission Denial: " 2152 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid); 2153 } else { 2154 // Try to get the main lock, but don't insist if we can't 2155 // (this would indicate SF is stuck, but we want to be able to 2156 // print something in dumpsys). 2157 int retry = 3; 2158 while (mStateLock.tryLock()<0 && --retry>=0) { 2159 usleep(1000000); 2160 } 2161 const bool locked(retry >= 0); 2162 if (!locked) { 2163 result.append( 2164 "SurfaceFlinger appears to be unresponsive, " 2165 "dumping anyways (no locks held)\n"); 2166 } 2167 2168 bool dumpAll = true; 2169 size_t index = 0; 2170 size_t numArgs = args.size(); 2171 if (numArgs) { 2172 if ((index < numArgs) && 2173 (args[index] == String16("--list"))) { 2174 index++; 2175 listLayersLocked(args, index, result); 2176 dumpAll = false; 2177 } 2178 2179 if ((index < numArgs) && 2180 (args[index] == String16("--latency"))) { 2181 index++; 2182 dumpStatsLocked(args, index, result); 2183 dumpAll = false; 2184 } 2185 2186 if ((index < numArgs) && 2187 (args[index] == String16("--latency-clear"))) { 2188 index++; 2189 clearStatsLocked(args, index, result); 2190 dumpAll = false; 2191 } 2192 } 2193 2194 if (dumpAll) { 2195 dumpAllLocked(args, index, result); 2196 } 2197 2198 if (locked) { 2199 mStateLock.unlock(); 2200 } 2201 } 2202 write(fd, result.string(), result.size()); 2203 return NO_ERROR; 2204} 2205 2206void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 2207 String8& result) const 2208{ 2209 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2210 const size_t count = currentLayers.size(); 2211 for (size_t i=0 ; i<count ; i++) { 2212 const sp<Layer>& layer(currentLayers[i]); 2213 result.appendFormat("%s\n", layer->getName().string()); 2214 } 2215} 2216 2217void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 2218 String8& result) const 2219{ 2220 String8 name; 2221 if (index < args.size()) { 2222 name = String8(args[index]); 2223 index++; 2224 } 2225 2226 const nsecs_t period = 2227 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); 2228 result.appendFormat("%" PRId64 "\n", period); 2229 2230 if (name.isEmpty()) { 2231 mAnimFrameTracker.dump(result); 2232 } else { 2233 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2234 const size_t count = currentLayers.size(); 2235 for (size_t i=0 ; i<count ; i++) { 2236 const sp<Layer>& layer(currentLayers[i]); 2237 if (name == layer->getName()) { 2238 layer->dumpStats(result); 2239 } 2240 } 2241 } 2242} 2243 2244void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 2245 String8& result) 2246{ 2247 String8 name; 2248 if (index < args.size()) { 2249 name = String8(args[index]); 2250 index++; 2251 } 2252 2253 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2254 const size_t count = currentLayers.size(); 2255 for (size_t i=0 ; i<count ; i++) { 2256 const sp<Layer>& layer(currentLayers[i]); 2257 if (name.isEmpty() || (name == layer->getName())) { 2258 layer->clearStats(); 2259 } 2260 } 2261 2262 mAnimFrameTracker.clear(); 2263} 2264 2265// This should only be called from the main thread. Otherwise it would need 2266// the lock and should use mCurrentState rather than mDrawingState. 2267void SurfaceFlinger::logFrameStats() { 2268 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ; 2269 const size_t count = drawingLayers.size(); 2270 for (size_t i=0 ; i<count ; i++) { 2271 const sp<Layer>& layer(drawingLayers[i]); 2272 layer->logFrameStats(); 2273 } 2274 2275 mAnimFrameTracker.logAndResetStats(String8("<win-anim>")); 2276} 2277 2278/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result) 2279{ 2280 static const char* config = 2281 " [sf" 2282#ifdef NO_RGBX_8888 2283 " NO_RGBX_8888" 2284#endif 2285#ifdef HAS_CONTEXT_PRIORITY 2286 " HAS_CONTEXT_PRIORITY" 2287#endif 2288#ifdef NEVER_DEFAULT_TO_ASYNC_MODE 2289 " NEVER_DEFAULT_TO_ASYNC_MODE" 2290#endif 2291#ifdef TARGET_DISABLE_TRIPLE_BUFFERING 2292 " TARGET_DISABLE_TRIPLE_BUFFERING" 2293#endif 2294 "]"; 2295 result.append(config); 2296} 2297 2298void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index, 2299 String8& result) const 2300{ 2301 bool colorize = false; 2302 if (index < args.size() 2303 && (args[index] == String16("--color"))) { 2304 colorize = true; 2305 index++; 2306 } 2307 2308 Colorizer colorizer(colorize); 2309 2310 // figure out if we're stuck somewhere 2311 const nsecs_t now = systemTime(); 2312 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 2313 const nsecs_t inTransaction(mDebugInTransaction); 2314 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 2315 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 2316 2317 /* 2318 * Dump library configuration. 2319 */ 2320 2321 colorizer.bold(result); 2322 result.append("Build configuration:"); 2323 colorizer.reset(result); 2324 appendSfConfigString(result); 2325 appendUiConfigString(result); 2326 appendGuiConfigString(result); 2327 result.append("\n"); 2328 2329 colorizer.bold(result); 2330 result.append("Sync configuration: "); 2331 colorizer.reset(result); 2332 result.append(SyncFeatures::getInstance().toString()); 2333 result.append("\n"); 2334 2335 /* 2336 * Dump the visible layer list 2337 */ 2338 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2339 const size_t count = currentLayers.size(); 2340 colorizer.bold(result); 2341 result.appendFormat("Visible layers (count = %zu)\n", count); 2342 colorizer.reset(result); 2343 for (size_t i=0 ; i<count ; i++) { 2344 const sp<Layer>& layer(currentLayers[i]); 2345 layer->dump(result, colorizer); 2346 } 2347 2348 /* 2349 * Dump Display state 2350 */ 2351 2352 colorizer.bold(result); 2353 result.appendFormat("Displays (%zu entries)\n", mDisplays.size()); 2354 colorizer.reset(result); 2355 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 2356 const sp<const DisplayDevice>& hw(mDisplays[dpy]); 2357 hw->dump(result); 2358 } 2359 2360 /* 2361 * Dump SurfaceFlinger global state 2362 */ 2363 2364 colorizer.bold(result); 2365 result.append("SurfaceFlinger global state:\n"); 2366 colorizer.reset(result); 2367 2368 HWComposer& hwc(getHwComposer()); 2369 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2370 2371 colorizer.bold(result); 2372 result.appendFormat("EGL implementation : %s\n", 2373 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION)); 2374 colorizer.reset(result); 2375 result.appendFormat("%s\n", 2376 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS)); 2377 2378 mRenderEngine->dump(result); 2379 2380 hw->undefinedRegion.dump(result, "undefinedRegion"); 2381 result.appendFormat(" orientation=%d, canDraw=%d\n", 2382 hw->getOrientation(), hw->canDraw()); 2383 result.appendFormat( 2384 " last eglSwapBuffers() time: %f us\n" 2385 " last transaction time : %f us\n" 2386 " transaction-flags : %08x\n" 2387 " refresh-rate : %f fps\n" 2388 " x-dpi : %f\n" 2389 " y-dpi : %f\n" 2390 " gpu_to_cpu_unsupported : %d\n" 2391 , 2392 mLastSwapBufferTime/1000.0, 2393 mLastTransactionTime/1000.0, 2394 mTransactionFlags, 2395 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY), 2396 hwc.getDpiX(HWC_DISPLAY_PRIMARY), 2397 hwc.getDpiY(HWC_DISPLAY_PRIMARY), 2398 !mGpuToCpuSupported); 2399 2400 result.appendFormat(" eglSwapBuffers time: %f us\n", 2401 inSwapBuffersDuration/1000.0); 2402 2403 result.appendFormat(" transaction time: %f us\n", 2404 inTransactionDuration/1000.0); 2405 2406 /* 2407 * VSYNC state 2408 */ 2409 mEventThread->dump(result); 2410 2411 /* 2412 * Dump HWComposer state 2413 */ 2414 colorizer.bold(result); 2415 result.append("h/w composer state:\n"); 2416 colorizer.reset(result); 2417 result.appendFormat(" h/w composer %s and %s\n", 2418 hwc.initCheck()==NO_ERROR ? "present" : "not present", 2419 (mDebugDisableHWC || mDebugRegion || mDaltonize) ? "disabled" : "enabled"); 2420 hwc.dump(result); 2421 2422 /* 2423 * Dump gralloc state 2424 */ 2425 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 2426 alloc.dump(result); 2427} 2428 2429const Vector< sp<Layer> >& 2430SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) { 2431 // Note: mStateLock is held here 2432 wp<IBinder> dpy; 2433 for (size_t i=0 ; i<mDisplays.size() ; i++) { 2434 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) { 2435 dpy = mDisplays.keyAt(i); 2436 break; 2437 } 2438 } 2439 if (dpy == NULL) { 2440 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id); 2441 // Just use the primary display so we have something to return 2442 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY); 2443 } 2444 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ(); 2445} 2446 2447bool SurfaceFlinger::startDdmConnection() 2448{ 2449 void* libddmconnection_dso = 2450 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); 2451 if (!libddmconnection_dso) { 2452 return false; 2453 } 2454 void (*DdmConnection_start)(const char* name); 2455 DdmConnection_start = 2456 (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start"); 2457 if (!DdmConnection_start) { 2458 dlclose(libddmconnection_dso); 2459 return false; 2460 } 2461 (*DdmConnection_start)(getServiceName()); 2462 return true; 2463} 2464 2465status_t SurfaceFlinger::onTransact( 2466 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2467{ 2468 switch (code) { 2469 case CREATE_CONNECTION: 2470 case CREATE_DISPLAY: 2471 case SET_TRANSACTION_STATE: 2472 case BOOT_FINISHED: 2473 case BLANK: 2474 case UNBLANK: 2475 { 2476 // codes that require permission check 2477 IPCThreadState* ipc = IPCThreadState::self(); 2478 const int pid = ipc->getCallingPid(); 2479 const int uid = ipc->getCallingUid(); 2480 if ((uid != AID_GRAPHICS) && 2481 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 2482 ALOGE("Permission Denial: " 2483 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2484 return PERMISSION_DENIED; 2485 } 2486 break; 2487 } 2488 case CAPTURE_SCREEN: 2489 { 2490 // codes that require permission check 2491 IPCThreadState* ipc = IPCThreadState::self(); 2492 const int pid = ipc->getCallingPid(); 2493 const int uid = ipc->getCallingUid(); 2494 if ((uid != AID_GRAPHICS) && 2495 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 2496 ALOGE("Permission Denial: " 2497 "can't read framebuffer pid=%d, uid=%d", pid, uid); 2498 return PERMISSION_DENIED; 2499 } 2500 break; 2501 } 2502 } 2503 2504 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 2505 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 2506 CHECK_INTERFACE(ISurfaceComposer, data, reply); 2507 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 2508 IPCThreadState* ipc = IPCThreadState::self(); 2509 const int pid = ipc->getCallingPid(); 2510 const int uid = ipc->getCallingUid(); 2511 ALOGE("Permission Denial: " 2512 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 2513 return PERMISSION_DENIED; 2514 } 2515 int n; 2516 switch (code) { 2517 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 2518 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 2519 return NO_ERROR; 2520 case 1002: // SHOW_UPDATES 2521 n = data.readInt32(); 2522 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 2523 invalidateHwcGeometry(); 2524 repaintEverything(); 2525 return NO_ERROR; 2526 case 1004:{ // repaint everything 2527 repaintEverything(); 2528 return NO_ERROR; 2529 } 2530 case 1005:{ // force transaction 2531 setTransactionFlags( 2532 eTransactionNeeded| 2533 eDisplayTransactionNeeded| 2534 eTraversalNeeded); 2535 return NO_ERROR; 2536 } 2537 case 1006:{ // send empty update 2538 signalRefresh(); 2539 return NO_ERROR; 2540 } 2541 case 1008: // toggle use of hw composer 2542 n = data.readInt32(); 2543 mDebugDisableHWC = n ? 1 : 0; 2544 invalidateHwcGeometry(); 2545 repaintEverything(); 2546 return NO_ERROR; 2547 case 1009: // toggle use of transform hint 2548 n = data.readInt32(); 2549 mDebugDisableTransformHint = n ? 1 : 0; 2550 invalidateHwcGeometry(); 2551 repaintEverything(); 2552 return NO_ERROR; 2553 case 1010: // interrogate. 2554 reply->writeInt32(0); 2555 reply->writeInt32(0); 2556 reply->writeInt32(mDebugRegion); 2557 reply->writeInt32(0); 2558 reply->writeInt32(mDebugDisableHWC); 2559 return NO_ERROR; 2560 case 1013: { 2561 Mutex::Autolock _l(mStateLock); 2562 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 2563 reply->writeInt32(hw->getPageFlipCount()); 2564 return NO_ERROR; 2565 } 2566 case 1014: { 2567 // daltonize 2568 n = data.readInt32(); 2569 switch (n % 10) { 2570 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break; 2571 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break; 2572 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break; 2573 } 2574 if (n >= 10) { 2575 mDaltonizer.setMode(Daltonizer::correction); 2576 } else { 2577 mDaltonizer.setMode(Daltonizer::simulation); 2578 } 2579 mDaltonize = n > 0; 2580 invalidateHwcGeometry(); 2581 repaintEverything(); 2582 } 2583 return NO_ERROR; 2584 } 2585 } 2586 return err; 2587} 2588 2589void SurfaceFlinger::repaintEverything() { 2590 android_atomic_or(1, &mRepaintEverything); 2591 signalTransaction(); 2592} 2593 2594// --------------------------------------------------------------------------- 2595// Capture screen into an IGraphiBufferProducer 2596// --------------------------------------------------------------------------- 2597 2598/* The code below is here to handle b/8734824 2599 * 2600 * We create a IGraphicBufferProducer wrapper that forwards all calls 2601 * to the calling binder thread, where they are executed. This allows 2602 * the calling thread to be reused (on the other side) and not 2603 * depend on having "enough" binder threads to handle the requests. 2604 * 2605 */ 2606 2607class GraphicProducerWrapper : public BBinder, public MessageHandler { 2608 sp<IGraphicBufferProducer> impl; 2609 sp<Looper> looper; 2610 status_t result; 2611 bool exitPending; 2612 bool exitRequested; 2613 mutable Barrier barrier; 2614 volatile int32_t memoryBarrier; 2615 uint32_t code; 2616 Parcel const* data; 2617 Parcel* reply; 2618 2619 enum { 2620 MSG_API_CALL, 2621 MSG_EXIT 2622 }; 2623 2624 /* 2625 * this is called by our "fake" BpGraphicBufferProducer. We package the 2626 * data and reply Parcel and forward them to the calling thread. 2627 */ 2628 virtual status_t transact(uint32_t code, 2629 const Parcel& data, Parcel* reply, uint32_t flags) { 2630 this->code = code; 2631 this->data = &data; 2632 this->reply = reply; 2633 android_atomic_acquire_store(0, &memoryBarrier); 2634 if (exitPending) { 2635 // if we've exited, we run the message synchronously right here 2636 handleMessage(Message(MSG_API_CALL)); 2637 } else { 2638 barrier.close(); 2639 looper->sendMessage(this, Message(MSG_API_CALL)); 2640 barrier.wait(); 2641 } 2642 return result; 2643 } 2644 2645 /* 2646 * here we run on the binder calling thread. All we've got to do is 2647 * call the real BpGraphicBufferProducer. 2648 */ 2649 virtual void handleMessage(const Message& message) { 2650 android_atomic_release_load(&memoryBarrier); 2651 if (message.what == MSG_API_CALL) { 2652 result = impl->asBinder()->transact(code, data[0], reply); 2653 barrier.open(); 2654 } else if (message.what == MSG_EXIT) { 2655 exitRequested = true; 2656 } 2657 } 2658 2659public: 2660 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) : 2661 impl(impl), looper(new Looper(true)), result(NO_ERROR), 2662 exitPending(false), exitRequested(false) { 2663 } 2664 2665 status_t waitForResponse() { 2666 do { 2667 looper->pollOnce(-1); 2668 } while (!exitRequested); 2669 return result; 2670 } 2671 2672 void exit(status_t result) { 2673 this->result = result; 2674 exitPending = true; 2675 looper->sendMessage(this, Message(MSG_EXIT)); 2676 } 2677}; 2678 2679 2680status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, 2681 const sp<IGraphicBufferProducer>& producer, 2682 uint32_t reqWidth, uint32_t reqHeight, 2683 uint32_t minLayerZ, uint32_t maxLayerZ) { 2684 2685 if (CC_UNLIKELY(display == 0)) 2686 return BAD_VALUE; 2687 2688 if (CC_UNLIKELY(producer == 0)) 2689 return BAD_VALUE; 2690 2691 // if we have secure windows on this display, never allow the screen capture 2692 // unless the producer interface is local (i.e.: we can take a screenshot for 2693 // ourselves). 2694 if (!producer->asBinder()->localBinder()) { 2695 Mutex::Autolock _l(mStateLock); 2696 sp<const DisplayDevice> hw(getDisplayDevice(display)); 2697 if (hw->getSecureLayerVisible()) { 2698 ALOGW("FB is protected: PERMISSION_DENIED"); 2699 return PERMISSION_DENIED; 2700 } 2701 } 2702 2703 class MessageCaptureScreen : public MessageBase { 2704 SurfaceFlinger* flinger; 2705 sp<IBinder> display; 2706 sp<IGraphicBufferProducer> producer; 2707 uint32_t reqWidth, reqHeight; 2708 uint32_t minLayerZ,maxLayerZ; 2709 status_t result; 2710 public: 2711 MessageCaptureScreen(SurfaceFlinger* flinger, 2712 const sp<IBinder>& display, 2713 const sp<IGraphicBufferProducer>& producer, 2714 uint32_t reqWidth, uint32_t reqHeight, 2715 uint32_t minLayerZ, uint32_t maxLayerZ) 2716 : flinger(flinger), display(display), producer(producer), 2717 reqWidth(reqWidth), reqHeight(reqHeight), 2718 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2719 result(PERMISSION_DENIED) 2720 { 2721 } 2722 status_t getResult() const { 2723 return result; 2724 } 2725 virtual bool handler() { 2726 Mutex::Autolock _l(flinger->mStateLock); 2727 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display)); 2728 result = flinger->captureScreenImplLocked(hw, 2729 producer, reqWidth, reqHeight, minLayerZ, maxLayerZ); 2730 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result); 2731 return true; 2732 } 2733 }; 2734 2735 // make sure to process transactions before screenshots -- a transaction 2736 // might already be pending but scheduled for VSYNC; this guarantees we 2737 // will handle it before the screenshot. When VSYNC finally arrives 2738 // the scheduled transaction will be a no-op. If no transactions are 2739 // scheduled at this time, this will end-up being a no-op as well. 2740 mEventQueue.invalidateTransactionNow(); 2741 2742 // this creates a "fake" BBinder which will serve as a "fake" remote 2743 // binder to receive the marshaled calls and forward them to the 2744 // real remote (a BpGraphicBufferProducer) 2745 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer); 2746 2747 // the asInterface() call below creates our "fake" BpGraphicBufferProducer 2748 // which does the marshaling work forwards to our "fake remote" above. 2749 sp<MessageBase> msg = new MessageCaptureScreen(this, 2750 display, IGraphicBufferProducer::asInterface( wrapper ), 2751 reqWidth, reqHeight, minLayerZ, maxLayerZ); 2752 2753 status_t res = postMessageAsync(msg); 2754 if (res == NO_ERROR) { 2755 res = wrapper->waitForResponse(); 2756 } 2757 return res; 2758} 2759 2760 2761void SurfaceFlinger::renderScreenImplLocked( 2762 const sp<const DisplayDevice>& hw, 2763 uint32_t reqWidth, uint32_t reqHeight, 2764 uint32_t minLayerZ, uint32_t maxLayerZ, 2765 bool yswap) 2766{ 2767 ATRACE_CALL(); 2768 RenderEngine& engine(getRenderEngine()); 2769 2770 // get screen geometry 2771 const uint32_t hw_w = hw->getWidth(); 2772 const uint32_t hw_h = hw->getHeight(); 2773 const bool filtering = reqWidth != hw_w || reqWidth != hw_h; 2774 2775 // make sure to clear all GL error flags 2776 engine.checkErrors(); 2777 2778 // set-up our viewport 2779 engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap); 2780 engine.disableTexturing(); 2781 2782 // redraw the screen entirely... 2783 engine.clearWithColor(0, 0, 0, 1); 2784 2785 const LayerVector& layers( mDrawingState.layersSortedByZ ); 2786 const size_t count = layers.size(); 2787 for (size_t i=0 ; i<count ; ++i) { 2788 const sp<Layer>& layer(layers[i]); 2789 const Layer::State& state(layer->getDrawingState()); 2790 if (state.layerStack == hw->getLayerStack()) { 2791 if (state.z >= minLayerZ && state.z <= maxLayerZ) { 2792 if (layer->isVisible()) { 2793 if (filtering) layer->setFiltering(true); 2794 layer->draw(hw); 2795 if (filtering) layer->setFiltering(false); 2796 } 2797 } 2798 } 2799 } 2800 2801 // compositionComplete is needed for older driver 2802 hw->compositionComplete(); 2803 hw->setViewportAndProjection(); 2804} 2805 2806 2807status_t SurfaceFlinger::captureScreenImplLocked( 2808 const sp<const DisplayDevice>& hw, 2809 const sp<IGraphicBufferProducer>& producer, 2810 uint32_t reqWidth, uint32_t reqHeight, 2811 uint32_t minLayerZ, uint32_t maxLayerZ) 2812{ 2813 ATRACE_CALL(); 2814 2815 // get screen geometry 2816 const uint32_t hw_w = hw->getWidth(); 2817 const uint32_t hw_h = hw->getHeight(); 2818 2819 if ((reqWidth > hw_w) || (reqHeight > hw_h)) { 2820 ALOGE("size mismatch (%d, %d) > (%d, %d)", 2821 reqWidth, reqHeight, hw_w, hw_h); 2822 return BAD_VALUE; 2823 } 2824 2825 reqWidth = (!reqWidth) ? hw_w : reqWidth; 2826 reqHeight = (!reqHeight) ? hw_h : reqHeight; 2827 2828 // create a surface (because we're a producer, and we need to 2829 // dequeue/queue a buffer) 2830 sp<Surface> sur = new Surface(producer, false); 2831 ANativeWindow* window = sur.get(); 2832 2833 status_t result = NO_ERROR; 2834 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) { 2835 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN | 2836 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; 2837 2838 int err = 0; 2839 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight); 2840 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); 2841 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888); 2842 err |= native_window_set_usage(window, usage); 2843 2844 if (err == NO_ERROR) { 2845 ANativeWindowBuffer* buffer; 2846 /* TODO: Once we have the sync framework everywhere this can use 2847 * server-side waits on the fence that dequeueBuffer returns. 2848 */ 2849 result = native_window_dequeue_buffer_and_wait(window, &buffer); 2850 if (result == NO_ERROR) { 2851 // create an EGLImage from the buffer so we can later 2852 // turn it into a texture 2853 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, 2854 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL); 2855 if (image != EGL_NO_IMAGE_KHR) { 2856 // this binds the given EGLImage as a framebuffer for the 2857 // duration of this scope. 2858 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image); 2859 if (imageBond.getStatus() == NO_ERROR) { 2860 // this will in fact render into our dequeued buffer 2861 // via an FBO, which means we didn't have to create 2862 // an EGLSurface and therefore we're not 2863 // dependent on the context's EGLConfig. 2864 renderScreenImplLocked(hw, reqWidth, reqHeight, 2865 minLayerZ, maxLayerZ, true); 2866 2867 // Create a sync point and wait on it, so we know the buffer is 2868 // ready before we pass it along. We can't trivially call glFlush(), 2869 // so we use a wait flag instead. 2870 // TODO: pass a sync fd to queueBuffer() and let the consumer wait. 2871 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL); 2872 if (sync != EGL_NO_SYNC_KHR) { 2873 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync, 2874 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/); 2875 EGLint eglErr = eglGetError(); 2876 eglDestroySyncKHR(mEGLDisplay, sync); 2877 if (result == EGL_TIMEOUT_EXPIRED_KHR) { 2878 ALOGW("captureScreen: fence wait timed out"); 2879 } else { 2880 ALOGW_IF(eglErr != EGL_SUCCESS, 2881 "captureScreen: error waiting on EGL fence: %#x", eglErr); 2882 } 2883 } else { 2884 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError()); 2885 // not fatal 2886 } 2887 2888 if (DEBUG_SCREENSHOTS) { 2889 uint32_t* pixels = new uint32_t[reqWidth*reqHeight]; 2890 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels); 2891 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, 2892 hw, minLayerZ, maxLayerZ); 2893 delete [] pixels; 2894 } 2895 2896 } else { 2897 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot"); 2898 result = INVALID_OPERATION; 2899 } 2900 // destroy our image 2901 eglDestroyImageKHR(mEGLDisplay, image); 2902 } else { 2903 result = BAD_VALUE; 2904 } 2905 window->queueBuffer(window, buffer, -1); 2906 } 2907 } else { 2908 result = BAD_VALUE; 2909 } 2910 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL); 2911 } 2912 2913 return result; 2914} 2915 2916void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr, 2917 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) { 2918 if (DEBUG_SCREENSHOTS) { 2919 for (size_t y=0 ; y<h ; y++) { 2920 uint32_t const * p = (uint32_t const *)vaddr + y*s; 2921 for (size_t x=0 ; x<w ; x++) { 2922 if (p[x] != 0xFF000000) return; 2923 } 2924 } 2925 ALOGE("*** we just took a black screenshot ***\n" 2926 "requested minz=%d, maxz=%d, layerStack=%d", 2927 minLayerZ, maxLayerZ, hw->getLayerStack()); 2928 const LayerVector& layers( mDrawingState.layersSortedByZ ); 2929 const size_t count = layers.size(); 2930 for (size_t i=0 ; i<count ; ++i) { 2931 const sp<Layer>& layer(layers[i]); 2932 const Layer::State& state(layer->getDrawingState()); 2933 const bool visible = (state.layerStack == hw->getLayerStack()) 2934 && (state.z >= minLayerZ && state.z <= maxLayerZ) 2935 && (layer->isVisible()); 2936 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x", 2937 visible ? '+' : '-', 2938 i, layer->getName().string(), state.layerStack, state.z, 2939 layer->isVisible(), state.flags, state.alpha); 2940 } 2941 } 2942} 2943 2944// --------------------------------------------------------------------------- 2945 2946SurfaceFlinger::LayerVector::LayerVector() { 2947} 2948 2949SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 2950 : SortedVector<sp<Layer> >(rhs) { 2951} 2952 2953int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 2954 const void* rhs) const 2955{ 2956 // sort layers per layer-stack, then by z-order and finally by sequence 2957 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs)); 2958 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs)); 2959 2960 uint32_t ls = l->getCurrentState().layerStack; 2961 uint32_t rs = r->getCurrentState().layerStack; 2962 if (ls != rs) 2963 return ls - rs; 2964 2965 uint32_t lz = l->getCurrentState().z; 2966 uint32_t rz = r->getCurrentState().z; 2967 if (lz != rz) 2968 return lz - rz; 2969 2970 return l->sequence - r->sequence; 2971} 2972 2973// --------------------------------------------------------------------------- 2974 2975SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() 2976 : type(DisplayDevice::DISPLAY_ID_INVALID) { 2977} 2978 2979SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type) 2980 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) { 2981 viewport.makeInvalid(); 2982 frame.makeInvalid(); 2983} 2984 2985// --------------------------------------------------------------------------- 2986 2987}; // namespace android 2988 2989 2990#if defined(__gl_h_) 2991#error "don't include gl/gl.h in this file" 2992#endif 2993 2994#if defined(__gl2_h_) 2995#error "don't include gl2/gl2.h in this file" 2996#endif 2997