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