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