blob: 5cd975f08ea0e5390e972ef57ae4d34b5ae9066d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
David Sodman0c69cad2017-08-21 12:12:51 -070073#include "BufferLayer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070075#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
chaviw1d044282017-09-27 12:19:28 -070092#include <layerproto/LayerProtoParser.h>
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094#define DISPLAY_COUNT 1
95
Mathias Agopianfee2b462013-07-03 12:34:01 -070096/*
97 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
98 * black pixels.
99 */
100#define DEBUG_SCREENSHOTS false
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Steven Thomasb02664d2017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700132int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700133bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800134uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800135bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800136bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800137int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800138// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
Kalle Raitaa099a242017-01-11 11:17:29 -0800141
142std::string getHwcServiceName() {
143 char value[PROPERTY_VALUE_MAX] = {};
144 property_get("debug.sf.hwc_service_name", value, "default");
145 ALOGI("Using HWComposer service: '%s'", value);
146 return std::string(value);
147}
148
149bool useTrebleTestingOverride() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.treble_testing_override", value, "false");
152 ALOGI("Treble testing override: '%s'", value);
153 return std::string(value) == "true";
154}
155
David Sodmanbc815282017-11-05 18:57:52 -0800156SurfaceFlingerBE::SurfaceFlingerBE()
157 : mHwcServiceName(getHwcServiceName()),
158 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800162 mComposerSequenceId(0) {
163}
164
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800165SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800166 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700168 mTransactionPending(false),
169 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700170 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700171 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700172 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800174 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800176 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800177 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700180 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700181 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700182 mDebugInSwapBuffers(0),
183 mLastSwapBufferTime(0),
184 mDebugInTransaction(0),
185 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700186 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700187 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800188 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800196 mMainThreadId(std::this_thread::get_id()),
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800197 mCreateBufferQueue(&BufferQueue::createBufferQueue) {}
198
199SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800200 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800201
202 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
203 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
204
205 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
206 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
207
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800208 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
209 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
212 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
213
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700214 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
215 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
216
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800217 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
218 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
219
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 // Vr flinger is only enabled on Daydream ready devices.
221 useVrFlinger = getBool< ISurfaceFlingerConfigs,
222 &ISurfaceFlingerConfigs::useVrFlinger>(false);
223
Fabien Sanglard1971b632017-03-10 14:50:03 -0800224 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
225 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
226
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227 hasWideColorDisplay =
228 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
229
David Sodman99974d22017-11-28 12:04:33 -0800230 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 // debugging stuff...
233 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700234
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700236 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 property_get("debug.sf.showupdates", value, "0");
239 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241 property_get("debug.sf.ddms", value, "0");
242 mDebugDDMS = atoi(value);
243 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700244 if (!startDdmConnection()) {
245 // start failed, and DDMS debugging not enabled
246 mDebugDDMS = 0;
247 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700249 ALOGI_IF(mDebugRegion, "showupdates enabled");
250 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700251
252 property_get("debug.sf.disable_backpressure", value, "0");
253 mPropagateBackpressure = !atoi(value);
254 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700255
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800256 property_get("debug.sf.enable_hwc_vds", value, "0");
257 mUseHwcVirtualDisplays = atoi(value);
258 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800259
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800260 property_get("ro.sf.disable_triple_buffer", value, "1");
261 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800262 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700263
Romain Guy11d63f42017-07-20 12:47:14 -0700264 // We should be reading 'persist.sys.sf.color_saturation' here
265 // but since /data may be encrypted, we need to wait until after vold
266 // comes online to attempt to read the property. The property is
267 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800268
269 if (useTrebleTestingOverride()) {
270 // Without the override SurfaceFlinger cannot connect to HIDL
271 // services that are not listed in the manifests. Considered
272 // deriving the setting from the set service name, but it
273 // would be brittle if the name that's not 'default' is used
274 // for production purposes later on.
275 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277}
278
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800279void SurfaceFlinger::onFirstRef()
280{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800281 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800282}
283
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284SurfaceFlinger::~SurfaceFlinger()
285{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286}
287
Dan Stozac7014012014-02-14 15:03:43 -0800288void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800289{
290 // the window manager died on us. prepare its eulogy.
291
Andy McFadden13a082e2012-08-24 10:16:42 -0700292 // restore initial conditions (default device unblank, etc)
293 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800294
295 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700296 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800297}
298
Robert Carr1db73f62016-12-21 12:58:51 -0800299static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700300 status_t err = client->initCheck();
301 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800302 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303 }
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return nullptr;
305}
306
307sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
308 return initClient(new Client(this));
309}
310
311sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
312 const sp<IGraphicBufferProducer>& gbp) {
313 if (authenticateSurfaceTexture(gbp) == false) {
314 return nullptr;
315 }
316 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
317 if (layer == nullptr) {
318 return nullptr;
319 }
320
321 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322}
323
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700324sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
325 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700326{
327 class DisplayToken : public BBinder {
328 sp<SurfaceFlinger> flinger;
329 virtual ~DisplayToken() {
330 // no more references, this display must be terminated
331 Mutex::Autolock _l(flinger->mStateLock);
332 flinger->mCurrentState.displays.removeItem(this);
333 flinger->setTransactionFlags(eDisplayTransactionNeeded);
334 }
335 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700336 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 : flinger(flinger) {
338 }
339 };
340
341 sp<BBinder> token = new DisplayToken(this);
342
343 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700344 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700345 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700347 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 return token;
349}
350
Jesse Hall6c913be2013-08-08 12:15:49 -0700351void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
352 Mutex::Autolock _l(mStateLock);
353
354 ssize_t idx = mCurrentState.displays.indexOfKey(display);
355 if (idx < 0) {
356 ALOGW("destroyDisplay: invalid display token");
357 return;
358 }
359
360 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
361 if (!info.isVirtualDisplay()) {
362 ALOGE("destroyDisplay called for non-virtual display");
363 return;
364 }
Irvelffc9efc2016-07-27 15:16:37 -0700365 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700366 mCurrentState.displays.removeItemsAt(idx);
367 setTransactionFlags(eDisplayTransactionNeeded);
368}
369
Mathias Agopiane57f2922012-08-09 16:29:12 -0700370sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700371 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700372 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800373 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700374 }
Jesse Hall692c7232012-11-08 15:41:56 -0800375 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700376}
377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378void SurfaceFlinger::bootFinished()
379{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700380 if (mStartPropertySetThread->join() != NO_ERROR) {
381 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383 const nsecs_t now = systemTime();
384 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000385 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700386
387 // wait patiently for the window manager death
388 const String16 name("window");
389 sp<IBinder> window(defaultServiceManager()->getService(name));
390 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700391 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700392 }
393
Steven Thomas050b2c82017-03-06 11:45:16 -0800394 if (mVrFlinger) {
395 mVrFlinger->OnBootFinished();
396 }
397
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700398 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700399 // formerly we would just kill the process, but we now ask it to exit so it
400 // can choose where to stop the animation.
401 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700402
403 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
404 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
405 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700406
Thierry Strudel2924d012017-08-14 15:19:37 -0700407 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700408 readPersistentProperties();
409 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700410 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411}
412
Mathias Agopian3f844832013-08-07 21:24:32 -0700413void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700414 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800415 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700416 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700417 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800418 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
419 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700420 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700421 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700422 return true;
423 }
424 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700425 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426}
427
Lloyd Piquee83f9312018-02-01 12:53:17 -0800428class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700430 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000431 const char* name) :
432 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700434 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000435 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
436 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 mDispSync(dispSync),
438 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 mVsyncMutex(),
440 mPhaseOffset(phaseOffset),
441 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700442
Lloyd Piquee83f9312018-02-01 12:53:17 -0800443 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444
Lloyd Piquee83f9312018-02-01 12:53:17 -0800445 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 static_cast<DispSync::Callback*>(this));
450 if (err != NO_ERROR) {
451 ALOGE("error registering vsync callback: %s (%d)",
452 strerror(-err), err);
453 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 } else {
456 status_t err = mDispSync->removeEventListener(
457 static_cast<DispSync::Callback*>(this));
458 if (err != NO_ERROR) {
459 ALOGE("error unregistering vsync callback: %s (%d)",
460 strerror(-err), err);
461 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700462 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700464 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 }
466
Lloyd Piquee83f9312018-02-01 12:53:17 -0800467 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 mCallback = callback;
470 }
471
Lloyd Piquee83f9312018-02-01 12:53:17 -0800472 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 Mutex::Autolock lock(mVsyncMutex);
474
475 // Normalize phaseOffset to [0, period)
476 auto period = mDispSync->getPeriod();
477 phaseOffset %= period;
478 if (phaseOffset < 0) {
479 // If we're here, then phaseOffset is in (-period, 0). After this
480 // operation, it will be in (0, period)
481 phaseOffset += period;
482 }
483 mPhaseOffset = phaseOffset;
484
485 // If we're not enabled, we don't need to mess with the listeners
486 if (!mEnabled) {
487 return;
488 }
489
490 // Remove the listener with the old offset
491 status_t err = mDispSync->removeEventListener(
492 static_cast<DispSync::Callback*>(this));
493 if (err != NO_ERROR) {
494 ALOGE("error unregistering vsync callback: %s (%d)",
495 strerror(-err), err);
496 }
497
498 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 static_cast<DispSync::Callback*>(this));
501 if (err != NO_ERROR) {
502 ALOGE("error registering vsync callback: %s (%d)",
503 strerror(-err), err);
504 }
505 }
506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507private:
508 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800509 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 callback = mCallback;
513
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514 if (mTraceVsync) {
515 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700516 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700517 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 }
519
Peiyong Lin566a3b42018-01-09 18:22:43 -0800520 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 callback->onVSyncEvent(when);
522 }
523 }
524
Tim Murray4a4e4a22016-04-19 16:29:23 +0000525 const char* const mName;
526
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 int mValue;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 const String8 mVsyncOnLabel;
531 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534
535 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537
538 Mutex mVsyncMutex; // Protects the following
539 nsecs_t mPhaseOffset;
540 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541};
542
Lloyd Piquee83f9312018-02-01 12:53:17 -0800543class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700544public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800545 InjectVSyncSource() = default;
546 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700547
Lloyd Piquee83f9312018-02-01 12:53:17 -0800548 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700549 std::lock_guard<std::mutex> lock(mCallbackMutex);
550 mCallback = callback;
551 }
552
Lloyd Piquee83f9312018-02-01 12:53:17 -0800553 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700554 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700555 if (mCallback) {
556 mCallback->onVSyncEvent(when);
557 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700558 }
559
Lloyd Piquee83f9312018-02-01 12:53:17 -0800560 void setVSyncEnabled(bool) override {}
561 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700562
563private:
564 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700566};
567
Wei Wangf9b05ee2017-07-19 20:59:39 -0700568// Do not call property_set on main thread which will be blocked by init
569// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700571 ALOGI( "SurfaceFlinger's main thread ready to run. "
572 "Initializing graphics H/W...");
573
Thierry Strudel2924d012017-08-14 15:19:37 -0700574 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900575
Steven Thomasb02664d2017-07-26 18:48:28 -0700576 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577
Steven Thomasb02664d2017-07-26 18:48:28 -0700578 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800579 mEventThreadSource =
580 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
581 true, "app");
582 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
583 "appEventThread");
584 mSfEventThreadSource =
585 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
586 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800587
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800588 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
589 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800590 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800593 getBE().mRenderEngine =
594 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
595 hasWideColorDisplay
596 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
597 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800598 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700599
600 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
601 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800602 getBE().mHwc.reset(
603 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700604 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800605 // Process any initial hotplug and resulting display changes.
606 processDisplayHotplugEventsLocked();
607 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
608 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800609
Lloyd Piquefcd86612017-12-14 17:15:36 -0800610 // make the default display GLContext current so that we can create textures
611 // when creating Layers (which may happens before we render something)
612 getDefaultDisplayDeviceLocked()->makeCurrent();
613
Steven Thomas050b2c82017-03-06 11:45:16 -0800614 if (useVrFlinger) {
615 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700616 // This callback is called from the vr flinger dispatch thread. We
617 // need to call signalTransaction(), which requires holding
618 // mStateLock when we're not on the main thread. Acquiring
619 // mStateLock from the vr flinger dispatch thread might trigger a
620 // deadlock in surface flinger (see b/66916578), so post a message
621 // to be handled on the main thread instead.
622 sp<LambdaMessage> message = new LambdaMessage([=]() {
623 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
624 mVrFlingerRequestsDisplay = requestDisplay;
625 signalTransaction();
626 });
627 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 };
David Sodman105b7dc2017-11-04 20:28:14 -0700629 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
630 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800631 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800632 if (!mVrFlinger) {
633 ALOGE("Failed to start vrflinger");
634 }
635 }
636
Lloyd Pique755e3192018-01-31 16:46:15 -0800637 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
638 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
639 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700640
Mathias Agopian92a979a2012-08-02 18:32:23 -0700641 // initialize our drawing state
642 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700643
Andy McFadden13a082e2012-08-24 10:16:42 -0700644 // set initial conditions (e.g. unblank default device)
645 initializeDisplays();
646
David Sodmanbc815282017-11-05 18:57:52 -0800647 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700648
Wei Wangf9b05ee2017-07-19 20:59:39 -0700649 // Inform native graphics APIs whether the present timestamp is supported:
650 if (getHwComposer().hasCapability(
651 HWC2::Capability::PresentFenceIsNotReliable)) {
652 mStartPropertySetThread = new StartPropertySetThread(false);
653 } else {
654 mStartPropertySetThread = new StartPropertySetThread(true);
655 }
656
657 if (mStartPropertySetThread->Start() != NO_ERROR) {
658 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800660
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700662}
663
Romain Guy11d63f42017-07-20 12:47:14 -0700664void SurfaceFlinger::readPersistentProperties() {
665 char value[PROPERTY_VALUE_MAX];
666
667 property_get("persist.sys.sf.color_saturation", value, "1.0");
668 mSaturation = atof(value);
669 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100670
671 property_get("persist.sys.sf.native_mode", value, "0");
672 mForceNativeColorMode = atoi(value) == 1;
673 if (mForceNativeColorMode) {
674 ALOGV("Forcing native color mode");
675 }
Romain Guy11d63f42017-07-20 12:47:14 -0700676}
677
Mathias Agopiana67e4182012-06-19 17:26:12 -0700678void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800679 // Start boot animation service by setting a property mailbox
680 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800682 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 if (mStartPropertySetThread->join() != NO_ERROR) {
684 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800685 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700686}
687
Mathias Agopian875d8e12013-06-07 15:35:48 -0700688size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800689 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800693 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800696// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800697
Jamie Gennis582270d2011-08-17 18:19:00 -0700698bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800699 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800700 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800701 return authenticateSurfaceTextureLocked(bufferProducer);
702}
703
704bool SurfaceFlinger::authenticateSurfaceTextureLocked(
705 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800706 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800707 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800708}
709
Brian Anderson6b376712017-04-04 10:51:39 -0700710status_t SurfaceFlinger::getSupportedFrameTimestamps(
711 std::vector<FrameEvent>* outSupported) const {
712 *outSupported = {
713 FrameEvent::REQUESTED_PRESENT,
714 FrameEvent::ACQUIRE,
715 FrameEvent::LATCH,
716 FrameEvent::FIRST_REFRESH_START,
717 FrameEvent::LAST_REFRESH_START,
718 FrameEvent::GPU_COMPOSITION_DONE,
719 FrameEvent::DEQUEUE_READY,
720 FrameEvent::RELEASE,
721 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700722 ConditionalLock _l(mStateLock,
723 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700724 if (!getHwComposer().hasCapability(
725 HWC2::Capability::PresentFenceIsNotReliable)) {
726 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
727 }
728 return NO_ERROR;
729}
730
Dan Stoza7f7da322014-05-02 15:26:25 -0700731status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
732 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800733 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700734 return BAD_VALUE;
735 }
736
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500737 if (!display.get())
738 return NAME_NOT_FOUND;
739
Jesse Hall692c7232012-11-08 15:41:56 -0800740 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700741 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800742 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700743 type = i;
744 break;
745 }
746 }
747
748 if (type < 0) {
749 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700750 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752 // TODO: Not sure if display density should handled by SF any longer
753 class Density {
754 static int getDensityFromProperty(char const* propName) {
755 char property[PROPERTY_VALUE_MAX];
756 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800757 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758 density = atoi(property);
759 }
760 return density;
761 }
762 public:
763 static int getEmuDensity() {
764 return getDensityFromProperty("qemu.sf.lcd_density"); }
765 static int getBuildDensity() {
766 return getDensityFromProperty("ro.sf.lcd_density"); }
767 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700768
Dan Stoza7f7da322014-05-02 15:26:25 -0700769 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700770
Steven Thomas6d8110b2017-08-31 18:24:21 -0700771 ConditionalLock _l(mStateLock,
772 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800773 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 DisplayInfo info = DisplayInfo();
775
Dan Stoza9e56aa02015-11-02 13:00:03 -0800776 float xdpi = hwConfig->getDpiX();
777 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700778
779 if (type == DisplayDevice::DISPLAY_PRIMARY) {
780 // The density of the device is provided by a build property
781 float density = Density::getBuildDensity() / 160.0f;
782 if (density == 0) {
783 // the build doesn't provide a density -- this is wrong!
784 // use xdpi instead
785 ALOGE("ro.sf.lcd_density must be defined as a build property");
786 density = xdpi / 160.0f;
787 }
788 if (Density::getEmuDensity()) {
789 // if "qemu.sf.lcd_density" is specified, it overrides everything
790 xdpi = ydpi = density = Density::getEmuDensity();
791 density /= 160.0f;
792 }
793 info.density = density;
794
795 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700796 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800797 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 } else {
799 // TODO: where should this value come from?
800 static const int TV_DENSITY = 213;
801 info.density = TV_DENSITY / 160.0f;
802 info.orientation = 0;
803 }
804
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 info.w = hwConfig->getWidth();
806 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 info.xdpi = xdpi;
808 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900810 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811
Andy McFadden91b2ca82014-06-13 14:04:23 -0700812 // This is how far in advance a buffer must be queued for
813 // presentation at a given time. If you want a buffer to appear
814 // on the screen at time N, you must submit the buffer before
815 // (N - presentationDeadline).
816 //
817 // Normally it's one full refresh period (to give SF a chance to
818 // latch the buffer), but this can be reduced by configuring a
819 // DispSync offset. Any additional delays introduced by the hardware
820 // composer or panel must be accounted for here.
821 //
822 // We add an additional 1ms to allow for processing time and
823 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800825 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700826
827 // All non-virtual displays are currently considered secure.
828 info.secure = true;
829
Michael Wright28f24d02016-07-12 13:30:53 -0700830 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 }
832
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 return NO_ERROR;
834}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700835
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800836status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700837 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800838 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700839 return BAD_VALUE;
840 }
841
842 // FIXME for now we always return stats for the primary display
843 memset(stats, 0, sizeof(*stats));
844 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
845 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
846 return NO_ERROR;
847}
848
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700849int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800850 if (display == nullptr) {
851 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800852 return BAD_VALUE;
853 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700854
855 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800856 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700857 return device->getActiveConfig();
858 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700859
Dan Stoza24a42e92015-03-09 10:04:11 -0700860 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700861}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700862
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700863void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
864 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
865 this);
866 int32_t type = hw->getDisplayType();
867 int currentMode = hw->getActiveConfig();
868
869 if (mode == currentMode) {
870 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
871 return;
872 }
873
874 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
875 ALOGW("Trying to set config for virtual display");
876 return;
877 }
878
879 hw->setActiveConfig(mode);
880 getHwComposer().setActiveConfig(type, mode);
881}
882
883status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
884 class MessageSetActiveConfig: public MessageBase {
885 SurfaceFlinger& mFlinger;
886 sp<IBinder> mDisplay;
887 int mMode;
888 public:
889 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
890 int mode) :
891 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
892 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700893 Vector<DisplayInfo> configs;
894 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700895 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700896 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700897 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700898 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700899 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700900 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800901 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700902 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700903 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
905 ALOGW("Attempt to set active config = %d for virtual display",
906 mMode);
907 } else {
908 mFlinger.setActiveConfigInternal(hw, mMode);
909 }
910 return true;
911 }
912 };
913 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
914 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700915 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700916}
Michael Wright28f24d02016-07-12 13:30:53 -0700917status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
918 Vector<android_color_mode_t>* outColorModes) {
919 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
920 return BAD_VALUE;
921 }
922
923 if (!display.get()) {
924 return NAME_NOT_FOUND;
925 }
926
927 int32_t type = NAME_NOT_FOUND;
928 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
929 if (display == mBuiltinDisplays[i]) {
930 type = i;
931 break;
932 }
933 }
934
935 if (type < 0) {
936 return type;
937 }
938
Steven Thomas6d8110b2017-08-31 18:24:21 -0700939 std::vector<android_color_mode_t> modes;
940 {
941 ConditionalLock _l(mStateLock,
942 std::this_thread::get_id() != mMainThreadId);
943 modes = getHwComposer().getColorModes(type);
944 }
Michael Wright28f24d02016-07-12 13:30:53 -0700945 outColorModes->clear();
946 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
947
948 return NO_ERROR;
949}
950
951android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700952 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700953 if (device != nullptr) {
954 return device->getActiveColorMode();
955 }
956 return static_cast<android_color_mode_t>(BAD_VALUE);
957}
958
959void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
960 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700961 int32_t type = hw->getDisplayType();
962 android_color_mode_t currentMode = hw->getActiveColorMode();
963
964 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700965 return;
966 }
967
968 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
969 ALOGW("Trying to set config for virtual display");
970 return;
971 }
972
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600973 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
974 hw->getDisplayType());
975
Michael Wright28f24d02016-07-12 13:30:53 -0700976 hw->setActiveColorMode(mode);
977 getHwComposer().setActiveColorMode(type, mode);
978}
979
980
981status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
982 android_color_mode_t colorMode) {
983 class MessageSetActiveColorMode: public MessageBase {
984 SurfaceFlinger& mFlinger;
985 sp<IBinder> mDisplay;
986 android_color_mode_t mMode;
987 public:
988 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
989 android_color_mode_t mode) :
990 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
991 virtual bool handler() {
992 Vector<android_color_mode_t> modes;
993 mFlinger.getDisplayColorModes(mDisplay, &modes);
994 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
995 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600996 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
997 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700998 return true;
999 }
1000 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1001 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001002 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1003 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001004 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGW("Attempt to set active color mode %s %d for virtual display",
1006 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001007 } else {
1008 mFlinger.setActiveColorModeInternal(hw, mMode);
1009 }
1010 return true;
1011 }
1012 };
1013 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1014 postMessageSync(msg);
1015 return NO_ERROR;
1016}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001017
Svetoslavd85084b2014-03-20 10:28:31 -07001018status_t SurfaceFlinger::clearAnimationFrameStats() {
1019 Mutex::Autolock _l(mStateLock);
1020 mAnimFrameTracker.clearStats();
1021 return NO_ERROR;
1022}
1023
1024status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1025 Mutex::Autolock _l(mStateLock);
1026 mAnimFrameTracker.getStats(outStats);
1027 return NO_ERROR;
1028}
1029
Dan Stozac4f471e2016-03-24 09:31:08 -07001030status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1031 HdrCapabilities* outCapabilities) const {
1032 Mutex::Autolock _l(mStateLock);
1033
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001034 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001035 if (displayDevice == nullptr) {
1036 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1037 return BAD_VALUE;
1038 }
1039
1040 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001041 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001042 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001043 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1044 // insert HDR10 as we will force client composition for HDR10
1045 // layers
1046 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1047 types.push_back(HAL_HDR_HDR10);
1048
1049 *outCapabilities = HdrCapabilities(types,
1050 capabilities->getDesiredMaxLuminance(),
1051 capabilities->getDesiredMaxAverageLuminance(),
1052 capabilities->getDesiredMinLuminance());
1053 } else {
1054 *outCapabilities = std::move(*capabilities);
1055 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001056 } else {
1057 return BAD_VALUE;
1058 }
1059
1060 return NO_ERROR;
1061}
1062
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001064 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1065 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 if (mInjectVSyncs == enable) {
1068 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070
1071 if (enable) {
1072 ALOGV("VSync Injections enabled");
1073 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001074 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001075 mInjectorEventThread =
1076 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1077 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001079 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001080 } else {
1081 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001082 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 }
1084
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 });
1087 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 return NO_ERROR;
1089}
1090
1091status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001092 Mutex::Autolock _l(mStateLock);
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094 if (!mInjectVSyncs) {
1095 ALOGE("VSync Injections not enabled");
1096 return BAD_VALUE;
1097 }
1098 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1099 ALOGV("Injecting VSync inside SurfaceFlinger");
1100 mVSyncInjector->onInjectSyncEvent(when);
1101 }
1102 return NO_ERROR;
1103}
1104
Lloyd Pique755e3192018-01-31 16:46:15 -08001105status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1106 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001107 IPCThreadState* ipc = IPCThreadState::self();
1108 const int pid = ipc->getCallingPid();
1109 const int uid = ipc->getCallingUid();
1110 if ((uid != AID_SHELL) &&
1111 !PermissionCache::checkPermission(sDump, pid, uid)) {
1112 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1113 return PERMISSION_DENIED;
1114 }
1115
1116 // Try to acquire a lock for 1s, fail gracefully
1117 const status_t err = mStateLock.timedLock(s2ns(1));
1118 const bool locked = (err == NO_ERROR);
1119 if (!locked) {
1120 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1121 return TIMED_OUT;
1122 }
1123
1124 outLayers->clear();
1125 mCurrentState.traverseInZOrder([&](Layer* layer) {
1126 outLayers->push_back(layer->getLayerDebugInfo());
1127 });
1128
1129 mStateLock.unlock();
1130 return NO_ERROR;
1131}
1132
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001133// ----------------------------------------------------------------------------
1134
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001135sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1136 ISurfaceComposer::VsyncSource vsyncSource) {
1137 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1138 return mSFEventThread->createEventConnection();
1139 } else {
1140 return mEventThread->createEventConnection();
1141 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001142}
1143
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001144// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145
1146void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001147 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148}
1149
1150void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001151 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152}
1153
1154void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001155 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156}
1157
1158void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001159 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001160 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161}
1162
1163status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001164 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166}
1167
1168status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001169 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001170 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001171 if (res == NO_ERROR) {
1172 msg->wait();
1173 }
1174 return res;
1175}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001177void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001178 do {
1179 waitForEvent();
1180 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181}
1182
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183void SurfaceFlinger::enableHardwareVsync() {
1184 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001187 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1188 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001190 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191}
1192
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 Mutex::Autolock _l(mHWVsyncLock);
1195
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (makeAvailable) {
1197 mHWVsyncAvailable = true;
1198 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001199 // Hardware vsync is not currently available, so abort the resync
1200 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001201 return;
1202 }
1203
David Sodman105b7dc2017-11-04 20:28:14 -07001204 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001205 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206
1207 mPrimaryDispSync.reset();
1208 mPrimaryDispSync.setPeriod(period);
1209
1210 if (!mPrimaryHWVsyncEnabled) {
1211 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001212 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1213 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214 mPrimaryHWVsyncEnabled = true;
1215 }
1216}
1217
Jesse Hall948fe0c2013-10-14 12:56:09 -07001218void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 Mutex::Autolock _l(mHWVsyncLock);
1220 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001221 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1222 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 mPrimaryDispSync.endResync();
1224 mPrimaryHWVsyncEnabled = false;
1225 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226 if (makeUnavailable) {
1227 mHWVsyncAvailable = false;
1228 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229}
1230
Tim Murray4a4e4a22016-04-19 16:29:23 +00001231void SurfaceFlinger::resyncWithRateLimit() {
1232 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001233
1234 // No explicit locking is needed here since EventThread holds a lock while calling this method
1235 static nsecs_t sLastResyncAttempted = 0;
1236 const nsecs_t now = systemTime();
1237 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239 }
Dan Stoza57164302017-05-08 14:03:54 -07001240 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001241}
1242
Steven Thomasb02664d2017-07-26 18:48:28 -07001243void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1244 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001245 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001247 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001248 return;
1249 }
1250
1251 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001252 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001253 return;
1254 }
1255
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 { // Scope for the lock
1259 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001260 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001263 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001264
1265 if (needsHwVsync) {
1266 enableHardwareVsync();
1267 } else {
1268 disableHardwareVsync(false);
1269 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001270}
1271
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001272void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001273 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1274 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001275}
1276
Lloyd Pique715a2c12017-12-14 17:18:08 -08001277void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1278 HWC2::Connection connection) {
1279 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1280 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001281
Lloyd Piqueba04e622017-12-14 17:11:26 -08001282 // Ignore events that do not have the right sequenceId.
1283 if (sequenceId != getBE().mComposerSequenceId) {
1284 return;
1285 }
1286
Steven Thomasb02664d2017-07-26 18:48:28 -07001287 // Only lock if we're not on the main thread. This function is normally
1288 // called on a hwbinder thread, but for the primary display it's called on
1289 // the main thread with the state lock already held, so don't attempt to
1290 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001291 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292
Lloyd Pique715a2c12017-12-14 17:18:08 -08001293 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001294
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001295 if (std::this_thread::get_id() == mMainThreadId) {
1296 // Process all pending hot plug events immediately if we are on the main thread.
1297 processDisplayHotplugEventsLocked();
1298 }
1299
Lloyd Piqueba04e622017-12-14 17:11:26 -08001300 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001301}
1302
Steven Thomasb02664d2017-07-26 18:48:28 -07001303void SurfaceFlinger::onRefreshReceived(int sequenceId,
1304 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001305 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001306 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001309 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001310}
1311
Dan Stoza9e56aa02015-11-02 13:00:03 -08001312void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001314 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 getHwComposer().setVsyncEnabled(disp,
1316 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001317}
1318
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001320void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001322 // Clear the drawing state so that the logic inside of
1323 // handleTransactionLocked will fire. It will determine the delta between
1324 // mCurrentState and mDrawingState and re-apply all changes when we make the
1325 // transition.
1326 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001327 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001328 mDisplays.clear();
1329}
1330
Steven Thomas050b2c82017-03-06 11:45:16 -08001331void SurfaceFlinger::updateVrFlinger() {
1332 if (!mVrFlinger)
1333 return;
1334 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001335 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001336 return;
1337 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 ALOGE("Vr flinger is only supported for remote hardware composer"
1341 " service connections. Ignoring request to transition to vr"
1342 " flinger.");
1343 mVrFlingerRequestsDisplay = false;
1344 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001345 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 int currentDisplayPowerMode = getDisplayDeviceLocked(
1350 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001351
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001357 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001358 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1359 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001360 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361
David Sodman105b7dc2017-11-04 20:28:14 -07001362 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1363 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001364
1365 if (vrFlingerRequestsDisplay) {
1366 mVrFlinger->GrantDisplayOwnership();
1367 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001369 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
1371 mVisibleRegionsDirty = true;
1372 invalidateHwcGeometry();
1373
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001374 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1376 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1377 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001380 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 const nsecs_t period = activeConfig->getVsyncPeriod();
1382 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 // Use phase of 0 since phase is not known.
1385 // Use latency of 0, which will snap to the ideal latency.
1386 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001387
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388 android_atomic_or(1, &mRepaintEverything);
1389 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390}
1391
Mathias Agopian4fec8732012-06-29 14:12:52 -07001392void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001393 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001394 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001395 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001396 bool frameMissed = !mHadClientComposition &&
1397 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001398 (mPreviousPresentFence->getSignalTime() ==
1399 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001400 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001401 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001402 signalLayerUpdate();
1403 break;
1404 }
1405
Steven Thomas050b2c82017-03-06 11:45:16 -08001406 // Now that we're going to make it to the handleMessageTransaction()
1407 // call below it's safe to call updateVrFlinger(), which will
1408 // potentially trigger a display handoff.
1409 updateVrFlinger();
1410
Dan Stoza6b9454d2014-11-07 16:00:59 -08001411 bool refreshNeeded = handleMessageTransaction();
1412 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001413 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001414 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001415 // Signal a refresh if a transaction modified the window state,
1416 // a new buffer was latched, or if HWC has requested a full
1417 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418 signalRefresh();
1419 }
1420 break;
1421 }
1422 case MessageQueue::REFRESH: {
1423 handleMessageRefresh();
1424 break;
1425 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 }
1427}
1428
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001430 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001431 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001432 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001436}
1437
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001441}
1442
1443void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001445
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001446 mRefreshPending = false;
1447
Pablo Ceballos40845df2016-01-25 17:41:15 -08001448 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001449
Brian Andersond6927fb2016-07-23 23:37:30 -07001450 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001451 rebuildLayerStacks();
1452 setUpHWComposer();
1453 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001454 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001455 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001456 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001457
David Sodman105b7dc2017-11-04 20:28:14 -07001458 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001459
1460 mHadClientComposition = false;
1461 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1462 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1463 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001464 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001465 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001466
Dan Stoza9e56aa02015-11-02 13:00:03 -08001467 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470void SurfaceFlinger::doDebugFlashRegions()
1471{
1472 // is debugging enabled
1473 if (CC_LIKELY(!mDebugRegion))
1474 return;
1475
1476 const bool repaintEverything = mRepaintEverything;
1477 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1478 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001479 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001480 // transform the dirty region into this screen's coordinate space
1481 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1482 if (!dirtyRegion.isEmpty()) {
1483 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001484 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485
1486 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001487 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001488 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001489 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1490
Mathias Agopianda27af92012-09-13 18:17:13 -07001491 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492 }
1493 }
1494 }
1495
1496 postFramebuffer();
1497
1498 if (mDebugRegion > 1) {
1499 usleep(mDebugRegion * 1000);
1500 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001501
Dan Stoza9e56aa02015-11-02 13:00:03 -08001502 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001503 auto& displayDevice = mDisplays[displayId];
1504 if (!displayDevice->isDisplayOn()) {
1505 continue;
1506 }
1507
David Sodman105b7dc2017-11-04 20:28:14 -07001508 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1509 ALOGE_IF(result != NO_ERROR,
1510 "prepareFrame for display %zd failed:"
1511 " %d (%s)",
1512 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001513 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514}
1515
Adrian Roos1e1a1282017-11-01 19:05:31 +01001516void SurfaceFlinger::doTracing(const char* where) {
1517 ATRACE_CALL();
1518 ATRACE_NAME(where);
1519 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001520 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001521 }
1522}
1523
Brian Andersond6927fb2016-07-23 23:37:30 -07001524void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001526 ATRACE_CALL();
1527 ALOGV("preComposition");
1528
Mathias Agopiancd60f992012-08-16 16:28:27 -07001529 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001530 mDrawingState.traverseInZOrder([&](Layer* layer) {
1531 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 needExtraInvalidate = true;
1533 }
Robert Carr2047fae2016-11-28 14:09:09 -08001534 });
1535
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536 if (needExtraInvalidate) {
1537 signalLayerUpdate();
1538 }
1539}
1540
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541void SurfaceFlinger::updateCompositorTiming(
1542 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1543 std::shared_ptr<FenceTime>& presentFenceTime) {
1544 // Update queue of past composite+present times and determine the
1545 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001546 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001547 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001548 while (!getBE().mCompositePresentTimes.empty()) {
1549 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001550 // Cached values should have been updated before calling this method,
1551 // which helps avoid duplicate syscalls.
1552 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1553 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1554 break;
1555 }
1556 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001557 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001558 }
1559
1560 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001561 while (getBE().mCompositePresentTimes.size() > 16) {
1562 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001563 }
1564
Brian Andersond0010582017-03-07 13:20:31 -08001565 setCompositorTimingSnapped(
1566 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1567}
1568
1569void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1570 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001571 // Integer division and modulo round toward 0 not -inf, so we need to
1572 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001573 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1575 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1576
Brian Andersond0010582017-03-07 13:20:31 -08001577 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1578 if (idealLatency <= 0) {
1579 idealLatency = vsyncInterval;
1580 }
1581
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582 // Snap the latency to a value that removes scheduling jitter from the
1583 // composition and present times, which often have >1ms of jitter.
1584 // Reducing jitter is important if an app attempts to extrapolate
1585 // something (such as user input) to an accurate diasplay time.
1586 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1587 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001588 nsecs_t bias = vsyncInterval / 2;
1589 int64_t extraVsyncs =
1590 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1591 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1592 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593
David Sodman99974d22017-11-28 12:04:33 -08001594 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1595 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1596 getBE().mCompositorTiming.interval = vsyncInterval;
1597 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598}
1599
1600void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001602 ATRACE_CALL();
1603 ALOGV("postComposition");
1604
Brian Anderson3546a3f2016-07-14 11:51:14 -07001605 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001606 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001607 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001608 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001609 }
1610
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001611 // |mStateLock| not needed as we are on the main thread
1612 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001613
David Sodman73beded2017-11-15 11:56:06 -08001614 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001615 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001616 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001617 glCompositionDoneFenceTime =
1618 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001619 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001620 } else {
1621 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1622 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001623
David Sodman73beded2017-11-15 11:56:06 -08001624 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001625 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001626 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001627 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001628
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1630 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1631
1632 // We use the refreshStartTime which might be sampled a little later than
1633 // when we started doing work for this frame, but that should be okay
1634 // since updateCompositorTiming has snapping logic.
1635 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001636 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001637 CompositorTiming compositorTiming;
1638 {
David Sodman99974d22017-11-28 12:04:33 -08001639 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1640 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001641 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642
Robert Carr2047fae2016-11-28 14:09:09 -08001643 mDrawingState.traverseInZOrder([&](Layer* layer) {
1644 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001645 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001646 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001647 recordBufferingStats(layer->getName().string(),
1648 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001649 }
Robert Carr2047fae2016-11-28 14:09:09 -08001650 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001651
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001652 if (presentFenceTime->isValid()) {
1653 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001654 enableHardwareVsync();
1655 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001656 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001657 }
1658 }
1659
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001660 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001661 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001662 enableHardwareVsync();
1663 }
1664 }
1665
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001666 if (mAnimCompositionPending) {
1667 mAnimCompositionPending = false;
1668
Brian Anderson4e606e32017-03-16 15:34:57 -07001669 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001670 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001671 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001672 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001673 // The HWC doesn't support present fences, so use the refresh
1674 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001675 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001676 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001677 mAnimFrameTracker.setActualPresentTime(presentTime);
1678 }
1679 mAnimFrameTracker.advanceFrame();
1680 }
Dan Stozab90cf072015-03-05 11:05:59 -08001681
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001682 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1683 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001684 return;
1685 }
1686
1687 nsecs_t currentTime = systemTime();
1688 if (mHasPoweredOff) {
1689 mHasPoweredOff = false;
1690 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001691 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001693 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1694 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001695 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001696 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001697 }
David Sodman4a36e932017-11-07 14:29:47 -08001698 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001699 }
David Sodman4a36e932017-11-07 14:29:47 -08001700 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701}
1702
1703void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 ATRACE_CALL();
1705 ALOGV("rebuildLayerStacks");
1706
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001708 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001709 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001710 mVisibleRegionsDirty = false;
1711 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001712
Jeff Sharkey76488112017-02-27 14:15:18 -07001713 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1714 Region opaqueRegion;
1715 Region dirtyRegion;
1716 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001717 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001718 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1719 const Transform& tr(displayDevice->getTransform());
1720 const Rect bounds(displayDevice->getBounds());
1721 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001722 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001723
Jeff Sharkey76488112017-02-27 14:15:18 -07001724 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001725 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001726 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1727 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001728 Region drawRegion(tr.transform(
1729 layer->visibleNonTransparentRegion));
1730 drawRegion.andSelf(bounds);
1731 if (!drawRegion.isEmpty()) {
1732 layersSortedByZ.add(layer);
1733 } else {
1734 // Clear out the HWC layer if this layer was
1735 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001736 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001738 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001739 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001740 // WM changes displayDevice->layerStack upon sleep/awake.
1741 // Here we make sure we delete the HWC layers even if
1742 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001743 hwcLayerDestroyed = layer->destroyHwcLayer(
1744 displayDevice->getHwcDisplayId());
1745 }
1746
1747 // If a layer is not going to get a release fence because
1748 // it is invisible, but it is also going to release its
1749 // old buffer, add it to the list of layers needing
1750 // fences.
1751 if (hwcLayerDestroyed) {
1752 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1753 mLayersWithQueuedFrames.cend(), layer);
1754 if (found != mLayersWithQueuedFrames.cend()) {
1755 layersNeedingFences.add(layer);
1756 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001757 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001758 });
1759 }
1760 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001761 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 displayDevice->undefinedRegion.set(bounds);
1763 displayDevice->undefinedRegion.subtractSelf(
1764 tr.transform(opaqueRegion));
1765 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001766 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001767 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001768}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001769
Romain Guy0147a172017-06-01 13:53:56 -07001770mat4 SurfaceFlinger::computeSaturationMatrix() const {
1771 if (mSaturation == 1.0f) {
1772 return mat4();
1773 }
1774
1775 // Rec.709 luma coefficients
1776 float3 luminance{0.213f, 0.715f, 0.072f};
1777 luminance *= 1.0f - mSaturation;
1778 return mat4(
1779 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1780 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1781 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1782 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1783 );
1784}
1785
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001786// pickColorMode translates a given dataspace into the best available color mode.
1787// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001788android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001789 if (mForceNativeColorMode) {
1790 return HAL_COLOR_MODE_NATIVE;
1791 }
1792
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001793 switch (dataSpace) {
1794 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1795 // system expects.
1796 case HAL_DATASPACE_UNKNOWN:
1797 case HAL_DATASPACE_SRGB:
1798 case HAL_DATASPACE_V0_SRGB:
1799 return HAL_COLOR_MODE_SRGB;
1800 break;
1801
1802 case HAL_DATASPACE_DISPLAY_P3:
1803 return HAL_COLOR_MODE_DISPLAY_P3;
1804 break;
1805
1806 default:
1807 // TODO (courtneygo): Do we want to assert an error here?
1808 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1809 dataSpace);
1810 return HAL_COLOR_MODE_SRGB;
1811 break;
1812 }
1813}
1814
Romain Guy0147a172017-06-01 13:53:56 -07001815android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001816 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001817 // Only support sRGB and Display-P3 right now.
1818 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1819 return HAL_DATASPACE_DISPLAY_P3;
1820 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001821 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1822 return HAL_DATASPACE_DISPLAY_P3;
1823 }
1824 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1825 return HAL_DATASPACE_DISPLAY_P3;
1826 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001827 if (!hasHdr) {
1828 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1829 return HAL_DATASPACE_DISPLAY_P3;
1830 }
1831 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1832 return HAL_DATASPACE_DISPLAY_P3;
1833 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001834 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001835
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001836 return HAL_DATASPACE_V0_SRGB;
1837}
1838
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001840 ATRACE_CALL();
1841 ALOGV("setUpHWComposer");
1842
Jesse Hall028dc8f2013-08-20 16:35:32 -07001843 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001844 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1845 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1846 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1847
1848 // If nothing has changed (!dirty), don't recompose.
1849 // If something changed, but we don't currently have any visible layers,
1850 // and didn't when we last did a composition, then skip it this time.
1851 // The second rule does two things:
1852 // - When all layers are removed from a display, we'll emit one black
1853 // frame, then nothing more until we get new layers.
1854 // - When a display is created with a private layer stack, we won't
1855 // emit any black frames until a layer is added to the layer stack.
1856 bool mustRecompose = dirty && !(empty && wasEmpty);
1857
1858 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1859 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1860 mustRecompose ? "doing" : "skipping",
1861 dirty ? "+" : "-",
1862 empty ? "+" : "-",
1863 wasEmpty ? "+" : "-");
1864
Dan Stoza71433162014-02-04 16:22:36 -08001865 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001866
1867 if (mustRecompose) {
1868 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1869 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001870 }
1871
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 // build the h/w work list
1873 if (CC_UNLIKELY(mGeometryInvalid)) {
1874 mGeometryInvalid = false;
1875 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1876 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1877 const auto hwcId = displayDevice->getHwcDisplayId();
1878 if (hwcId >= 0) {
1879 const Vector<sp<Layer>>& currentLayers(
1880 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001881 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001884 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001887 }
1888 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001889
Robert Carrae060832016-11-28 10:51:00 -08001890 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001891 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001893 }
1894 }
1895 }
1896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 }
Riley Andrews03414a12014-07-01 14:22:59 -07001898
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001899
Romain Guy0147a172017-06-01 13:53:56 -07001900 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001901
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 // Set the per-frame data
1903 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1904 auto& displayDevice = mDisplays[displayId];
1905 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001906
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 if (hwcId < 0) {
1908 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001909 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001910 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001911 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001912 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1913 "display %zd: %d", displayId, result);
1914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001916 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1917 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001918 !displayDevice->getHdrSupport()) {
1919 layer->forceClientComposition(hwcId);
1920 }
1921
chaviwc9232ed2017-11-14 15:31:15 -08001922 if (layer->getForceClientComposition(hwcId)) {
1923 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1924 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1925 continue;
1926 }
1927
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 layer->setPerFrameData(displayDevice);
1929 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001930
1931 if (hasWideColorDisplay) {
1932 android_color_mode newColorMode;
1933 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1934
1935 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001936 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1937 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001938 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1939 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1940 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1941 }
1942 newColorMode = pickColorMode(newDataSpace);
1943
Thierry Strudel2924d012017-08-14 15:19:37 -07001944 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001945 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 }
1947
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001948 mPreviousColorMatrix = colorMatrix;
1949
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001951 auto& displayDevice = mDisplays[displayId];
1952 if (!displayDevice->isDisplayOn()) {
1953 continue;
1954 }
1955
David Sodman105b7dc2017-11-04 20:28:14 -07001956 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1958 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001959 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001960}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001961
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962void SurfaceFlinger::doComposition() {
1963 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 ALOGV("doComposition");
1965
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001966 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001967 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001968 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001969 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001970 // transform the dirty region into this screen's coordinate space
1971 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001972
1973 // repaint the framebuffer (if needed)
1974 doDisplayComposition(hw, dirtyRegion);
1975
Mathias Agopiancd60f992012-08-16 16:28:27 -07001976 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001977 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001978 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001979 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001980 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001981}
1982
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001983void SurfaceFlinger::postFramebuffer()
1984{
Mathias Agopian841cde52012-03-01 15:44:37 -08001985 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001986 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001987
Mathias Agopiana44b0412011-10-16 18:46:35 -07001988 const nsecs_t now = systemTime();
1989 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001990
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1992 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001993 if (!displayDevice->isDisplayOn()) {
1994 continue;
1995 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 const auto hwcId = displayDevice->getHwcDisplayId();
1997 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001998 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001999 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002000 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002001 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002003 // The layer buffer from the previous frame (if any) is released
2004 // by HWC only when the release fence from this frame (if any) is
2005 // signaled. Always get the release fence from HWC first.
2006 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002007 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002008
2009 // If the layer was client composited in the previous frame, we
2010 // need to merge with the previous client target acquire fence.
2011 // Since we do not track that, always merge with the current
2012 // client target acquire fence when it is available, even though
2013 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002015 releaseFence = Fence::merge("LayerRelease", releaseFence,
2016 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002017 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002018
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 layer->onLayerDisplayed(releaseFence);
2020 }
Chia-I Wu83806892017-11-16 10:50:20 -08002021
2022 // We've got a list of layers needing fences, that are disjoint with
2023 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2024 // supply them with the present fence.
2025 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002026 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002027 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2028 layer->onLayerDisplayed(presentFence);
2029 }
2030 }
2031
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002033 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002034 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002035 }
2036
Mathias Agopiana44b0412011-10-16 18:46:35 -07002037 mLastSwapBufferTime = systemTime() - now;
2038 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002039
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002040 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002041 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2042 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2043 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2044 logFrameStats();
2045 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002046 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047}
2048
Mathias Agopian87baae12012-07-31 12:38:26 -07002049void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050{
Mathias Agopian841cde52012-03-01 15:44:37 -08002051 ATRACE_CALL();
2052
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002053 // here we keep a copy of the drawing state (that is the state that's
2054 // going to be overwritten by handleTransactionLocked()) outside of
2055 // mStateLock so that the side-effects of the State assignment
2056 // don't happen with mStateLock held (which can cause deadlocks).
2057 State drawingState(mDrawingState);
2058
Mathias Agopianca4d3602011-05-19 15:38:14 -07002059 Mutex::Autolock _l(mStateLock);
2060 const nsecs_t now = systemTime();
2061 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002062
Mathias Agopianca4d3602011-05-19 15:38:14 -07002063 // Here we're guaranteed that some transaction flags are set
2064 // so we can call handleTransactionLocked() unconditionally.
2065 // We call getTransactionFlags(), which will also clear the flags,
2066 // with mStateLock held to guarantee that mCurrentState won't change
2067 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002068
Mathias Agopiane57f2922012-08-09 16:29:12 -07002069 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002070 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002071
Mathias Agopianca4d3602011-05-19 15:38:14 -07002072 mLastTransactionTime = systemTime() - now;
2073 mDebugInTransaction = 0;
2074 invalidateHwcGeometry();
2075 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002076}
2077
Lloyd Pique715a2c12017-12-14 17:18:08 -08002078DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2079 HWC2::Connection connection) const {
2080 // Figure out whether the event is for the primary display or an
2081 // external display by matching the Hwc display id against one for a
2082 // connected display. If we did not find a match, we then check what
2083 // displays are not already connected to determine the type. If we don't
2084 // have a connected primary display, we assume the new display is meant to
2085 // be the primary display, and then if we don't have an external display,
2086 // we assume it is that.
2087 const auto primaryDisplayId =
2088 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2089 const auto externalDisplayId =
2090 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2091 if (primaryDisplayId && primaryDisplayId == display) {
2092 return DisplayDevice::DISPLAY_PRIMARY;
2093 } else if (externalDisplayId && externalDisplayId == display) {
2094 return DisplayDevice::DISPLAY_EXTERNAL;
2095 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2096 return DisplayDevice::DISPLAY_PRIMARY;
2097 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2098 return DisplayDevice::DISPLAY_EXTERNAL;
2099 }
2100
2101 return DisplayDevice::DISPLAY_ID_INVALID;
2102}
2103
Lloyd Piqueba04e622017-12-14 17:11:26 -08002104void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2105 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002106 auto displayType = determineDisplayType(event.display, event.connection);
2107 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2108 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2109 continue;
2110 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002111
2112 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2113 ALOGE("External displays are not supported by the vr hardware composer.");
2114 continue;
2115 }
2116
Lloyd Pique715a2c12017-12-14 17:18:08 -08002117 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002118
2119 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002120 ALOGV("Creating built in display %d", displayType);
2121 ALOGW_IF(mBuiltinDisplays[displayType],
2122 "Overwriting display token for display type %d", displayType);
2123 mBuiltinDisplays[displayType] = new BBinder();
2124 // All non-virtual displays are currently considered secure.
2125 DisplayDeviceState info(displayType, true);
2126 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2127 "Built-in Screen" : "External Screen";
2128 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2129 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002130 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002131 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002132
Lloyd Piquefcd86612017-12-14 17:15:36 -08002133 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2134 if (idx >= 0) {
2135 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2136 mInterceptor.saveDisplayDeletion(info.displayId);
2137 mCurrentState.displays.removeItemsAt(idx);
2138 }
2139 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002140 }
2141
2142 processDisplayChangesLocked();
2143 }
2144
2145 mPendingHotplugEvents.clear();
2146}
2147
Lloyd Pique347200f2017-12-14 17:00:15 -08002148void SurfaceFlinger::processDisplayChangesLocked() {
2149 // here we take advantage of Vector's copy-on-write semantics to
2150 // improve performance by skipping the transaction entirely when
2151 // know that the lists are identical
2152 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2153 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2154 if (!curr.isIdenticalTo(draw)) {
2155 mVisibleRegionsDirty = true;
2156 const size_t cc = curr.size();
2157 size_t dc = draw.size();
2158
2159 // find the displays that were removed
2160 // (ie: in drawing state but not in current state)
2161 // also handle displays that changed
2162 // (ie: displays that are in both lists)
2163 for (size_t i = 0; i < dc;) {
2164 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2165 if (j < 0) {
2166 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002167 // Call makeCurrent() on the primary display so we can
2168 // be sure that nothing associated with this display
2169 // is current.
2170 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2171 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2172 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2173 if (hw != nullptr) hw->disconnect(getHwComposer());
2174 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2175 mEventThread->onHotplugReceived(draw[i].type, false);
2176 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002177 } else {
2178 // this display is in both lists. see if something changed.
2179 const DisplayDeviceState& state(curr[j]);
2180 const wp<IBinder>& display(curr.keyAt(j));
2181 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2182 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2183 if (state_binder != draw_binder) {
2184 // changing the surface is like destroying and
2185 // recreating the DisplayDevice, so we just remove it
2186 // from the drawing state, so that it get re-added
2187 // below.
2188 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2189 if (hw != nullptr) hw->disconnect(getHwComposer());
2190 mDisplays.removeItem(display);
2191 mDrawingState.displays.removeItemsAt(i);
2192 dc--;
2193 // at this point we must loop to the next item
2194 continue;
2195 }
2196
2197 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2198 if (disp != nullptr) {
2199 if (state.layerStack != draw[i].layerStack) {
2200 disp->setLayerStack(state.layerStack);
2201 }
2202 if ((state.orientation != draw[i].orientation) ||
2203 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2204 disp->setProjection(state.orientation, state.viewport, state.frame);
2205 }
2206 if (state.width != draw[i].width || state.height != draw[i].height) {
2207 disp->setDisplaySize(state.width, state.height);
2208 }
2209 }
2210 }
2211 ++i;
2212 }
2213
2214 // find displays that were added
2215 // (ie: in current state but not in drawing state)
2216 for (size_t i = 0; i < cc; i++) {
2217 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2218 const DisplayDeviceState& state(curr[i]);
2219
2220 sp<DisplaySurface> dispSurface;
2221 sp<IGraphicBufferProducer> producer;
2222 sp<IGraphicBufferProducer> bqProducer;
2223 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002224 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002225
2226 int32_t hwcId = -1;
2227 if (state.isVirtualDisplay()) {
2228 // Virtual displays without a surface are dormant:
2229 // they have external state (layer stack, projection,
2230 // etc.) but no internal state (i.e. a DisplayDevice).
2231 if (state.surface != nullptr) {
2232 // Allow VR composer to use virtual displays.
2233 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2234 int width = 0;
2235 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2236 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2237 int height = 0;
2238 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2239 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2240 int intFormat = 0;
2241 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2242 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2243 auto format = static_cast<android_pixel_format_t>(intFormat);
2244
2245 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2246 }
2247
2248 // TODO: Plumb requested format back up to consumer
2249
2250 sp<VirtualDisplaySurface> vds =
2251 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2252 bqProducer, bqConsumer,
2253 state.displayName);
2254
2255 dispSurface = vds;
2256 producer = vds;
2257 }
2258 } else {
2259 ALOGE_IF(state.surface != nullptr,
2260 "adding a supported display, but rendering "
2261 "surface is provided (%p), ignoring it",
2262 state.surface.get());
2263
2264 hwcId = state.type;
2265 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2266 producer = bqProducer;
2267 }
2268
2269 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002270
Lloyd Pique347200f2017-12-14 17:00:15 -08002271 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002272 bool hasWideColorSupport = false;
2273 if (hasWideColorDisplay) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002274 std::vector<android_color_mode_t> modes =
2275 getHwComposer().getColorModes(state.type);
2276 for (android_color_mode_t colorMode : modes) {
2277 switch (colorMode) {
2278 case HAL_COLOR_MODE_DISPLAY_P3:
2279 case HAL_COLOR_MODE_ADOBE_RGB:
2280 case HAL_COLOR_MODE_DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002281 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002282 break;
2283 default:
2284 break;
2285 }
2286 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002287 }
2288
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002289 bool hasHdrSupport = false;
2290 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2291 getHwComposer().getHdrCapabilities(state.type);
2292 if (hdrCapabilities) {
2293 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2294 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2295 hasHdrSupport = iter != types.cend();
2296 }
2297
Lloyd Pique347200f2017-12-14 17:00:15 -08002298 sp<DisplayDevice> hw =
2299 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002300 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002301 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002302
Lloyd Piquec5208312018-01-08 17:59:02 -08002303 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002304 if (hasWideColorSupport) {
Lloyd Piquec5208312018-01-08 17:59:02 -08002305 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002306 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002307 setActiveColorModeInternal(hw, defaultColorMode);
2308 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002309 hw->setLayerStack(state.layerStack);
2310 hw->setProjection(state.orientation, state.viewport, state.frame);
2311 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002312
Lloyd Pique347200f2017-12-14 17:00:15 -08002313 mDisplays.add(display, hw);
2314 if (!state.isVirtualDisplay()) {
2315 mEventThread->onHotplugReceived(state.type, true);
2316 }
2317 }
2318 }
2319 }
2320 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002321
2322 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002323}
2324
Mathias Agopian87baae12012-07-31 12:38:26 -07002325void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002326{
Dan Stoza7dde5992015-05-22 09:51:44 -07002327 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002328 mCurrentState.traverseInZOrder([](Layer* layer) {
2329 layer->notifyAvailableFrames();
2330 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002331
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002332 /*
2333 * Traversal of the children
2334 * (perform the transaction for each of them if needed)
2335 */
2336
Mathias Agopian3559b072012-08-15 13:46:03 -07002337 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002338 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002340 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341
2342 const uint32_t flags = layer->doTransaction(0);
2343 if (flags & Layer::eVisibleRegion)
2344 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002345 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346 }
2347
2348 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002349 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350 */
2351
Mathias Agopiane57f2922012-08-09 16:29:12 -07002352 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002353 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002354 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356
Mathias Agopian84300952012-11-21 16:02:13 -08002357 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2358 // The transform hint might have changed for some layers
2359 // (either because a display has changed, or because a layer
2360 // as changed).
2361 //
2362 // Walk through all the layers in currentLayers,
2363 // and update their transform hint.
2364 //
2365 // If a layer is visible only on a single display, then that
2366 // display is used to calculate the hint, otherwise we use the
2367 // default display.
2368 //
2369 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2370 // the hint is set before we acquire a buffer from the surface texture.
2371 //
2372 // NOTE: layer transactions have taken place already, so we use their
2373 // drawing state. However, SurfaceFlinger's own transaction has not
2374 // happened yet, so we must use the current state layer list
2375 // (soon to become the drawing state list).
2376 //
2377 sp<const DisplayDevice> disp;
2378 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002379 bool first = true;
2380 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002381 // NOTE: we rely on the fact that layers are sorted by
2382 // layerStack first (so we don't have to traverse the list
2383 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002384 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002385 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002386 currentlayerStack = layerStack;
2387 // figure out if this layerstack is mirrored
2388 // (more than one display) if so, pick the default display,
2389 // if not, pick the only display it's on.
2390 disp.clear();
2391 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2392 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002393 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002394 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002395 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002396 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002397 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002398 break;
2399 }
2400 }
2401 }
2402 }
Chet Haase91d25932013-04-11 15:24:55 -07002403
Robert Carr56a0b9a2017-12-04 16:06:13 -08002404 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002405 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002406 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2407 // redraw after transform hint changes. See bug 8508397.
2408
2409 // could be null when this layer is using a layerStack
2410 // that is not visible on any display. Also can occur at
2411 // screen off/on times.
2412 disp = getDefaultDisplayDeviceLocked();
2413 }
2414 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002415 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002416 if (disp != nullptr) {
2417 layer->updateTransformHint(disp);
2418 }
Robert Carr2047fae2016-11-28 14:09:09 -08002419
2420 first = false;
2421 });
Mathias Agopian84300952012-11-21 16:02:13 -08002422 }
2423
2424
Mathias Agopian3559b072012-08-15 13:46:03 -07002425 /*
2426 * Perform our own transaction if needed
2427 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002428
2429 if (mLayersAdded) {
2430 mLayersAdded = false;
2431 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002432 mVisibleRegionsDirty = true;
2433 }
2434
2435 // some layers might have been removed, so
2436 // we need to update the regions they're exposing.
2437 if (mLayersRemoved) {
2438 mLayersRemoved = false;
2439 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002440 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002441 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002442 // this layer is not visible anymore
2443 // TODO: we could traverse the tree from front to back and
2444 // compute the actual visible region
2445 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002446 Region visibleReg;
2447 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002448 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002449 }
Robert Carr2047fae2016-11-28 14:09:09 -08002450 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451 }
2452
2453 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002454
2455 updateCursorAsync();
2456}
2457
2458void SurfaceFlinger::updateCursorAsync()
2459{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2461 auto& displayDevice = mDisplays[displayId];
2462 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002463 continue;
2464 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465
2466 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2467 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002468 }
2469 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002470}
2471
2472void SurfaceFlinger::commitTransaction()
2473{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002474 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002475 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002476 for (const auto& l : mLayersPendingRemoval) {
2477 recordBufferingStats(l->getName().string(),
2478 l->getOccupancyHistory(true));
2479 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480 }
2481 mLayersPendingRemoval.clear();
2482 }
2483
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002484 // If this transaction is part of a window animation then the next frame
2485 // we composite should be considered an animation as well.
2486 mAnimCompositionPending = mAnimTransactionPending;
2487
Mathias Agopian4fec8732012-06-29 14:12:52 -07002488 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002489 mDrawingState.traverseInZOrder([](Layer* layer) {
2490 layer->commitChildList();
2491 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002492 mTransactionPending = false;
2493 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002494 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495}
2496
Chia-I Wuab0c3192017-08-01 11:29:00 -07002497void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002498 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499{
Mathias Agopian841cde52012-03-01 15:44:37 -08002500 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002502
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503 Region aboveOpaqueLayers;
2504 Region aboveCoveredLayers;
2505 Region dirty;
2506
Mathias Agopian87baae12012-07-31 12:38:26 -07002507 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508
Robert Carr2047fae2016-11-28 14:09:09 -08002509 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002511 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512
Jesse Hall01e29052013-02-19 16:13:35 -08002513 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002514 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002515 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002516
Mathias Agopianab028732010-03-16 16:41:46 -07002517 /*
2518 * opaqueRegion: area of a surface that is fully opaque.
2519 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002521
2522 /*
2523 * visibleRegion: area of a surface that is visible on screen
2524 * and not fully transparent. This is essentially the layer's
2525 * footprint minus the opaque regions above it.
2526 * Areas covered by a translucent surface are considered visible.
2527 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002529
2530 /*
2531 * coveredRegion: area of a surface that is covered by all
2532 * visible regions above it (which includes the translucent areas).
2533 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002535
Jesse Halla8026d22012-09-25 13:25:04 -07002536 /*
2537 * transparentRegion: area of a surface that is hinted to be completely
2538 * transparent. This is only used to tell when the layer has no visible
2539 * non-transparent regions and can be removed from the layer list. It
2540 * does not affect the visibleRegion of this layer or any layers
2541 * beneath it. The hint may not be correct if apps don't respect the
2542 * SurfaceView restrictions (which, sadly, some don't).
2543 */
2544 Region transparentRegion;
2545
Mathias Agopianab028732010-03-16 16:41:46 -07002546
2547 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002548 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002549 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002552 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002553 if (!visibleRegion.isEmpty()) {
2554 // Remove the transparent area from the visible region
2555 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002556 if (tr.preserveRects()) {
2557 // transform the transparent region
2558 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002559 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002560 // transformation too complex, can't do the
2561 // transparent region optimization.
2562 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563 }
Mathias Agopianab028732010-03-16 16:41:46 -07002564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565
Mathias Agopianab028732010-03-16 16:41:46 -07002566 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002568 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002569 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2570 // the opaque region is the layer's footprint
2571 opaqueRegion = visibleRegion;
2572 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 }
2574 }
2575
Robert Carre5f4f692018-01-12 13:12:28 -08002576 if (visibleRegion.isEmpty()) {
2577 layer->clearVisibilityRegions();
2578 return;
2579 }
2580
Mathias Agopianab028732010-03-16 16:41:46 -07002581 // Clip the covered region to the visible region
2582 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2583
2584 // Update aboveCoveredLayers for next (lower) layer
2585 aboveCoveredLayers.orSelf(visibleRegion);
2586
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 // subtract the opaque region covered by the layers above us
2588 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589
2590 // compute this layer's dirty region
2591 if (layer->contentDirty) {
2592 // we need to invalidate the whole region
2593 dirty = visibleRegion;
2594 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002595 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 layer->contentDirty = false;
2597 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002598 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002599 * the exposed region consists of two components:
2600 * 1) what's VISIBLE now and was COVERED before
2601 * 2) what's EXPOSED now less what was EXPOSED before
2602 *
2603 * note that (1) is conservative, we start with the whole
2604 * visible region but only keep what used to be covered by
2605 * something -- which mean it may have been exposed.
2606 *
2607 * (2) handles areas that were not covered by anything but got
2608 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002609 */
Mathias Agopianab028732010-03-16 16:41:46 -07002610 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002611 const Region oldVisibleRegion = layer->visibleRegion;
2612 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002613 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2614 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 }
2616 dirty.subtractSelf(aboveOpaqueLayers);
2617
2618 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002619 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620
Mathias Agopianab028732010-03-16 16:41:46 -07002621 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002623
Jesse Halla8026d22012-09-25 13:25:04 -07002624 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 layer->setVisibleRegion(visibleRegion);
2626 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002627 layer->setVisibleNonTransparentRegion(
2628 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002629 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630
Mathias Agopian87baae12012-07-31 12:38:26 -07002631 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632}
2633
Chia-I Wuab0c3192017-08-01 11:29:00 -07002634void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002635 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002636 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002637 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002638 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002639 }
2640 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002641}
2642
Dan Stoza6b9454d2014-11-07 16:00:59 -08002643bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 ALOGV("handlePageFlip");
2646
Brian Andersond6927fb2016-07-23 23:37:30 -07002647 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648
Mathias Agopian4fec8732012-06-29 14:12:52 -07002649 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002650 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002651 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002652
2653 // Store the set of layers that need updates. This set must not change as
2654 // buffers are being latched, as this could result in a deadlock.
2655 // Example: Two producers share the same command stream and:
2656 // 1.) Layer 0 is latched
2657 // 2.) Layer 0 gets a new frame
2658 // 2.) Layer 1 gets a new frame
2659 // 3.) Layer 1 is latched.
2660 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2661 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002662 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002663 if (layer->hasQueuedFrame()) {
2664 frameQueued = true;
2665 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002666 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002667 } else {
2668 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002669 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002670 } else {
2671 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002672 }
Robert Carr2047fae2016-11-28 14:09:09 -08002673 });
2674
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002676 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002677 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002678 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002679 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002680 newDataLatched = true;
2681 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002682 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002683
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002684 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002685
2686 // If we will need to wake up at some time in the future to deal with a
2687 // queued frame that shouldn't be displayed during this vsync period, wake
2688 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002689 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002690 signalLayerUpdate();
2691 }
2692
2693 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002694 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695}
2696
Mathias Agopianad456f92011-01-13 17:53:01 -08002697void SurfaceFlinger::invalidateHwcGeometry()
2698{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002700}
2701
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002702
Fabien Sanglard830b8472016-11-30 16:35:58 -08002703void SurfaceFlinger::doDisplayComposition(
2704 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002705 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706{
Dan Stoza71433162014-02-04 16:22:36 -08002707 // We only need to actually compose the display if:
2708 // 1) It is being handled by hardware composer, which may need this to
2709 // keep its virtual display state machine in sync, or
2710 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002711 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002712 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002714 return;
2715 }
2716
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002718 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002719
2720 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002721 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722}
2723
Chia-I Wub02087d2017-11-09 10:19:54 -08002724bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002725{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002727
Chia-I Wub02087d2017-11-09 10:19:54 -08002728 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002729 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002731
2732 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002733 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2734 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002735 if (applyColorMatrix) {
2736 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2737 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2738 }
2739
David Sodman105b7dc2017-11-04 20:28:14 -07002740 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 if (hasClientComposition) {
2742 ALOGV("hasClientComposition");
2743
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002744 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002745 if (displayDevice->getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002746 displayDevice->getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
2747 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2748 }
2749 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2750
Chia-I Wu7f402902017-11-09 12:51:10 -08002751 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002752 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002754 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002755
2756 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002757 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002758 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2759 }
2760 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002761 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002762
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002763 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002764 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002766 // when using overlays, we assume a fully transparent framebuffer
2767 // NOTE: we could reduce how much we need to clear, for instance
2768 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002769 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002770 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002771 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002772 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002773 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002774 // we're left with the letterbox region
2775 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002777
2778 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002780
Mathias Agopianb9494d52012-04-18 02:28:45 -07002781 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002782 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002783 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002785 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002786 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002787
Dan Stoza9e56aa02015-11-02 13:00:03 -08002788 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002789 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002790 // scissor on the main display. It should never be needed
2791 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 const Rect& bounds(displayDevice->getBounds());
2793 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002794 if (scissor != bounds) {
2795 // scissor doesn't match the screen's dimensions, so we
2796 // need to clear everything outside of it and enable
2797 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002798
Mathias Agopianf45c5102012-10-24 16:29:17 -07002799 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002801 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002802 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002803 }
2804 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002805 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002806
Mathias Agopian85d751c2012-08-29 16:59:24 -07002807 /*
2808 * and then, render the layers targeted at the framebuffer
2809 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002810
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 ALOGV("Rendering client layers");
2812 const Transform& displayTransform = displayDevice->getTransform();
2813 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002814 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 bool firstLayer = true;
2816 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002817 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 displayTransform.transform(layer->visibleRegion)));
2819 ALOGV("Layer: %s", layer->getName().string());
2820 ALOGV(" Composition type: %s",
2821 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002822 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 switch (layer->getCompositionType(hwcId)) {
2824 case HWC2::Composition::Cursor:
2825 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002826 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002828 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002830 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002832 // never clear the very first layer since we're
2833 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002834 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002835 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002836 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002837 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002838 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002839 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002840 break;
2841 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002843 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002844 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 } else {
2846 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002849 }
2850 } else {
2851 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002852 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002853 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002855 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002856 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002857 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002858 }
2859 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002860
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002861 if (applyColorMatrix) {
2862 getRenderEngine().setupColorTransform(oldColorMatrix);
2863 }
2864
Mathias Agopianf45c5102012-10-24 16:29:17 -07002865 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002866 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002867 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868}
2869
Fabien Sanglard830b8472016-11-30 16:35:58 -08002870void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2871 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002872 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002873 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874}
2875
Dan Stoza7d89d062015-04-30 13:29:25 -07002876status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002877 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002878 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002879 const sp<Layer>& lbc,
2880 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002881{
Dan Stoza7d89d062015-04-30 13:29:25 -07002882 // add this layer to the current state list
2883 {
2884 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002886 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2887 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002888 return NO_MEMORY;
2889 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890 if (parent == nullptr) {
2891 mCurrentState.layersSortedByZ.add(lbc);
2892 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002893 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002894 ALOGE("addClientLayer called with a removed parent");
2895 return NAME_NOT_FOUND;
2896 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002897 parent->addChild(lbc);
2898 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002899
Dan Stoza101d8dc2018-02-27 15:42:25 -08002900 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2901 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() > MAX_LAYERS,
2902 "Suspected IGBP leak");
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 mLayersAdded = true;
2904 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002905 }
2906
Mathias Agopian96f08192010-06-02 23:28:45 -07002907 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002908 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002909
Dan Stoza7d89d062015-04-30 13:29:25 -07002910 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002911}
2912
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002913status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002914 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002915 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2916}
Robert Carr7f9b8992017-03-10 11:08:39 -08002917
chaviwca27f252018-02-06 16:46:39 -08002918status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2919 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002920 if (layer->isPendingRemoval()) {
2921 return NO_ERROR;
2922 }
2923
Robert Carr1f0a16a2016-10-24 16:27:39 -07002924 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002925 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002926 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002927 if (topLevelOnly) {
2928 return NO_ERROR;
2929 }
2930
Chia-I Wu98f1c102017-05-30 14:54:08 -07002931 sp<Layer> ancestor = p;
2932 while (ancestor->getParent() != nullptr) {
2933 ancestor = ancestor->getParent();
2934 }
2935 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2936 ALOGE("removeLayer called with a layer whose parent has been removed");
2937 return NAME_NOT_FOUND;
2938 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002939
2940 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002941 } else {
2942 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002943 }
2944
Robert Carr136e2f62017-02-08 17:54:29 -08002945 // As a matter of normal operation, the LayerCleaner will produce a second
2946 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2947 // so we will succeed in promoting it, but it's already been removed
2948 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2949 // otherwise something has gone wrong and we are leaking the layer.
2950 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2952 layer->getName().string(),
2953 (p != nullptr) ? p->getName().string() : "no-parent");
2954 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002955 } else if (index < 0) {
2956 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002957 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002958
Chia-I Wuc6657022017-08-15 11:18:17 -07002959 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002960 mLayersPendingRemoval.add(layer);
2961 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002962 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002963 setTransactionFlags(eTransactionNeeded);
2964 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965}
2966
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002967uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002968 return android_atomic_release_load(&mTransactionFlags);
2969}
2970
Mathias Agopian3f844832013-08-07 21:24:32 -07002971uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2973}
2974
Mathias Agopian3f844832013-08-07 21:24:32 -07002975uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2977 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002978 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 }
2980 return old;
2981}
2982
chaviwca27f252018-02-06 16:46:39 -08002983bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
2984 for (const ComposerState& state : states) {
2985 // Here we need to check that the interface we're given is indeed
2986 // one of our own. A malicious client could give us a nullptr
2987 // IInterface, or one of its own or even one of our own but a
2988 // different type. All these situations would cause us to crash.
2989 if (state.client == nullptr) {
2990 return true;
2991 }
2992
2993 sp<IBinder> binder = IInterface::asBinder(state.client);
2994 if (binder == nullptr) {
2995 return true;
2996 }
2997
2998 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
2999 return true;
3000 }
3001 }
3002 return false;
3003}
3004
Mathias Agopian8b33f032012-07-24 20:43:54 -07003005void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003006 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003007 const Vector<DisplayState>& displays,
3008 uint32_t flags)
3009{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003010 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003011 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003012 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003013
chaviwca27f252018-02-06 16:46:39 -08003014 if (containsAnyInvalidClientState(states)) {
3015 return;
3016 }
3017
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003018 if (flags & eAnimation) {
3019 // For window updates that are part of an animation we must wait for
3020 // previous animation "frames" to be handled.
3021 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003022 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003023 if (CC_UNLIKELY(err != NO_ERROR)) {
3024 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003025 // caller after a few seconds.
3026 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3027 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003028 mAnimTransactionPending = false;
3029 break;
3030 }
3031 }
3032 }
3033
chaviwca27f252018-02-06 16:46:39 -08003034 for (const DisplayState& display : displays) {
3035 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003036 }
3037
chaviwca27f252018-02-06 16:46:39 -08003038 for (const ComposerState& state : states) {
3039 transactionFlags |= setClientStateLocked(state);
3040 }
3041
3042 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3043 // as destroyed should only occur after setting all other states. This is to allow for a
3044 // child re-parent to happen before marking its original parent as destroyed (which would
3045 // then mark the child as destroyed).
3046 for (const ComposerState& state : states) {
3047 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003048 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003049
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003050 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3051 // anyway. This can be used as a flush mechanism for previous async transactions.
3052 // Empty animation transaction can be used to simulate back-pressure, so also force a
3053 // transaction for empty animation transactions.
3054 if (transactionFlags == 0 &&
3055 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003056 transactionFlags = eTransactionNeeded;
3057 }
3058
Mathias Agopian386aa982011-11-07 21:58:03 -08003059 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003060 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003061 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003062 }
Irvel468051e2016-06-13 16:44:44 -07003063
Mathias Agopian386aa982011-11-07 21:58:03 -08003064 // this triggers the transaction
3065 setTransactionFlags(transactionFlags);
3066
3067 // if this is a synchronous transaction, wait for it to take effect
3068 // before returning.
3069 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003070 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003071 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003072 if (flags & eAnimation) {
3073 mAnimTransactionPending = true;
3074 }
3075 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003076 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3077 if (CC_UNLIKELY(err != NO_ERROR)) {
3078 // just in case something goes wrong in SF, return to the
3079 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003080 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3081 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003082 break;
3083 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003084 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 }
3086}
3087
Mathias Agopiane57f2922012-08-09 16:29:12 -07003088uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3089{
Jesse Hall9a143922012-10-04 16:29:19 -07003090 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3091 if (dpyIdx < 0)
3092 return 0;
3093
Mathias Agopiane57f2922012-08-09 16:29:12 -07003094 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003095 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003096 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003097 const uint32_t what = s.what;
3098 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003099 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 disp.surface = s.surface;
3101 flags |= eDisplayTransactionNeeded;
3102 }
3103 }
3104 if (what & DisplayState::eLayerStackChanged) {
3105 if (disp.layerStack != s.layerStack) {
3106 disp.layerStack = s.layerStack;
3107 flags |= eDisplayTransactionNeeded;
3108 }
3109 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003110 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003111 if (disp.orientation != s.orientation) {
3112 disp.orientation = s.orientation;
3113 flags |= eDisplayTransactionNeeded;
3114 }
3115 if (disp.frame != s.frame) {
3116 disp.frame = s.frame;
3117 flags |= eDisplayTransactionNeeded;
3118 }
3119 if (disp.viewport != s.viewport) {
3120 disp.viewport = s.viewport;
3121 flags |= eDisplayTransactionNeeded;
3122 }
3123 }
Michael Lentine47e45402014-07-18 15:34:25 -07003124 if (what & DisplayState::eDisplaySizeChanged) {
3125 if (disp.width != s.width) {
3126 disp.width = s.width;
3127 flags |= eDisplayTransactionNeeded;
3128 }
3129 if (disp.height != s.height) {
3130 disp.height = s.height;
3131 flags |= eDisplayTransactionNeeded;
3132 }
3133 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003134 }
3135 return flags;
3136}
3137
chaviwca27f252018-02-06 16:46:39 -08003138uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3139 const layer_state_t& s = composerState.state;
3140 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3141
Mathias Agopian13127d82013-03-05 17:47:11 -08003142 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003143 if (layer == nullptr) {
3144 return 0;
3145 }
3146
3147 if (layer->isPendingRemoval()) {
3148 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3149 return 0;
3150 }
3151
3152 uint32_t flags = 0;
3153
3154 const uint32_t what = s.what;
3155 bool geometryAppliesWithResize =
3156 what & layer_state_t::eGeometryAppliesWithResize;
3157 if (what & layer_state_t::ePositionChanged) {
3158 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3159 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003160 }
chaviw8b3871a2017-11-01 17:41:01 -07003161 }
3162 if (what & layer_state_t::eLayerChanged) {
3163 // NOTE: index needs to be calculated before we update the state
3164 const auto& p = layer->getParent();
3165 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003166 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003167 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003168 mCurrentState.layersSortedByZ.removeAt(idx);
3169 mCurrentState.layersSortedByZ.add(layer);
3170 // we need traversal (state changed)
3171 // AND transaction (list changed)
3172 flags |= eTransactionNeeded|eTraversalNeeded;
3173 }
chaviw8b3871a2017-11-01 17:41:01 -07003174 } else {
3175 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003176 flags |= eTransactionNeeded|eTraversalNeeded;
3177 }
3178 }
chaviw8b3871a2017-11-01 17:41:01 -07003179 }
3180 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003181 // NOTE: index needs to be calculated before we update the state
3182 const auto& p = layer->getParent();
3183 if (p == nullptr) {
3184 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3185 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3186 mCurrentState.layersSortedByZ.removeAt(idx);
3187 mCurrentState.layersSortedByZ.add(layer);
3188 // we need traversal (state changed)
3189 // AND transaction (list changed)
3190 flags |= eTransactionNeeded|eTraversalNeeded;
3191 }
3192 } else {
3193 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3194 flags |= eTransactionNeeded|eTraversalNeeded;
3195 }
chaviw8b3871a2017-11-01 17:41:01 -07003196 }
3197 }
3198 if (what & layer_state_t::eSizeChanged) {
3199 if (layer->setSize(s.w, s.h)) {
3200 flags |= eTraversalNeeded;
3201 }
3202 }
3203 if (what & layer_state_t::eAlphaChanged) {
3204 if (layer->setAlpha(s.alpha))
3205 flags |= eTraversalNeeded;
3206 }
3207 if (what & layer_state_t::eColorChanged) {
3208 if (layer->setColor(s.color))
3209 flags |= eTraversalNeeded;
3210 }
3211 if (what & layer_state_t::eMatrixChanged) {
3212 if (layer->setMatrix(s.matrix))
3213 flags |= eTraversalNeeded;
3214 }
3215 if (what & layer_state_t::eTransparentRegionChanged) {
3216 if (layer->setTransparentRegionHint(s.transparentRegion))
3217 flags |= eTraversalNeeded;
3218 }
3219 if (what & layer_state_t::eFlagsChanged) {
3220 if (layer->setFlags(s.flags, s.mask))
3221 flags |= eTraversalNeeded;
3222 }
3223 if (what & layer_state_t::eCropChanged) {
3224 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3225 flags |= eTraversalNeeded;
3226 }
3227 if (what & layer_state_t::eFinalCropChanged) {
3228 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3229 flags |= eTraversalNeeded;
3230 }
3231 if (what & layer_state_t::eLayerStackChanged) {
3232 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3233 // We only allow setting layer stacks for top level layers,
3234 // everything else inherits layer stack from its parent.
3235 if (layer->hasParent()) {
3236 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3237 layer->getName().string());
3238 } else if (idx < 0) {
3239 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3240 "that also does not appear in the top level layer list. Something"
3241 " has gone wrong.", layer->getName().string());
3242 } else if (layer->setLayerStack(s.layerStack)) {
3243 mCurrentState.layersSortedByZ.removeAt(idx);
3244 mCurrentState.layersSortedByZ.add(layer);
3245 // we need traversal (state changed)
3246 // AND transaction (list changed)
3247 flags |= eTransactionNeeded|eTraversalNeeded;
3248 }
3249 }
3250 if (what & layer_state_t::eDeferTransaction) {
3251 if (s.barrierHandle != nullptr) {
3252 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3253 } else if (s.barrierGbp != nullptr) {
3254 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3255 if (authenticateSurfaceTextureLocked(gbp)) {
3256 const auto& otherLayer =
3257 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3258 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3259 } else {
3260 ALOGE("Attempt to defer transaction to to an"
3261 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003262 }
3263 }
chaviw8b3871a2017-11-01 17:41:01 -07003264 // We don't trigger a traversal here because if no other state is
3265 // changed, we don't want this to cause any more work
3266 }
3267 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003268 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003269 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003270 if (!hadParent) {
3271 mCurrentState.layersSortedByZ.remove(layer);
3272 }
chaviw8b3871a2017-11-01 17:41:01 -07003273 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003274 }
chaviw8b3871a2017-11-01 17:41:01 -07003275 }
3276 if (what & layer_state_t::eReparentChildren) {
3277 if (layer->reparentChildren(s.reparentHandle)) {
3278 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003279 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 if (what & layer_state_t::eDetachChildren) {
3282 layer->detachChildren();
3283 }
3284 if (what & layer_state_t::eOverrideScalingModeChanged) {
3285 layer->setOverrideScalingMode(s.overrideScalingMode);
3286 // We don't trigger a traversal here because if no other state is
3287 // changed, we don't want this to cause any more work
3288 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289 return flags;
3290}
3291
chaviwca27f252018-02-06 16:46:39 -08003292void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3293 const layer_state_t& state = composerState.state;
3294 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3295
3296 sp<Layer> layer(client->getLayerUser(state.surface));
3297 if (layer == nullptr) {
3298 return;
3299 }
3300
3301 if (layer->isPendingRemoval()) {
3302 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3303 return;
3304 }
3305
3306 if (state.what & layer_state_t::eDestroySurface) {
3307 removeLayerLocked(mStateLock, layer);
3308 }
3309}
3310
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003311status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003312 const String8& name,
3313 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003314 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003315 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3316 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003317{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003318 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003319 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003320 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003321 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003322 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003323
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003324 status_t result = NO_ERROR;
3325
3326 sp<Layer> layer;
3327
Cody Northropbc755282017-03-31 12:00:08 -06003328 String8 uniqueName = getUniqueLayerName(name);
3329
Mathias Agopian3165cc22012-08-08 19:42:09 -07003330 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3331 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003332 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003333 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003334 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336 break;
chaviw13fdc492017-06-27 12:40:18 -07003337 case ISurfaceComposerClient::eFXSurfaceColor:
3338 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003339 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003340 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003341 break;
3342 default:
3343 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344 break;
3345 }
3346
Dan Stoza7d89d062015-04-30 13:29:25 -07003347 if (result != NO_ERROR) {
3348 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003350
Chia-I Wuab0c3192017-08-01 11:29:00 -07003351 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3352 // TODO b/64227542
3353 if (windowType == 441731) {
3354 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3355 layer->setPrimaryDisplayOnly();
3356 }
3357
Albert Chaulk479c60c2017-01-27 14:21:34 -05003358 layer->setInfo(windowType, ownerUid);
3359
Robert Carr1f0a16a2016-10-24 16:27:39 -07003360 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003361 if (result != NO_ERROR) {
3362 return result;
3363 }
Irvelffc9efc2016-07-27 15:16:37 -07003364 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003365
3366 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003367 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003368}
3369
Cody Northropbc755282017-03-31 12:00:08 -06003370String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3371{
3372 bool matchFound = true;
3373 uint32_t dupeCounter = 0;
3374
3375 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3376 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3377
3378 // Loop over layers until we're sure there is no matching name
3379 while (matchFound) {
3380 matchFound = false;
3381 mDrawingState.traverseInZOrder([&](Layer* layer) {
3382 if (layer->getName() == uniqueName) {
3383 matchFound = true;
3384 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3385 }
3386 });
3387 }
3388
3389 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3390
3391 return uniqueName;
3392}
3393
David Sodman0c69cad2017-08-21 12:12:51 -07003394status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003395 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3396 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003397{
3398 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003399 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003400 case PIXEL_FORMAT_TRANSPARENT:
3401 case PIXEL_FORMAT_TRANSLUCENT:
3402 format = PIXEL_FORMAT_RGBA_8888;
3403 break;
3404 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003405 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003406 break;
3407 }
3408
David Sodman0c69cad2017-08-21 12:12:51 -07003409 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3410 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003411 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003412 *handle = layer->getHandle();
3413 *gbp = layer->getProducer();
3414 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003415 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003416
David Sodman0c69cad2017-08-21 12:12:51 -07003417 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003418 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003419}
3420
chaviw13fdc492017-06-27 12:40:18 -07003421status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003422 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003423 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003424{
chaviw13fdc492017-06-27 12:40:18 -07003425 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003426 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003427 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003428}
3429
Mathias Agopianac9fa422013-02-11 16:40:36 -08003430status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003431{
Robert Carr9524cb32017-02-13 11:32:32 -08003432 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003433 status_t err = NO_ERROR;
3434 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003435 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003436 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003437 err = removeLayer(l);
3438 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3439 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003440 }
3441 return err;
3442}
3443
Mathias Agopian13127d82013-03-05 17:47:11 -08003444status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003445{
Mathias Agopian67106042013-03-14 19:18:13 -07003446 // called by ~LayerCleaner() when all references to the IBinder (handle)
3447 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003448 sp<Layer> l = layer.promote();
3449 if (l == nullptr) {
3450 // The layer has already been removed, carry on
3451 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003452 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003453 // If we have a parent, then we can continue to live as long as it does.
3454 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455}
3456
Mathias Agopianb60314a2012-04-10 22:09:54 -07003457// ---------------------------------------------------------------------------
3458
Andy McFadden13a082e2012-08-24 10:16:42 -07003459void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003460 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003461 Vector<ComposerState> state;
3462 Vector<DisplayState> displays;
3463 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003464 d.what = DisplayState::eDisplayProjectionChanged |
3465 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003466 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003467 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003468 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003469 d.frame.makeInvalid();
3470 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003471 d.width = 0;
3472 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003473 displays.add(d);
3474 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003475 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3476 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003477
David Sodman105b7dc2017-11-04 20:28:14 -07003478 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003479 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003480 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003481
Brian Andersond0010582017-03-07 13:20:31 -08003482 // Use phase of 0 since phase is not known.
3483 // Use latency of 0, which will snap to the ideal latency.
3484 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003485}
3486
3487void SurfaceFlinger::initializeDisplays() {
3488 class MessageScreenInitialized : public MessageBase {
3489 SurfaceFlinger* flinger;
3490 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003491 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003492 virtual bool handler() {
3493 flinger->onInitializeDisplays();
3494 return true;
3495 }
3496 };
3497 sp<MessageBase> msg = new MessageScreenInitialized(this);
3498 postMessageAsync(msg); // we may be called from main thread, use async message
3499}
3500
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003501void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003502 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003503 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3504 this);
3505 int32_t type = hw->getDisplayType();
3506 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003507
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003508 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003509 return;
3510 }
3511
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003512 hw->setPowerMode(mode);
3513 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3514 ALOGW("Trying to set power mode for virtual display");
3515 return;
3516 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003517
Irvelffc9efc2016-07-27 15:16:37 -07003518 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003519 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003520 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3521 if (idx < 0) {
3522 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3523 return;
3524 }
3525 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3526 }
3527
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003528 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003529 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003531 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3532 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003533 // FIXME: eventthread only knows about the main display right now
3534 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003535 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003538 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003539 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003540 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003541
3542 struct sched_param param = {0};
3543 param.sched_priority = 1;
3544 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3545 ALOGW("Couldn't set SCHED_FIFO on display on");
3546 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003547 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003548 // Turn off the display
3549 struct sched_param param = {0};
3550 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3551 ALOGW("Couldn't set SCHED_OTHER on display off");
3552 }
3553
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003554 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3555 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003556 disableHardwareVsync(true); // also cancels any in-progress resync
3557
Mathias Agopiancde87a32012-09-13 14:09:01 -07003558 // FIXME: eventthread only knows about the main display right now
3559 mEventThread->onScreenReleased();
3560 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003561
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003562 getHwComposer().setPowerMode(type, mode);
3563 mVisibleRegionsDirty = true;
3564 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003565 } else if (mode == HWC_POWER_MODE_DOZE ||
3566 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003567 // Update display while dozing
3568 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003569 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3570 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003571 // FIXME: eventthread only knows about the main display right now
3572 mEventThread->onScreenAcquired();
3573 resyncToHardwareVsync(true);
3574 }
3575 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3576 // Leave display going to doze
3577 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3578 disableHardwareVsync(true); // also cancels any in-progress resync
3579 // FIXME: eventthread only knows about the main display right now
3580 mEventThread->onScreenReleased();
3581 }
3582 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003583 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003584 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003585 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003586 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003587}
3588
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003589void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3590 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003591 SurfaceFlinger& mFlinger;
3592 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003593 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003594 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003595 MessageSetPowerMode(SurfaceFlinger& flinger,
3596 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3597 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003598 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003599 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003600 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003601 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003602 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003603 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003604 ALOGW("Attempt to set power mode = %d for virtual display",
3605 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003606 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003607 mFlinger.setPowerModeInternal(
3608 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003609 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003610 return true;
3611 }
3612 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003613 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003614 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003615}
3616
3617// ---------------------------------------------------------------------------
3618
Lloyd Pique755e3192018-01-31 16:46:15 -08003619status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3620 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003622
Mathias Agopianbd115332013-04-18 16:41:04 -07003623 IPCThreadState* ipc = IPCThreadState::self();
3624 const int pid = ipc->getCallingPid();
3625 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003626
Mathias Agopianbd115332013-04-18 16:41:04 -07003627 if ((uid != AID_SHELL) &&
3628 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003629 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003630 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003632 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003633 // (this would indicate SF is stuck, but we want to be able to
3634 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003635 status_t err = mStateLock.timedLock(s2ns(1));
3636 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003637 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003638 result.appendFormat(
3639 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3640 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003641 }
3642
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003643 bool dumpAll = true;
3644 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003645 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003646
3647 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003648 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003649 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3650 dumpAll = false;
3651 }
3652
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003653 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003654 if ((index < numArgs) &&
3655 (args[index] == String16("--list"))) {
3656 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003657 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003658 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003659 }
3660
3661 if ((index < numArgs) &&
3662 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003663 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003664 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003665 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003666 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003667
3668 if ((index < numArgs) &&
3669 (args[index] == String16("--latency-clear"))) {
3670 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003671 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003672 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003673 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003674
3675 if ((index < numArgs) &&
3676 (args[index] == String16("--dispsync"))) {
3677 index++;
3678 mPrimaryDispSync.dump(result);
3679 dumpAll = false;
3680 }
Dan Stozab90cf072015-03-05 11:05:59 -08003681
3682 if ((index < numArgs) &&
3683 (args[index] == String16("--static-screen"))) {
3684 index++;
3685 dumpStaticScreenStats(result);
3686 dumpAll = false;
3687 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003688
3689 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003690 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003691 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003692 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003693 dumpAll = false;
3694 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003695
3696 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3697 index++;
3698 dumpWideColorInfo(result);
3699 dumpAll = false;
3700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003702
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003703 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003704 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003705 }
3706
Mathias Agopian9795c422009-08-26 16:36:26 -07003707 if (locked) {
3708 mStateLock.unlock();
3709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 }
3711 write(fd, result.string(), result.size());
3712 return NO_ERROR;
3713}
3714
Dan Stozac7014012014-02-14 15:03:43 -08003715void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3716 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003717{
Robert Carr2047fae2016-11-28 14:09:09 -08003718 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003719 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003720 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003721}
3722
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003723void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003724 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003725{
3726 String8 name;
3727 if (index < args.size()) {
3728 name = String8(args[index]);
3729 index++;
3730 }
3731
David Sodman105b7dc2017-11-04 20:28:14 -07003732 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003733 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003734 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003735
3736 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003737 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003738 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003739 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003740 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003741 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003742 }
Robert Carr2047fae2016-11-28 14:09:09 -08003743 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003744 }
3745}
3746
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003747void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003748 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003749{
3750 String8 name;
3751 if (index < args.size()) {
3752 name = String8(args[index]);
3753 index++;
3754 }
3755
Robert Carr2047fae2016-11-28 14:09:09 -08003756 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003757 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003758 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003759 }
Robert Carr2047fae2016-11-28 14:09:09 -08003760 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003761
Svetoslavd85084b2014-03-20 10:28:31 -07003762 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003763}
3764
Jamie Gennis6547ff42013-07-16 20:12:42 -07003765// This should only be called from the main thread. Otherwise it would need
3766// the lock and should use mCurrentState rather than mDrawingState.
3767void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003768 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003769 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003770 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003771
3772 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3773}
3774
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003775void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003776{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003777 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003778
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003779 if (isLayerTripleBufferingDisabled())
3780 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003781
3782 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003783 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003784 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003785 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003786 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3787 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003788 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003789}
3790
Dan Stozab90cf072015-03-05 11:05:59 -08003791void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3792{
3793 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003794 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3795 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003796 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003797 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003798 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3799 b + 1, bucketTimeSec, percent);
3800 }
David Sodman4a36e932017-11-07 14:29:47 -08003801 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003802 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003803 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003804 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003805 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003806}
3807
Dan Stozae77c7662016-05-13 11:37:28 -07003808void SurfaceFlinger::recordBufferingStats(const char* layerName,
3809 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003810 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3811 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003812 for (const auto& segment : history) {
3813 if (!segment.usedThirdBuffer) {
3814 stats.twoBufferTime += segment.totalTime;
3815 }
3816 if (segment.occupancyAverage < 1.0f) {
3817 stats.doubleBufferedTime += segment.totalTime;
3818 } else if (segment.occupancyAverage < 2.0f) {
3819 stats.tripleBufferedTime += segment.totalTime;
3820 }
3821 ++stats.numSegments;
3822 stats.totalTime += segment.totalTime;
3823 }
3824}
3825
Brian Andersond6927fb2016-07-23 23:37:30 -07003826void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3827 result.appendFormat("Layer frame timestamps:\n");
3828
3829 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3830 const size_t count = currentLayers.size();
3831 for (size_t i=0 ; i<count ; i++) {
3832 currentLayers[i]->dumpFrameEvents(result);
3833 }
3834}
3835
Dan Stozae77c7662016-05-13 11:37:28 -07003836void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3837 result.append("Buffering stats:\n");
3838 result.append(" [Layer name] <Active time> <Two buffer> "
3839 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003840 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003841 typedef std::tuple<std::string, float, float, float> BufferTuple;
3842 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003843 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003844 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003845 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003846 if (stats.numSegments == 0) {
3847 continue;
3848 }
3849 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3850 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3851 stats.totalTime;
3852 float doubleBufferRatio = static_cast<float>(
3853 stats.doubleBufferedTime) / stats.totalTime;
3854 float tripleBufferRatio = static_cast<float>(
3855 stats.tripleBufferedTime) / stats.totalTime;
3856 sorted.insert({activeTime, {name, twoBufferRatio,
3857 doubleBufferRatio, tripleBufferRatio}});
3858 }
3859 for (const auto& sortedPair : sorted) {
3860 float activeTime = sortedPair.first;
3861 const BufferTuple& values = sortedPair.second;
3862 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3863 std::get<0>(values).c_str(), activeTime,
3864 std::get<1>(values), std::get<2>(values),
3865 std::get<3>(values));
3866 }
3867 result.append("\n");
3868}
3869
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003870void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3871 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003872 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003873
3874 // TODO: print out if wide-color mode is active or not
3875
3876 for (size_t d = 0; d < mDisplays.size(); d++) {
3877 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3878 int32_t hwcId = displayDevice->getHwcDisplayId();
3879 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3880 continue;
3881 }
3882
3883 result.appendFormat("Display %d color modes:\n", hwcId);
3884 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3885 for (auto&& mode : modes) {
3886 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3887 }
3888
3889 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3890 result.appendFormat(" Current color mode: %s (%d)\n",
3891 decodeColorMode(currentMode).c_str(), currentMode);
3892 }
3893 result.append("\n");
3894}
3895
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003896LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003897 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003898 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3899 const State& state = useDrawing ? mDrawingState : mCurrentState;
3900 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003901 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003902 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003903 });
3904
3905 return layersProto;
3906}
3907
Mathias Agopian74d211a2013-04-22 16:55:35 +02003908void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3909 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003911 bool colorize = false;
3912 if (index < args.size()
3913 && (args[index] == String16("--color"))) {
3914 colorize = true;
3915 index++;
3916 }
3917
3918 Colorizer colorizer(colorize);
3919
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003920 // figure out if we're stuck somewhere
3921 const nsecs_t now = systemTime();
3922 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3923 const nsecs_t inTransaction(mDebugInTransaction);
3924 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3925 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3926
3927 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003928 * Dump library configuration.
3929 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003930
3931 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003932 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003933 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003934 appendSfConfigString(result);
3935 appendUiConfigString(result);
3936 appendGuiConfigString(result);
3937 result.append("\n");
3938
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003939 result.append("\nWide-Color information:\n");
3940 dumpWideColorInfo(result);
3941
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003943 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003944 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003945 result.append(SyncFeatures::getInstance().toString());
3946 result.append("\n");
3947
David Sodman105b7dc2017-11-04 20:28:14 -07003948 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003949
Andy McFadden41d67d72014-04-25 16:58:34 -07003950 colorizer.bold(result);
3951 result.append("DispSync configuration: ");
3952 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003953 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003954 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003955 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003956 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003957 result.append("\n");
3958
Dan Stozab90cf072015-03-05 11:05:59 -08003959 // Dump static screen stats
3960 result.append("\n");
3961 dumpStaticScreenStats(result);
3962 result.append("\n");
3963
Dan Stozae77c7662016-05-13 11:37:28 -07003964 dumpBufferingStats(result);
3965
Andy McFadden4803b742012-09-24 19:07:20 -07003966 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003967 * Dump the visible layer list
3968 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003969 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003970 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003971 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003972
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003973 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003974 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3975 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976
3977 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003978 * Dump Display state
3979 */
3980
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003981 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003982 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003983 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003984 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3985 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003986 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003987 }
3988
3989 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003990 * Dump SurfaceFlinger global state
3991 */
3992
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003993 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003994 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003995 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003996
Mathias Agopian888c8222012-08-04 21:10:38 -07003997 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003998 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003999
David Sodmanbc815282017-11-05 18:57:52 -08004000 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004001
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004002 if (hw) {
4003 hw->undefinedRegion.dump(result, "undefinedRegion");
4004 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4005 hw->getOrientation(), hw->isDisplayOn());
4006 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004007 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004008 " last eglSwapBuffers() time: %f us\n"
4009 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004010 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004011 " refresh-rate : %f fps\n"
4012 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004013 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004014 " gpu_to_cpu_unsupported : %d\n"
4015 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004016 mLastSwapBufferTime/1000.0,
4017 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004018 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004019 1e9 / activeConfig->getVsyncPeriod(),
4020 activeConfig->getDpiX(),
4021 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004022 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004023
Mathias Agopian74d211a2013-04-22 16:55:35 +02004024 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004025 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004026
Mathias Agopian74d211a2013-04-22 16:55:35 +02004027 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004028 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004029
4030 /*
4031 * VSYNC state
4032 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004033 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004034 result.append("\n");
4035
4036 /*
4037 * HWC layer minidump
4038 */
4039 for (size_t d = 0; d < mDisplays.size(); d++) {
4040 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4041 int32_t hwcId = displayDevice->getHwcDisplayId();
4042 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4043 continue;
4044 }
4045
4046 result.appendFormat("Display %d HWC layers:\n", hwcId);
4047 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004048 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004049 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004050 });
Dan Stozae22aec72016-08-01 13:20:59 -07004051 result.append("\n");
4052 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004053
4054 /*
4055 * Dump HWComposer state
4056 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004057 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004058 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004059 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004060 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004061 result.appendFormat(" h/w composer %s\n",
4062 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004063 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004064
4065 /*
4066 * Dump gralloc state
4067 */
4068 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4069 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004070
4071 /*
4072 * Dump VrFlinger state if in use.
4073 */
4074 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4075 result.append("VrFlinger state:\n");
4076 result.append(mVrFlinger->Dump().c_str());
4077 result.append("\n");
4078 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004079}
4080
Mathias Agopian13127d82013-03-05 17:47:11 -08004081const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004082SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004083 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004084 wp<IBinder> dpy;
4085 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4086 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4087 dpy = mDisplays.keyAt(i);
4088 break;
4089 }
4090 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004091 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004092 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4093 // Just use the primary display so we have something to return
4094 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4095 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004096 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004097}
4098
Keun young Park63f165f2012-08-31 10:53:36 -07004099bool SurfaceFlinger::startDdmConnection()
4100{
4101 void* libddmconnection_dso =
4102 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4103 if (!libddmconnection_dso) {
4104 return false;
4105 }
4106 void (*DdmConnection_start)(const char* name);
4107 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004108 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004109 if (!DdmConnection_start) {
4110 dlclose(libddmconnection_dso);
4111 return false;
4112 }
4113 (*DdmConnection_start)(getServiceName());
4114 return true;
4115}
4116
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004117status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 switch (code) {
4119 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004120 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004122 case CLEAR_ANIMATION_FRAME_STATS:
4123 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004124 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004125 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004126 case ENABLE_VSYNC_INJECTIONS:
4127 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 {
4129 // codes that require permission check
4130 IPCThreadState* ipc = IPCThreadState::self();
4131 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004132 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004133 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004134 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004135 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004136 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004138 break;
4139 }
Robert Carr1db73f62016-12-21 12:58:51 -08004140 /*
4141 * Calling setTransactionState is safe, because you need to have been
4142 * granted a reference to Client* and Handle* to do anything with it.
4143 *
4144 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4145 */
4146 case SET_TRANSACTION_STATE:
4147 case CREATE_SCOPED_CONNECTION:
4148 {
4149 return OK;
4150 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004151 case CAPTURE_SCREEN:
4152 {
4153 // codes that require permission check
4154 IPCThreadState* ipc = IPCThreadState::self();
4155 const int pid = ipc->getCallingPid();
4156 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004157 if ((uid != AID_GRAPHICS) &&
4158 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004159 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004160 return PERMISSION_DENIED;
4161 }
4162 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004163 }
chaviwa76b2712017-09-20 12:02:26 -07004164 case CAPTURE_LAYERS: {
4165 IPCThreadState* ipc = IPCThreadState::self();
4166 const int pid = ipc->getCallingPid();
4167 const int uid = ipc->getCallingUid();
4168 if ((uid != AID_GRAPHICS) &&
4169 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4170 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4171 return PERMISSION_DENIED;
4172 }
4173 break;
4174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004175 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004176 return OK;
4177}
4178
4179status_t SurfaceFlinger::onTransact(
4180 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4181{
4182 status_t credentialCheck = CheckTransactCodeCredentials(code);
4183 if (credentialCheck != OK) {
4184 return credentialCheck;
4185 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004186
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4188 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004189 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004190 IPCThreadState* ipc = IPCThreadState::self();
4191 const int uid = ipc->getCallingUid();
4192 if (CC_UNLIKELY(uid != AID_SYSTEM
4193 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004194 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004195 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004196 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197 return PERMISSION_DENIED;
4198 }
4199 int n;
4200 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004201 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004202 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203 return NO_ERROR;
4204 case 1002: // SHOW_UPDATES
4205 n = data.readInt32();
4206 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004207 invalidateHwcGeometry();
4208 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004210 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004211 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004212 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004213 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004214 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004215 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004216 setTransactionFlags(
4217 eTransactionNeeded|
4218 eDisplayTransactionNeeded|
4219 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004220 return NO_ERROR;
4221 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004222 case 1006:{ // send empty update
4223 signalRefresh();
4224 return NO_ERROR;
4225 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004226 case 1008: // toggle use of hw composer
4227 n = data.readInt32();
4228 mDebugDisableHWC = n ? 1 : 0;
4229 invalidateHwcGeometry();
4230 repaintEverything();
4231 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004232 case 1009: // toggle use of transform hint
4233 n = data.readInt32();
4234 mDebugDisableTransformHint = n ? 1 : 0;
4235 invalidateHwcGeometry();
4236 repaintEverything();
4237 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004238 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004239 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004240 reply->writeInt32(0);
4241 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004242 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004243 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004244 return NO_ERROR;
4245 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004246 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004247 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004248 return NO_ERROR;
4249 }
4250 case 1014: {
4251 // daltonize
4252 n = data.readInt32();
4253 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004254 case 1:
4255 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4256 break;
4257 case 2:
4258 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4259 break;
4260 case 3:
4261 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4262 break;
4263 default:
4264 mDaltonizer.setType(ColorBlindnessType::None);
4265 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004266 }
4267 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004268 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004269 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004270 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004271 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004272 invalidateHwcGeometry();
4273 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004274 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004275 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004276 case 1015: {
4277 // apply a color matrix
4278 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004279 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004280 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004281 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004282 for (size_t j = 0; j < 4; j++) {
4283 mColorMatrix[i][j] = data.readFloat();
4284 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004285 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004286 } else {
4287 mColorMatrix = mat4();
4288 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004289
4290 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4291 // the division by w in the fragment shader
4292 float4 lastRow(transpose(mColorMatrix)[3]);
4293 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4294 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4295 }
4296
Alan Viverette9c5a3332013-09-12 20:04:35 -07004297 invalidateHwcGeometry();
4298 repaintEverything();
4299 return NO_ERROR;
4300 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004301 // This is an experimental interface
4302 // Needs to be shifted to proper binder interface when we productize
4303 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004304 n = data.readInt32();
4305 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004306 return NO_ERROR;
4307 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004308 case 1017: {
4309 n = data.readInt32();
4310 mForceFullDamage = static_cast<bool>(n);
4311 return NO_ERROR;
4312 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004313 case 1018: { // Modify Choreographer's phase offset
4314 n = data.readInt32();
4315 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4316 return NO_ERROR;
4317 }
4318 case 1019: { // Modify SurfaceFlinger's phase offset
4319 n = data.readInt32();
4320 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4321 return NO_ERROR;
4322 }
Irvel468051e2016-06-13 16:44:44 -07004323 case 1020: { // Layer updates interceptor
4324 n = data.readInt32();
4325 if (n) {
4326 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004327 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004328 }
4329 else{
4330 ALOGV("Interceptor disabled");
4331 mInterceptor.disable();
4332 }
4333 return NO_ERROR;
4334 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004335 case 1021: { // Disable HWC virtual displays
4336 n = data.readInt32();
4337 mUseHwcVirtualDisplays = !n;
4338 return NO_ERROR;
4339 }
Romain Guy0147a172017-06-01 13:53:56 -07004340 case 1022: { // Set saturation boost
4341 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4342
4343 invalidateHwcGeometry();
4344 repaintEverything();
4345 return NO_ERROR;
4346 }
Romain Guy54f154a2017-10-24 21:40:32 +01004347 case 1023: { // Set native mode
4348 mForceNativeColorMode = data.readInt32() == 1;
4349
4350 invalidateHwcGeometry();
4351 repaintEverything();
4352 return NO_ERROR;
4353 }
4354 case 1024: { // Is wide color gamut rendering/color management supported?
4355 reply->writeBool(hasWideColorDisplay);
4356 return NO_ERROR;
4357 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004358 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004359 n = data.readInt32();
4360 if (n) {
4361 ALOGV("LayerTracing enabled");
4362 mTracing.enable();
4363 doTracing("tracing.enable");
4364 reply->writeInt32(NO_ERROR);
4365 } else {
4366 ALOGV("LayerTracing disabled");
4367 status_t err = mTracing.disable();
4368 reply->writeInt32(err);
4369 }
4370 return NO_ERROR;
4371 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004372 case 1026: { // Get layer tracing status
4373 reply->writeBool(mTracing.isEnabled());
4374 return NO_ERROR;
4375 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004376 }
4377 }
4378 return err;
4379}
4380
Steven Thomas6d8110b2017-08-31 18:24:21 -07004381void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004382 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004383 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004384}
4385
Steven Thomas6d8110b2017-08-31 18:24:21 -07004386void SurfaceFlinger::repaintEverything() {
4387 ConditionalLock _l(mStateLock,
4388 std::this_thread::get_id() != mMainThreadId);
4389 repaintEverythingLocked();
4390}
4391
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004392// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4393class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004394public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004395 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4396 ~WindowDisconnector() {
4397 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004398 }
4399
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004400private:
4401 ANativeWindow* mWindow;
4402 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004403};
4404
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004405status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4406 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4407 int32_t minLayerZ, int32_t maxLayerZ,
4408 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004409 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004410 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004411
chaviwa76b2712017-09-20 12:02:26 -07004412 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4413
4414 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4415 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4416
4417 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4418 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004419 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004420}
4421
4422status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004423 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004424 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004425 ATRACE_CALL();
4426
4427 class LayerRenderArea : public RenderArea {
4428 public:
chaviw7206d492017-11-10 16:16:12 -08004429 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004430 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004431 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004432 const Transform& getTransform() const override {
4433 // Make the top level transform the inverse the transform and it's parent so it sets
4434 // the whole capture back to 0,0
4435 return *new Transform(mLayer->getTransform().inverse());
4436 }
4437 Rect getBounds() const override {
4438 const Layer::State& layerState(mLayer->getDrawingState());
4439 return Rect(layerState.active.w, layerState.active.h);
4440 }
4441 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4442 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4443 bool isSecure() const override { return false; }
4444 bool needsFiltering() const override { return false; }
4445
chaviw7206d492017-11-10 16:16:12 -08004446 Rect getSourceCrop() const override {
4447 if (mCrop.isEmpty()) {
4448 return getBounds();
4449 } else {
4450 return mCrop;
4451 }
4452 }
chaviwa76b2712017-09-20 12:02:26 -07004453 bool getWideColorSupport() const override { return false; }
4454 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4455
4456 private:
chaviw7206d492017-11-10 16:16:12 -08004457 const sp<Layer> mLayer;
4458 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004459 };
4460
4461 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4462 auto parent = layerHandle->owner.promote();
4463
chaviw7206d492017-11-10 16:16:12 -08004464 if (parent == nullptr || parent->isPendingRemoval()) {
4465 ALOGE("captureLayers called with a removed parent");
4466 return NAME_NOT_FOUND;
4467 }
4468
4469 Rect crop(sourceCrop);
4470 if (sourceCrop.width() <= 0) {
4471 crop.left = 0;
4472 crop.right = parent->getCurrentState().active.w;
4473 }
4474
4475 if (sourceCrop.height() <= 0) {
4476 crop.top = 0;
4477 crop.bottom = parent->getCurrentState().active.h;
4478 }
4479
4480 int32_t reqWidth = crop.width() * frameScale;
4481 int32_t reqHeight = crop.height() * frameScale;
4482
4483 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4484
chaviwa76b2712017-09-20 12:02:26 -07004485 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4486 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4487 if (!layer->isVisible()) {
4488 return;
4489 }
4490 visitor(layer);
4491 });
4492 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004493 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004494}
4495
4496status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4497 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004498 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004499 bool useIdentityTransform) {
4500 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004501
chaviwa76b2712017-09-20 12:02:26 -07004502 renderArea.updateDimensions();
4503
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004504 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4505 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4506 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4507 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004508
4509 // This mutex protects syncFd and captureResult for communication of the return values from the
4510 // main thread back to this Binder thread
4511 std::mutex captureMutex;
4512 std::condition_variable captureCondition;
4513 std::unique_lock<std::mutex> captureLock(captureMutex);
4514 int syncFd = -1;
4515 std::optional<status_t> captureResult;
4516
Robert Carr03480e22018-01-04 16:02:06 -08004517 const int uid = IPCThreadState::self()->getCallingUid();
4518 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4519
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004520 sp<LambdaMessage> message = new LambdaMessage([&]() {
4521 // If there is a refresh pending, bug out early and tell the binder thread to try again
4522 // after the refresh.
4523 if (mRefreshPending) {
4524 ATRACE_NAME("Skipping screenshot for now");
4525 std::unique_lock<std::mutex> captureLock(captureMutex);
4526 captureResult = std::make_optional<status_t>(EAGAIN);
4527 captureCondition.notify_one();
4528 return;
4529 }
4530
4531 status_t result = NO_ERROR;
4532 int fd = -1;
4533 {
4534 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004535 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004536 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004537 }
4538
4539 {
4540 std::unique_lock<std::mutex> captureLock(captureMutex);
4541 syncFd = fd;
4542 captureResult = std::make_optional<status_t>(result);
4543 captureCondition.notify_one();
4544 }
4545 });
4546
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004547 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004548 if (result == NO_ERROR) {
4549 captureCondition.wait(captureLock, [&]() { return captureResult; });
4550 while (*captureResult == EAGAIN) {
4551 captureResult.reset();
4552 result = postMessageAsync(message);
4553 if (result != NO_ERROR) {
4554 return result;
4555 }
4556 captureCondition.wait(captureLock, [&]() { return captureResult; });
4557 }
4558 result = *captureResult;
4559 }
4560
4561 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004562 sync_wait(syncFd, -1);
4563 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004564 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004565
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004566 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004567}
4568
chaviwa76b2712017-09-20 12:02:26 -07004569void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4570 TraverseLayersFunction traverseLayers, bool yswap,
4571 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004572 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004573
Lloyd Pique144e1162017-12-20 16:44:52 -08004574 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004575
4576 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004577 const auto raWidth = renderArea.getWidth();
4578 const auto raHeight = renderArea.getHeight();
4579
4580 const auto reqWidth = renderArea.getReqWidth();
4581 const auto reqHeight = renderArea.getReqHeight();
4582 Rect sourceCrop = renderArea.getSourceCrop();
4583
4584 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4585 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004586
Dan Stozac1879002014-05-22 15:59:05 -07004587 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004588 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004589 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004590 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004591 }
4592
4593 // ensure that sourceCrop is inside screen
4594 if (sourceCrop.left < 0) {
4595 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4596 }
chaviwa76b2712017-09-20 12:02:26 -07004597 if (sourceCrop.right > raWidth) {
4598 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004599 }
4600 if (sourceCrop.top < 0) {
4601 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4602 }
chaviwa76b2712017-09-20 12:02:26 -07004603 if (sourceCrop.bottom > raHeight) {
4604 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004605 }
4606
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004607 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004608 if (renderArea.getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004609 renderArea.getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
4610 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4611 }
4612 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004613
Mathias Agopian180f10d2013-04-10 22:55:41 -07004614 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004615 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004616
4617 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004618 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4619 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004620 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004621
4622 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004623 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004624
chaviwa76b2712017-09-20 12:02:26 -07004625 traverseLayers([&](Layer* layer) {
4626 if (filtering) layer->setFiltering(true);
4627 layer->draw(renderArea, useIdentityTransform);
4628 if (filtering) layer->setFiltering(false);
4629 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004630}
4631
chaviwa76b2712017-09-20 12:02:26 -07004632status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4633 TraverseLayersFunction traverseLayers,
4634 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004635 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004636 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004637 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004638 ATRACE_CALL();
4639
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004640 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004641
4642 traverseLayers([&](Layer* layer) {
4643 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4644 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004645
Robert Carr03480e22018-01-04 16:02:06 -08004646 // We allow the system server to take screenshots of secure layers for
4647 // use in situations like the Screen-rotation animation and place
4648 // the impetus on WindowManager to not persist them.
4649 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004650 ALOGW("FB is protected: PERMISSION_DENIED");
4651 return PERMISSION_DENIED;
4652 }
4653
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004654 // this binds the given EGLImage as a framebuffer for the
4655 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004656 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004657 if (bufferBond.getStatus() != NO_ERROR) {
4658 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004659 return INVALID_OPERATION;
4660 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004661
Dan Stozaabcda352017-06-01 14:37:39 -07004662 // this will in fact render into our dequeued buffer
4663 // via an FBO, which means we didn't have to create
4664 // an EGLSurface and therefore we're not
4665 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004666 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004667
Dan Stozaabcda352017-06-01 14:37:39 -07004668 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004669 getRenderEngine().finish();
4670 *outSyncFd = -1;
4671
chaviwa76b2712017-09-20 12:02:26 -07004672 const auto reqWidth = renderArea.getReqWidth();
4673 const auto reqHeight = renderArea.getReqHeight();
4674
Dan Stozaabcda352017-06-01 14:37:39 -07004675 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4676 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004677 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004678 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004679 } else {
4680 base::unique_fd syncFd = getRenderEngine().flush();
4681 if (syncFd < 0) {
4682 getRenderEngine().finish();
4683 }
4684 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004685 }
4686
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004687 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004688}
4689
Mathias Agopiand5556842013-09-19 17:08:37 -07004690void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004691 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004692 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004693 for (size_t y = 0; y < h; y++) {
4694 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4695 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004696 if (p[x] != 0xFF000000) return;
4697 }
4698 }
chaviwa76b2712017-09-20 12:02:26 -07004699 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004700
Robert Carr2047fae2016-11-28 14:09:09 -08004701 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004702 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004703 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004704 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4705 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4706 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4707 static_cast<float>(state.color.a));
4708 i++;
4709 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004710 }
4711}
4712
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004713// ---------------------------------------------------------------------------
4714
Dan Stoza412903f2017-04-27 13:42:17 -07004715void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4716 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004717}
4718
Dan Stoza412903f2017-04-27 13:42:17 -07004719void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4720 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004721}
4722
chaviwa76b2712017-09-20 12:02:26 -07004723void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4724 int32_t maxLayerZ,
4725 const LayerVector::Visitor& visitor) {
4726 // We loop through the first level of layers without traversing,
4727 // as we need to interpret min/max layer Z in the top level Z space.
4728 for (const auto& layer : mDrawingState.layersSortedByZ) {
4729 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4730 continue;
4731 }
4732 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004733 // relative layers are traversed in Layer::traverseInZOrder
4734 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004735 continue;
4736 }
4737 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004738 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4739 return;
4740 }
chaviwa76b2712017-09-20 12:02:26 -07004741 if (!layer->isVisible()) {
4742 return;
4743 }
4744 visitor(layer);
4745 });
4746 }
4747}
4748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004749}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004750
4751
4752#if defined(__gl_h_)
4753#error "don't include gl/gl.h in this file"
4754#endif
4755
4756#if defined(__gl2_h_)
4757#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004758#endif