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 LOG_NDEBUG 0 18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS 19 20 #include <stdint.h> 21 #include <sys/types.h> 22 #include <errno.h> 23 #include <math.h> 24 #include <dlfcn.h> 25 #include <inttypes.h> 26 #include <stdatomic.h> 27 28 #include <EGL/egl.h> 29 30 #include <cutils/log.h> 31 #include <cutils/properties.h> 32 33 #include <binder/IPCThreadState.h> 34 #include <binder/IServiceManager.h> 35 #include <binder/MemoryHeapBase.h> 36 #include <binder/PermissionCache.h> 37 38 #include <ui/DisplayInfo.h> 39 #include <ui/DisplayStatInfo.h> 40 41 #include <gui/BitTube.h> 42 #include <gui/BufferQueue.h> 43 #include <gui/GuiConfig.h> 44 #include <gui/IDisplayEventConnection.h> 45 #include <gui/Surface.h> 46 #include <gui/GraphicBufferAlloc.h> 47 48 #include <ui/GraphicBufferAllocator.h> 49 #include <ui/PixelFormat.h> 50 #include <ui/UiConfig.h> 51 52 #include <utils/misc.h> 53 #include <utils/String8.h> 54 #include <utils/String16.h> 55 #include <utils/StopWatch.h> 56 #include <utils/Timers.h> 57 #include <utils/Trace.h> 58 59 #include <private/android_filesystem_config.h> 60 #include <private/gui/SyncFeatures.h> 61 62 #include "Client.h" 63 #include "clz.h" 64 #include "Colorizer.h" 65 #include "DdmConnection.h" 66 #include "DisplayDevice.h" 67 #include "DispSync.h" 68 #include "EventControlThread.h" 69 #include "EventThread.h" 70 #include "Layer.h" 71 #include "LayerDim.h" 72 #include "SurfaceFlinger.h" 73 74 #include "DisplayHardware/FramebufferSurface.h" 75 #include "DisplayHardware/HWComposer.h" 76 #include "DisplayHardware/VirtualDisplaySurface.h" 77 78 #include "Effects/Daltonizer.h" 79 80 #include "RenderEngine/RenderEngine.h" 81 #include <cutils/compiler.h> 82 83 #define DISPLAY_COUNT 1 84 85 /* 86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all 87 * black pixels. 88 */ 89 #define DEBUG_SCREENSHOTS false 90 91 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name); 92 93 namespace android { 94 95 // This is the phase offset in nanoseconds of the software vsync event 96 // relative to the vsync event reported by HWComposer. The software vsync 97 // event is when SurfaceFlinger and Choreographer-based applications run each 98 // frame. 99 // 100 // This phase offset allows adjustment of the minimum latency from application 101 // wake-up (by Choregographer) time to the time at which the resulting window 102 // image is displayed. This value may be either positive (after the HW vsync) 103 // or negative (before the HW vsync). Setting it to 0 will result in a 104 // minimum latency of two vsync periods because the app and SurfaceFlinger 105 // will run just after the HW vsync. Setting it to a positive number will 106 // result in the minimum latency being: 107 // 108 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD)) 109 // 110 // Note that reducing this latency makes it more likely for the applications 111 // to not have their window content image ready in time. When this happens 112 // the latency will end up being an additional vsync period, and animations 113 // will hiccup. Therefore, this latency should be tuned somewhat 114 // conservatively (or at least with awareness of the trade-off being made). 115 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS; 116 117 // This is the phase offset at which SurfaceFlinger's composition runs. 118 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS; 119 120 // --------------------------------------------------------------------------- 121 122 const String16 sHardwareTest("android.permission.HARDWARE_TEST"); 123 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); 124 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER"); 125 const String16 sDump("android.permission.DUMP"); 126 127 // --------------------------------------------------------------------------- 128 129 SurfaceFlinger::SurfaceFlinger() 130 : BnSurfaceComposer(), 131 mTransactionFlags(0), 132 mTransactionPending(false), 133 mAnimTransactionPending(false), 134 mLayersRemoved(false), 135 mRepaintEverything(0), 136 mRenderEngine(NULL), 137 mBootTime(systemTime()), 138 mBuiltinDisplays(), 139 mVisibleRegionsDirty(false), 140 mGeometryInvalid(false), 141 mAnimCompositionPending(false), 142 mDebugRegion(0), 143 mDebugDDMS(0), 144 mDebugDisableHWC(0), 145 mDebugDisableTransformHint(0), 146 mDebugInSwapBuffers(0), 147 mLastSwapBufferTime(0), 148 mDebugInTransaction(0), 149 mLastTransactionTime(0), 150 mBootFinished(false), 151 mForceFullDamage(false), 152 mPrimaryDispSync("PrimaryDispSync"), 153 mPrimaryHWVsyncEnabled(false), 154 mHWVsyncAvailable(false), 155 mHasColorMatrix(false), 156 mHasPoweredOff(false), 157 mFrameBuckets(), 158 mTotalTime(0), 159 mLastSwapTime(0) 160 { 161 ALOGI("SurfaceFlinger is starting"); 162 163 // debugging stuff... 164 char value[PROPERTY_VALUE_MAX]; 165 166 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0"); 167 mGpuToCpuSupported = !atoi(value); 168 169 property_get("debug.sf.showupdates", value, "0"); 170 mDebugRegion = atoi(value); 171 172 property_get("debug.sf.ddms", value, "0"); 173 mDebugDDMS = atoi(value); 174 if (mDebugDDMS) { 175 if (!startDdmConnection()) { 176 // start failed, and DDMS debugging not enabled 177 mDebugDDMS = 0; 178 } 179 } 180 ALOGI_IF(mDebugRegion, "showupdates enabled"); 181 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled"); 182 183 property_get("debug.sf.disable_backpressure", value, "0"); 184 mPropagateBackpressure = !atoi(value); 185 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation"); 186 187 property_get("debug.sf.disable_hwc_vds", value, "0"); 188 mUseHwcVirtualDisplays = !atoi(value); 189 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays"); 190 } 191 192 void SurfaceFlinger::onFirstRef() 193 { 194 mEventQueue.init(this); 195 } 196 197 SurfaceFlinger::~SurfaceFlinger() 198 { 199 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); 200 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 201 eglTerminate(display); 202 } 203 204 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */) 205 { 206 // the window manager died on us. prepare its eulogy. 207 208 // restore initial conditions (default device unblank, etc) 209 initializeDisplays(); 210 211 // restart the boot-animation 212 startBootAnim(); 213 } 214 215 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 216 { 217 sp<ISurfaceComposerClient> bclient; 218 sp<Client> client(new Client(this)); 219 status_t err = client->initCheck(); 220 if (err == NO_ERROR) { 221 bclient = client; 222 } 223 return bclient; 224 } 225 226 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, 227 bool secure) 228 { 229 class DisplayToken : public BBinder { 230 sp<SurfaceFlinger> flinger; 231 virtual ~DisplayToken() { 232 // no more references, this display must be terminated 233 Mutex::Autolock _l(flinger->mStateLock); 234 flinger->mCurrentState.displays.removeItem(this); 235 flinger->setTransactionFlags(eDisplayTransactionNeeded); 236 } 237 public: 238 DisplayToken(const sp<SurfaceFlinger>& flinger) 239 : flinger(flinger) { 240 } 241 }; 242 243 sp<BBinder> token = new DisplayToken(this); 244 245 Mutex::Autolock _l(mStateLock); 246 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure); 247 info.displayName = displayName; 248 mCurrentState.displays.add(token, info); 249 250 return token; 251 } 252 253 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) { 254 Mutex::Autolock _l(mStateLock); 255 256 ssize_t idx = mCurrentState.displays.indexOfKey(display); 257 if (idx < 0) { 258 ALOGW("destroyDisplay: invalid display token"); 259 return; 260 } 261 262 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx)); 263 if (!info.isVirtualDisplay()) { 264 ALOGE("destroyDisplay called for non-virtual display"); 265 return; 266 } 267 268 mCurrentState.displays.removeItemsAt(idx); 269 setTransactionFlags(eDisplayTransactionNeeded); 270 } 271 272 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) { 273 ALOGV("createBuiltinDisplayLocked(%d)", type); 274 ALOGW_IF(mBuiltinDisplays[type], 275 "Overwriting display token for display type %d", type); 276 mBuiltinDisplays[type] = new BBinder(); 277 // All non-virtual displays are currently considered secure. 278 DisplayDeviceState info(type, true); 279 mCurrentState.displays.add(mBuiltinDisplays[type], info); 280 } 281 282 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) { 283 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 284 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id); 285 return NULL; 286 } 287 return mBuiltinDisplays[id]; 288 } 289 290 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() 291 { 292 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); 293 return gba; 294 } 295 296 void SurfaceFlinger::bootFinished() 297 { 298 const nsecs_t now = systemTime(); 299 const nsecs_t duration = now - mBootTime; 300 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 301 mBootFinished = true; 302 303 // wait patiently for the window manager death 304 const String16 name("window"); 305 sp<IBinder> window(defaultServiceManager()->getService(name)); 306 if (window != 0) { 307 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this)); 308 } 309 310 // stop boot animation 311 // formerly we would just kill the process, but we now ask it to exit so it 312 // can choose where to stop the animation. 313 property_set("service.bootanim.exit", "1"); 314 315 const int LOGTAG_SF_STOP_BOOTANIM = 60110; 316 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM, 317 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC))); 318 } 319 320 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) { 321 class MessageDestroyGLTexture : public MessageBase { 322 RenderEngine& engine; 323 uint32_t texture; 324 public: 325 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture) 326 : engine(engine), texture(texture) { 327 } 328 virtual bool handler() { 329 engine.deleteTextures(1, &texture); 330 return true; 331 } 332 }; 333 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture)); 334 } 335 336 class DispSyncSource : public VSyncSource, private DispSync::Callback { 337 public: 338 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync, 339 const char* name) : 340 mName(name), 341 mValue(0), 342 mTraceVsync(traceVsync), 343 mVsyncOnLabel(String8::format("VsyncOn-%s", name)), 344 mVsyncEventLabel(String8::format("VSYNC-%s", name)), 345 mDispSync(dispSync), 346 mCallbackMutex(), 347 mCallback(), 348 mVsyncMutex(), 349 mPhaseOffset(phaseOffset), 350 mEnabled(false) {} 351 352 virtual ~DispSyncSource() {} 353 354 virtual void setVSyncEnabled(bool enable) { 355 Mutex::Autolock lock(mVsyncMutex); 356 if (enable) { 357 status_t err = mDispSync->addEventListener(mName, mPhaseOffset, 358 static_cast<DispSync::Callback*>(this)); 359 if (err != NO_ERROR) { 360 ALOGE("error registering vsync callback: %s (%d)", 361 strerror(-err), err); 362 } 363 //ATRACE_INT(mVsyncOnLabel.string(), 1); 364 } else { 365 status_t err = mDispSync->removeEventListener( 366 static_cast<DispSync::Callback*>(this)); 367 if (err != NO_ERROR) { 368 ALOGE("error unregistering vsync callback: %s (%d)", 369 strerror(-err), err); 370 } 371 //ATRACE_INT(mVsyncOnLabel.string(), 0); 372 } 373 mEnabled = enable; 374 } 375 376 virtual void setCallback(const sp<VSyncSource::Callback>& callback) { 377 Mutex::Autolock lock(mCallbackMutex); 378 mCallback = callback; 379 } 380 381 virtual void setPhaseOffset(nsecs_t phaseOffset) { 382 Mutex::Autolock lock(mVsyncMutex); 383 384 // Normalize phaseOffset to [0, period) 385 auto period = mDispSync->getPeriod(); 386 phaseOffset %= period; 387 if (phaseOffset < 0) { 388 // If we're here, then phaseOffset is in (-period, 0). After this 389 // operation, it will be in (0, period) 390 phaseOffset += period; 391 } 392 mPhaseOffset = phaseOffset; 393 394 // If we're not enabled, we don't need to mess with the listeners 395 if (!mEnabled) { 396 return; 397 } 398 399 // Remove the listener with the old offset 400 status_t err = mDispSync->removeEventListener( 401 static_cast<DispSync::Callback*>(this)); 402 if (err != NO_ERROR) { 403 ALOGE("error unregistering vsync callback: %s (%d)", 404 strerror(-err), err); 405 } 406 407 // Add a listener with the new offset 408 err = mDispSync->addEventListener(mName, mPhaseOffset, 409 static_cast<DispSync::Callback*>(this)); 410 if (err != NO_ERROR) { 411 ALOGE("error registering vsync callback: %s (%d)", 412 strerror(-err), err); 413 } 414 } 415 416 private: 417 virtual void onDispSyncEvent(nsecs_t when) { 418 sp<VSyncSource::Callback> callback; 419 { 420 Mutex::Autolock lock(mCallbackMutex); 421 callback = mCallback; 422 423 if (mTraceVsync) { 424 mValue = (mValue + 1) % 2; 425 ATRACE_INT(mVsyncEventLabel.string(), mValue); 426 } 427 } 428 429 if (callback != NULL) { 430 callback->onVSyncEvent(when); 431 } 432 } 433 434 const char* const mName; 435 436 int mValue; 437 438 const bool mTraceVsync; 439 const String8 mVsyncOnLabel; 440 const String8 mVsyncEventLabel; 441 442 DispSync* mDispSync; 443 444 Mutex mCallbackMutex; // Protects the following 445 sp<VSyncSource::Callback> mCallback; 446 447 Mutex mVsyncMutex; // Protects the following 448 nsecs_t mPhaseOffset; 449 bool mEnabled; 450 }; 451 452 void SurfaceFlinger::init() { 453 ALOGI( "SurfaceFlinger's main thread ready to run. " 454 "Initializing graphics H/W..."); 455 456 { // Autolock scope 457 Mutex::Autolock _l(mStateLock); 458 459 // initialize EGL for the default display 460 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 461 eglInitialize(mEGLDisplay, NULL, NULL); 462 463 // start the EventThread 464 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync, 465 vsyncPhaseOffsetNs, true, "app"); 466 mEventThread = new EventThread(vsyncSrc, *this); 467 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync, 468 sfVsyncPhaseOffsetNs, true, "sf"); 469 mSFEventThread = new EventThread(sfVsyncSrc, *this); 470 mEventQueue.setEventThread(mSFEventThread); 471 472 // set SFEventThread to SCHED_FIFO to minimize jitter 473 struct sched_param param = {0}; 474 param.sched_priority = 1; 475 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, ¶m) != 0) { 476 ALOGE("Couldn't set SCHED_FIFO for SFEventThread"); 477 } 478 479 // Get a RenderEngine for the given display / config (can't fail) 480 mRenderEngine = RenderEngine::create(mEGLDisplay, 481 HAL_PIXEL_FORMAT_RGBA_8888); 482 } 483 484 // Drop the state lock while we initialize the hardware composer. We drop 485 // the lock because on creation, it will call back into SurfaceFlinger to 486 // initialize the primary display. 487 mHwc = new HWComposer(this); 488 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this)); 489 490 Mutex::Autolock _l(mStateLock); 491 492 // retrieve the EGL context that was selected/created 493 mEGLContext = mRenderEngine->getEGLContext(); 494 495 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT, 496 "couldn't create EGLContext"); 497 498 // make the GLContext current so that we can create textures when creating 499 // Layers (which may happens before we render something) 500 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext); 501 502 mEventControlThread = new EventControlThread(this); 503 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY); 504 505 // initialize our drawing state 506 mDrawingState = mCurrentState; 507 508 // set initial conditions (e.g. unblank default device) 509 initializeDisplays(); 510 511 mRenderEngine->primeCache(); 512 513 // start boot animation 514 startBootAnim(); 515 516 ALOGV("Done initializing"); 517 } 518 519 void SurfaceFlinger::startBootAnim() { 520 // start boot animation 521 property_set("service.bootanim.exit", "0"); 522 property_set("ctl.start", "bootanim"); 523 } 524 525 size_t SurfaceFlinger::getMaxTextureSize() const { 526 return mRenderEngine->getMaxTextureSize(); 527 } 528 529 size_t SurfaceFlinger::getMaxViewportDims() const { 530 return mRenderEngine->getMaxViewportDims(); 531 } 532 533 // ---------------------------------------------------------------------------- 534 535 bool SurfaceFlinger::authenticateSurfaceTexture( 536 const sp<IGraphicBufferProducer>& bufferProducer) const { 537 Mutex::Autolock _l(mStateLock); 538 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer)); 539 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0; 540 } 541 542 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display, 543 Vector<DisplayInfo>* configs) { 544 if ((configs == NULL) || (display.get() == NULL)) { 545 return BAD_VALUE; 546 } 547 548 if (!display.get()) 549 return NAME_NOT_FOUND; 550 551 int32_t type = NAME_NOT_FOUND; 552 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) { 553 if (display == mBuiltinDisplays[i]) { 554 type = i; 555 break; 556 } 557 } 558 559 if (type < 0) { 560 return type; 561 } 562 563 // TODO: Not sure if display density should handled by SF any longer 564 class Density { 565 static int getDensityFromProperty(char const* propName) { 566 char property[PROPERTY_VALUE_MAX]; 567 int density = 0; 568 if (property_get(propName, property, NULL) > 0) { 569 density = atoi(property); 570 } 571 return density; 572 } 573 public: 574 static int getEmuDensity() { 575 return getDensityFromProperty("qemu.sf.lcd_density"); } 576 static int getBuildDensity() { 577 return getDensityFromProperty("ro.sf.lcd_density"); } 578 }; 579 580 configs->clear(); 581 582 for (const auto& hwConfig : getHwComposer().getConfigs(type)) { 583 DisplayInfo info = DisplayInfo(); 584 585 float xdpi = hwConfig->getDpiX(); 586 float ydpi = hwConfig->getDpiY(); 587 588 if (type == DisplayDevice::DISPLAY_PRIMARY) { 589 // The density of the device is provided by a build property 590 float density = Density::getBuildDensity() / 160.0f; 591 if (density == 0) { 592 // the build doesn't provide a density -- this is wrong! 593 // use xdpi instead 594 ALOGE("ro.sf.lcd_density must be defined as a build property"); 595 density = xdpi / 160.0f; 596 } 597 if (Density::getEmuDensity()) { 598 // if "qemu.sf.lcd_density" is specified, it overrides everything 599 xdpi = ydpi = density = Density::getEmuDensity(); 600 density /= 160.0f; 601 } 602 info.density = density; 603 604 // TODO: this needs to go away (currently needed only by webkit) 605 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 606 info.orientation = hw->getOrientation(); 607 } else { 608 // TODO: where should this value come from? 609 static const int TV_DENSITY = 213; 610 info.density = TV_DENSITY / 160.0f; 611 info.orientation = 0; 612 } 613 614 info.w = hwConfig->getWidth(); 615 info.h = hwConfig->getHeight(); 616 info.xdpi = xdpi; 617 info.ydpi = ydpi; 618 info.fps = 1e9 / hwConfig->getVsyncPeriod(); 619 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS; 620 621 // This is how far in advance a buffer must be queued for 622 // presentation at a given time. If you want a buffer to appear 623 // on the screen at time N, you must submit the buffer before 624 // (N - presentationDeadline). 625 // 626 // Normally it's one full refresh period (to give SF a chance to 627 // latch the buffer), but this can be reduced by configuring a 628 // DispSync offset. Any additional delays introduced by the hardware 629 // composer or panel must be accounted for here. 630 // 631 // We add an additional 1ms to allow for processing time and 632 // differences between the ideal and actual refresh rate. 633 info.presentationDeadline = hwConfig->getVsyncPeriod() - 634 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000; 635 636 // All non-virtual displays are currently considered secure. 637 info.secure = true; 638 639 configs->push_back(info); 640 } 641 642 return NO_ERROR; 643 } 644 645 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */, 646 DisplayStatInfo* stats) { 647 if (stats == NULL) { 648 return BAD_VALUE; 649 } 650 651 // FIXME for now we always return stats for the primary display 652 memset(stats, 0, sizeof(*stats)); 653 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0); 654 stats->vsyncPeriod = mPrimaryDispSync.getPeriod(); 655 return NO_ERROR; 656 } 657 658 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) { 659 sp<DisplayDevice> device(getDisplayDevice(display)); 660 if (device != NULL) { 661 return device->getActiveConfig(); 662 } 663 return BAD_VALUE; 664 } 665 666 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) { 667 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(), 668 this); 669 int32_t type = hw->getDisplayType(); 670 int currentMode = hw->getActiveConfig(); 671 672 if (mode == currentMode) { 673 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode); 674 return; 675 } 676 677 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 678 ALOGW("Trying to set config for virtual display"); 679 return; 680 } 681 682 hw->setActiveConfig(mode); 683 getHwComposer().setActiveConfig(type, mode); 684 } 685 686 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) { 687 class MessageSetActiveConfig: public MessageBase { 688 SurfaceFlinger& mFlinger; 689 sp<IBinder> mDisplay; 690 int mMode; 691 public: 692 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp, 693 int mode) : 694 mFlinger(flinger), mDisplay(disp) { mMode = mode; } 695 virtual bool handler() { 696 Vector<DisplayInfo> configs; 697 mFlinger.getDisplayConfigs(mDisplay, &configs); 698 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) { 699 ALOGE("Attempt to set active config = %d for display with %zu configs", 700 mMode, configs.size()); 701 return true; 702 } 703 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 704 if (hw == NULL) { 705 ALOGE("Attempt to set active config = %d for null display %p", 706 mMode, mDisplay.get()); 707 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 708 ALOGW("Attempt to set active config = %d for virtual display", 709 mMode); 710 } else { 711 mFlinger.setActiveConfigInternal(hw, mMode); 712 } 713 return true; 714 } 715 }; 716 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode); 717 postMessageSync(msg); 718 return NO_ERROR; 719 } 720 status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display, 721 Vector<android_color_mode_t>* outColorModes) { 722 if ((outColorModes == nullptr) || (display.get() == nullptr)) { 723 return BAD_VALUE; 724 } 725 726 if (!display.get()) { 727 return NAME_NOT_FOUND; 728 } 729 730 int32_t type = NAME_NOT_FOUND; 731 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) { 732 if (display == mBuiltinDisplays[i]) { 733 type = i; 734 break; 735 } 736 } 737 738 if (type < 0) { 739 return type; 740 } 741 742 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type); 743 outColorModes->clear(); 744 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes)); 745 746 return NO_ERROR; 747 } 748 749 android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) { 750 sp<DisplayDevice> device(getDisplayDevice(display)); 751 if (device != nullptr) { 752 return device->getActiveColorMode(); 753 } 754 return static_cast<android_color_mode_t>(BAD_VALUE); 755 } 756 757 void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw, 758 android_color_mode_t mode) { 759 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(), 760 this); 761 int32_t type = hw->getDisplayType(); 762 android_color_mode_t currentMode = hw->getActiveColorMode(); 763 764 if (mode == currentMode) { 765 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode); 766 return; 767 } 768 769 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 770 ALOGW("Trying to set config for virtual display"); 771 return; 772 } 773 774 hw->setActiveColorMode(mode); 775 getHwComposer().setActiveColorMode(type, mode); 776 } 777 778 779 status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display, 780 android_color_mode_t colorMode) { 781 class MessageSetActiveColorMode: public MessageBase { 782 SurfaceFlinger& mFlinger; 783 sp<IBinder> mDisplay; 784 android_color_mode_t mMode; 785 public: 786 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp, 787 android_color_mode_t mode) : 788 mFlinger(flinger), mDisplay(disp) { mMode = mode; } 789 virtual bool handler() { 790 Vector<android_color_mode_t> modes; 791 mFlinger.getDisplayColorModes(mDisplay, &modes); 792 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes); 793 if (mMode < 0 || !exists) { 794 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode, 795 mDisplay.get()); 796 return true; 797 } 798 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 799 if (hw == nullptr) { 800 ALOGE("Attempt to set active color mode = %d for null display %p", 801 mMode, mDisplay.get()); 802 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 803 ALOGW("Attempt to set active color mode= %d for virtual display", 804 mMode); 805 } else { 806 mFlinger.setActiveColorModeInternal(hw, mMode); 807 } 808 return true; 809 } 810 }; 811 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode); 812 postMessageSync(msg); 813 return NO_ERROR; 814 } 815 816 status_t SurfaceFlinger::clearAnimationFrameStats() { 817 Mutex::Autolock _l(mStateLock); 818 mAnimFrameTracker.clearStats(); 819 return NO_ERROR; 820 } 821 822 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const { 823 Mutex::Autolock _l(mStateLock); 824 mAnimFrameTracker.getStats(outStats); 825 return NO_ERROR; 826 } 827 828 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display, 829 HdrCapabilities* outCapabilities) const { 830 Mutex::Autolock _l(mStateLock); 831 832 sp<const DisplayDevice> displayDevice(getDisplayDevice(display)); 833 if (displayDevice == nullptr) { 834 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get()); 835 return BAD_VALUE; 836 } 837 838 std::unique_ptr<HdrCapabilities> capabilities = 839 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId()); 840 if (capabilities) { 841 std::swap(*outCapabilities, *capabilities); 842 } else { 843 return BAD_VALUE; 844 } 845 846 return NO_ERROR; 847 } 848 849 // ---------------------------------------------------------------------------- 850 851 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() { 852 return mEventThread->createEventConnection(); 853 } 854 855 // ---------------------------------------------------------------------------- 856 857 void SurfaceFlinger::waitForEvent() { 858 mEventQueue.waitMessage(); 859 } 860 861 void SurfaceFlinger::signalTransaction() { 862 mEventQueue.invalidate(); 863 } 864 865 void SurfaceFlinger::signalLayerUpdate() { 866 mEventQueue.invalidate(); 867 } 868 869 void SurfaceFlinger::signalRefresh() { 870 mEventQueue.refresh(); 871 } 872 873 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 874 nsecs_t reltime, uint32_t /* flags */) { 875 return mEventQueue.postMessage(msg, reltime); 876 } 877 878 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 879 nsecs_t reltime, uint32_t /* flags */) { 880 status_t res = mEventQueue.postMessage(msg, reltime); 881 if (res == NO_ERROR) { 882 msg->wait(); 883 } 884 return res; 885 } 886 887 void SurfaceFlinger::run() { 888 do { 889 waitForEvent(); 890 } while (true); 891 } 892 893 void SurfaceFlinger::enableHardwareVsync() { 894 Mutex::Autolock _l(mHWVsyncLock); 895 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) { 896 mPrimaryDispSync.beginResync(); 897 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true); 898 mEventControlThread->setVsyncEnabled(true); 899 mPrimaryHWVsyncEnabled = true; 900 } 901 } 902 903 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) { 904 Mutex::Autolock _l(mHWVsyncLock); 905 906 if (makeAvailable) { 907 mHWVsyncAvailable = true; 908 } else if (!mHWVsyncAvailable) { 909 // Hardware vsync is not currently available, so abort the resync 910 // attempt for now 911 return; 912 } 913 914 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY); 915 const nsecs_t period = activeConfig->getVsyncPeriod(); 916 917 mPrimaryDispSync.reset(); 918 mPrimaryDispSync.setPeriod(period); 919 920 if (!mPrimaryHWVsyncEnabled) { 921 mPrimaryDispSync.beginResync(); 922 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true); 923 mEventControlThread->setVsyncEnabled(true); 924 mPrimaryHWVsyncEnabled = true; 925 } 926 } 927 928 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) { 929 Mutex::Autolock _l(mHWVsyncLock); 930 if (mPrimaryHWVsyncEnabled) { 931 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false); 932 mEventControlThread->setVsyncEnabled(false); 933 mPrimaryDispSync.endResync(); 934 mPrimaryHWVsyncEnabled = false; 935 } 936 if (makeUnavailable) { 937 mHWVsyncAvailable = false; 938 } 939 } 940 941 void SurfaceFlinger::resyncWithRateLimit() { 942 static constexpr nsecs_t kIgnoreDelay = ms2ns(500); 943 if (systemTime() - mLastSwapTime > kIgnoreDelay) { 944 resyncToHardwareVsync(false); 945 } 946 } 947 948 void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) { 949 bool needsHwVsync = false; 950 951 { // Scope for the lock 952 Mutex::Autolock _l(mHWVsyncLock); 953 if (type == 0 && mPrimaryHWVsyncEnabled) { 954 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp); 955 } 956 } 957 958 if (needsHwVsync) { 959 enableHardwareVsync(); 960 } else { 961 disableHardwareVsync(false); 962 } 963 } 964 965 void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) { 966 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false"); 967 if (disp == DisplayDevice::DISPLAY_PRIMARY) { 968 Mutex::Autolock lock(mStateLock); 969 970 // All non-virtual displays are currently considered secure. 971 bool isSecure = true; 972 973 int32_t type = DisplayDevice::DISPLAY_PRIMARY; 974 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY); 975 wp<IBinder> token = mBuiltinDisplays[type]; 976 977 sp<IGraphicBufferProducer> producer; 978 sp<IGraphicBufferConsumer> consumer; 979 BufferQueue::createBufferQueue(&producer, &consumer, 980 new GraphicBufferAlloc()); 981 982 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, 983 DisplayDevice::DISPLAY_PRIMARY, consumer); 984 sp<DisplayDevice> hw = new DisplayDevice(this, 985 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs, 986 producer, mRenderEngine->getEGLConfig()); 987 mDisplays.add(token, hw); 988 } else { 989 auto type = DisplayDevice::DISPLAY_EXTERNAL; 990 Mutex::Autolock _l(mStateLock); 991 if (connected) { 992 createBuiltinDisplayLocked(type); 993 } else { 994 mCurrentState.displays.removeItem(mBuiltinDisplays[type]); 995 mBuiltinDisplays[type].clear(); 996 } 997 setTransactionFlags(eDisplayTransactionNeeded); 998 999 // Defer EventThread notification until SF has updated mDisplays. 1000 } 1001 } 1002 1003 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) { 1004 ATRACE_CALL(); 1005 getHwComposer().setVsyncEnabled(disp, 1006 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable); 1007 } 1008 1009 void SurfaceFlinger::onMessageReceived(int32_t what) { 1010 ATRACE_CALL(); 1011 switch (what) { 1012 case MessageQueue::INVALIDATE: { 1013 bool frameMissed = !mHadClientComposition && 1014 mPreviousPresentFence != Fence::NO_FENCE && 1015 mPreviousPresentFence->getSignalTime() == INT64_MAX; 1016 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed)); 1017 if (mPropagateBackpressure && frameMissed) { 1018 signalLayerUpdate(); 1019 break; 1020 } 1021 1022 bool refreshNeeded = handleMessageTransaction(); 1023 refreshNeeded |= handleMessageInvalidate(); 1024 refreshNeeded |= mRepaintEverything; 1025 if (refreshNeeded) { 1026 // Signal a refresh if a transaction modified the window state, 1027 // a new buffer was latched, or if HWC has requested a full 1028 // repaint 1029 signalRefresh(); 1030 } 1031 break; 1032 } 1033 case MessageQueue::REFRESH: { 1034 handleMessageRefresh(); 1035 break; 1036 } 1037 } 1038 } 1039 1040 bool SurfaceFlinger::handleMessageTransaction() { 1041 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask); 1042 if (transactionFlags) { 1043 handleTransaction(transactionFlags); 1044 return true; 1045 } 1046 return false; 1047 } 1048 1049 bool SurfaceFlinger::handleMessageInvalidate() { 1050 ATRACE_CALL(); 1051 return handlePageFlip(); 1052 } 1053 1054 void SurfaceFlinger::handleMessageRefresh() { 1055 ATRACE_CALL(); 1056 1057 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC); 1058 1059 preComposition(); 1060 rebuildLayerStacks(); 1061 setUpHWComposer(); 1062 doDebugFlashRegions(); 1063 doComposition(); 1064 postComposition(refreshStartTime); 1065 1066 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY); 1067 1068 mHadClientComposition = false; 1069 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) { 1070 const sp<DisplayDevice>& displayDevice = mDisplays[displayId]; 1071 mHadClientComposition = mHadClientComposition || 1072 mHwc->hasClientComposition(displayDevice->getHwcDisplayId()); 1073 } 1074 1075 // Release any buffers which were replaced this frame 1076 for (auto& layer : mLayersWithQueuedFrames) { 1077 layer->releasePendingBuffer(); 1078 } 1079 mLayersWithQueuedFrames.clear(); 1080 } 1081 1082 void SurfaceFlinger::doDebugFlashRegions() 1083 { 1084 // is debugging enabled 1085 if (CC_LIKELY(!mDebugRegion)) 1086 return; 1087 1088 const bool repaintEverything = mRepaintEverything; 1089 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1090 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1091 if (hw->isDisplayOn()) { 1092 // transform the dirty region into this screen's coordinate space 1093 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 1094 if (!dirtyRegion.isEmpty()) { 1095 // redraw the whole screen 1096 doComposeSurfaces(hw, Region(hw->bounds())); 1097 1098 // and draw the dirty region 1099 const int32_t height = hw->getHeight(); 1100 RenderEngine& engine(getRenderEngine()); 1101 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1); 1102 1103 hw->swapBuffers(getHwComposer()); 1104 } 1105 } 1106 } 1107 1108 postFramebuffer(); 1109 1110 if (mDebugRegion > 1) { 1111 usleep(mDebugRegion * 1000); 1112 } 1113 1114 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) { 1115 auto& displayDevice = mDisplays[displayId]; 1116 if (!displayDevice->isDisplayOn()) { 1117 continue; 1118 } 1119 1120 status_t result = displayDevice->prepareFrame(*mHwc); 1121 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:" 1122 " %d (%s)", displayId, result, strerror(-result)); 1123 } 1124 } 1125 1126 void SurfaceFlinger::preComposition() 1127 { 1128 ATRACE_CALL(); 1129 ALOGV("preComposition"); 1130 1131 bool needExtraInvalidate = false; 1132 const LayerVector& layers(mDrawingState.layersSortedByZ); 1133 const size_t count = layers.size(); 1134 for (size_t i=0 ; i<count ; i++) { 1135 if (layers[i]->onPreComposition()) { 1136 needExtraInvalidate = true; 1137 } 1138 } 1139 if (needExtraInvalidate) { 1140 signalLayerUpdate(); 1141 } 1142 } 1143 1144 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime) 1145 { 1146 ATRACE_CALL(); 1147 ALOGV("postComposition"); 1148 1149 const LayerVector& layers(mDrawingState.layersSortedByZ); 1150 const size_t count = layers.size(); 1151 for (size_t i=0 ; i<count ; i++) { 1152 bool frameLatched = layers[i]->onPostComposition(); 1153 if (frameLatched) { 1154 recordBufferingStats(layers[i]->getName().string(), 1155 layers[i]->getOccupancyHistory(false)); 1156 } 1157 } 1158 1159 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY); 1160 1161 if (presentFence->isValid()) { 1162 if (mPrimaryDispSync.addPresentFence(presentFence)) { 1163 enableHardwareVsync(); 1164 } else { 1165 disableHardwareVsync(false); 1166 } 1167 } 1168 1169 const sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 1170 if (kIgnorePresentFences) { 1171 if (hw->isDisplayOn()) { 1172 enableHardwareVsync(); 1173 } 1174 } 1175 1176 mFenceTracker.addFrame(refreshStartTime, presentFence, 1177 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence()); 1178 1179 if (mAnimCompositionPending) { 1180 mAnimCompositionPending = false; 1181 1182 if (presentFence->isValid()) { 1183 mAnimFrameTracker.setActualPresentFence(presentFence); 1184 } else { 1185 // The HWC doesn't support present fences, so use the refresh 1186 // timestamp instead. 1187 nsecs_t presentTime = 1188 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 1189 mAnimFrameTracker.setActualPresentTime(presentTime); 1190 } 1191 mAnimFrameTracker.advanceFrame(); 1192 } 1193 1194 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) { 1195 return; 1196 } 1197 1198 nsecs_t currentTime = systemTime(); 1199 if (mHasPoweredOff) { 1200 mHasPoweredOff = false; 1201 } else { 1202 nsecs_t period = mPrimaryDispSync.getPeriod(); 1203 nsecs_t elapsedTime = currentTime - mLastSwapTime; 1204 size_t numPeriods = static_cast<size_t>(elapsedTime / period); 1205 if (numPeriods < NUM_BUCKETS - 1) { 1206 mFrameBuckets[numPeriods] += elapsedTime; 1207 } else { 1208 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime; 1209 } 1210 mTotalTime += elapsedTime; 1211 } 1212 mLastSwapTime = currentTime; 1213 } 1214 1215 void SurfaceFlinger::rebuildLayerStacks() { 1216 ATRACE_CALL(); 1217 ALOGV("rebuildLayerStacks"); 1218 1219 // rebuild the visible layer list per screen 1220 if (CC_UNLIKELY(mVisibleRegionsDirty)) { 1221 ATRACE_CALL(); 1222 mVisibleRegionsDirty = false; 1223 invalidateHwcGeometry(); 1224 1225 const LayerVector& layers(mDrawingState.layersSortedByZ); 1226 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1227 Region opaqueRegion; 1228 Region dirtyRegion; 1229 Vector<sp<Layer>> layersSortedByZ; 1230 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]); 1231 const Transform& tr(displayDevice->getTransform()); 1232 const Rect bounds(displayDevice->getBounds()); 1233 if (displayDevice->isDisplayOn()) { 1234 SurfaceFlinger::computeVisibleRegions(layers, 1235 displayDevice->getLayerStack(), dirtyRegion, 1236 opaqueRegion); 1237 1238 const size_t count = layers.size(); 1239 for (size_t i=0 ; i<count ; i++) { 1240 const sp<Layer>& layer(layers[i]); 1241 const Layer::State& s(layer->getDrawingState()); 1242 if (s.layerStack == displayDevice->getLayerStack()) { 1243 Region drawRegion(tr.transform( 1244 layer->visibleNonTransparentRegion)); 1245 drawRegion.andSelf(bounds); 1246 if (!drawRegion.isEmpty()) { 1247 layersSortedByZ.add(layer); 1248 } else { 1249 // Clear out the HWC layer if this layer was 1250 // previously visible, but no longer is 1251 layer->setHwcLayer(displayDevice->getHwcDisplayId(), 1252 nullptr); 1253 } 1254 } 1255 } 1256 } 1257 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ); 1258 displayDevice->undefinedRegion.set(bounds); 1259 displayDevice->undefinedRegion.subtractSelf( 1260 tr.transform(opaqueRegion)); 1261 displayDevice->dirtyRegion.orSelf(dirtyRegion); 1262 } 1263 } 1264 } 1265 1266 void SurfaceFlinger::setUpHWComposer() { 1267 ATRACE_CALL(); 1268 ALOGV("setUpHWComposer"); 1269 1270 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1271 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty(); 1272 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0; 1273 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers; 1274 1275 // If nothing has changed (!dirty), don't recompose. 1276 // If something changed, but we don't currently have any visible layers, 1277 // and didn't when we last did a composition, then skip it this time. 1278 // The second rule does two things: 1279 // - When all layers are removed from a display, we'll emit one black 1280 // frame, then nothing more until we get new layers. 1281 // - When a display is created with a private layer stack, we won't 1282 // emit any black frames until a layer is added to the layer stack. 1283 bool mustRecompose = dirty && !(empty && wasEmpty); 1284 1285 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL, 1286 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy, 1287 mustRecompose ? "doing" : "skipping", 1288 dirty ? "+" : "-", 1289 empty ? "+" : "-", 1290 wasEmpty ? "+" : "-"); 1291 1292 mDisplays[dpy]->beginFrame(mustRecompose); 1293 1294 if (mustRecompose) { 1295 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty; 1296 } 1297 } 1298 1299 // build the h/w work list 1300 if (CC_UNLIKELY(mGeometryInvalid)) { 1301 mGeometryInvalid = false; 1302 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1303 sp<const DisplayDevice> displayDevice(mDisplays[dpy]); 1304 const auto hwcId = displayDevice->getHwcDisplayId(); 1305 if (hwcId >= 0) { 1306 const Vector<sp<Layer>>& currentLayers( 1307 displayDevice->getVisibleLayersSortedByZ()); 1308 bool foundLayerWithoutHwc = false; 1309 for (auto& layer : currentLayers) { 1310 if (!layer->hasHwcLayer(hwcId)) { 1311 auto hwcLayer = mHwc->createLayer(hwcId); 1312 if (hwcLayer) { 1313 layer->setHwcLayer(hwcId, std::move(hwcLayer)); 1314 } else { 1315 layer->forceClientComposition(hwcId); 1316 foundLayerWithoutHwc = true; 1317 continue; 1318 } 1319 } 1320 1321 layer->setGeometry(displayDevice); 1322 if (mDebugDisableHWC || mDebugRegion) { 1323 layer->forceClientComposition(hwcId); 1324 } 1325 } 1326 } 1327 } 1328 } 1329 1330 1331 mat4 colorMatrix = mColorMatrix * mDaltonizer(); 1332 1333 // Set the per-frame data 1334 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) { 1335 auto& displayDevice = mDisplays[displayId]; 1336 const auto hwcId = displayDevice->getHwcDisplayId(); 1337 if (hwcId < 0) { 1338 continue; 1339 } 1340 if (colorMatrix != mPreviousColorMatrix) { 1341 status_t result = mHwc->setColorTransform(hwcId, colorMatrix); 1342 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on " 1343 "display %zd: %d", displayId, result); 1344 } 1345 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) { 1346 layer->setPerFrameData(displayDevice); 1347 } 1348 } 1349 1350 mPreviousColorMatrix = colorMatrix; 1351 1352 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) { 1353 auto& displayDevice = mDisplays[displayId]; 1354 if (!displayDevice->isDisplayOn()) { 1355 continue; 1356 } 1357 1358 status_t result = displayDevice->prepareFrame(*mHwc); 1359 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:" 1360 " %d (%s)", displayId, result, strerror(-result)); 1361 } 1362 } 1363 1364 void SurfaceFlinger::doComposition() { 1365 ATRACE_CALL(); 1366 ALOGV("doComposition"); 1367 1368 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything); 1369 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1370 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1371 if (hw->isDisplayOn()) { 1372 // transform the dirty region into this screen's coordinate space 1373 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything)); 1374 1375 // repaint the framebuffer (if needed) 1376 doDisplayComposition(hw, dirtyRegion); 1377 1378 hw->dirtyRegion.clear(); 1379 hw->flip(hw->swapRegion); 1380 hw->swapRegion.clear(); 1381 } 1382 } 1383 postFramebuffer(); 1384 } 1385 1386 void SurfaceFlinger::postFramebuffer() 1387 { 1388 ATRACE_CALL(); 1389 ALOGV("postFramebuffer"); 1390 1391 const nsecs_t now = systemTime(); 1392 mDebugInSwapBuffers = now; 1393 1394 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) { 1395 auto& displayDevice = mDisplays[displayId]; 1396 if (!displayDevice->isDisplayOn()) { 1397 continue; 1398 } 1399 const auto hwcId = displayDevice->getHwcDisplayId(); 1400 if (hwcId >= 0) { 1401 mHwc->commit(hwcId); 1402 } 1403 displayDevice->onSwapBuffersCompleted(); 1404 if (displayId == 0) { 1405 // Make the default display current because the VirtualDisplayDevice 1406 // code cannot deal with dequeueBuffer() being called outside of the 1407 // composition loop; however the code below can call glFlush() which 1408 // is allowed to (and does in some case) call dequeueBuffer(). 1409 displayDevice->makeCurrent(mEGLDisplay, mEGLContext); 1410 } 1411 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) { 1412 sp<Fence> releaseFence = Fence::NO_FENCE; 1413 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) { 1414 releaseFence = displayDevice->getClientTargetAcquireFence(); 1415 } else { 1416 auto hwcLayer = layer->getHwcLayer(hwcId); 1417 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer); 1418 } 1419 layer->onLayerDisplayed(releaseFence); 1420 } 1421 if (hwcId >= 0) { 1422 mHwc->clearReleaseFences(hwcId); 1423 } 1424 } 1425 1426 mLastSwapBufferTime = systemTime() - now; 1427 mDebugInSwapBuffers = 0; 1428 1429 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount(); 1430 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) { 1431 logFrameStats(); 1432 } 1433 } 1434 1435 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 1436 { 1437 ATRACE_CALL(); 1438 1439 // here we keep a copy of the drawing state (that is the state that's 1440 // going to be overwritten by handleTransactionLocked()) outside of 1441 // mStateLock so that the side-effects of the State assignment 1442 // don't happen with mStateLock held (which can cause deadlocks). 1443 State drawingState(mDrawingState); 1444 1445 Mutex::Autolock _l(mStateLock); 1446 const nsecs_t now = systemTime(); 1447 mDebugInTransaction = now; 1448 1449 // Here we're guaranteed that some transaction flags are set 1450 // so we can call handleTransactionLocked() unconditionally. 1451 // We call getTransactionFlags(), which will also clear the flags, 1452 // with mStateLock held to guarantee that mCurrentState won't change 1453 // until the transaction is committed. 1454 1455 transactionFlags = getTransactionFlags(eTransactionMask); 1456 handleTransactionLocked(transactionFlags); 1457 1458 mLastTransactionTime = systemTime() - now; 1459 mDebugInTransaction = 0; 1460 invalidateHwcGeometry(); 1461 // here the transaction has been committed 1462 } 1463 1464 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags) 1465 { 1466 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 1467 const size_t count = currentLayers.size(); 1468 1469 // Notify all layers of available frames 1470 for (size_t i = 0; i < count; ++i) { 1471 currentLayers[i]->notifyAvailableFrames(); 1472 } 1473 1474 /* 1475 * Traversal of the children 1476 * (perform the transaction for each of them if needed) 1477 */ 1478 1479 if (transactionFlags & eTraversalNeeded) { 1480 for (size_t i=0 ; i<count ; i++) { 1481 const sp<Layer>& layer(currentLayers[i]); 1482 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 1483 if (!trFlags) continue; 1484 1485 const uint32_t flags = layer->doTransaction(0); 1486 if (flags & Layer::eVisibleRegion) 1487 mVisibleRegionsDirty = true; 1488 } 1489 } 1490 1491 /* 1492 * Perform display own transactions if needed 1493 */ 1494 1495 if (transactionFlags & eDisplayTransactionNeeded) { 1496 // here we take advantage of Vector's copy-on-write semantics to 1497 // improve performance by skipping the transaction entirely when 1498 // know that the lists are identical 1499 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays); 1500 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays); 1501 if (!curr.isIdenticalTo(draw)) { 1502 mVisibleRegionsDirty = true; 1503 const size_t cc = curr.size(); 1504 size_t dc = draw.size(); 1505 1506 // find the displays that were removed 1507 // (ie: in drawing state but not in current state) 1508 // also handle displays that changed 1509 // (ie: displays that are in both lists) 1510 for (size_t i=0 ; i<dc ; i++) { 1511 const ssize_t j = curr.indexOfKey(draw.keyAt(i)); 1512 if (j < 0) { 1513 // in drawing state but not in current state 1514 if (!draw[i].isMainDisplay()) { 1515 // Call makeCurrent() on the primary display so we can 1516 // be sure that nothing associated with this display 1517 // is current. 1518 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice()); 1519 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext); 1520 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i))); 1521 if (hw != NULL) 1522 hw->disconnect(getHwComposer()); 1523 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) 1524 mEventThread->onHotplugReceived(draw[i].type, false); 1525 mDisplays.removeItem(draw.keyAt(i)); 1526 } else { 1527 ALOGW("trying to remove the main display"); 1528 } 1529 } else { 1530 // this display is in both lists. see if something changed. 1531 const DisplayDeviceState& state(curr[j]); 1532 const wp<IBinder>& display(curr.keyAt(j)); 1533 const sp<IBinder> state_binder = IInterface::asBinder(state.surface); 1534 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface); 1535 if (state_binder != draw_binder) { 1536 // changing the surface is like destroying and 1537 // recreating the DisplayDevice, so we just remove it 1538 // from the drawing state, so that it get re-added 1539 // below. 1540 sp<DisplayDevice> hw(getDisplayDevice(display)); 1541 if (hw != NULL) 1542 hw->disconnect(getHwComposer()); 1543 mDisplays.removeItem(display); 1544 mDrawingState.displays.removeItemsAt(i); 1545 dc--; i--; 1546 // at this point we must loop to the next item 1547 continue; 1548 } 1549 1550 const sp<DisplayDevice> disp(getDisplayDevice(display)); 1551 if (disp != NULL) { 1552 if (state.layerStack != draw[i].layerStack) { 1553 disp->setLayerStack(state.layerStack); 1554 } 1555 if ((state.orientation != draw[i].orientation) 1556 || (state.viewport != draw[i].viewport) 1557 || (state.frame != draw[i].frame)) 1558 { 1559 disp->setProjection(state.orientation, 1560 state.viewport, state.frame); 1561 } 1562 if (state.width != draw[i].width || state.height != draw[i].height) { 1563 disp->setDisplaySize(state.width, state.height); 1564 } 1565 } 1566 } 1567 } 1568 1569 // find displays that were added 1570 // (ie: in current state but not in drawing state) 1571 for (size_t i=0 ; i<cc ; i++) { 1572 if (draw.indexOfKey(curr.keyAt(i)) < 0) { 1573 const DisplayDeviceState& state(curr[i]); 1574 1575 sp<DisplaySurface> dispSurface; 1576 sp<IGraphicBufferProducer> producer; 1577 sp<IGraphicBufferProducer> bqProducer; 1578 sp<IGraphicBufferConsumer> bqConsumer; 1579 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer, 1580 new GraphicBufferAlloc()); 1581 1582 int32_t hwcId = -1; 1583 if (state.isVirtualDisplay()) { 1584 // Virtual displays without a surface are dormant: 1585 // they have external state (layer stack, projection, 1586 // etc.) but no internal state (i.e. a DisplayDevice). 1587 if (state.surface != NULL) { 1588 1589 if (mUseHwcVirtualDisplays) { 1590 int width = 0; 1591 int status = state.surface->query( 1592 NATIVE_WINDOW_WIDTH, &width); 1593 ALOGE_IF(status != NO_ERROR, 1594 "Unable to query width (%d)", status); 1595 int height = 0; 1596 status = state.surface->query( 1597 NATIVE_WINDOW_HEIGHT, &height); 1598 ALOGE_IF(status != NO_ERROR, 1599 "Unable to query height (%d)", status); 1600 int intFormat = 0; 1601 status = state.surface->query( 1602 NATIVE_WINDOW_FORMAT, &intFormat); 1603 ALOGE_IF(status != NO_ERROR, 1604 "Unable to query format (%d)", status); 1605 auto format = static_cast<android_pixel_format_t>( 1606 intFormat); 1607 1608 mHwc->allocateVirtualDisplay(width, height, &format, 1609 &hwcId); 1610 } 1611 1612 // TODO: Plumb requested format back up to consumer 1613 1614 sp<VirtualDisplaySurface> vds = 1615 new VirtualDisplaySurface(*mHwc, 1616 hwcId, state.surface, bqProducer, 1617 bqConsumer, state.displayName); 1618 1619 dispSurface = vds; 1620 producer = vds; 1621 } 1622 } else { 1623 ALOGE_IF(state.surface!=NULL, 1624 "adding a supported display, but rendering " 1625 "surface is provided (%p), ignoring it", 1626 state.surface.get()); 1627 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) { 1628 hwcId = DisplayDevice::DISPLAY_EXTERNAL; 1629 dispSurface = new FramebufferSurface(*mHwc, 1630 DisplayDevice::DISPLAY_EXTERNAL, 1631 bqConsumer); 1632 producer = bqProducer; 1633 } else { 1634 ALOGE("Attempted to add non-external non-virtual" 1635 " display"); 1636 } 1637 } 1638 1639 const wp<IBinder>& display(curr.keyAt(i)); 1640 if (dispSurface != NULL) { 1641 sp<DisplayDevice> hw = new DisplayDevice(this, 1642 state.type, hwcId, state.isSecure, display, 1643 dispSurface, producer, 1644 mRenderEngine->getEGLConfig()); 1645 hw->setLayerStack(state.layerStack); 1646 hw->setProjection(state.orientation, 1647 state.viewport, state.frame); 1648 hw->setDisplayName(state.displayName); 1649 mDisplays.add(display, hw); 1650 if (!state.isVirtualDisplay()) { 1651 mEventThread->onHotplugReceived(state.type, true); 1652 } 1653 } 1654 } 1655 } 1656 } 1657 } 1658 1659 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) { 1660 // The transform hint might have changed for some layers 1661 // (either because a display has changed, or because a layer 1662 // as changed). 1663 // 1664 // Walk through all the layers in currentLayers, 1665 // and update their transform hint. 1666 // 1667 // If a layer is visible only on a single display, then that 1668 // display is used to calculate the hint, otherwise we use the 1669 // default display. 1670 // 1671 // NOTE: we do this here, rather than in rebuildLayerStacks() so that 1672 // the hint is set before we acquire a buffer from the surface texture. 1673 // 1674 // NOTE: layer transactions have taken place already, so we use their 1675 // drawing state. However, SurfaceFlinger's own transaction has not 1676 // happened yet, so we must use the current state layer list 1677 // (soon to become the drawing state list). 1678 // 1679 sp<const DisplayDevice> disp; 1680 uint32_t currentlayerStack = 0; 1681 for (size_t i=0; i<count; i++) { 1682 // NOTE: we rely on the fact that layers are sorted by 1683 // layerStack first (so we don't have to traverse the list 1684 // of displays for every layer). 1685 const sp<Layer>& layer(currentLayers[i]); 1686 uint32_t layerStack = layer->getDrawingState().layerStack; 1687 if (i==0 || currentlayerStack != layerStack) { 1688 currentlayerStack = layerStack; 1689 // figure out if this layerstack is mirrored 1690 // (more than one display) if so, pick the default display, 1691 // if not, pick the only display it's on. 1692 disp.clear(); 1693 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1694 sp<const DisplayDevice> hw(mDisplays[dpy]); 1695 if (hw->getLayerStack() == currentlayerStack) { 1696 if (disp == NULL) { 1697 disp = hw; 1698 } else { 1699 disp = NULL; 1700 break; 1701 } 1702 } 1703 } 1704 } 1705 if (disp == NULL) { 1706 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to 1707 // redraw after transform hint changes. See bug 8508397. 1708 1709 // could be null when this layer is using a layerStack 1710 // that is not visible on any display. Also can occur at 1711 // screen off/on times. 1712 disp = getDefaultDisplayDevice(); 1713 } 1714 layer->updateTransformHint(disp); 1715 } 1716 } 1717 1718 1719 /* 1720 * Perform our own transaction if needed 1721 */ 1722 1723 const LayerVector& layers(mDrawingState.layersSortedByZ); 1724 if (currentLayers.size() > layers.size()) { 1725 // layers have been added 1726 mVisibleRegionsDirty = true; 1727 } 1728 1729 // some layers might have been removed, so 1730 // we need to update the regions they're exposing. 1731 if (mLayersRemoved) { 1732 mLayersRemoved = false; 1733 mVisibleRegionsDirty = true; 1734 const size_t count = layers.size(); 1735 for (size_t i=0 ; i<count ; i++) { 1736 const sp<Layer>& layer(layers[i]); 1737 if (currentLayers.indexOf(layer) < 0) { 1738 // this layer is not visible anymore 1739 // TODO: we could traverse the tree from front to back and 1740 // compute the actual visible region 1741 // TODO: we could cache the transformed region 1742 const Layer::State& s(layer->getDrawingState()); 1743 Region visibleReg = s.active.transform.transform( 1744 Region(Rect(s.active.w, s.active.h))); 1745 invalidateLayerStack(s.layerStack, visibleReg); 1746 } 1747 } 1748 } 1749 1750 commitTransaction(); 1751 1752 updateCursorAsync(); 1753 } 1754 1755 void SurfaceFlinger::updateCursorAsync() 1756 { 1757 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) { 1758 auto& displayDevice = mDisplays[displayId]; 1759 if (displayDevice->getHwcDisplayId() < 0) { 1760 continue; 1761 } 1762 1763 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) { 1764 layer->updateCursorPosition(displayDevice); 1765 } 1766 } 1767 } 1768 1769 void SurfaceFlinger::commitTransaction() 1770 { 1771 if (!mLayersPendingRemoval.isEmpty()) { 1772 // Notify removed layers now that they can't be drawn from 1773 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) { 1774 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(), 1775 mLayersPendingRemoval[i]->getOccupancyHistory(true)); 1776 mLayersPendingRemoval[i]->onRemoved(); 1777 } 1778 mLayersPendingRemoval.clear(); 1779 } 1780 1781 // If this transaction is part of a window animation then the next frame 1782 // we composite should be considered an animation as well. 1783 mAnimCompositionPending = mAnimTransactionPending; 1784 1785 mDrawingState = mCurrentState; 1786 mTransactionPending = false; 1787 mAnimTransactionPending = false; 1788 mTransactionCV.broadcast(); 1789 } 1790 1791 void SurfaceFlinger::computeVisibleRegions( 1792 const LayerVector& currentLayers, uint32_t layerStack, 1793 Region& outDirtyRegion, Region& outOpaqueRegion) 1794 { 1795 ATRACE_CALL(); 1796 ALOGV("computeVisibleRegions"); 1797 1798 Region aboveOpaqueLayers; 1799 Region aboveCoveredLayers; 1800 Region dirty; 1801 1802 outDirtyRegion.clear(); 1803 1804 size_t i = currentLayers.size(); 1805 while (i--) { 1806 const sp<Layer>& layer = currentLayers[i]; 1807 1808 // start with the whole surface at its current location 1809 const Layer::State& s(layer->getDrawingState()); 1810 1811 // only consider the layers on the given layer stack 1812 if (s.layerStack != layerStack) 1813 continue; 1814 1815 /* 1816 * opaqueRegion: area of a surface that is fully opaque. 1817 */ 1818 Region opaqueRegion; 1819 1820 /* 1821 * visibleRegion: area of a surface that is visible on screen 1822 * and not fully transparent. This is essentially the layer's 1823 * footprint minus the opaque regions above it. 1824 * Areas covered by a translucent surface are considered visible. 1825 */ 1826 Region visibleRegion; 1827 1828 /* 1829 * coveredRegion: area of a surface that is covered by all 1830 * visible regions above it (which includes the translucent areas). 1831 */ 1832 Region coveredRegion; 1833 1834 /* 1835 * transparentRegion: area of a surface that is hinted to be completely 1836 * transparent. This is only used to tell when the layer has no visible 1837 * non-transparent regions and can be removed from the layer list. It 1838 * does not affect the visibleRegion of this layer or any layers 1839 * beneath it. The hint may not be correct if apps don't respect the 1840 * SurfaceView restrictions (which, sadly, some don't). 1841 */ 1842 Region transparentRegion; 1843 1844 1845 // handle hidden surfaces by setting the visible region to empty 1846 if (CC_LIKELY(layer->isVisible())) { 1847 const bool translucent = !layer->isOpaque(s); 1848 Rect bounds(s.active.transform.transform(layer->computeBounds())); 1849 visibleRegion.set(bounds); 1850 if (!visibleRegion.isEmpty()) { 1851 // Remove the transparent area from the visible region 1852 if (translucent) { 1853 const Transform tr(s.active.transform); 1854 if (tr.preserveRects()) { 1855 // transform the transparent region 1856 transparentRegion = tr.transform(s.activeTransparentRegion); 1857 } else { 1858 // transformation too complex, can't do the 1859 // transparent region optimization. 1860 transparentRegion.clear(); 1861 } 1862 } 1863 1864 // compute the opaque region 1865 const int32_t layerOrientation = s.active.transform.getOrientation(); 1866 if (s.alpha == 1.0f && !translucent && 1867 ((layerOrientation & Transform::ROT_INVALID) == false)) { 1868 // the opaque region is the layer's footprint 1869 opaqueRegion = visibleRegion; 1870 } 1871 } 1872 } 1873 1874 // Clip the covered region to the visible region 1875 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 1876 1877 // Update aboveCoveredLayers for next (lower) layer 1878 aboveCoveredLayers.orSelf(visibleRegion); 1879 1880 // subtract the opaque region covered by the layers above us 1881 visibleRegion.subtractSelf(aboveOpaqueLayers); 1882 1883 // compute this layer's dirty region 1884 if (layer->contentDirty) { 1885 // we need to invalidate the whole region 1886 dirty = visibleRegion; 1887 // as well, as the old visible region 1888 dirty.orSelf(layer->visibleRegion); 1889 layer->contentDirty = false; 1890 } else { 1891 /* compute the exposed region: 1892 * the exposed region consists of two components: 1893 * 1) what's VISIBLE now and was COVERED before 1894 * 2) what's EXPOSED now less what was EXPOSED before 1895 * 1896 * note that (1) is conservative, we start with the whole 1897 * visible region but only keep what used to be covered by 1898 * something -- which mean it may have been exposed. 1899 * 1900 * (2) handles areas that were not covered by anything but got 1901 * exposed because of a resize. 1902 */ 1903 const Region newExposed = visibleRegion - coveredRegion; 1904 const Region oldVisibleRegion = layer->visibleRegion; 1905 const Region oldCoveredRegion = layer->coveredRegion; 1906 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 1907 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 1908 } 1909 dirty.subtractSelf(aboveOpaqueLayers); 1910 1911 // accumulate to the screen dirty region 1912 outDirtyRegion.orSelf(dirty); 1913 1914 // Update aboveOpaqueLayers for next (lower) layer 1915 aboveOpaqueLayers.orSelf(opaqueRegion); 1916 1917 // Store the visible region in screen space 1918 layer->setVisibleRegion(visibleRegion); 1919 layer->setCoveredRegion(coveredRegion); 1920 layer->setVisibleNonTransparentRegion( 1921 visibleRegion.subtract(transparentRegion)); 1922 } 1923 1924 outOpaqueRegion = aboveOpaqueLayers; 1925 } 1926 1927 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack, 1928 const Region& dirty) { 1929 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 1930 const sp<DisplayDevice>& hw(mDisplays[dpy]); 1931 if (hw->getLayerStack() == layerStack) { 1932 hw->dirtyRegion.orSelf(dirty); 1933 } 1934 } 1935 } 1936 1937 bool SurfaceFlinger::handlePageFlip() 1938 { 1939 ALOGV("handlePageFlip"); 1940 1941 Region dirtyRegion; 1942 1943 bool visibleRegions = false; 1944 const LayerVector& layers(mDrawingState.layersSortedByZ); 1945 bool frameQueued = false; 1946 1947 // Store the set of layers that need updates. This set must not change as 1948 // buffers are being latched, as this could result in a deadlock. 1949 // Example: Two producers share the same command stream and: 1950 // 1.) Layer 0 is latched 1951 // 2.) Layer 0 gets a new frame 1952 // 2.) Layer 1 gets a new frame 1953 // 3.) Layer 1 is latched. 1954 // Display is now waiting on Layer 1's frame, which is behind layer 0's 1955 // second frame. But layer 0's second frame could be waiting on display. 1956 for (size_t i = 0, count = layers.size(); i<count ; i++) { 1957 const sp<Layer>& layer(layers[i]); 1958 if (layer->hasQueuedFrame()) { 1959 frameQueued = true; 1960 if (layer->shouldPresentNow(mPrimaryDispSync)) { 1961 mLayersWithQueuedFrames.push_back(layer.get()); 1962 } else { 1963 layer->useEmptyDamage(); 1964 } 1965 } else { 1966 layer->useEmptyDamage(); 1967 } 1968 } 1969 for (auto& layer : mLayersWithQueuedFrames) { 1970 const Region dirty(layer->latchBuffer(visibleRegions)); 1971 layer->useSurfaceDamage(); 1972 const Layer::State& s(layer->getDrawingState()); 1973 invalidateLayerStack(s.layerStack, dirty); 1974 } 1975 1976 mVisibleRegionsDirty |= visibleRegions; 1977 1978 // If we will need to wake up at some time in the future to deal with a 1979 // queued frame that shouldn't be displayed during this vsync period, wake 1980 // up during the next vsync period to check again. 1981 if (frameQueued && mLayersWithQueuedFrames.empty()) { 1982 signalLayerUpdate(); 1983 } 1984 1985 // Only continue with the refresh if there is actually new work to do 1986 return !mLayersWithQueuedFrames.empty(); 1987 } 1988 1989 void SurfaceFlinger::invalidateHwcGeometry() 1990 { 1991 mGeometryInvalid = true; 1992 } 1993 1994 1995 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw, 1996 const Region& inDirtyRegion) 1997 { 1998 // We only need to actually compose the display if: 1999 // 1) It is being handled by hardware composer, which may need this to 2000 // keep its virtual display state machine in sync, or 2001 // 2) There is work to be done (the dirty region isn't empty) 2002 bool isHwcDisplay = hw->getHwcDisplayId() >= 0; 2003 if (!isHwcDisplay && inDirtyRegion.isEmpty()) { 2004 ALOGV("Skipping display composition"); 2005 return; 2006 } 2007 2008 ALOGV("doDisplayComposition"); 2009 2010 Region dirtyRegion(inDirtyRegion); 2011 2012 // compute the invalid region 2013 hw->swapRegion.orSelf(dirtyRegion); 2014 2015 uint32_t flags = hw->getFlags(); 2016 if (flags & DisplayDevice::SWAP_RECTANGLE) { 2017 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 2018 // takes a rectangle, we must make sure to update that whole 2019 // rectangle in that case 2020 dirtyRegion.set(hw->swapRegion.bounds()); 2021 } else { 2022 if (flags & DisplayDevice::PARTIAL_UPDATES) { 2023 // We need to redraw the rectangle that will be updated 2024 // (pushed to the framebuffer). 2025 // This is needed because PARTIAL_UPDATES only takes one 2026 // rectangle instead of a region (see DisplayDevice::flip()) 2027 dirtyRegion.set(hw->swapRegion.bounds()); 2028 } else { 2029 // we need to redraw everything (the whole screen) 2030 dirtyRegion.set(hw->bounds()); 2031 hw->swapRegion = dirtyRegion; 2032 } 2033 } 2034 2035 if (!doComposeSurfaces(hw, dirtyRegion)) return; 2036 2037 // update the swap region and clear the dirty region 2038 hw->swapRegion.orSelf(dirtyRegion); 2039 2040 // swap buffers (presentation) 2041 hw->swapBuffers(getHwComposer()); 2042 } 2043 2044 bool SurfaceFlinger::doComposeSurfaces( 2045 const sp<const DisplayDevice>& displayDevice, const Region& dirty) 2046 { 2047 ALOGV("doComposeSurfaces"); 2048 2049 const auto hwcId = displayDevice->getHwcDisplayId(); 2050 2051 mat4 oldColorMatrix; 2052 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) && 2053 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform); 2054 if (applyColorMatrix) { 2055 mat4 colorMatrix = mColorMatrix * mDaltonizer(); 2056 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix); 2057 } 2058 2059 bool hasClientComposition = mHwc->hasClientComposition(hwcId); 2060 if (hasClientComposition) { 2061 ALOGV("hasClientComposition"); 2062 2063 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) { 2064 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s", 2065 displayDevice->getDisplayName().string()); 2066 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 2067 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) { 2068 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting."); 2069 } 2070 return false; 2071 } 2072 2073 // Never touch the framebuffer if we don't have any framebuffer layers 2074 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId); 2075 if (hasDeviceComposition) { 2076 // when using overlays, we assume a fully transparent framebuffer 2077 // NOTE: we could reduce how much we need to clear, for instance 2078 // remove where there are opaque FB layers. however, on some 2079 // GPUs doing a "clean slate" clear might be more efficient. 2080 // We'll revisit later if needed. 2081 mRenderEngine->clearWithColor(0, 0, 0, 0); 2082 } else { 2083 // we start with the whole screen area 2084 const Region bounds(displayDevice->getBounds()); 2085 2086 // we remove the scissor part 2087 // we're left with the letterbox region 2088 // (common case is that letterbox ends-up being empty) 2089 const Region letterbox(bounds.subtract(displayDevice->getScissor())); 2090 2091 // compute the area to clear 2092 Region region(displayDevice->undefinedRegion.merge(letterbox)); 2093 2094 // but limit it to the dirty region 2095 region.andSelf(dirty); 2096 2097 // screen is already cleared here 2098 if (!region.isEmpty()) { 2099 // can happen with SurfaceView 2100 drawWormhole(displayDevice, region); 2101 } 2102 } 2103 2104 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) { 2105 // just to be on the safe side, we don't set the 2106 // scissor on the main display. It should never be needed 2107 // anyways (though in theory it could since the API allows it). 2108 const Rect& bounds(displayDevice->getBounds()); 2109 const Rect& scissor(displayDevice->getScissor()); 2110 if (scissor != bounds) { 2111 // scissor doesn't match the screen's dimensions, so we 2112 // need to clear everything outside of it and enable 2113 // the GL scissor so we don't draw anything where we shouldn't 2114 2115 // enable scissor for this frame 2116 const uint32_t height = displayDevice->getHeight(); 2117 mRenderEngine->setScissor(scissor.left, height - scissor.bottom, 2118 scissor.getWidth(), scissor.getHeight()); 2119 } 2120 } 2121 } 2122 2123 /* 2124 * and then, render the layers targeted at the framebuffer 2125 */ 2126 2127 ALOGV("Rendering client layers"); 2128 const Transform& displayTransform = displayDevice->getTransform(); 2129 if (hwcId >= 0) { 2130 // we're using h/w composer 2131 bool firstLayer = true; 2132 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) { 2133 const Region clip(dirty.intersect( 2134 displayTransform.transform(layer->visibleRegion))); 2135 ALOGV("Layer: %s", layer->getName().string()); 2136 ALOGV(" Composition type: %s", 2137 to_string(layer->getCompositionType(hwcId)).c_str()); 2138 if (!clip.isEmpty()) { 2139 switch (layer->getCompositionType(hwcId)) { 2140 case HWC2::Composition::Cursor: 2141 case HWC2::Composition::Device: 2142 case HWC2::Composition::SolidColor: { 2143 const Layer::State& state(layer->getDrawingState()); 2144 if (layer->getClearClientTarget(hwcId) && !firstLayer && 2145 layer->isOpaque(state) && (state.alpha == 1.0f) 2146 && hasClientComposition) { 2147 // never clear the very first layer since we're 2148 // guaranteed the FB is already cleared 2149 layer->clearWithOpenGL(displayDevice, clip); 2150 } 2151 break; 2152 } 2153 case HWC2::Composition::Client: { 2154 layer->draw(displayDevice, clip); 2155 break; 2156 } 2157 default: 2158 break; 2159 } 2160 } else { 2161 ALOGV(" Skipping for empty clip"); 2162 } 2163 firstLayer = false; 2164 } 2165 } else { 2166 // we're not using h/w composer 2167 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) { 2168 const Region clip(dirty.intersect( 2169 displayTransform.transform(layer->visibleRegion))); 2170 if (!clip.isEmpty()) { 2171 layer->draw(displayDevice, clip); 2172 } 2173 } 2174 } 2175 2176 if (applyColorMatrix) { 2177 getRenderEngine().setupColorTransform(oldColorMatrix); 2178 } 2179 2180 // disable scissor at the end of the frame 2181 mRenderEngine->disableScissor(); 2182 return true; 2183 } 2184 2185 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const { 2186 const int32_t height = hw->getHeight(); 2187 RenderEngine& engine(getRenderEngine()); 2188 engine.fillRegionWithColor(region, height, 0, 0, 0, 0); 2189 } 2190 2191 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 2192 const sp<IBinder>& handle, 2193 const sp<IGraphicBufferProducer>& gbc, 2194 const sp<Layer>& lbc) 2195 { 2196 // add this layer to the current state list 2197 { 2198 Mutex::Autolock _l(mStateLock); 2199 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) { 2200 return NO_MEMORY; 2201 } 2202 mCurrentState.layersSortedByZ.add(lbc); 2203 mGraphicBufferProducerList.add(IInterface::asBinder(gbc)); 2204 } 2205 2206 // attach this layer to the client 2207 client->attachLayer(handle, lbc); 2208 2209 return NO_ERROR; 2210 } 2211 2212 status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) { 2213 Mutex::Autolock _l(mStateLock); 2214 sp<Layer> layer = weakLayer.promote(); 2215 if (layer == nullptr) { 2216 // The layer has already been removed, carry on 2217 return NO_ERROR; 2218 } 2219 2220 ssize_t index = mCurrentState.layersSortedByZ.remove(layer); 2221 if (index >= 0) { 2222 mLayersPendingRemoval.push(layer); 2223 mLayersRemoved = true; 2224 setTransactionFlags(eTransactionNeeded); 2225 return NO_ERROR; 2226 } 2227 return status_t(index); 2228 } 2229 2230 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) { 2231 return android_atomic_release_load(&mTransactionFlags); 2232 } 2233 2234 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) { 2235 return android_atomic_and(~flags, &mTransactionFlags) & flags; 2236 } 2237 2238 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) { 2239 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 2240 if ((old & flags)==0) { // wake the server up 2241 signalTransaction(); 2242 } 2243 return old; 2244 } 2245 2246 void SurfaceFlinger::setTransactionState( 2247 const Vector<ComposerState>& state, 2248 const Vector<DisplayState>& displays, 2249 uint32_t flags) 2250 { 2251 ATRACE_CALL(); 2252 Mutex::Autolock _l(mStateLock); 2253 uint32_t transactionFlags = 0; 2254 2255 if (flags & eAnimation) { 2256 // For window updates that are part of an animation we must wait for 2257 // previous animation "frames" to be handled. 2258 while (mAnimTransactionPending) { 2259 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 2260 if (CC_UNLIKELY(err != NO_ERROR)) { 2261 // just in case something goes wrong in SF, return to the 2262 // caller after a few seconds. 2263 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out " 2264 "waiting for previous animation frame"); 2265 mAnimTransactionPending = false; 2266 break; 2267 } 2268 } 2269 } 2270 2271 size_t count = displays.size(); 2272 for (size_t i=0 ; i<count ; i++) { 2273 const DisplayState& s(displays[i]); 2274 transactionFlags |= setDisplayStateLocked(s); 2275 } 2276 2277 count = state.size(); 2278 for (size_t i=0 ; i<count ; i++) { 2279 const ComposerState& s(state[i]); 2280 // Here we need to check that the interface we're given is indeed 2281 // one of our own. A malicious client could give us a NULL 2282 // IInterface, or one of its own or even one of our own but a 2283 // different type. All these situations would cause us to crash. 2284 // 2285 // NOTE: it would be better to use RTTI as we could directly check 2286 // that we have a Client*. however, RTTI is disabled in Android. 2287 if (s.client != NULL) { 2288 sp<IBinder> binder = IInterface::asBinder(s.client); 2289 if (binder != NULL) { 2290 String16 desc(binder->getInterfaceDescriptor()); 2291 if (desc == ISurfaceComposerClient::descriptor) { 2292 sp<Client> client( static_cast<Client *>(s.client.get()) ); 2293 transactionFlags |= setClientStateLocked(client, s.state); 2294 } 2295 } 2296 } 2297 } 2298 2299 // If a synchronous transaction is explicitly requested without any changes, 2300 // force a transaction anyway. This can be used as a flush mechanism for 2301 // previous async transactions. 2302 if (transactionFlags == 0 && (flags & eSynchronous)) { 2303 transactionFlags = eTransactionNeeded; 2304 } 2305 2306 if (transactionFlags) { 2307 // this triggers the transaction 2308 setTransactionFlags(transactionFlags); 2309 2310 // if this is a synchronous transaction, wait for it to take effect 2311 // before returning. 2312 if (flags & eSynchronous) { 2313 mTransactionPending = true; 2314 } 2315 if (flags & eAnimation) { 2316 mAnimTransactionPending = true; 2317 } 2318 while (mTransactionPending) { 2319 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 2320 if (CC_UNLIKELY(err != NO_ERROR)) { 2321 // just in case something goes wrong in SF, return to the 2322 // called after a few seconds. 2323 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!"); 2324 mTransactionPending = false; 2325 break; 2326 } 2327 } 2328 } 2329 } 2330 2331 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) 2332 { 2333 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token); 2334 if (dpyIdx < 0) 2335 return 0; 2336 2337 uint32_t flags = 0; 2338 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx)); 2339 if (disp.isValid()) { 2340 const uint32_t what = s.what; 2341 if (what & DisplayState::eSurfaceChanged) { 2342 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) { 2343 disp.surface = s.surface; 2344 flags |= eDisplayTransactionNeeded; 2345 } 2346 } 2347 if (what & DisplayState::eLayerStackChanged) { 2348 if (disp.layerStack != s.layerStack) { 2349 disp.layerStack = s.layerStack; 2350 flags |= eDisplayTransactionNeeded; 2351 } 2352 } 2353 if (what & DisplayState::eDisplayProjectionChanged) { 2354 if (disp.orientation != s.orientation) { 2355 disp.orientation = s.orientation; 2356 flags |= eDisplayTransactionNeeded; 2357 } 2358 if (disp.frame != s.frame) { 2359 disp.frame = s.frame; 2360 flags |= eDisplayTransactionNeeded; 2361 } 2362 if (disp.viewport != s.viewport) { 2363 disp.viewport = s.viewport; 2364 flags |= eDisplayTransactionNeeded; 2365 } 2366 } 2367 if (what & DisplayState::eDisplaySizeChanged) { 2368 if (disp.width != s.width) { 2369 disp.width = s.width; 2370 flags |= eDisplayTransactionNeeded; 2371 } 2372 if (disp.height != s.height) { 2373 disp.height = s.height; 2374 flags |= eDisplayTransactionNeeded; 2375 } 2376 } 2377 } 2378 return flags; 2379 } 2380 2381 uint32_t SurfaceFlinger::setClientStateLocked( 2382 const sp<Client>& client, 2383 const layer_state_t& s) 2384 { 2385 uint32_t flags = 0; 2386 sp<Layer> layer(client->getLayerUser(s.surface)); 2387 if (layer != 0) { 2388 const uint32_t what = s.what; 2389 bool geometryAppliesWithResize = 2390 what & layer_state_t::eGeometryAppliesWithResize; 2391 if (what & layer_state_t::ePositionChanged) { 2392 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) { 2393 flags |= eTraversalNeeded; 2394 } 2395 } 2396 if (what & layer_state_t::eLayerChanged) { 2397 // NOTE: index needs to be calculated before we update the state 2398 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 2399 if (layer->setLayer(s.z) && idx >= 0) { 2400 mCurrentState.layersSortedByZ.removeAt(idx); 2401 mCurrentState.layersSortedByZ.add(layer); 2402 // we need traversal (state changed) 2403 // AND transaction (list changed) 2404 flags |= eTransactionNeeded|eTraversalNeeded; 2405 } 2406 } 2407 if (what & layer_state_t::eSizeChanged) { 2408 if (layer->setSize(s.w, s.h)) { 2409 flags |= eTraversalNeeded; 2410 } 2411 } 2412 if (what & layer_state_t::eAlphaChanged) { 2413 if (layer->setAlpha(s.alpha)) 2414 flags |= eTraversalNeeded; 2415 } 2416 if (what & layer_state_t::eMatrixChanged) { 2417 if (layer->setMatrix(s.matrix)) 2418 flags |= eTraversalNeeded; 2419 } 2420 if (what & layer_state_t::eTransparentRegionChanged) { 2421 if (layer->setTransparentRegionHint(s.transparentRegion)) 2422 flags |= eTraversalNeeded; 2423 } 2424 if (what & layer_state_t::eFlagsChanged) { 2425 if (layer->setFlags(s.flags, s.mask)) 2426 flags |= eTraversalNeeded; 2427 } 2428 if (what & layer_state_t::eCropChanged) { 2429 if (layer->setCrop(s.crop, !geometryAppliesWithResize)) 2430 flags |= eTraversalNeeded; 2431 } 2432 if (what & layer_state_t::eFinalCropChanged) { 2433 if (layer->setFinalCrop(s.finalCrop)) 2434 flags |= eTraversalNeeded; 2435 } 2436 if (what & layer_state_t::eLayerStackChanged) { 2437 // NOTE: index needs to be calculated before we update the state 2438 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 2439 if (layer->setLayerStack(s.layerStack) && idx >= 0) { 2440 mCurrentState.layersSortedByZ.removeAt(idx); 2441 mCurrentState.layersSortedByZ.add(layer); 2442 // we need traversal (state changed) 2443 // AND transaction (list changed) 2444 flags |= eTransactionNeeded|eTraversalNeeded; 2445 } 2446 } 2447 if (what & layer_state_t::eDeferTransaction) { 2448 layer->deferTransactionUntil(s.handle, s.frameNumber); 2449 // We don't trigger a traversal here because if no other state is 2450 // changed, we don't want this to cause any more work 2451 } 2452 if (what & layer_state_t::eOverrideScalingModeChanged) { 2453 layer->setOverrideScalingMode(s.overrideScalingMode); 2454 // We don't trigger a traversal here because if no other state is 2455 // changed, we don't want this to cause any more work 2456 } 2457 } 2458 return flags; 2459 } 2460 2461 status_t SurfaceFlinger::createLayer( 2462 const String8& name, 2463 const sp<Client>& client, 2464 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags, 2465 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp) 2466 { 2467 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string()); 2468 if (int32_t(w|h) < 0) { 2469 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)", 2470 int(w), int(h)); 2471 return BAD_VALUE; 2472 } 2473 2474 status_t result = NO_ERROR; 2475 2476 sp<Layer> layer; 2477 2478 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) { 2479 case ISurfaceComposerClient::eFXSurfaceNormal: 2480 result = createNormalLayer(client, 2481 name, w, h, flags, format, 2482 handle, gbp, &layer); 2483 break; 2484 case ISurfaceComposerClient::eFXSurfaceDim: 2485 result = createDimLayer(client, 2486 name, w, h, flags, 2487 handle, gbp, &layer); 2488 break; 2489 default: 2490 result = BAD_VALUE; 2491 break; 2492 } 2493 2494 if (result != NO_ERROR) { 2495 return result; 2496 } 2497 2498 result = addClientLayer(client, *handle, *gbp, layer); 2499 if (result != NO_ERROR) { 2500 return result; 2501 } 2502 2503 setTransactionFlags(eTransactionNeeded); 2504 return result; 2505 } 2506 2507 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client, 2508 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format, 2509 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) 2510 { 2511 // initialize the surfaces 2512 switch (format) { 2513 case PIXEL_FORMAT_TRANSPARENT: 2514 case PIXEL_FORMAT_TRANSLUCENT: 2515 format = PIXEL_FORMAT_RGBA_8888; 2516 break; 2517 case PIXEL_FORMAT_OPAQUE: 2518 format = PIXEL_FORMAT_RGBX_8888; 2519 break; 2520 } 2521 2522 *outLayer = new Layer(this, client, name, w, h, flags); 2523 status_t err = (*outLayer)->setBuffers(w, h, format, flags); 2524 if (err == NO_ERROR) { 2525 *handle = (*outLayer)->getHandle(); 2526 *gbp = (*outLayer)->getProducer(); 2527 } 2528 2529 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err)); 2530 return err; 2531 } 2532 2533 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client, 2534 const String8& name, uint32_t w, uint32_t h, uint32_t flags, 2535 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer) 2536 { 2537 *outLayer = new LayerDim(this, client, name, w, h, flags); 2538 *handle = (*outLayer)->getHandle(); 2539 *gbp = (*outLayer)->getProducer(); 2540 return NO_ERROR; 2541 } 2542 2543 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle) 2544 { 2545 // called by the window manager when it wants to remove a Layer 2546 status_t err = NO_ERROR; 2547 sp<Layer> l(client->getLayerUser(handle)); 2548 if (l != NULL) { 2549 err = removeLayer(l); 2550 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 2551 "error removing layer=%p (%s)", l.get(), strerror(-err)); 2552 } 2553 return err; 2554 } 2555 2556 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer) 2557 { 2558 // called by ~LayerCleaner() when all references to the IBinder (handle) 2559 // are gone 2560 return removeLayer(layer); 2561 } 2562 2563 // --------------------------------------------------------------------------- 2564 2565 void SurfaceFlinger::onInitializeDisplays() { 2566 // reset screen orientation and use primary layer stack 2567 Vector<ComposerState> state; 2568 Vector<DisplayState> displays; 2569 DisplayState d; 2570 d.what = DisplayState::eDisplayProjectionChanged | 2571 DisplayState::eLayerStackChanged; 2572 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]; 2573 d.layerStack = 0; 2574 d.orientation = DisplayState::eOrientationDefault; 2575 d.frame.makeInvalid(); 2576 d.viewport.makeInvalid(); 2577 d.width = 0; 2578 d.height = 0; 2579 displays.add(d); 2580 setTransactionState(state, displays, 0); 2581 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL); 2582 2583 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY); 2584 const nsecs_t period = activeConfig->getVsyncPeriod(); 2585 mAnimFrameTracker.setDisplayRefreshPeriod(period); 2586 } 2587 2588 void SurfaceFlinger::initializeDisplays() { 2589 class MessageScreenInitialized : public MessageBase { 2590 SurfaceFlinger* flinger; 2591 public: 2592 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { } 2593 virtual bool handler() { 2594 flinger->onInitializeDisplays(); 2595 return true; 2596 } 2597 }; 2598 sp<MessageBase> msg = new MessageScreenInitialized(this); 2599 postMessageAsync(msg); // we may be called from main thread, use async message 2600 } 2601 2602 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw, 2603 int mode) { 2604 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(), 2605 this); 2606 int32_t type = hw->getDisplayType(); 2607 int currentMode = hw->getPowerMode(); 2608 2609 if (mode == currentMode) { 2610 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode); 2611 return; 2612 } 2613 2614 hw->setPowerMode(mode); 2615 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) { 2616 ALOGW("Trying to set power mode for virtual display"); 2617 return; 2618 } 2619 2620 if (currentMode == HWC_POWER_MODE_OFF) { 2621 // Turn on the display 2622 getHwComposer().setPowerMode(type, mode); 2623 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2624 // FIXME: eventthread only knows about the main display right now 2625 mEventThread->onScreenAcquired(); 2626 resyncToHardwareVsync(true); 2627 } 2628 2629 mVisibleRegionsDirty = true; 2630 mHasPoweredOff = true; 2631 repaintEverything(); 2632 2633 struct sched_param param = {0}; 2634 param.sched_priority = 1; 2635 if (sched_setscheduler(0, SCHED_FIFO, ¶m) != 0) { 2636 ALOGW("Couldn't set SCHED_FIFO on display on"); 2637 } 2638 } else if (mode == HWC_POWER_MODE_OFF) { 2639 // Turn off the display 2640 struct sched_param param = {0}; 2641 if (sched_setscheduler(0, SCHED_OTHER, ¶m) != 0) { 2642 ALOGW("Couldn't set SCHED_OTHER on display off"); 2643 } 2644 2645 if (type == DisplayDevice::DISPLAY_PRIMARY) { 2646 disableHardwareVsync(true); // also cancels any in-progress resync 2647 2648 // FIXME: eventthread only knows about the main display right now 2649 mEventThread->onScreenReleased(); 2650 } 2651 2652 getHwComposer().setPowerMode(type, mode); 2653 mVisibleRegionsDirty = true; 2654 // from this point on, SF will stop drawing on this display 2655 } else { 2656 getHwComposer().setPowerMode(type, mode); 2657 } 2658 } 2659 2660 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) { 2661 class MessageSetPowerMode: public MessageBase { 2662 SurfaceFlinger& mFlinger; 2663 sp<IBinder> mDisplay; 2664 int mMode; 2665 public: 2666 MessageSetPowerMode(SurfaceFlinger& flinger, 2667 const sp<IBinder>& disp, int mode) : mFlinger(flinger), 2668 mDisplay(disp) { mMode = mode; } 2669 virtual bool handler() { 2670 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay)); 2671 if (hw == NULL) { 2672 ALOGE("Attempt to set power mode = %d for null display %p", 2673 mMode, mDisplay.get()); 2674 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) { 2675 ALOGW("Attempt to set power mode = %d for virtual display", 2676 mMode); 2677 } else { 2678 mFlinger.setPowerModeInternal(hw, mMode); 2679 } 2680 return true; 2681 } 2682 }; 2683 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode); 2684 postMessageSync(msg); 2685 } 2686 2687 // --------------------------------------------------------------------------- 2688 2689 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 2690 { 2691 String8 result; 2692 2693 IPCThreadState* ipc = IPCThreadState::self(); 2694 const int pid = ipc->getCallingPid(); 2695 const int uid = ipc->getCallingUid(); 2696 if ((uid != AID_SHELL) && 2697 !PermissionCache::checkPermission(sDump, pid, uid)) { 2698 result.appendFormat("Permission Denial: " 2699 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid); 2700 } else { 2701 // Try to get the main lock, but give up after one second 2702 // (this would indicate SF is stuck, but we want to be able to 2703 // print something in dumpsys). 2704 status_t err = mStateLock.timedLock(s2ns(1)); 2705 bool locked = (err == NO_ERROR); 2706 if (!locked) { 2707 result.appendFormat( 2708 "SurfaceFlinger appears to be unresponsive (%s [%d]), " 2709 "dumping anyways (no locks held)\n", strerror(-err), err); 2710 } 2711 2712 bool dumpAll = true; 2713 size_t index = 0; 2714 size_t numArgs = args.size(); 2715 if (numArgs) { 2716 if ((index < numArgs) && 2717 (args[index] == String16("--list"))) { 2718 index++; 2719 listLayersLocked(args, index, result); 2720 dumpAll = false; 2721 } 2722 2723 if ((index < numArgs) && 2724 (args[index] == String16("--latency"))) { 2725 index++; 2726 dumpStatsLocked(args, index, result); 2727 dumpAll = false; 2728 } 2729 2730 if ((index < numArgs) && 2731 (args[index] == String16("--latency-clear"))) { 2732 index++; 2733 clearStatsLocked(args, index, result); 2734 dumpAll = false; 2735 } 2736 2737 if ((index < numArgs) && 2738 (args[index] == String16("--dispsync"))) { 2739 index++; 2740 mPrimaryDispSync.dump(result); 2741 dumpAll = false; 2742 } 2743 2744 if ((index < numArgs) && 2745 (args[index] == String16("--static-screen"))) { 2746 index++; 2747 dumpStaticScreenStats(result); 2748 dumpAll = false; 2749 } 2750 2751 if ((index < numArgs) && 2752 (args[index] == String16("--fences"))) { 2753 index++; 2754 mFenceTracker.dump(&result); 2755 dumpAll = false; 2756 } 2757 } 2758 2759 if (dumpAll) { 2760 dumpAllLocked(args, index, result); 2761 } 2762 2763 if (locked) { 2764 mStateLock.unlock(); 2765 } 2766 } 2767 write(fd, result.string(), result.size()); 2768 return NO_ERROR; 2769 } 2770 2771 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, 2772 size_t& /* index */, String8& result) const 2773 { 2774 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2775 const size_t count = currentLayers.size(); 2776 for (size_t i=0 ; i<count ; i++) { 2777 const sp<Layer>& layer(currentLayers[i]); 2778 result.appendFormat("%s\n", layer->getName().string()); 2779 } 2780 } 2781 2782 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 2783 String8& result) const 2784 { 2785 String8 name; 2786 if (index < args.size()) { 2787 name = String8(args[index]); 2788 index++; 2789 } 2790 2791 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY); 2792 const nsecs_t period = activeConfig->getVsyncPeriod(); 2793 result.appendFormat("%" PRId64 "\n", period); 2794 2795 if (name.isEmpty()) { 2796 mAnimFrameTracker.dumpStats(result); 2797 } else { 2798 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2799 const size_t count = currentLayers.size(); 2800 for (size_t i=0 ; i<count ; i++) { 2801 const sp<Layer>& layer(currentLayers[i]); 2802 if (name == layer->getName()) { 2803 layer->dumpFrameStats(result); 2804 } 2805 } 2806 } 2807 } 2808 2809 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 2810 String8& /* result */) 2811 { 2812 String8 name; 2813 if (index < args.size()) { 2814 name = String8(args[index]); 2815 index++; 2816 } 2817 2818 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2819 const size_t count = currentLayers.size(); 2820 for (size_t i=0 ; i<count ; i++) { 2821 const sp<Layer>& layer(currentLayers[i]); 2822 if (name.isEmpty() || (name == layer->getName())) { 2823 layer->clearFrameStats(); 2824 } 2825 } 2826 2827 mAnimFrameTracker.clearStats(); 2828 } 2829 2830 // This should only be called from the main thread. Otherwise it would need 2831 // the lock and should use mCurrentState rather than mDrawingState. 2832 void SurfaceFlinger::logFrameStats() { 2833 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ; 2834 const size_t count = drawingLayers.size(); 2835 for (size_t i=0 ; i<count ; i++) { 2836 const sp<Layer>& layer(drawingLayers[i]); 2837 layer->logFrameStats(); 2838 } 2839 2840 mAnimFrameTracker.logAndResetStats(String8("<win-anim>")); 2841 } 2842 2843 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result) 2844 { 2845 static const char* config = 2846 " [sf" 2847 #ifdef HAS_CONTEXT_PRIORITY 2848 " HAS_CONTEXT_PRIORITY" 2849 #endif 2850 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE 2851 " NEVER_DEFAULT_TO_ASYNC_MODE" 2852 #endif 2853 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING 2854 " TARGET_DISABLE_TRIPLE_BUFFERING" 2855 #endif 2856 "]"; 2857 result.append(config); 2858 } 2859 2860 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const 2861 { 2862 result.appendFormat("Static screen stats:\n"); 2863 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) { 2864 float bucketTimeSec = mFrameBuckets[b] / 1e9; 2865 float percent = 100.0f * 2866 static_cast<float>(mFrameBuckets[b]) / mTotalTime; 2867 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n", 2868 b + 1, bucketTimeSec, percent); 2869 } 2870 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9; 2871 float percent = 100.0f * 2872 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime; 2873 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n", 2874 NUM_BUCKETS - 1, bucketTimeSec, percent); 2875 } 2876 2877 void SurfaceFlinger::recordBufferingStats(const char* layerName, 2878 std::vector<OccupancyTracker::Segment>&& history) { 2879 Mutex::Autolock lock(mBufferingStatsMutex); 2880 auto& stats = mBufferingStats[layerName]; 2881 for (const auto& segment : history) { 2882 if (!segment.usedThirdBuffer) { 2883 stats.twoBufferTime += segment.totalTime; 2884 } 2885 if (segment.occupancyAverage < 1.0f) { 2886 stats.doubleBufferedTime += segment.totalTime; 2887 } else if (segment.occupancyAverage < 2.0f) { 2888 stats.tripleBufferedTime += segment.totalTime; 2889 } 2890 ++stats.numSegments; 2891 stats.totalTime += segment.totalTime; 2892 } 2893 } 2894 2895 void SurfaceFlinger::dumpBufferingStats(String8& result) const { 2896 result.append("Buffering stats:\n"); 2897 result.append(" [Layer name] <Active time> <Two buffer> " 2898 "<Double buffered> <Triple buffered>\n"); 2899 Mutex::Autolock lock(mBufferingStatsMutex); 2900 typedef std::tuple<std::string, float, float, float> BufferTuple; 2901 std::map<float, BufferTuple, std::greater<float>> sorted; 2902 for (const auto& statsPair : mBufferingStats) { 2903 const char* name = statsPair.first.c_str(); 2904 const BufferingStats& stats = statsPair.second; 2905 if (stats.numSegments == 0) { 2906 continue; 2907 } 2908 float activeTime = ns2ms(stats.totalTime) / 1000.0f; 2909 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) / 2910 stats.totalTime; 2911 float doubleBufferRatio = static_cast<float>( 2912 stats.doubleBufferedTime) / stats.totalTime; 2913 float tripleBufferRatio = static_cast<float>( 2914 stats.tripleBufferedTime) / stats.totalTime; 2915 sorted.insert({activeTime, {name, twoBufferRatio, 2916 doubleBufferRatio, tripleBufferRatio}}); 2917 } 2918 for (const auto& sortedPair : sorted) { 2919 float activeTime = sortedPair.first; 2920 const BufferTuple& values = sortedPair.second; 2921 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n", 2922 std::get<0>(values).c_str(), activeTime, 2923 std::get<1>(values), std::get<2>(values), 2924 std::get<3>(values)); 2925 } 2926 result.append("\n"); 2927 } 2928 2929 2930 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index, 2931 String8& result) const 2932 { 2933 bool colorize = false; 2934 if (index < args.size() 2935 && (args[index] == String16("--color"))) { 2936 colorize = true; 2937 index++; 2938 } 2939 2940 Colorizer colorizer(colorize); 2941 2942 // figure out if we're stuck somewhere 2943 const nsecs_t now = systemTime(); 2944 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 2945 const nsecs_t inTransaction(mDebugInTransaction); 2946 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 2947 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 2948 2949 /* 2950 * Dump library configuration. 2951 */ 2952 2953 colorizer.bold(result); 2954 result.append("Build configuration:"); 2955 colorizer.reset(result); 2956 appendSfConfigString(result); 2957 appendUiConfigString(result); 2958 appendGuiConfigString(result); 2959 result.append("\n"); 2960 2961 colorizer.bold(result); 2962 result.append("Sync configuration: "); 2963 colorizer.reset(result); 2964 result.append(SyncFeatures::getInstance().toString()); 2965 result.append("\n"); 2966 2967 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY); 2968 2969 colorizer.bold(result); 2970 result.append("DispSync configuration: "); 2971 colorizer.reset(result); 2972 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, " 2973 "present offset %d ns (refresh %" PRId64 " ns)", 2974 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, 2975 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod()); 2976 result.append("\n"); 2977 2978 // Dump static screen stats 2979 result.append("\n"); 2980 dumpStaticScreenStats(result); 2981 result.append("\n"); 2982 2983 dumpBufferingStats(result); 2984 2985 /* 2986 * Dump the visible layer list 2987 */ 2988 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 2989 const size_t count = currentLayers.size(); 2990 colorizer.bold(result); 2991 result.appendFormat("Visible layers (count = %zu)\n", count); 2992 colorizer.reset(result); 2993 for (size_t i=0 ; i<count ; i++) { 2994 const sp<Layer>& layer(currentLayers[i]); 2995 layer->dump(result, colorizer); 2996 } 2997 2998 /* 2999 * Dump Display state 3000 */ 3001 3002 colorizer.bold(result); 3003 result.appendFormat("Displays (%zu entries)\n", mDisplays.size()); 3004 colorizer.reset(result); 3005 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { 3006 const sp<const DisplayDevice>& hw(mDisplays[dpy]); 3007 hw->dump(result); 3008 } 3009 3010 /* 3011 * Dump SurfaceFlinger global state 3012 */ 3013 3014 colorizer.bold(result); 3015 result.append("SurfaceFlinger global state:\n"); 3016 colorizer.reset(result); 3017 3018 HWComposer& hwc(getHwComposer()); 3019 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 3020 3021 colorizer.bold(result); 3022 result.appendFormat("EGL implementation : %s\n", 3023 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION)); 3024 colorizer.reset(result); 3025 result.appendFormat("%s\n", 3026 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS)); 3027 3028 mRenderEngine->dump(result); 3029 3030 hw->undefinedRegion.dump(result, "undefinedRegion"); 3031 result.appendFormat(" orientation=%d, isDisplayOn=%d\n", 3032 hw->getOrientation(), hw->isDisplayOn()); 3033 result.appendFormat( 3034 " last eglSwapBuffers() time: %f us\n" 3035 " last transaction time : %f us\n" 3036 " transaction-flags : %08x\n" 3037 " refresh-rate : %f fps\n" 3038 " x-dpi : %f\n" 3039 " y-dpi : %f\n" 3040 " gpu_to_cpu_unsupported : %d\n" 3041 , 3042 mLastSwapBufferTime/1000.0, 3043 mLastTransactionTime/1000.0, 3044 mTransactionFlags, 3045 1e9 / activeConfig->getVsyncPeriod(), 3046 activeConfig->getDpiX(), 3047 activeConfig->getDpiY(), 3048 !mGpuToCpuSupported); 3049 3050 result.appendFormat(" eglSwapBuffers time: %f us\n", 3051 inSwapBuffersDuration/1000.0); 3052 3053 result.appendFormat(" transaction time: %f us\n", 3054 inTransactionDuration/1000.0); 3055 3056 /* 3057 * VSYNC state 3058 */ 3059 mEventThread->dump(result); 3060 3061 /* 3062 * Dump HWComposer state 3063 */ 3064 colorizer.bold(result); 3065 result.append("h/w composer state:\n"); 3066 colorizer.reset(result); 3067 bool hwcDisabled = mDebugDisableHWC || mDebugRegion; 3068 result.appendFormat(" h/w composer %s\n", 3069 hwcDisabled ? "disabled" : "enabled"); 3070 hwc.dump(result); 3071 3072 /* 3073 * Dump gralloc state 3074 */ 3075 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 3076 alloc.dump(result); 3077 } 3078 3079 const Vector< sp<Layer> >& 3080 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) { 3081 // Note: mStateLock is held here 3082 wp<IBinder> dpy; 3083 for (size_t i=0 ; i<mDisplays.size() ; i++) { 3084 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) { 3085 dpy = mDisplays.keyAt(i); 3086 break; 3087 } 3088 } 3089 if (dpy == NULL) { 3090 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id); 3091 // Just use the primary display so we have something to return 3092 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY); 3093 } 3094 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ(); 3095 } 3096 3097 bool SurfaceFlinger::startDdmConnection() 3098 { 3099 void* libddmconnection_dso = 3100 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW); 3101 if (!libddmconnection_dso) { 3102 return false; 3103 } 3104 void (*DdmConnection_start)(const char* name); 3105 DdmConnection_start = 3106 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start"); 3107 if (!DdmConnection_start) { 3108 dlclose(libddmconnection_dso); 3109 return false; 3110 } 3111 (*DdmConnection_start)(getServiceName()); 3112 return true; 3113 } 3114 3115 status_t SurfaceFlinger::onTransact( 3116 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 3117 { 3118 switch (code) { 3119 case CREATE_CONNECTION: 3120 case CREATE_DISPLAY: 3121 case SET_TRANSACTION_STATE: 3122 case BOOT_FINISHED: 3123 case CLEAR_ANIMATION_FRAME_STATS: 3124 case GET_ANIMATION_FRAME_STATS: 3125 case SET_POWER_MODE: 3126 case GET_HDR_CAPABILITIES: 3127 { 3128 // codes that require permission check 3129 IPCThreadState* ipc = IPCThreadState::self(); 3130 const int pid = ipc->getCallingPid(); 3131 const int uid = ipc->getCallingUid(); 3132 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) && 3133 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 3134 ALOGE("Permission Denial: " 3135 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 3136 return PERMISSION_DENIED; 3137 } 3138 break; 3139 } 3140 case CAPTURE_SCREEN: 3141 { 3142 // codes that require permission check 3143 IPCThreadState* ipc = IPCThreadState::self(); 3144 const int pid = ipc->getCallingPid(); 3145 const int uid = ipc->getCallingUid(); 3146 if ((uid != AID_GRAPHICS) && 3147 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 3148 ALOGE("Permission Denial: " 3149 "can't read framebuffer pid=%d, uid=%d", pid, uid); 3150 return PERMISSION_DENIED; 3151 } 3152 break; 3153 } 3154 } 3155 3156 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 3157 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 3158 CHECK_INTERFACE(ISurfaceComposer, data, reply); 3159 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 3160 IPCThreadState* ipc = IPCThreadState::self(); 3161 const int pid = ipc->getCallingPid(); 3162 const int uid = ipc->getCallingUid(); 3163 ALOGE("Permission Denial: " 3164 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 3165 return PERMISSION_DENIED; 3166 } 3167 int n; 3168 switch (code) { 3169 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 3170 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 3171 return NO_ERROR; 3172 case 1002: // SHOW_UPDATES 3173 n = data.readInt32(); 3174 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 3175 invalidateHwcGeometry(); 3176 repaintEverything(); 3177 return NO_ERROR; 3178 case 1004:{ // repaint everything 3179 repaintEverything(); 3180 return NO_ERROR; 3181 } 3182 case 1005:{ // force transaction 3183 setTransactionFlags( 3184 eTransactionNeeded| 3185 eDisplayTransactionNeeded| 3186 eTraversalNeeded); 3187 return NO_ERROR; 3188 } 3189 case 1006:{ // send empty update 3190 signalRefresh(); 3191 return NO_ERROR; 3192 } 3193 case 1008: // toggle use of hw composer 3194 n = data.readInt32(); 3195 mDebugDisableHWC = n ? 1 : 0; 3196 invalidateHwcGeometry(); 3197 repaintEverything(); 3198 return NO_ERROR; 3199 case 1009: // toggle use of transform hint 3200 n = data.readInt32(); 3201 mDebugDisableTransformHint = n ? 1 : 0; 3202 invalidateHwcGeometry(); 3203 repaintEverything(); 3204 return NO_ERROR; 3205 case 1010: // interrogate. 3206 reply->writeInt32(0); 3207 reply->writeInt32(0); 3208 reply->writeInt32(mDebugRegion); 3209 reply->writeInt32(0); 3210 reply->writeInt32(mDebugDisableHWC); 3211 return NO_ERROR; 3212 case 1013: { 3213 Mutex::Autolock _l(mStateLock); 3214 sp<const DisplayDevice> hw(getDefaultDisplayDevice()); 3215 reply->writeInt32(hw->getPageFlipCount()); 3216 return NO_ERROR; 3217 } 3218 case 1014: { 3219 // daltonize 3220 n = data.readInt32(); 3221 switch (n % 10) { 3222 case 1: 3223 mDaltonizer.setType(ColorBlindnessType::Protanomaly); 3224 break; 3225 case 2: 3226 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly); 3227 break; 3228 case 3: 3229 mDaltonizer.setType(ColorBlindnessType::Tritanomaly); 3230 break; 3231 default: 3232 mDaltonizer.setType(ColorBlindnessType::None); 3233 break; 3234 } 3235 if (n >= 10) { 3236 mDaltonizer.setMode(ColorBlindnessMode::Correction); 3237 } else { 3238 mDaltonizer.setMode(ColorBlindnessMode::Simulation); 3239 } 3240 invalidateHwcGeometry(); 3241 repaintEverything(); 3242 return NO_ERROR; 3243 } 3244 case 1015: { 3245 // apply a color matrix 3246 n = data.readInt32(); 3247 if (n) { 3248 // color matrix is sent as mat3 matrix followed by vec3 3249 // offset, then packed into a mat4 where the last row is 3250 // the offset and extra values are 0 3251 for (size_t i = 0 ; i < 4; i++) { 3252 for (size_t j = 0; j < 4; j++) { 3253 mColorMatrix[i][j] = data.readFloat(); 3254 } 3255 } 3256 } else { 3257 mColorMatrix = mat4(); 3258 } 3259 invalidateHwcGeometry(); 3260 repaintEverything(); 3261 return NO_ERROR; 3262 } 3263 // This is an experimental interface 3264 // Needs to be shifted to proper binder interface when we productize 3265 case 1016: { 3266 n = data.readInt32(); 3267 mPrimaryDispSync.setRefreshSkipCount(n); 3268 return NO_ERROR; 3269 } 3270 case 1017: { 3271 n = data.readInt32(); 3272 mForceFullDamage = static_cast<bool>(n); 3273 return NO_ERROR; 3274 } 3275 case 1018: { // Modify Choreographer's phase offset 3276 n = data.readInt32(); 3277 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n)); 3278 return NO_ERROR; 3279 } 3280 case 1019: { // Modify SurfaceFlinger's phase offset 3281 n = data.readInt32(); 3282 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n)); 3283 return NO_ERROR; 3284 } 3285 case 1021: { // Disable HWC virtual displays 3286 n = data.readInt32(); 3287 mUseHwcVirtualDisplays = !n; 3288 return NO_ERROR; 3289 } 3290 } 3291 } 3292 return err; 3293 } 3294 3295 void SurfaceFlinger::repaintEverything() { 3296 android_atomic_or(1, &mRepaintEverything); 3297 signalTransaction(); 3298 } 3299 3300 // --------------------------------------------------------------------------- 3301 // Capture screen into an IGraphiBufferProducer 3302 // --------------------------------------------------------------------------- 3303 3304 /* The code below is here to handle b/8734824 3305 * 3306 * We create a IGraphicBufferProducer wrapper that forwards all calls 3307 * from the surfaceflinger thread to the calling binder thread, where they 3308 * are executed. This allows the calling thread in the calling process to be 3309 * reused and not depend on having "enough" binder threads to handle the 3310 * requests. 3311 */ 3312 class GraphicProducerWrapper : public BBinder, public MessageHandler { 3313 /* Parts of GraphicProducerWrapper are run on two different threads, 3314 * communicating by sending messages via Looper but also by shared member 3315 * data. Coherence maintenance is subtle and in places implicit (ugh). 3316 * 3317 * Don't rely on Looper's sendMessage/handleMessage providing 3318 * release/acquire semantics for any data not actually in the Message. 3319 * Data going from surfaceflinger to binder threads needs to be 3320 * synchronized explicitly. 3321 * 3322 * Barrier open/wait do provide release/acquire semantics. This provides 3323 * implicit synchronization for data coming back from binder to 3324 * surfaceflinger threads. 3325 */ 3326 3327 sp<IGraphicBufferProducer> impl; 3328 sp<Looper> looper; 3329 status_t result; 3330 bool exitPending; 3331 bool exitRequested; 3332 Barrier barrier; 3333 uint32_t code; 3334 Parcel const* data; 3335 Parcel* reply; 3336 3337 enum { 3338 MSG_API_CALL, 3339 MSG_EXIT 3340 }; 3341 3342 /* 3343 * Called on surfaceflinger thread. This is called by our "fake" 3344 * BpGraphicBufferProducer. We package the data and reply Parcel and 3345 * forward them to the binder thread. 3346 */ 3347 virtual status_t transact(uint32_t code, 3348 const Parcel& data, Parcel* reply, uint32_t /* flags */) { 3349 this->code = code; 3350 this->data = &data; 3351 this->reply = reply; 3352 if (exitPending) { 3353 // if we've exited, we run the message synchronously right here. 3354 // note (JH): as far as I can tell from looking at the code, this 3355 // never actually happens. if it does, i'm not sure if it happens 3356 // on the surfaceflinger or binder thread. 3357 handleMessage(Message(MSG_API_CALL)); 3358 } else { 3359 barrier.close(); 3360 // Prevent stores to this->{code, data, reply} from being 3361 // reordered later than the construction of Message. 3362 atomic_thread_fence(memory_order_release); 3363 looper->sendMessage(this, Message(MSG_API_CALL)); 3364 barrier.wait(); 3365 } 3366 return result; 3367 } 3368 3369 /* 3370 * here we run on the binder thread. All we've got to do is 3371 * call the real BpGraphicBufferProducer. 3372 */ 3373 virtual void handleMessage(const Message& message) { 3374 int what = message.what; 3375 // Prevent reads below from happening before the read from Message 3376 atomic_thread_fence(memory_order_acquire); 3377 if (what == MSG_API_CALL) { 3378 result = IInterface::asBinder(impl)->transact(code, data[0], reply); 3379 barrier.open(); 3380 } else if (what == MSG_EXIT) { 3381 exitRequested = true; 3382 } 3383 } 3384 3385 public: 3386 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) 3387 : impl(impl), 3388 looper(new Looper(true)), 3389 result(NO_ERROR), 3390 exitPending(false), 3391 exitRequested(false), 3392 code(0), 3393 data(NULL), 3394 reply(NULL) 3395 {} 3396 3397 // Binder thread 3398 status_t waitForResponse() { 3399 do { 3400 looper->pollOnce(-1); 3401 } while (!exitRequested); 3402 return result; 3403 } 3404 3405 // Client thread 3406 void exit(status_t result) { 3407 this->result = result; 3408 exitPending = true; 3409 // Ensure this->result is visible to the binder thread before it 3410 // handles the message. 3411 atomic_thread_fence(memory_order_release); 3412 looper->sendMessage(this, Message(MSG_EXIT)); 3413 } 3414 }; 3415 3416 3417 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, 3418 const sp<IGraphicBufferProducer>& producer, 3419 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 3420 uint32_t minLayerZ, uint32_t maxLayerZ, 3421 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) { 3422 3423 if (CC_UNLIKELY(display == 0)) 3424 return BAD_VALUE; 3425 3426 if (CC_UNLIKELY(producer == 0)) 3427 return BAD_VALUE; 3428 3429 // if we have secure windows on this display, never allow the screen capture 3430 // unless the producer interface is local (i.e.: we can take a screenshot for 3431 // ourselves). 3432 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder(); 3433 3434 // Convert to surfaceflinger's internal rotation type. 3435 Transform::orientation_flags rotationFlags; 3436 switch (rotation) { 3437 case ISurfaceComposer::eRotateNone: 3438 rotationFlags = Transform::ROT_0; 3439 break; 3440 case ISurfaceComposer::eRotate90: 3441 rotationFlags = Transform::ROT_90; 3442 break; 3443 case ISurfaceComposer::eRotate180: 3444 rotationFlags = Transform::ROT_180; 3445 break; 3446 case ISurfaceComposer::eRotate270: 3447 rotationFlags = Transform::ROT_270; 3448 break; 3449 default: 3450 rotationFlags = Transform::ROT_0; 3451 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation); 3452 break; 3453 } 3454 3455 class MessageCaptureScreen : public MessageBase { 3456 SurfaceFlinger* flinger; 3457 sp<IBinder> display; 3458 sp<IGraphicBufferProducer> producer; 3459 Rect sourceCrop; 3460 uint32_t reqWidth, reqHeight; 3461 uint32_t minLayerZ,maxLayerZ; 3462 bool useIdentityTransform; 3463 Transform::orientation_flags rotation; 3464 status_t result; 3465 bool isLocalScreenshot; 3466 public: 3467 MessageCaptureScreen(SurfaceFlinger* flinger, 3468 const sp<IBinder>& display, 3469 const sp<IGraphicBufferProducer>& producer, 3470 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 3471 uint32_t minLayerZ, uint32_t maxLayerZ, 3472 bool useIdentityTransform, 3473 Transform::orientation_flags rotation, 3474 bool isLocalScreenshot) 3475 : flinger(flinger), display(display), producer(producer), 3476 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight), 3477 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 3478 useIdentityTransform(useIdentityTransform), 3479 rotation(rotation), result(PERMISSION_DENIED), 3480 isLocalScreenshot(isLocalScreenshot) 3481 { 3482 } 3483 status_t getResult() const { 3484 return result; 3485 } 3486 virtual bool handler() { 3487 Mutex::Autolock _l(flinger->mStateLock); 3488 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display)); 3489 result = flinger->captureScreenImplLocked(hw, producer, 3490 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, 3491 useIdentityTransform, rotation, isLocalScreenshot); 3492 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result); 3493 return true; 3494 } 3495 }; 3496 3497 // this creates a "fake" BBinder which will serve as a "fake" remote 3498 // binder to receive the marshaled calls and forward them to the 3499 // real remote (a BpGraphicBufferProducer) 3500 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer); 3501 3502 // the asInterface() call below creates our "fake" BpGraphicBufferProducer 3503 // which does the marshaling work forwards to our "fake remote" above. 3504 sp<MessageBase> msg = new MessageCaptureScreen(this, 3505 display, IGraphicBufferProducer::asInterface( wrapper ), 3506 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, 3507 useIdentityTransform, rotationFlags, isLocalScreenshot); 3508 3509 status_t res = postMessageAsync(msg); 3510 if (res == NO_ERROR) { 3511 res = wrapper->waitForResponse(); 3512 } 3513 return res; 3514 } 3515 3516 3517 void SurfaceFlinger::renderScreenImplLocked( 3518 const sp<const DisplayDevice>& hw, 3519 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 3520 uint32_t minLayerZ, uint32_t maxLayerZ, 3521 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation) 3522 { 3523 ATRACE_CALL(); 3524 RenderEngine& engine(getRenderEngine()); 3525 3526 // get screen geometry 3527 const int32_t hw_w = hw->getWidth(); 3528 const int32_t hw_h = hw->getHeight(); 3529 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w || 3530 static_cast<int32_t>(reqHeight) != hw_h; 3531 3532 // if a default or invalid sourceCrop is passed in, set reasonable values 3533 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || 3534 !sourceCrop.isValid()) { 3535 sourceCrop.setLeftTop(Point(0, 0)); 3536 sourceCrop.setRightBottom(Point(hw_w, hw_h)); 3537 } 3538 3539 // ensure that sourceCrop is inside screen 3540 if (sourceCrop.left < 0) { 3541 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left); 3542 } 3543 if (sourceCrop.right > hw_w) { 3544 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w); 3545 } 3546 if (sourceCrop.top < 0) { 3547 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top); 3548 } 3549 if (sourceCrop.bottom > hw_h) { 3550 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h); 3551 } 3552 3553 // make sure to clear all GL error flags 3554 engine.checkErrors(); 3555 3556 // set-up our viewport 3557 engine.setViewportAndProjection( 3558 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation); 3559 engine.disableTexturing(); 3560 3561 // redraw the screen entirely... 3562 engine.clearWithColor(0, 0, 0, 1); 3563 3564 const LayerVector& layers( mDrawingState.layersSortedByZ ); 3565 const size_t count = layers.size(); 3566 for (size_t i=0 ; i<count ; ++i) { 3567 const sp<Layer>& layer(layers[i]); 3568 const Layer::State& state(layer->getDrawingState()); 3569 if (state.layerStack == hw->getLayerStack()) { 3570 if (state.z >= minLayerZ && state.z <= maxLayerZ) { 3571 if (layer->isVisible()) { 3572 if (filtering) layer->setFiltering(true); 3573 layer->draw(hw, useIdentityTransform); 3574 if (filtering) layer->setFiltering(false); 3575 } 3576 } 3577 } 3578 } 3579 3580 hw->setViewportAndProjection(); 3581 } 3582 3583 3584 status_t SurfaceFlinger::captureScreenImplLocked( 3585 const sp<const DisplayDevice>& hw, 3586 const sp<IGraphicBufferProducer>& producer, 3587 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight, 3588 uint32_t minLayerZ, uint32_t maxLayerZ, 3589 bool useIdentityTransform, Transform::orientation_flags rotation, 3590 bool isLocalScreenshot) 3591 { 3592 ATRACE_CALL(); 3593 3594 // get screen geometry 3595 uint32_t hw_w = hw->getWidth(); 3596 uint32_t hw_h = hw->getHeight(); 3597 3598 if (rotation & Transform::ROT_90) { 3599 std::swap(hw_w, hw_h); 3600 } 3601 3602 if ((reqWidth > hw_w) || (reqHeight > hw_h)) { 3603 ALOGE("size mismatch (%d, %d) > (%d, %d)", 3604 reqWidth, reqHeight, hw_w, hw_h); 3605 return BAD_VALUE; 3606 } 3607 3608 reqWidth = (!reqWidth) ? hw_w : reqWidth; 3609 reqHeight = (!reqHeight) ? hw_h : reqHeight; 3610 3611 bool secureLayerIsVisible = false; 3612 const LayerVector& layers(mDrawingState.layersSortedByZ); 3613 const size_t count = layers.size(); 3614 for (size_t i = 0 ; i < count ; ++i) { 3615 const sp<Layer>& layer(layers[i]); 3616 const Layer::State& state(layer->getDrawingState()); 3617 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ && 3618 state.z <= maxLayerZ && layer->isVisible() && 3619 layer->isSecure()) { 3620 secureLayerIsVisible = true; 3621 } 3622 } 3623 3624 if (!isLocalScreenshot && secureLayerIsVisible) { 3625 ALOGW("FB is protected: PERMISSION_DENIED"); 3626 return PERMISSION_DENIED; 3627 } 3628 3629 // create a surface (because we're a producer, and we need to 3630 // dequeue/queue a buffer) 3631 sp<Surface> sur = new Surface(producer, false); 3632 3633 // Put the screenshot Surface into async mode so that 3634 // Layer::headFenceHasSignaled will always return true and we'll latch the 3635 // first buffer regardless of whether or not its acquire fence has 3636 // signaled. This is needed to avoid a race condition in the rotation 3637 // animation. See b/30209608 3638 sur->setAsyncMode(true); 3639 3640 ANativeWindow* window = sur.get(); 3641 3642 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL); 3643 if (result == NO_ERROR) { 3644 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN | 3645 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE; 3646 3647 int err = 0; 3648 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight); 3649 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW); 3650 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888); 3651 err |= native_window_set_usage(window, usage); 3652 3653 if (err == NO_ERROR) { 3654 ANativeWindowBuffer* buffer; 3655 /* TODO: Once we have the sync framework everywhere this can use 3656 * server-side waits on the fence that dequeueBuffer returns. 3657 */ 3658 result = native_window_dequeue_buffer_and_wait(window, &buffer); 3659 if (result == NO_ERROR) { 3660 int syncFd = -1; 3661 // create an EGLImage from the buffer so we can later 3662 // turn it into a texture 3663 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, 3664 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL); 3665 if (image != EGL_NO_IMAGE_KHR) { 3666 // this binds the given EGLImage as a framebuffer for the 3667 // duration of this scope. 3668 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image); 3669 if (imageBond.getStatus() == NO_ERROR) { 3670 // this will in fact render into our dequeued buffer 3671 // via an FBO, which means we didn't have to create 3672 // an EGLSurface and therefore we're not 3673 // dependent on the context's EGLConfig. 3674 renderScreenImplLocked( 3675 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true, 3676 useIdentityTransform, rotation); 3677 3678 // Attempt to create a sync khr object that can produce a sync point. If that 3679 // isn't available, create a non-dupable sync object in the fallback path and 3680 // wait on it directly. 3681 EGLSyncKHR sync; 3682 if (!DEBUG_SCREENSHOTS) { 3683 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL); 3684 // native fence fd will not be populated until flush() is done. 3685 getRenderEngine().flush(); 3686 } else { 3687 sync = EGL_NO_SYNC_KHR; 3688 } 3689 if (sync != EGL_NO_SYNC_KHR) { 3690 // get the sync fd 3691 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync); 3692 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) { 3693 ALOGW("captureScreen: failed to dup sync khr object"); 3694 syncFd = -1; 3695 } 3696 eglDestroySyncKHR(mEGLDisplay, sync); 3697 } else { 3698 // fallback path 3699 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL); 3700 if (sync != EGL_NO_SYNC_KHR) { 3701 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync, 3702 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/); 3703 EGLint eglErr = eglGetError(); 3704 if (result == EGL_TIMEOUT_EXPIRED_KHR) { 3705 ALOGW("captureScreen: fence wait timed out"); 3706 } else { 3707 ALOGW_IF(eglErr != EGL_SUCCESS, 3708 "captureScreen: error waiting on EGL fence: %#x", eglErr); 3709 } 3710 eglDestroySyncKHR(mEGLDisplay, sync); 3711 } else { 3712 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError()); 3713 } 3714 } 3715 if (DEBUG_SCREENSHOTS) { 3716 uint32_t* pixels = new uint32_t[reqWidth*reqHeight]; 3717 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels); 3718 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, 3719 hw, minLayerZ, maxLayerZ); 3720 delete [] pixels; 3721 } 3722 3723 } else { 3724 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot"); 3725 result = INVALID_OPERATION; 3726 window->cancelBuffer(window, buffer, syncFd); 3727 buffer = NULL; 3728 } 3729 // destroy our image 3730 eglDestroyImageKHR(mEGLDisplay, image); 3731 } else { 3732 result = BAD_VALUE; 3733 } 3734 if (buffer) { 3735 // queueBuffer takes ownership of syncFd 3736 result = window->queueBuffer(window, buffer, syncFd); 3737 } 3738 } 3739 } else { 3740 result = BAD_VALUE; 3741 } 3742 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL); 3743 } 3744 3745 return result; 3746 } 3747 3748 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr, 3749 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) { 3750 if (DEBUG_SCREENSHOTS) { 3751 for (size_t y=0 ; y<h ; y++) { 3752 uint32_t const * p = (uint32_t const *)vaddr + y*s; 3753 for (size_t x=0 ; x<w ; x++) { 3754 if (p[x] != 0xFF000000) return; 3755 } 3756 } 3757 ALOGE("*** we just took a black screenshot ***\n" 3758 "requested minz=%d, maxz=%d, layerStack=%d", 3759 minLayerZ, maxLayerZ, hw->getLayerStack()); 3760 const LayerVector& layers( mDrawingState.layersSortedByZ ); 3761 const size_t count = layers.size(); 3762 for (size_t i=0 ; i<count ; ++i) { 3763 const sp<Layer>& layer(layers[i]); 3764 const Layer::State& state(layer->getDrawingState()); 3765 const bool visible = (state.layerStack == hw->getLayerStack()) 3766 && (state.z >= minLayerZ && state.z <= maxLayerZ) 3767 && (layer->isVisible()); 3768 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f", 3769 visible ? '+' : '-', 3770 i, layer->getName().string(), state.layerStack, state.z, 3771 layer->isVisible(), state.flags, state.alpha); 3772 } 3773 } 3774 } 3775 3776 bool SurfaceFlinger::getFrameTimestamps(const Layer& layer, 3777 uint64_t frameNumber, FrameTimestamps* outTimestamps) { 3778 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps); 3779 } 3780 3781 // --------------------------------------------------------------------------- 3782 3783 SurfaceFlinger::LayerVector::LayerVector() { 3784 } 3785 3786 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs) 3787 : SortedVector<sp<Layer> >(rhs) { 3788 } 3789 3790 int SurfaceFlinger::LayerVector::do_compare(const void* lhs, 3791 const void* rhs) const 3792 { 3793 // sort layers per layer-stack, then by z-order and finally by sequence 3794 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs)); 3795 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs)); 3796 3797 uint32_t ls = l->getCurrentState().layerStack; 3798 uint32_t rs = r->getCurrentState().layerStack; 3799 if (ls != rs) 3800 return ls - rs; 3801 3802 uint32_t lz = l->getCurrentState().z; 3803 uint32_t rz = r->getCurrentState().z; 3804 if (lz != rz) 3805 return lz - rz; 3806 3807 return l->sequence - r->sequence; 3808 } 3809 3810 // --------------------------------------------------------------------------- 3811 3812 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState() 3813 : type(DisplayDevice::DISPLAY_ID_INVALID), 3814 layerStack(DisplayDevice::NO_LAYER_STACK), 3815 orientation(0), 3816 width(0), 3817 height(0), 3818 isSecure(false) { 3819 } 3820 3821 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState( 3822 DisplayDevice::DisplayType type, bool isSecure) 3823 : type(type), 3824 layerStack(DisplayDevice::NO_LAYER_STACK), 3825 orientation(0), 3826 width(0), 3827 height(0), 3828 isSecure(isSecure) { 3829 viewport.makeInvalid(); 3830 frame.makeInvalid(); 3831 } 3832 3833 // --------------------------------------------------------------------------- 3834 3835 }; // namespace android 3836 3837 3838 #if defined(__gl_h_) 3839 #error "don't include gl/gl.h in this file" 3840 #endif 3841 3842 #if defined(__gl2_h_) 3843 #error "don't include gl2/gl2.h in this file" 3844 #endif 3845