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