blob: db472a73965ce0749312df3a51ec9762255dd082 [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{
281 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");
587 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
588 "sfEventThread");
Lloyd Piquee83f9312018-02-01 12:53:17 -0800589 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590
Steven Thomasb02664d2017-07-26 18:48:28 -0700591 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800592 getBE().mRenderEngine =
593 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
594 hasWideColorDisplay
595 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
596 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800597 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700598
599 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
600 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800601 getBE().mHwc.reset(
602 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700603 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800604 // Process any initial hotplug and resulting display changes.
605 processDisplayHotplugEventsLocked();
606 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
607 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800608
Lloyd Piquefcd86612017-12-14 17:15:36 -0800609 // make the default display GLContext current so that we can create textures
610 // when creating Layers (which may happens before we render something)
611 getDefaultDisplayDeviceLocked()->makeCurrent();
612
Steven Thomas050b2c82017-03-06 11:45:16 -0800613 if (useVrFlinger) {
614 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700615 // This callback is called from the vr flinger dispatch thread. We
616 // need to call signalTransaction(), which requires holding
617 // mStateLock when we're not on the main thread. Acquiring
618 // mStateLock from the vr flinger dispatch thread might trigger a
619 // deadlock in surface flinger (see b/66916578), so post a message
620 // to be handled on the main thread instead.
621 sp<LambdaMessage> message = new LambdaMessage([=]() {
622 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
623 mVrFlingerRequestsDisplay = requestDisplay;
624 signalTransaction();
625 });
626 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 };
David Sodman105b7dc2017-11-04 20:28:14 -0700628 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
629 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800630 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800631 if (!mVrFlinger) {
632 ALOGE("Failed to start vrflinger");
633 }
634 }
635
Lloyd Pique755e3192018-01-31 16:46:15 -0800636 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
637 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
638 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700639
Mathias Agopian92a979a2012-08-02 18:32:23 -0700640 // initialize our drawing state
641 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700642
Andy McFadden13a082e2012-08-24 10:16:42 -0700643 // set initial conditions (e.g. unblank default device)
644 initializeDisplays();
645
David Sodmanbc815282017-11-05 18:57:52 -0800646 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700647
Wei Wangf9b05ee2017-07-19 20:59:39 -0700648 // Inform native graphics APIs whether the present timestamp is supported:
649 if (getHwComposer().hasCapability(
650 HWC2::Capability::PresentFenceIsNotReliable)) {
651 mStartPropertySetThread = new StartPropertySetThread(false);
652 } else {
653 mStartPropertySetThread = new StartPropertySetThread(true);
654 }
655
656 if (mStartPropertySetThread->Start() != NO_ERROR) {
657 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800658 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800659
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700661}
662
Romain Guy11d63f42017-07-20 12:47:14 -0700663void SurfaceFlinger::readPersistentProperties() {
664 char value[PROPERTY_VALUE_MAX];
665
666 property_get("persist.sys.sf.color_saturation", value, "1.0");
667 mSaturation = atof(value);
668 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100669
670 property_get("persist.sys.sf.native_mode", value, "0");
671 mForceNativeColorMode = atoi(value) == 1;
672 if (mForceNativeColorMode) {
673 ALOGV("Forcing native color mode");
674 }
Romain Guy11d63f42017-07-20 12:47:14 -0700675}
676
Mathias Agopiana67e4182012-06-19 17:26:12 -0700677void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800678 // Start boot animation service by setting a property mailbox
679 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800681 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 if (mStartPropertySetThread->join() != NO_ERROR) {
683 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800684 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700685}
686
Mathias Agopian875d8e12013-06-07 15:35:48 -0700687size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800688 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700689}
690
Mathias Agopian875d8e12013-06-07 15:35:48 -0700691size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800692 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700693}
694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800695// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800696
Jamie Gennis582270d2011-08-17 18:19:00 -0700697bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800698 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800699 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800700 return authenticateSurfaceTextureLocked(bufferProducer);
701}
702
703bool SurfaceFlinger::authenticateSurfaceTextureLocked(
704 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800705 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800706 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800707}
708
Brian Anderson6b376712017-04-04 10:51:39 -0700709status_t SurfaceFlinger::getSupportedFrameTimestamps(
710 std::vector<FrameEvent>* outSupported) const {
711 *outSupported = {
712 FrameEvent::REQUESTED_PRESENT,
713 FrameEvent::ACQUIRE,
714 FrameEvent::LATCH,
715 FrameEvent::FIRST_REFRESH_START,
716 FrameEvent::LAST_REFRESH_START,
717 FrameEvent::GPU_COMPOSITION_DONE,
718 FrameEvent::DEQUEUE_READY,
719 FrameEvent::RELEASE,
720 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700721 ConditionalLock _l(mStateLock,
722 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700723 if (!getHwComposer().hasCapability(
724 HWC2::Capability::PresentFenceIsNotReliable)) {
725 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
726 }
727 return NO_ERROR;
728}
729
Dan Stoza7f7da322014-05-02 15:26:25 -0700730status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
731 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800732 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700733 return BAD_VALUE;
734 }
735
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500736 if (!display.get())
737 return NAME_NOT_FOUND;
738
Jesse Hall692c7232012-11-08 15:41:56 -0800739 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700740 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800741 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700742 type = i;
743 break;
744 }
745 }
746
747 if (type < 0) {
748 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700749 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700750
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751 // TODO: Not sure if display density should handled by SF any longer
752 class Density {
753 static int getDensityFromProperty(char const* propName) {
754 char property[PROPERTY_VALUE_MAX];
755 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800756 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757 density = atoi(property);
758 }
759 return density;
760 }
761 public:
762 static int getEmuDensity() {
763 return getDensityFromProperty("qemu.sf.lcd_density"); }
764 static int getBuildDensity() {
765 return getDensityFromProperty("ro.sf.lcd_density"); }
766 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700767
Dan Stoza7f7da322014-05-02 15:26:25 -0700768 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700769
Steven Thomas6d8110b2017-08-31 18:24:21 -0700770 ConditionalLock _l(mStateLock,
771 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 DisplayInfo info = DisplayInfo();
774
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 float xdpi = hwConfig->getDpiX();
776 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700777
778 if (type == DisplayDevice::DISPLAY_PRIMARY) {
779 // The density of the device is provided by a build property
780 float density = Density::getBuildDensity() / 160.0f;
781 if (density == 0) {
782 // the build doesn't provide a density -- this is wrong!
783 // use xdpi instead
784 ALOGE("ro.sf.lcd_density must be defined as a build property");
785 density = xdpi / 160.0f;
786 }
787 if (Density::getEmuDensity()) {
788 // if "qemu.sf.lcd_density" is specified, it overrides everything
789 xdpi = ydpi = density = Density::getEmuDensity();
790 density /= 160.0f;
791 }
792 info.density = density;
793
794 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700795 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800796 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 } else {
798 // TODO: where should this value come from?
799 static const int TV_DENSITY = 213;
800 info.density = TV_DENSITY / 160.0f;
801 info.orientation = 0;
802 }
803
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 info.w = hwConfig->getWidth();
805 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 info.xdpi = xdpi;
807 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900809 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810
Andy McFadden91b2ca82014-06-13 14:04:23 -0700811 // This is how far in advance a buffer must be queued for
812 // presentation at a given time. If you want a buffer to appear
813 // on the screen at time N, you must submit the buffer before
814 // (N - presentationDeadline).
815 //
816 // Normally it's one full refresh period (to give SF a chance to
817 // latch the buffer), but this can be reduced by configuring a
818 // DispSync offset. Any additional delays introduced by the hardware
819 // composer or panel must be accounted for here.
820 //
821 // We add an additional 1ms to allow for processing time and
822 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800824 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700825
826 // All non-virtual displays are currently considered secure.
827 info.secure = true;
828
Michael Wright28f24d02016-07-12 13:30:53 -0700829 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 }
831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 return NO_ERROR;
833}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700834
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800835status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700836 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800837 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700838 return BAD_VALUE;
839 }
840
841 // FIXME for now we always return stats for the primary display
842 memset(stats, 0, sizeof(*stats));
843 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
844 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
845 return NO_ERROR;
846}
847
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700848int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800849 if (display == nullptr) {
850 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800851 return BAD_VALUE;
852 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700853
854 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800855 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700856 return device->getActiveConfig();
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
Dan Stoza24a42e92015-03-09 10:04:11 -0700859 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700861
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700862void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
863 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
864 this);
865 int32_t type = hw->getDisplayType();
866 int currentMode = hw->getActiveConfig();
867
868 if (mode == currentMode) {
869 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
870 return;
871 }
872
873 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
874 ALOGW("Trying to set config for virtual display");
875 return;
876 }
877
878 hw->setActiveConfig(mode);
879 getHwComposer().setActiveConfig(type, mode);
880}
881
882status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
883 class MessageSetActiveConfig: public MessageBase {
884 SurfaceFlinger& mFlinger;
885 sp<IBinder> mDisplay;
886 int mMode;
887 public:
888 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
889 int mode) :
890 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
891 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700892 Vector<DisplayInfo> configs;
893 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700894 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700895 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700896 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700897 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700898 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700899 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800900 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700901 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700902 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700903 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
904 ALOGW("Attempt to set active config = %d for virtual display",
905 mMode);
906 } else {
907 mFlinger.setActiveConfigInternal(hw, mMode);
908 }
909 return true;
910 }
911 };
912 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
913 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700914 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700915}
Michael Wright28f24d02016-07-12 13:30:53 -0700916status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
917 Vector<android_color_mode_t>* outColorModes) {
918 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
919 return BAD_VALUE;
920 }
921
922 if (!display.get()) {
923 return NAME_NOT_FOUND;
924 }
925
926 int32_t type = NAME_NOT_FOUND;
927 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
928 if (display == mBuiltinDisplays[i]) {
929 type = i;
930 break;
931 }
932 }
933
934 if (type < 0) {
935 return type;
936 }
937
Steven Thomas6d8110b2017-08-31 18:24:21 -0700938 std::vector<android_color_mode_t> modes;
939 {
940 ConditionalLock _l(mStateLock,
941 std::this_thread::get_id() != mMainThreadId);
942 modes = getHwComposer().getColorModes(type);
943 }
Michael Wright28f24d02016-07-12 13:30:53 -0700944 outColorModes->clear();
945 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
946
947 return NO_ERROR;
948}
949
950android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700951 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700952 if (device != nullptr) {
953 return device->getActiveColorMode();
954 }
955 return static_cast<android_color_mode_t>(BAD_VALUE);
956}
957
958void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
959 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700960 int32_t type = hw->getDisplayType();
961 android_color_mode_t currentMode = hw->getActiveColorMode();
962
963 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700964 return;
965 }
966
967 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
968 ALOGW("Trying to set config for virtual display");
969 return;
970 }
971
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600972 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
973 hw->getDisplayType());
974
Michael Wright28f24d02016-07-12 13:30:53 -0700975 hw->setActiveColorMode(mode);
976 getHwComposer().setActiveColorMode(type, mode);
977}
978
979
980status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
981 android_color_mode_t colorMode) {
982 class MessageSetActiveColorMode: public MessageBase {
983 SurfaceFlinger& mFlinger;
984 sp<IBinder> mDisplay;
985 android_color_mode_t mMode;
986 public:
987 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
988 android_color_mode_t mode) :
989 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
990 virtual bool handler() {
991 Vector<android_color_mode_t> modes;
992 mFlinger.getDisplayColorModes(mDisplay, &modes);
993 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
994 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600995 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
996 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return true;
998 }
999 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1000 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001001 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1002 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001003 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001004 ALOGW("Attempt to set active color mode %s %d for virtual display",
1005 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001006 } else {
1007 mFlinger.setActiveColorModeInternal(hw, mMode);
1008 }
1009 return true;
1010 }
1011 };
1012 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1013 postMessageSync(msg);
1014 return NO_ERROR;
1015}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001016
Svetoslavd85084b2014-03-20 10:28:31 -07001017status_t SurfaceFlinger::clearAnimationFrameStats() {
1018 Mutex::Autolock _l(mStateLock);
1019 mAnimFrameTracker.clearStats();
1020 return NO_ERROR;
1021}
1022
1023status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1024 Mutex::Autolock _l(mStateLock);
1025 mAnimFrameTracker.getStats(outStats);
1026 return NO_ERROR;
1027}
1028
Dan Stozac4f471e2016-03-24 09:31:08 -07001029status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1030 HdrCapabilities* outCapabilities) const {
1031 Mutex::Autolock _l(mStateLock);
1032
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001033 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001034 if (displayDevice == nullptr) {
1035 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1036 return BAD_VALUE;
1037 }
1038
1039 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001040 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001041 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001042 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1043 // insert HDR10 as we will force client composition for HDR10
1044 // layers
1045 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1046 types.push_back(HAL_HDR_HDR10);
1047
1048 *outCapabilities = HdrCapabilities(types,
1049 capabilities->getDesiredMaxLuminance(),
1050 capabilities->getDesiredMaxAverageLuminance(),
1051 capabilities->getDesiredMinLuminance());
1052 } else {
1053 *outCapabilities = std::move(*capabilities);
1054 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001055 } else {
1056 return BAD_VALUE;
1057 }
1058
1059 return NO_ERROR;
1060}
1061
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001062status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001063 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1064 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065
Chia-I Wu90f669f2017-10-05 14:24:41 -07001066 if (mInjectVSyncs == enable) {
1067 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069
1070 if (enable) {
1071 ALOGV("VSync Injections enabled");
1072 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001073 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001074 mInjectorEventThread =
1075 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1076 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001078 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079 } else {
1080 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001081 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 }
1083
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 });
1086 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001087 return NO_ERROR;
1088}
1089
1090status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 Mutex::Autolock _l(mStateLock);
1092
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001093 if (!mInjectVSyncs) {
1094 ALOGE("VSync Injections not enabled");
1095 return BAD_VALUE;
1096 }
1097 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1098 ALOGV("Injecting VSync inside SurfaceFlinger");
1099 mVSyncInjector->onInjectSyncEvent(when);
1100 }
1101 return NO_ERROR;
1102}
1103
Lloyd Pique755e3192018-01-31 16:46:15 -08001104status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1105 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001106 IPCThreadState* ipc = IPCThreadState::self();
1107 const int pid = ipc->getCallingPid();
1108 const int uid = ipc->getCallingUid();
1109 if ((uid != AID_SHELL) &&
1110 !PermissionCache::checkPermission(sDump, pid, uid)) {
1111 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1112 return PERMISSION_DENIED;
1113 }
1114
1115 // Try to acquire a lock for 1s, fail gracefully
1116 const status_t err = mStateLock.timedLock(s2ns(1));
1117 const bool locked = (err == NO_ERROR);
1118 if (!locked) {
1119 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1120 return TIMED_OUT;
1121 }
1122
1123 outLayers->clear();
1124 mCurrentState.traverseInZOrder([&](Layer* layer) {
1125 outLayers->push_back(layer->getLayerDebugInfo());
1126 });
1127
1128 mStateLock.unlock();
1129 return NO_ERROR;
1130}
1131
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001132// ----------------------------------------------------------------------------
1133
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001134sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1135 ISurfaceComposer::VsyncSource vsyncSource) {
1136 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1137 return mSFEventThread->createEventConnection();
1138 } else {
1139 return mEventThread->createEventConnection();
1140 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001141}
1142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001143// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001144
1145void SurfaceFlinger::waitForEvent() {
1146 mEventQueue.waitMessage();
1147}
1148
1149void SurfaceFlinger::signalTransaction() {
1150 mEventQueue.invalidate();
1151}
1152
1153void SurfaceFlinger::signalLayerUpdate() {
1154 mEventQueue.invalidate();
1155}
1156
1157void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001158 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159 mEventQueue.refresh();
1160}
1161
1162status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001163 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001164 return mEventQueue.postMessage(msg, reltime);
1165}
1166
1167status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001168 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001169 status_t res = mEventQueue.postMessage(msg, reltime);
1170 if (res == NO_ERROR) {
1171 msg->wait();
1172 }
1173 return res;
1174}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001176void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001177 do {
1178 waitForEvent();
1179 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001180}
1181
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182void SurfaceFlinger::enableHardwareVsync() {
1183 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001184 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001186 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1187 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001189 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190}
1191
Jesse Hall948fe0c2013-10-14 12:56:09 -07001192void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 Mutex::Autolock _l(mHWVsyncLock);
1194
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195 if (makeAvailable) {
1196 mHWVsyncAvailable = true;
1197 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001198 // Hardware vsync is not currently available, so abort the resync
1199 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200 return;
1201 }
1202
David Sodman105b7dc2017-11-04 20:28:14 -07001203 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001204 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205
1206 mPrimaryDispSync.reset();
1207 mPrimaryDispSync.setPeriod(period);
1208
1209 if (!mPrimaryHWVsyncEnabled) {
1210 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001211 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1212 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001213 mPrimaryHWVsyncEnabled = true;
1214 }
1215}
1216
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 Mutex::Autolock _l(mHWVsyncLock);
1219 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001220 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1221 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222 mPrimaryDispSync.endResync();
1223 mPrimaryHWVsyncEnabled = false;
1224 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225 if (makeUnavailable) {
1226 mHWVsyncAvailable = false;
1227 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001228}
1229
Tim Murray4a4e4a22016-04-19 16:29:23 +00001230void SurfaceFlinger::resyncWithRateLimit() {
1231 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001232
1233 // No explicit locking is needed here since EventThread holds a lock while calling this method
1234 static nsecs_t sLastResyncAttempted = 0;
1235 const nsecs_t now = systemTime();
1236 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001237 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001238 }
Dan Stoza57164302017-05-08 14:03:54 -07001239 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001240}
1241
Steven Thomasb02664d2017-07-26 18:48:28 -07001242void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1243 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001244 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001245 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001246 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001247 return;
1248 }
1249
1250 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001251 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001252 return;
1253 }
1254
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256
Jamie Gennisd1700752013-10-14 12:22:52 -07001257 { // Scope for the lock
1258 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001259 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001262 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001263
1264 if (needsHwVsync) {
1265 enableHardwareVsync();
1266 } else {
1267 disableHardwareVsync(false);
1268 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001269}
1270
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001271void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001272 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1273 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001274}
1275
Lloyd Pique715a2c12017-12-14 17:18:08 -08001276void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1277 HWC2::Connection connection) {
1278 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1279 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001280
Lloyd Piqueba04e622017-12-14 17:11:26 -08001281 // Ignore events that do not have the right sequenceId.
1282 if (sequenceId != getBE().mComposerSequenceId) {
1283 return;
1284 }
1285
Steven Thomasb02664d2017-07-26 18:48:28 -07001286 // Only lock if we're not on the main thread. This function is normally
1287 // called on a hwbinder thread, but for the primary display it's called on
1288 // the main thread with the state lock already held, so don't attempt to
1289 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001290 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001291
Lloyd Pique715a2c12017-12-14 17:18:08 -08001292 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001293
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001294 if (std::this_thread::get_id() == mMainThreadId) {
1295 // Process all pending hot plug events immediately if we are on the main thread.
1296 processDisplayHotplugEventsLocked();
1297 }
1298
Lloyd Piqueba04e622017-12-14 17:11:26 -08001299 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001300}
1301
Steven Thomasb02664d2017-07-26 18:48:28 -07001302void SurfaceFlinger::onRefreshReceived(int sequenceId,
1303 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001304 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001305 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001306 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001307 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001308 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001309}
1310
Dan Stoza9e56aa02015-11-02 13:00:03 -08001311void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001314 getHwComposer().setVsyncEnabled(disp,
1315 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001316}
1317
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001318// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001319void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321 // Clear the drawing state so that the logic inside of
1322 // handleTransactionLocked will fire. It will determine the delta between
1323 // mCurrentState and mDrawingState and re-apply all changes when we make the
1324 // transition.
1325 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001326 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327 mDisplays.clear();
1328}
1329
Steven Thomas050b2c82017-03-06 11:45:16 -08001330void SurfaceFlinger::updateVrFlinger() {
1331 if (!mVrFlinger)
1332 return;
1333 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001334 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001335 return;
1336 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 ALOGE("Vr flinger is only supported for remote hardware composer"
1340 " service connections. Ignoring request to transition to vr"
1341 " flinger.");
1342 mVrFlingerRequestsDisplay = false;
1343 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001344 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001345
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001346 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 int currentDisplayPowerMode = getDisplayDeviceLocked(
1349 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001356 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001357 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1358 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001359 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360
David Sodman105b7dc2017-11-04 20:28:14 -07001361 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1362 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001363
1364 if (vrFlingerRequestsDisplay) {
1365 mVrFlinger->GrantDisplayOwnership();
1366 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001367 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001368 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
1370 mVisibleRegionsDirty = true;
1371 invalidateHwcGeometry();
1372
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001373 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1375 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1376 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001377
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001379 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 const nsecs_t period = activeConfig->getVsyncPeriod();
1381 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 // Use phase of 0 since phase is not known.
1384 // Use latency of 0, which will snap to the ideal latency.
1385 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001386
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387 android_atomic_or(1, &mRepaintEverything);
1388 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389}
1390
Mathias Agopian4fec8732012-06-29 14:12:52 -07001391void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001392 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001393 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001395 bool frameMissed = !mHadClientComposition &&
1396 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397 (mPreviousPresentFence->getSignalTime() ==
1398 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001399 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001400 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001401 signalLayerUpdate();
1402 break;
1403 }
1404
Steven Thomas050b2c82017-03-06 11:45:16 -08001405 // Now that we're going to make it to the handleMessageTransaction()
1406 // call below it's safe to call updateVrFlinger(), which will
1407 // potentially trigger a display handoff.
1408 updateVrFlinger();
1409
Dan Stoza6b9454d2014-11-07 16:00:59 -08001410 bool refreshNeeded = handleMessageTransaction();
1411 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001412 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001413 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001414 // Signal a refresh if a transaction modified the window state,
1415 // a new buffer was latched, or if HWC has requested a full
1416 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001417 signalRefresh();
1418 }
1419 break;
1420 }
1421 case MessageQueue::REFRESH: {
1422 handleMessageRefresh();
1423 break;
1424 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001425 }
1426}
1427
Dan Stoza6b9454d2014-11-07 16:00:59 -08001428bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001429 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001430 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001431 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001433 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435}
1436
Dan Stoza6b9454d2014-11-07 16:00:59 -08001437bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001438 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001439 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001440}
1441
1442void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001444
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001445 mRefreshPending = false;
1446
Pablo Ceballos40845df2016-01-25 17:41:15 -08001447 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001448
Brian Andersond6927fb2016-07-23 23:37:30 -07001449 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001450 rebuildLayerStacks();
1451 setUpHWComposer();
1452 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001453 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001454 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001455 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001456
David Sodman105b7dc2017-11-04 20:28:14 -07001457 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001458
1459 mHadClientComposition = false;
1460 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1461 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1462 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001463 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001464 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001465
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469void SurfaceFlinger::doDebugFlashRegions()
1470{
1471 // is debugging enabled
1472 if (CC_LIKELY(!mDebugRegion))
1473 return;
1474
1475 const bool repaintEverything = mRepaintEverything;
1476 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1477 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001478 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 // transform the dirty region into this screen's coordinate space
1480 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1481 if (!dirtyRegion.isEmpty()) {
1482 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001483 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484
1485 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001486 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001487 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001488 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1489
Mathias Agopianda27af92012-09-13 18:17:13 -07001490 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 }
1492 }
1493 }
1494
1495 postFramebuffer();
1496
1497 if (mDebugRegion > 1) {
1498 usleep(mDebugRegion * 1000);
1499 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001500
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001502 auto& displayDevice = mDisplays[displayId];
1503 if (!displayDevice->isDisplayOn()) {
1504 continue;
1505 }
1506
David Sodman105b7dc2017-11-04 20:28:14 -07001507 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1508 ALOGE_IF(result != NO_ERROR,
1509 "prepareFrame for display %zd failed:"
1510 " %d (%s)",
1511 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001512 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513}
1514
Adrian Roos1e1a1282017-11-01 19:05:31 +01001515void SurfaceFlinger::doTracing(const char* where) {
1516 ATRACE_CALL();
1517 ATRACE_NAME(where);
1518 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001519 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001520 }
1521}
1522
Brian Andersond6927fb2016-07-23 23:37:30 -07001523void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001525 ATRACE_CALL();
1526 ALOGV("preComposition");
1527
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001529 mDrawingState.traverseInZOrder([&](Layer* layer) {
1530 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 needExtraInvalidate = true;
1532 }
Robert Carr2047fae2016-11-28 14:09:09 -08001533 });
1534
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535 if (needExtraInvalidate) {
1536 signalLayerUpdate();
1537 }
1538}
1539
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001540void SurfaceFlinger::updateCompositorTiming(
1541 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1542 std::shared_ptr<FenceTime>& presentFenceTime) {
1543 // Update queue of past composite+present times and determine the
1544 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001545 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001547 while (!getBE().mCompositePresentTimes.empty()) {
1548 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001549 // Cached values should have been updated before calling this method,
1550 // which helps avoid duplicate syscalls.
1551 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1552 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1553 break;
1554 }
1555 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001556 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557 }
1558
1559 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001560 while (getBE().mCompositePresentTimes.size() > 16) {
1561 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562 }
1563
Brian Andersond0010582017-03-07 13:20:31 -08001564 setCompositorTimingSnapped(
1565 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1566}
1567
1568void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1569 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570 // Integer division and modulo round toward 0 not -inf, so we need to
1571 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001572 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1574 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1575
Brian Andersond0010582017-03-07 13:20:31 -08001576 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1577 if (idealLatency <= 0) {
1578 idealLatency = vsyncInterval;
1579 }
1580
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581 // Snap the latency to a value that removes scheduling jitter from the
1582 // composition and present times, which often have >1ms of jitter.
1583 // Reducing jitter is important if an app attempts to extrapolate
1584 // something (such as user input) to an accurate diasplay time.
1585 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1586 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001587 nsecs_t bias = vsyncInterval / 2;
1588 int64_t extraVsyncs =
1589 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1590 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1591 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592
David Sodman99974d22017-11-28 12:04:33 -08001593 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1594 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1595 getBE().mCompositorTiming.interval = vsyncInterval;
1596 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001597}
1598
1599void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001600{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001601 ATRACE_CALL();
1602 ALOGV("postComposition");
1603
Brian Anderson3546a3f2016-07-14 11:51:14 -07001604 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001605 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001606 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001607 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001608 }
1609
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001610 // |mStateLock| not needed as we are on the main thread
1611 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001612
David Sodman73beded2017-11-15 11:56:06 -08001613 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001614 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001615 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001616 glCompositionDoneFenceTime =
1617 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001618 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001619 } else {
1620 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1621 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001622
David Sodman73beded2017-11-15 11:56:06 -08001623 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001624 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001625 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001626 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001627
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001628 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1629 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1630
1631 // We use the refreshStartTime which might be sampled a little later than
1632 // when we started doing work for this frame, but that should be okay
1633 // since updateCompositorTiming has snapping logic.
1634 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001635 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001636 CompositorTiming compositorTiming;
1637 {
David Sodman99974d22017-11-28 12:04:33 -08001638 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1639 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001640 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001641
Robert Carr2047fae2016-11-28 14:09:09 -08001642 mDrawingState.traverseInZOrder([&](Layer* layer) {
1643 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001644 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001645 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001646 recordBufferingStats(layer->getName().string(),
1647 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001648 }
Robert Carr2047fae2016-11-28 14:09:09 -08001649 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001650
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001651 if (presentFenceTime->isValid()) {
1652 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001653 enableHardwareVsync();
1654 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001655 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001656 }
1657 }
1658
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001659 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001660 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001661 enableHardwareVsync();
1662 }
1663 }
1664
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001665 if (mAnimCompositionPending) {
1666 mAnimCompositionPending = false;
1667
Brian Anderson4e606e32017-03-16 15:34:57 -07001668 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001670 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001671 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001672 // The HWC doesn't support present fences, so use the refresh
1673 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001674 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001675 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001676 mAnimFrameTracker.setActualPresentTime(presentTime);
1677 }
1678 mAnimFrameTracker.advanceFrame();
1679 }
Dan Stozab90cf072015-03-05 11:05:59 -08001680
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001681 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1682 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001683 return;
1684 }
1685
1686 nsecs_t currentTime = systemTime();
1687 if (mHasPoweredOff) {
1688 mHasPoweredOff = false;
1689 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001690 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001692 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1693 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001694 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001695 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001696 }
David Sodman4a36e932017-11-07 14:29:47 -08001697 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001698 }
David Sodman4a36e932017-11-07 14:29:47 -08001699 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700}
1701
1702void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001703 ATRACE_CALL();
1704 ALOGV("rebuildLayerStacks");
1705
Mathias Agopiancd60f992012-08-16 16:28:27 -07001706 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001707 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001708 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001709 mVisibleRegionsDirty = false;
1710 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001711
Jeff Sharkey76488112017-02-27 14:15:18 -07001712 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1713 Region opaqueRegion;
1714 Region dirtyRegion;
1715 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001716 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001717 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1718 const Transform& tr(displayDevice->getTransform());
1719 const Rect bounds(displayDevice->getBounds());
1720 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001721 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001722
Jeff Sharkey76488112017-02-27 14:15:18 -07001723 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001724 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001725 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1726 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001727 Region drawRegion(tr.transform(
1728 layer->visibleNonTransparentRegion));
1729 drawRegion.andSelf(bounds);
1730 if (!drawRegion.isEmpty()) {
1731 layersSortedByZ.add(layer);
1732 } else {
1733 // Clear out the HWC layer if this layer was
1734 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001735 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001736 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001737 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001738 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001739 // WM changes displayDevice->layerStack upon sleep/awake.
1740 // Here we make sure we delete the HWC layers even if
1741 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001742 hwcLayerDestroyed = layer->destroyHwcLayer(
1743 displayDevice->getHwcDisplayId());
1744 }
1745
1746 // If a layer is not going to get a release fence because
1747 // it is invisible, but it is also going to release its
1748 // old buffer, add it to the list of layers needing
1749 // fences.
1750 if (hwcLayerDestroyed) {
1751 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1752 mLayersWithQueuedFrames.cend(), layer);
1753 if (found != mLayersWithQueuedFrames.cend()) {
1754 layersNeedingFences.add(layer);
1755 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001756 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001757 });
1758 }
1759 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001760 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001761 displayDevice->undefinedRegion.set(bounds);
1762 displayDevice->undefinedRegion.subtractSelf(
1763 tr.transform(opaqueRegion));
1764 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001765 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001766 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001768
Romain Guy0147a172017-06-01 13:53:56 -07001769mat4 SurfaceFlinger::computeSaturationMatrix() const {
1770 if (mSaturation == 1.0f) {
1771 return mat4();
1772 }
1773
1774 // Rec.709 luma coefficients
1775 float3 luminance{0.213f, 0.715f, 0.072f};
1776 luminance *= 1.0f - mSaturation;
1777 return mat4(
1778 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1779 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1780 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1781 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1782 );
1783}
1784
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001785// pickColorMode translates a given dataspace into the best available color mode.
1786// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001787android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001788 if (mForceNativeColorMode) {
1789 return HAL_COLOR_MODE_NATIVE;
1790 }
1791
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001792 switch (dataSpace) {
1793 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1794 // system expects.
1795 case HAL_DATASPACE_UNKNOWN:
1796 case HAL_DATASPACE_SRGB:
1797 case HAL_DATASPACE_V0_SRGB:
1798 return HAL_COLOR_MODE_SRGB;
1799 break;
1800
1801 case HAL_DATASPACE_DISPLAY_P3:
1802 return HAL_COLOR_MODE_DISPLAY_P3;
1803 break;
1804
1805 default:
1806 // TODO (courtneygo): Do we want to assert an error here?
1807 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1808 dataSpace);
1809 return HAL_COLOR_MODE_SRGB;
1810 break;
1811 }
1812}
1813
Romain Guy0147a172017-06-01 13:53:56 -07001814android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001815 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001816 // Only support sRGB and Display-P3 right now.
1817 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1818 return HAL_DATASPACE_DISPLAY_P3;
1819 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001820 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1821 return HAL_DATASPACE_DISPLAY_P3;
1822 }
1823 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1824 return HAL_DATASPACE_DISPLAY_P3;
1825 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001826 if (!hasHdr) {
1827 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1828 return HAL_DATASPACE_DISPLAY_P3;
1829 }
1830 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1831 return HAL_DATASPACE_DISPLAY_P3;
1832 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001833 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001834
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001835 return HAL_DATASPACE_V0_SRGB;
1836}
1837
Mathias Agopiancd60f992012-08-16 16:28:27 -07001838void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001839 ATRACE_CALL();
1840 ALOGV("setUpHWComposer");
1841
Jesse Hall028dc8f2013-08-20 16:35:32 -07001842 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001843 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1844 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1845 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1846
1847 // If nothing has changed (!dirty), don't recompose.
1848 // If something changed, but we don't currently have any visible layers,
1849 // and didn't when we last did a composition, then skip it this time.
1850 // The second rule does two things:
1851 // - When all layers are removed from a display, we'll emit one black
1852 // frame, then nothing more until we get new layers.
1853 // - When a display is created with a private layer stack, we won't
1854 // emit any black frames until a layer is added to the layer stack.
1855 bool mustRecompose = dirty && !(empty && wasEmpty);
1856
1857 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1858 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1859 mustRecompose ? "doing" : "skipping",
1860 dirty ? "+" : "-",
1861 empty ? "+" : "-",
1862 wasEmpty ? "+" : "-");
1863
Dan Stoza71433162014-02-04 16:22:36 -08001864 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001865
1866 if (mustRecompose) {
1867 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1868 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001869 }
1870
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 // build the h/w work list
1872 if (CC_UNLIKELY(mGeometryInvalid)) {
1873 mGeometryInvalid = false;
1874 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1875 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1876 const auto hwcId = displayDevice->getHwcDisplayId();
1877 if (hwcId >= 0) {
1878 const Vector<sp<Layer>>& currentLayers(
1879 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001880 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001881 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001883 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001886 }
1887 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001888
Robert Carrae060832016-11-28 10:51:00 -08001889 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001890 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001892 }
1893 }
1894 }
1895 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 }
Riley Andrews03414a12014-07-01 14:22:59 -07001897
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001898
Romain Guy0147a172017-06-01 13:53:56 -07001899 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001900
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 // Set the per-frame data
1902 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1903 auto& displayDevice = mDisplays[displayId];
1904 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001905
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 if (hwcId < 0) {
1907 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001908 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001909 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001910 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001911 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1912 "display %zd: %d", displayId, result);
1913 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001915 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1916 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001917 !displayDevice->getHdrSupport()) {
1918 layer->forceClientComposition(hwcId);
1919 }
1920
chaviwc9232ed2017-11-14 15:31:15 -08001921 if (layer->getForceClientComposition(hwcId)) {
1922 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1923 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1924 continue;
1925 }
1926
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 layer->setPerFrameData(displayDevice);
1928 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001929
1930 if (hasWideColorDisplay) {
1931 android_color_mode newColorMode;
1932 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1933
1934 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001935 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1936 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1938 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1939 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1940 }
1941 newColorMode = pickColorMode(newDataSpace);
1942
Thierry Strudel2924d012017-08-14 15:19:37 -07001943 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001944 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 }
1946
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001947 mPreviousColorMatrix = colorMatrix;
1948
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001950 auto& displayDevice = mDisplays[displayId];
1951 if (!displayDevice->isDisplayOn()) {
1952 continue;
1953 }
1954
David Sodman105b7dc2017-11-04 20:28:14 -07001955 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1957 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001959}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001960
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961void SurfaceFlinger::doComposition() {
1962 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 ALOGV("doComposition");
1964
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001965 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001966 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001967 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001968 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001969 // transform the dirty region into this screen's coordinate space
1970 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001971
1972 // repaint the framebuffer (if needed)
1973 doDisplayComposition(hw, dirtyRegion);
1974
Mathias Agopiancd60f992012-08-16 16:28:27 -07001975 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001976 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001977 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001978 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001979 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001980}
1981
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001982void SurfaceFlinger::postFramebuffer()
1983{
Mathias Agopian841cde52012-03-01 15:44:37 -08001984 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001986
Mathias Agopiana44b0412011-10-16 18:46:35 -07001987 const nsecs_t now = systemTime();
1988 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001989
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1991 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001992 if (!displayDevice->isDisplayOn()) {
1993 continue;
1994 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 const auto hwcId = displayDevice->getHwcDisplayId();
1996 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001997 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001998 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001999 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002000 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002002 // The layer buffer from the previous frame (if any) is released
2003 // by HWC only when the release fence from this frame (if any) is
2004 // signaled. Always get the release fence from HWC first.
2005 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002006 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002007
2008 // If the layer was client composited in the previous frame, we
2009 // need to merge with the previous client target acquire fence.
2010 // Since we do not track that, always merge with the current
2011 // client target acquire fence when it is available, even though
2012 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002014 releaseFence = Fence::merge("LayerRelease", releaseFence,
2015 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002016 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002017
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 layer->onLayerDisplayed(releaseFence);
2019 }
Chia-I Wu83806892017-11-16 10:50:20 -08002020
2021 // We've got a list of layers needing fences, that are disjoint with
2022 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2023 // supply them with the present fence.
2024 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002025 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002026 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2027 layer->onLayerDisplayed(presentFence);
2028 }
2029 }
2030
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002032 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002033 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002034 }
2035
Mathias Agopiana44b0412011-10-16 18:46:35 -07002036 mLastSwapBufferTime = systemTime() - now;
2037 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002038
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002039 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002040 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2041 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2042 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2043 logFrameStats();
2044 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046}
2047
Mathias Agopian87baae12012-07-31 12:38:26 -07002048void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049{
Mathias Agopian841cde52012-03-01 15:44:37 -08002050 ATRACE_CALL();
2051
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002052 // here we keep a copy of the drawing state (that is the state that's
2053 // going to be overwritten by handleTransactionLocked()) outside of
2054 // mStateLock so that the side-effects of the State assignment
2055 // don't happen with mStateLock held (which can cause deadlocks).
2056 State drawingState(mDrawingState);
2057
Mathias Agopianca4d3602011-05-19 15:38:14 -07002058 Mutex::Autolock _l(mStateLock);
2059 const nsecs_t now = systemTime();
2060 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002061
Mathias Agopianca4d3602011-05-19 15:38:14 -07002062 // Here we're guaranteed that some transaction flags are set
2063 // so we can call handleTransactionLocked() unconditionally.
2064 // We call getTransactionFlags(), which will also clear the flags,
2065 // with mStateLock held to guarantee that mCurrentState won't change
2066 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002067
Mathias Agopiane57f2922012-08-09 16:29:12 -07002068 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002069 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002070
Mathias Agopianca4d3602011-05-19 15:38:14 -07002071 mLastTransactionTime = systemTime() - now;
2072 mDebugInTransaction = 0;
2073 invalidateHwcGeometry();
2074 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002075}
2076
Lloyd Pique715a2c12017-12-14 17:18:08 -08002077DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2078 HWC2::Connection connection) const {
2079 // Figure out whether the event is for the primary display or an
2080 // external display by matching the Hwc display id against one for a
2081 // connected display. If we did not find a match, we then check what
2082 // displays are not already connected to determine the type. If we don't
2083 // have a connected primary display, we assume the new display is meant to
2084 // be the primary display, and then if we don't have an external display,
2085 // we assume it is that.
2086 const auto primaryDisplayId =
2087 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2088 const auto externalDisplayId =
2089 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2090 if (primaryDisplayId && primaryDisplayId == display) {
2091 return DisplayDevice::DISPLAY_PRIMARY;
2092 } else if (externalDisplayId && externalDisplayId == display) {
2093 return DisplayDevice::DISPLAY_EXTERNAL;
2094 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2095 return DisplayDevice::DISPLAY_PRIMARY;
2096 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2097 return DisplayDevice::DISPLAY_EXTERNAL;
2098 }
2099
2100 return DisplayDevice::DISPLAY_ID_INVALID;
2101}
2102
Lloyd Piqueba04e622017-12-14 17:11:26 -08002103void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2104 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002105 auto displayType = determineDisplayType(event.display, event.connection);
2106 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2107 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2108 continue;
2109 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002110
2111 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2112 ALOGE("External displays are not supported by the vr hardware composer.");
2113 continue;
2114 }
2115
Lloyd Pique715a2c12017-12-14 17:18:08 -08002116 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002117
2118 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002119 ALOGV("Creating built in display %d", displayType);
2120 ALOGW_IF(mBuiltinDisplays[displayType],
2121 "Overwriting display token for display type %d", displayType);
2122 mBuiltinDisplays[displayType] = new BBinder();
2123 // All non-virtual displays are currently considered secure.
2124 DisplayDeviceState info(displayType, true);
2125 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2126 "Built-in Screen" : "External Screen";
2127 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2128 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002129 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002130 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002131
Lloyd Piquefcd86612017-12-14 17:15:36 -08002132 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2133 if (idx >= 0) {
2134 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2135 mInterceptor.saveDisplayDeletion(info.displayId);
2136 mCurrentState.displays.removeItemsAt(idx);
2137 }
2138 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002139 }
2140
2141 processDisplayChangesLocked();
2142 }
2143
2144 mPendingHotplugEvents.clear();
2145}
2146
Lloyd Pique347200f2017-12-14 17:00:15 -08002147void SurfaceFlinger::processDisplayChangesLocked() {
2148 // here we take advantage of Vector's copy-on-write semantics to
2149 // improve performance by skipping the transaction entirely when
2150 // know that the lists are identical
2151 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2152 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2153 if (!curr.isIdenticalTo(draw)) {
2154 mVisibleRegionsDirty = true;
2155 const size_t cc = curr.size();
2156 size_t dc = draw.size();
2157
2158 // find the displays that were removed
2159 // (ie: in drawing state but not in current state)
2160 // also handle displays that changed
2161 // (ie: displays that are in both lists)
2162 for (size_t i = 0; i < dc;) {
2163 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2164 if (j < 0) {
2165 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002166 // Call makeCurrent() on the primary display so we can
2167 // be sure that nothing associated with this display
2168 // is current.
2169 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2170 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2171 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2172 if (hw != nullptr) hw->disconnect(getHwComposer());
2173 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2174 mEventThread->onHotplugReceived(draw[i].type, false);
2175 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002176 } else {
2177 // this display is in both lists. see if something changed.
2178 const DisplayDeviceState& state(curr[j]);
2179 const wp<IBinder>& display(curr.keyAt(j));
2180 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2181 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2182 if (state_binder != draw_binder) {
2183 // changing the surface is like destroying and
2184 // recreating the DisplayDevice, so we just remove it
2185 // from the drawing state, so that it get re-added
2186 // below.
2187 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2188 if (hw != nullptr) hw->disconnect(getHwComposer());
2189 mDisplays.removeItem(display);
2190 mDrawingState.displays.removeItemsAt(i);
2191 dc--;
2192 // at this point we must loop to the next item
2193 continue;
2194 }
2195
2196 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2197 if (disp != nullptr) {
2198 if (state.layerStack != draw[i].layerStack) {
2199 disp->setLayerStack(state.layerStack);
2200 }
2201 if ((state.orientation != draw[i].orientation) ||
2202 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2203 disp->setProjection(state.orientation, state.viewport, state.frame);
2204 }
2205 if (state.width != draw[i].width || state.height != draw[i].height) {
2206 disp->setDisplaySize(state.width, state.height);
2207 }
2208 }
2209 }
2210 ++i;
2211 }
2212
2213 // find displays that were added
2214 // (ie: in current state but not in drawing state)
2215 for (size_t i = 0; i < cc; i++) {
2216 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2217 const DisplayDeviceState& state(curr[i]);
2218
2219 sp<DisplaySurface> dispSurface;
2220 sp<IGraphicBufferProducer> producer;
2221 sp<IGraphicBufferProducer> bqProducer;
2222 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002223 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002224
2225 int32_t hwcId = -1;
2226 if (state.isVirtualDisplay()) {
2227 // Virtual displays without a surface are dormant:
2228 // they have external state (layer stack, projection,
2229 // etc.) but no internal state (i.e. a DisplayDevice).
2230 if (state.surface != nullptr) {
2231 // Allow VR composer to use virtual displays.
2232 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2233 int width = 0;
2234 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2235 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2236 int height = 0;
2237 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2238 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2239 int intFormat = 0;
2240 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2241 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2242 auto format = static_cast<android_pixel_format_t>(intFormat);
2243
2244 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2245 }
2246
2247 // TODO: Plumb requested format back up to consumer
2248
2249 sp<VirtualDisplaySurface> vds =
2250 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2251 bqProducer, bqConsumer,
2252 state.displayName);
2253
2254 dispSurface = vds;
2255 producer = vds;
2256 }
2257 } else {
2258 ALOGE_IF(state.surface != nullptr,
2259 "adding a supported display, but rendering "
2260 "surface is provided (%p), ignoring it",
2261 state.surface.get());
2262
2263 hwcId = state.type;
2264 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2265 producer = bqProducer;
2266 }
2267
2268 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002269
Lloyd Pique347200f2017-12-14 17:00:15 -08002270 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002271 bool hasWideColorSupport = false;
2272 if (hasWideColorDisplay) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002273 std::vector<android_color_mode_t> modes =
2274 getHwComposer().getColorModes(state.type);
2275 for (android_color_mode_t colorMode : modes) {
2276 switch (colorMode) {
2277 case HAL_COLOR_MODE_DISPLAY_P3:
2278 case HAL_COLOR_MODE_ADOBE_RGB:
2279 case HAL_COLOR_MODE_DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002280 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002281 break;
2282 default:
2283 break;
2284 }
2285 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002286 }
2287
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002288 bool hasHdrSupport = false;
2289 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2290 getHwComposer().getHdrCapabilities(state.type);
2291 if (hdrCapabilities) {
2292 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2293 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2294 hasHdrSupport = iter != types.cend();
2295 }
2296
Lloyd Pique347200f2017-12-14 17:00:15 -08002297 sp<DisplayDevice> hw =
2298 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002299 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002300 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002301
Lloyd Piquec5208312018-01-08 17:59:02 -08002302 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002303 if (hasWideColorSupport) {
Lloyd Piquec5208312018-01-08 17:59:02 -08002304 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002305 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002306 setActiveColorModeInternal(hw, defaultColorMode);
2307 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002308 hw->setLayerStack(state.layerStack);
2309 hw->setProjection(state.orientation, state.viewport, state.frame);
2310 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002311
Lloyd Pique347200f2017-12-14 17:00:15 -08002312 mDisplays.add(display, hw);
2313 if (!state.isVirtualDisplay()) {
2314 mEventThread->onHotplugReceived(state.type, true);
2315 }
2316 }
2317 }
2318 }
2319 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002320
2321 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002322}
2323
Mathias Agopian87baae12012-07-31 12:38:26 -07002324void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002325{
Dan Stoza7dde5992015-05-22 09:51:44 -07002326 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002327 mCurrentState.traverseInZOrder([](Layer* layer) {
2328 layer->notifyAvailableFrames();
2329 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331 /*
2332 * Traversal of the children
2333 * (perform the transaction for each of them if needed)
2334 */
2335
Mathias Agopian3559b072012-08-15 13:46:03 -07002336 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002337 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002339 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340
2341 const uint32_t flags = layer->doTransaction(0);
2342 if (flags & Layer::eVisibleRegion)
2343 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002344 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 }
2346
2347 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002348 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 */
2350
Mathias Agopiane57f2922012-08-09 16:29:12 -07002351 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002352 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002353 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355
Mathias Agopian84300952012-11-21 16:02:13 -08002356 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2357 // The transform hint might have changed for some layers
2358 // (either because a display has changed, or because a layer
2359 // as changed).
2360 //
2361 // Walk through all the layers in currentLayers,
2362 // and update their transform hint.
2363 //
2364 // If a layer is visible only on a single display, then that
2365 // display is used to calculate the hint, otherwise we use the
2366 // default display.
2367 //
2368 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2369 // the hint is set before we acquire a buffer from the surface texture.
2370 //
2371 // NOTE: layer transactions have taken place already, so we use their
2372 // drawing state. However, SurfaceFlinger's own transaction has not
2373 // happened yet, so we must use the current state layer list
2374 // (soon to become the drawing state list).
2375 //
2376 sp<const DisplayDevice> disp;
2377 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002378 bool first = true;
2379 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002380 // NOTE: we rely on the fact that layers are sorted by
2381 // layerStack first (so we don't have to traverse the list
2382 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002383 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002384 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002385 currentlayerStack = layerStack;
2386 // figure out if this layerstack is mirrored
2387 // (more than one display) if so, pick the default display,
2388 // if not, pick the only display it's on.
2389 disp.clear();
2390 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2391 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002392 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002393 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002394 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002395 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002396 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002397 break;
2398 }
2399 }
2400 }
2401 }
Chet Haase91d25932013-04-11 15:24:55 -07002402
Robert Carr56a0b9a2017-12-04 16:06:13 -08002403 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002404 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002405 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2406 // redraw after transform hint changes. See bug 8508397.
2407
2408 // could be null when this layer is using a layerStack
2409 // that is not visible on any display. Also can occur at
2410 // screen off/on times.
2411 disp = getDefaultDisplayDeviceLocked();
2412 }
2413 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002414 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002415 if (disp != nullptr) {
2416 layer->updateTransformHint(disp);
2417 }
Robert Carr2047fae2016-11-28 14:09:09 -08002418
2419 first = false;
2420 });
Mathias Agopian84300952012-11-21 16:02:13 -08002421 }
2422
2423
Mathias Agopian3559b072012-08-15 13:46:03 -07002424 /*
2425 * Perform our own transaction if needed
2426 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002427
2428 if (mLayersAdded) {
2429 mLayersAdded = false;
2430 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002431 mVisibleRegionsDirty = true;
2432 }
2433
2434 // some layers might have been removed, so
2435 // we need to update the regions they're exposing.
2436 if (mLayersRemoved) {
2437 mLayersRemoved = false;
2438 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002439 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002440 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002441 // this layer is not visible anymore
2442 // TODO: we could traverse the tree from front to back and
2443 // compute the actual visible region
2444 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002445 Region visibleReg;
2446 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002447 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002448 }
Robert Carr2047fae2016-11-28 14:09:09 -08002449 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450 }
2451
2452 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002453
2454 updateCursorAsync();
2455}
2456
2457void SurfaceFlinger::updateCursorAsync()
2458{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2460 auto& displayDevice = mDisplays[displayId];
2461 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002462 continue;
2463 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464
2465 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2466 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002467 }
2468 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002469}
2470
2471void SurfaceFlinger::commitTransaction()
2472{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002473 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002474 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002475 for (const auto& l : mLayersPendingRemoval) {
2476 recordBufferingStats(l->getName().string(),
2477 l->getOccupancyHistory(true));
2478 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002479 }
2480 mLayersPendingRemoval.clear();
2481 }
2482
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002483 // If this transaction is part of a window animation then the next frame
2484 // we composite should be considered an animation as well.
2485 mAnimCompositionPending = mAnimTransactionPending;
2486
Mathias Agopian4fec8732012-06-29 14:12:52 -07002487 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002488 mDrawingState.traverseInZOrder([](Layer* layer) {
2489 layer->commitChildList();
2490 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002491 mTransactionPending = false;
2492 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002493 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494}
2495
Chia-I Wuab0c3192017-08-01 11:29:00 -07002496void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002497 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498{
Mathias Agopian841cde52012-03-01 15:44:37 -08002499 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 Region aboveOpaqueLayers;
2503 Region aboveCoveredLayers;
2504 Region dirty;
2505
Mathias Agopian87baae12012-07-31 12:38:26 -07002506 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Robert Carr2047fae2016-11-28 14:09:09 -08002508 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002510 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
Jesse Hall01e29052013-02-19 16:13:35 -08002512 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002513 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002514 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002515
Mathias Agopianab028732010-03-16 16:41:46 -07002516 /*
2517 * opaqueRegion: area of a surface that is fully opaque.
2518 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002520
2521 /*
2522 * visibleRegion: area of a surface that is visible on screen
2523 * and not fully transparent. This is essentially the layer's
2524 * footprint minus the opaque regions above it.
2525 * Areas covered by a translucent surface are considered visible.
2526 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002528
2529 /*
2530 * coveredRegion: area of a surface that is covered by all
2531 * visible regions above it (which includes the translucent areas).
2532 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002534
Jesse Halla8026d22012-09-25 13:25:04 -07002535 /*
2536 * transparentRegion: area of a surface that is hinted to be completely
2537 * transparent. This is only used to tell when the layer has no visible
2538 * non-transparent regions and can be removed from the layer list. It
2539 * does not affect the visibleRegion of this layer or any layers
2540 * beneath it. The hint may not be correct if apps don't respect the
2541 * SurfaceView restrictions (which, sadly, some don't).
2542 */
2543 Region transparentRegion;
2544
Mathias Agopianab028732010-03-16 16:41:46 -07002545
2546 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002547 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002548 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002549 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002551 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002552 if (!visibleRegion.isEmpty()) {
2553 // Remove the transparent area from the visible region
2554 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002555 if (tr.preserveRects()) {
2556 // transform the transparent region
2557 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002558 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002559 // transformation too complex, can't do the
2560 // transparent region optimization.
2561 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002562 }
Mathias Agopianab028732010-03-16 16:41:46 -07002563 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564
Mathias Agopianab028732010-03-16 16:41:46 -07002565 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002566 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002567 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002568 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2569 // the opaque region is the layer's footprint
2570 opaqueRegion = visibleRegion;
2571 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 }
2573 }
2574
Robert Carre5f4f692018-01-12 13:12:28 -08002575 if (visibleRegion.isEmpty()) {
2576 layer->clearVisibilityRegions();
2577 return;
2578 }
2579
Mathias Agopianab028732010-03-16 16:41:46 -07002580 // Clip the covered region to the visible region
2581 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2582
2583 // Update aboveCoveredLayers for next (lower) layer
2584 aboveCoveredLayers.orSelf(visibleRegion);
2585
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 // subtract the opaque region covered by the layers above us
2587 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588
2589 // compute this layer's dirty region
2590 if (layer->contentDirty) {
2591 // we need to invalidate the whole region
2592 dirty = visibleRegion;
2593 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002594 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 layer->contentDirty = false;
2596 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002597 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002598 * the exposed region consists of two components:
2599 * 1) what's VISIBLE now and was COVERED before
2600 * 2) what's EXPOSED now less what was EXPOSED before
2601 *
2602 * note that (1) is conservative, we start with the whole
2603 * visible region but only keep what used to be covered by
2604 * something -- which mean it may have been exposed.
2605 *
2606 * (2) handles areas that were not covered by anything but got
2607 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002608 */
Mathias Agopianab028732010-03-16 16:41:46 -07002609 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002610 const Region oldVisibleRegion = layer->visibleRegion;
2611 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002612 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2613 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 }
2615 dirty.subtractSelf(aboveOpaqueLayers);
2616
2617 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002618 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619
Mathias Agopianab028732010-03-16 16:41:46 -07002620 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002622
Jesse Halla8026d22012-09-25 13:25:04 -07002623 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 layer->setVisibleRegion(visibleRegion);
2625 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002626 layer->setVisibleNonTransparentRegion(
2627 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002628 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629
Mathias Agopian87baae12012-07-31 12:38:26 -07002630 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631}
2632
Chia-I Wuab0c3192017-08-01 11:29:00 -07002633void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002634 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002635 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002636 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002637 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002638 }
2639 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002640}
2641
Dan Stoza6b9454d2014-11-07 16:00:59 -08002642bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 ALOGV("handlePageFlip");
2645
Brian Andersond6927fb2016-07-23 23:37:30 -07002646 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
Mathias Agopian4fec8732012-06-29 14:12:52 -07002648 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002649 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002650 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002651
2652 // Store the set of layers that need updates. This set must not change as
2653 // buffers are being latched, as this could result in a deadlock.
2654 // Example: Two producers share the same command stream and:
2655 // 1.) Layer 0 is latched
2656 // 2.) Layer 0 gets a new frame
2657 // 2.) Layer 1 gets a new frame
2658 // 3.) Layer 1 is latched.
2659 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2660 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002661 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002662 if (layer->hasQueuedFrame()) {
2663 frameQueued = true;
2664 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002665 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002666 } else {
2667 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002668 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002669 } else {
2670 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002671 }
Robert Carr2047fae2016-11-28 14:09:09 -08002672 });
2673
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002675 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002676 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002677 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002678 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002679 newDataLatched = true;
2680 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002681 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002682
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002683 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002684
2685 // If we will need to wake up at some time in the future to deal with a
2686 // queued frame that shouldn't be displayed during this vsync period, wake
2687 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002688 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689 signalLayerUpdate();
2690 }
2691
2692 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002693 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694}
2695
Mathias Agopianad456f92011-01-13 17:53:01 -08002696void SurfaceFlinger::invalidateHwcGeometry()
2697{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002699}
2700
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002701
Fabien Sanglard830b8472016-11-30 16:35:58 -08002702void SurfaceFlinger::doDisplayComposition(
2703 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002704 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705{
Dan Stoza71433162014-02-04 16:22:36 -08002706 // We only need to actually compose the display if:
2707 // 1) It is being handled by hardware composer, which may need this to
2708 // keep its virtual display state machine in sync, or
2709 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002710 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002711 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002713 return;
2714 }
2715
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002717 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002718
2719 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002720 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721}
2722
Chia-I Wub02087d2017-11-09 10:19:54 -08002723bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002724{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002726
Chia-I Wub02087d2017-11-09 10:19:54 -08002727 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002728 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002730
2731 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002732 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2733 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002734 if (applyColorMatrix) {
2735 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2736 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2737 }
2738
David Sodman105b7dc2017-11-04 20:28:14 -07002739 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 if (hasClientComposition) {
2741 ALOGV("hasClientComposition");
2742
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002743 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002744 if (displayDevice->getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002745 displayDevice->getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
2746 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2747 }
2748 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2749
Chia-I Wu7f402902017-11-09 12:51:10 -08002750 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002751 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002753 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002754
2755 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002756 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002757 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2758 }
2759 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002760 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002761
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002762 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002763 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002765 // when using overlays, we assume a fully transparent framebuffer
2766 // NOTE: we could reduce how much we need to clear, for instance
2767 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002768 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002769 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002770 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002771 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002772 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002773 // we're left with the letterbox region
2774 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002775 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002776
2777 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002778 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002779
Mathias Agopianb9494d52012-04-18 02:28:45 -07002780 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002781 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002782 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002784 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002785 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002786
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002788 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002789 // scissor on the main display. It should never be needed
2790 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 const Rect& bounds(displayDevice->getBounds());
2792 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002793 if (scissor != bounds) {
2794 // scissor doesn't match the screen's dimensions, so we
2795 // need to clear everything outside of it and enable
2796 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002797
Mathias Agopianf45c5102012-10-24 16:29:17 -07002798 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002799 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002800 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002801 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002802 }
2803 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002804 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002805
Mathias Agopian85d751c2012-08-29 16:59:24 -07002806 /*
2807 * and then, render the layers targeted at the framebuffer
2808 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002809
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 ALOGV("Rendering client layers");
2811 const Transform& displayTransform = displayDevice->getTransform();
2812 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002813 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 bool firstLayer = true;
2815 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002816 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 displayTransform.transform(layer->visibleRegion)));
2818 ALOGV("Layer: %s", layer->getName().string());
2819 ALOGV(" Composition type: %s",
2820 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002821 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 switch (layer->getCompositionType(hwcId)) {
2823 case HWC2::Composition::Cursor:
2824 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002825 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002827 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002829 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002831 // never clear the very first layer since we're
2832 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002833 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002834 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002835 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002836 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002838 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002839 break;
2840 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002842 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002843 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 } else {
2845 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002846 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002848 }
2849 } else {
2850 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002851 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002852 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002853 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002854 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002855 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002856 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002857 }
2858 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002859
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002860 if (applyColorMatrix) {
2861 getRenderEngine().setupColorTransform(oldColorMatrix);
2862 }
2863
Mathias Agopianf45c5102012-10-24 16:29:17 -07002864 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002865 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002866 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867}
2868
Fabien Sanglard830b8472016-11-30 16:35:58 -08002869void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2870 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002871 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002872 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Dan Stoza7d89d062015-04-30 13:29:25 -07002875status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002876 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002877 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 const sp<Layer>& lbc,
2879 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002880{
Dan Stoza7d89d062015-04-30 13:29:25 -07002881 // add this layer to the current state list
2882 {
2883 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002884 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002885 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2886 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002887 return NO_MEMORY;
2888 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002889 if (parent == nullptr) {
2890 mCurrentState.layersSortedByZ.add(lbc);
2891 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002892 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002893 ALOGE("addClientLayer called with a removed parent");
2894 return NAME_NOT_FOUND;
2895 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 parent->addChild(lbc);
2897 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002898
Dan Stoza101d8dc2018-02-27 15:42:25 -08002899 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2900 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() > MAX_LAYERS,
2901 "Suspected IGBP leak");
Robert Carr1f0a16a2016-10-24 16:27:39 -07002902 mLayersAdded = true;
2903 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002904 }
2905
Mathias Agopian96f08192010-06-02 23:28:45 -07002906 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002907 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002908
Dan Stoza7d89d062015-04-30 13:29:25 -07002909 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002910}
2911
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002912status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002913 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002914 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2915}
Robert Carr7f9b8992017-03-10 11:08:39 -08002916
chaviwca27f252018-02-06 16:46:39 -08002917status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2918 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002919 if (layer->isPendingRemoval()) {
2920 return NO_ERROR;
2921 }
2922
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002924 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002925 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002926 if (topLevelOnly) {
2927 return NO_ERROR;
2928 }
2929
Chia-I Wu98f1c102017-05-30 14:54:08 -07002930 sp<Layer> ancestor = p;
2931 while (ancestor->getParent() != nullptr) {
2932 ancestor = ancestor->getParent();
2933 }
2934 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2935 ALOGE("removeLayer called with a layer whose parent has been removed");
2936 return NAME_NOT_FOUND;
2937 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002938
2939 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002940 } else {
2941 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002942 }
2943
Robert Carr136e2f62017-02-08 17:54:29 -08002944 // As a matter of normal operation, the LayerCleaner will produce a second
2945 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2946 // so we will succeed in promoting it, but it's already been removed
2947 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2948 // otherwise something has gone wrong and we are leaking the layer.
2949 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002950 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2951 layer->getName().string(),
2952 (p != nullptr) ? p->getName().string() : "no-parent");
2953 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002954 } else if (index < 0) {
2955 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002956 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002957
Chia-I Wuc6657022017-08-15 11:18:17 -07002958 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959 mLayersPendingRemoval.add(layer);
2960 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002961 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002962 setTransactionFlags(eTransactionNeeded);
2963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964}
2965
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002966uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002967 return android_atomic_release_load(&mTransactionFlags);
2968}
2969
Mathias Agopian3f844832013-08-07 21:24:32 -07002970uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2972}
2973
Mathias Agopian3f844832013-08-07 21:24:32 -07002974uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2976 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002977 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 }
2979 return old;
2980}
2981
chaviwca27f252018-02-06 16:46:39 -08002982bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
2983 for (const ComposerState& state : states) {
2984 // Here we need to check that the interface we're given is indeed
2985 // one of our own. A malicious client could give us a nullptr
2986 // IInterface, or one of its own or even one of our own but a
2987 // different type. All these situations would cause us to crash.
2988 if (state.client == nullptr) {
2989 return true;
2990 }
2991
2992 sp<IBinder> binder = IInterface::asBinder(state.client);
2993 if (binder == nullptr) {
2994 return true;
2995 }
2996
2997 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
2998 return true;
2999 }
3000 }
3001 return false;
3002}
3003
Mathias Agopian8b33f032012-07-24 20:43:54 -07003004void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003005 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003006 const Vector<DisplayState>& displays,
3007 uint32_t flags)
3008{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003009 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003010 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003011 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003012
chaviwca27f252018-02-06 16:46:39 -08003013 if (containsAnyInvalidClientState(states)) {
3014 return;
3015 }
3016
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003017 if (flags & eAnimation) {
3018 // For window updates that are part of an animation we must wait for
3019 // previous animation "frames" to be handled.
3020 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003021 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003022 if (CC_UNLIKELY(err != NO_ERROR)) {
3023 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003024 // caller after a few seconds.
3025 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3026 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003027 mAnimTransactionPending = false;
3028 break;
3029 }
3030 }
3031 }
3032
chaviwca27f252018-02-06 16:46:39 -08003033 for (const DisplayState& display : displays) {
3034 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003035 }
3036
chaviwca27f252018-02-06 16:46:39 -08003037 for (const ComposerState& state : states) {
3038 transactionFlags |= setClientStateLocked(state);
3039 }
3040
3041 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3042 // as destroyed should only occur after setting all other states. This is to allow for a
3043 // child re-parent to happen before marking its original parent as destroyed (which would
3044 // then mark the child as destroyed).
3045 for (const ComposerState& state : states) {
3046 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003047 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003048
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003049 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3050 // anyway. This can be used as a flush mechanism for previous async transactions.
3051 // Empty animation transaction can be used to simulate back-pressure, so also force a
3052 // transaction for empty animation transactions.
3053 if (transactionFlags == 0 &&
3054 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003055 transactionFlags = eTransactionNeeded;
3056 }
3057
Mathias Agopian386aa982011-11-07 21:58:03 -08003058 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003059 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003060 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003061 }
Irvel468051e2016-06-13 16:44:44 -07003062
Mathias Agopian386aa982011-11-07 21:58:03 -08003063 // this triggers the transaction
3064 setTransactionFlags(transactionFlags);
3065
3066 // if this is a synchronous transaction, wait for it to take effect
3067 // before returning.
3068 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003069 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003070 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003071 if (flags & eAnimation) {
3072 mAnimTransactionPending = true;
3073 }
3074 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003075 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3076 if (CC_UNLIKELY(err != NO_ERROR)) {
3077 // just in case something goes wrong in SF, return to the
3078 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003079 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3080 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003081 break;
3082 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003083 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 }
3085}
3086
Mathias Agopiane57f2922012-08-09 16:29:12 -07003087uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3088{
Jesse Hall9a143922012-10-04 16:29:19 -07003089 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3090 if (dpyIdx < 0)
3091 return 0;
3092
Mathias Agopiane57f2922012-08-09 16:29:12 -07003093 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003094 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003095 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003096 const uint32_t what = s.what;
3097 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003098 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003099 disp.surface = s.surface;
3100 flags |= eDisplayTransactionNeeded;
3101 }
3102 }
3103 if (what & DisplayState::eLayerStackChanged) {
3104 if (disp.layerStack != s.layerStack) {
3105 disp.layerStack = s.layerStack;
3106 flags |= eDisplayTransactionNeeded;
3107 }
3108 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003109 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003110 if (disp.orientation != s.orientation) {
3111 disp.orientation = s.orientation;
3112 flags |= eDisplayTransactionNeeded;
3113 }
3114 if (disp.frame != s.frame) {
3115 disp.frame = s.frame;
3116 flags |= eDisplayTransactionNeeded;
3117 }
3118 if (disp.viewport != s.viewport) {
3119 disp.viewport = s.viewport;
3120 flags |= eDisplayTransactionNeeded;
3121 }
3122 }
Michael Lentine47e45402014-07-18 15:34:25 -07003123 if (what & DisplayState::eDisplaySizeChanged) {
3124 if (disp.width != s.width) {
3125 disp.width = s.width;
3126 flags |= eDisplayTransactionNeeded;
3127 }
3128 if (disp.height != s.height) {
3129 disp.height = s.height;
3130 flags |= eDisplayTransactionNeeded;
3131 }
3132 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003133 }
3134 return flags;
3135}
3136
chaviwca27f252018-02-06 16:46:39 -08003137uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3138 const layer_state_t& s = composerState.state;
3139 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3140
Mathias Agopian13127d82013-03-05 17:47:11 -08003141 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003142 if (layer == nullptr) {
3143 return 0;
3144 }
3145
3146 if (layer->isPendingRemoval()) {
3147 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3148 return 0;
3149 }
3150
3151 uint32_t flags = 0;
3152
3153 const uint32_t what = s.what;
3154 bool geometryAppliesWithResize =
3155 what & layer_state_t::eGeometryAppliesWithResize;
3156 if (what & layer_state_t::ePositionChanged) {
3157 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3158 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003159 }
chaviw8b3871a2017-11-01 17:41:01 -07003160 }
3161 if (what & layer_state_t::eLayerChanged) {
3162 // NOTE: index needs to be calculated before we update the state
3163 const auto& p = layer->getParent();
3164 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003165 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003166 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003167 mCurrentState.layersSortedByZ.removeAt(idx);
3168 mCurrentState.layersSortedByZ.add(layer);
3169 // we need traversal (state changed)
3170 // AND transaction (list changed)
3171 flags |= eTransactionNeeded|eTraversalNeeded;
3172 }
chaviw8b3871a2017-11-01 17:41:01 -07003173 } else {
3174 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003175 flags |= eTransactionNeeded|eTraversalNeeded;
3176 }
3177 }
chaviw8b3871a2017-11-01 17:41:01 -07003178 }
3179 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003180 // NOTE: index needs to be calculated before we update the state
3181 const auto& p = layer->getParent();
3182 if (p == nullptr) {
3183 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3184 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3185 mCurrentState.layersSortedByZ.removeAt(idx);
3186 mCurrentState.layersSortedByZ.add(layer);
3187 // we need traversal (state changed)
3188 // AND transaction (list changed)
3189 flags |= eTransactionNeeded|eTraversalNeeded;
3190 }
3191 } else {
3192 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3193 flags |= eTransactionNeeded|eTraversalNeeded;
3194 }
chaviw8b3871a2017-11-01 17:41:01 -07003195 }
3196 }
3197 if (what & layer_state_t::eSizeChanged) {
3198 if (layer->setSize(s.w, s.h)) {
3199 flags |= eTraversalNeeded;
3200 }
3201 }
3202 if (what & layer_state_t::eAlphaChanged) {
3203 if (layer->setAlpha(s.alpha))
3204 flags |= eTraversalNeeded;
3205 }
3206 if (what & layer_state_t::eColorChanged) {
3207 if (layer->setColor(s.color))
3208 flags |= eTraversalNeeded;
3209 }
3210 if (what & layer_state_t::eMatrixChanged) {
3211 if (layer->setMatrix(s.matrix))
3212 flags |= eTraversalNeeded;
3213 }
3214 if (what & layer_state_t::eTransparentRegionChanged) {
3215 if (layer->setTransparentRegionHint(s.transparentRegion))
3216 flags |= eTraversalNeeded;
3217 }
3218 if (what & layer_state_t::eFlagsChanged) {
3219 if (layer->setFlags(s.flags, s.mask))
3220 flags |= eTraversalNeeded;
3221 }
3222 if (what & layer_state_t::eCropChanged) {
3223 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3224 flags |= eTraversalNeeded;
3225 }
3226 if (what & layer_state_t::eFinalCropChanged) {
3227 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3228 flags |= eTraversalNeeded;
3229 }
3230 if (what & layer_state_t::eLayerStackChanged) {
3231 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3232 // We only allow setting layer stacks for top level layers,
3233 // everything else inherits layer stack from its parent.
3234 if (layer->hasParent()) {
3235 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3236 layer->getName().string());
3237 } else if (idx < 0) {
3238 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3239 "that also does not appear in the top level layer list. Something"
3240 " has gone wrong.", layer->getName().string());
3241 } else if (layer->setLayerStack(s.layerStack)) {
3242 mCurrentState.layersSortedByZ.removeAt(idx);
3243 mCurrentState.layersSortedByZ.add(layer);
3244 // we need traversal (state changed)
3245 // AND transaction (list changed)
3246 flags |= eTransactionNeeded|eTraversalNeeded;
3247 }
3248 }
3249 if (what & layer_state_t::eDeferTransaction) {
3250 if (s.barrierHandle != nullptr) {
3251 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3252 } else if (s.barrierGbp != nullptr) {
3253 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3254 if (authenticateSurfaceTextureLocked(gbp)) {
3255 const auto& otherLayer =
3256 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3257 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3258 } else {
3259 ALOGE("Attempt to defer transaction to to an"
3260 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003261 }
3262 }
chaviw8b3871a2017-11-01 17:41:01 -07003263 // We don't trigger a traversal here because if no other state is
3264 // changed, we don't want this to cause any more work
3265 }
3266 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003267 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003268 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003269 if (!hadParent) {
3270 mCurrentState.layersSortedByZ.remove(layer);
3271 }
chaviw8b3871a2017-11-01 17:41:01 -07003272 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003273 }
chaviw8b3871a2017-11-01 17:41:01 -07003274 }
3275 if (what & layer_state_t::eReparentChildren) {
3276 if (layer->reparentChildren(s.reparentHandle)) {
3277 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003278 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 if (what & layer_state_t::eDetachChildren) {
3281 layer->detachChildren();
3282 }
3283 if (what & layer_state_t::eOverrideScalingModeChanged) {
3284 layer->setOverrideScalingMode(s.overrideScalingMode);
3285 // We don't trigger a traversal here because if no other state is
3286 // changed, we don't want this to cause any more work
3287 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 return flags;
3289}
3290
chaviwca27f252018-02-06 16:46:39 -08003291void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3292 const layer_state_t& state = composerState.state;
3293 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3294
3295 sp<Layer> layer(client->getLayerUser(state.surface));
3296 if (layer == nullptr) {
3297 return;
3298 }
3299
3300 if (layer->isPendingRemoval()) {
3301 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3302 return;
3303 }
3304
3305 if (state.what & layer_state_t::eDestroySurface) {
3306 removeLayerLocked(mStateLock, layer);
3307 }
3308}
3309
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003310status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003311 const String8& name,
3312 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003313 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003314 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3315 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003317 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003318 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003319 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003320 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003321 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003322
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003323 status_t result = NO_ERROR;
3324
3325 sp<Layer> layer;
3326
Cody Northropbc755282017-03-31 12:00:08 -06003327 String8 uniqueName = getUniqueLayerName(name);
3328
Mathias Agopian3165cc22012-08-08 19:42:09 -07003329 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3330 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003331 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003332 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003333 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335 break;
chaviw13fdc492017-06-27 12:40:18 -07003336 case ISurfaceComposerClient::eFXSurfaceColor:
3337 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003338 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003339 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003340 break;
3341 default:
3342 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003343 break;
3344 }
3345
Dan Stoza7d89d062015-04-30 13:29:25 -07003346 if (result != NO_ERROR) {
3347 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003349
Chia-I Wuab0c3192017-08-01 11:29:00 -07003350 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3351 // TODO b/64227542
3352 if (windowType == 441731) {
3353 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3354 layer->setPrimaryDisplayOnly();
3355 }
3356
Albert Chaulk479c60c2017-01-27 14:21:34 -05003357 layer->setInfo(windowType, ownerUid);
3358
Robert Carr1f0a16a2016-10-24 16:27:39 -07003359 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003360 if (result != NO_ERROR) {
3361 return result;
3362 }
Irvelffc9efc2016-07-27 15:16:37 -07003363 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003364
3365 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003366 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367}
3368
Cody Northropbc755282017-03-31 12:00:08 -06003369String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3370{
3371 bool matchFound = true;
3372 uint32_t dupeCounter = 0;
3373
3374 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3375 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3376
3377 // Loop over layers until we're sure there is no matching name
3378 while (matchFound) {
3379 matchFound = false;
3380 mDrawingState.traverseInZOrder([&](Layer* layer) {
3381 if (layer->getName() == uniqueName) {
3382 matchFound = true;
3383 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3384 }
3385 });
3386 }
3387
3388 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3389
3390 return uniqueName;
3391}
3392
David Sodman0c69cad2017-08-21 12:12:51 -07003393status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003394 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3395 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003396{
3397 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003398 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003399 case PIXEL_FORMAT_TRANSPARENT:
3400 case PIXEL_FORMAT_TRANSLUCENT:
3401 format = PIXEL_FORMAT_RGBA_8888;
3402 break;
3403 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003404 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003405 break;
3406 }
3407
David Sodman0c69cad2017-08-21 12:12:51 -07003408 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3409 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003410 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003411 *handle = layer->getHandle();
3412 *gbp = layer->getProducer();
3413 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003415
David Sodman0c69cad2017-08-21 12:12:51 -07003416 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003417 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003418}
3419
chaviw13fdc492017-06-27 12:40:18 -07003420status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003421 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003422 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423{
chaviw13fdc492017-06-27 12:40:18 -07003424 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003425 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003426 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003427}
3428
Mathias Agopianac9fa422013-02-11 16:40:36 -08003429status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003430{
Robert Carr9524cb32017-02-13 11:32:32 -08003431 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003432 status_t err = NO_ERROR;
3433 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003434 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003435 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003436 err = removeLayer(l);
3437 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3438 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003439 }
3440 return err;
3441}
3442
Mathias Agopian13127d82013-03-05 17:47:11 -08003443status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003444{
Mathias Agopian67106042013-03-14 19:18:13 -07003445 // called by ~LayerCleaner() when all references to the IBinder (handle)
3446 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003447 sp<Layer> l = layer.promote();
3448 if (l == nullptr) {
3449 // The layer has already been removed, carry on
3450 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003451 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003452 // If we have a parent, then we can continue to live as long as it does.
3453 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454}
3455
Mathias Agopianb60314a2012-04-10 22:09:54 -07003456// ---------------------------------------------------------------------------
3457
Andy McFadden13a082e2012-08-24 10:16:42 -07003458void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003459 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003460 Vector<ComposerState> state;
3461 Vector<DisplayState> displays;
3462 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003463 d.what = DisplayState::eDisplayProjectionChanged |
3464 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003465 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003466 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003467 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003468 d.frame.makeInvalid();
3469 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003470 d.width = 0;
3471 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003472 displays.add(d);
3473 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003474 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3475 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003476
David Sodman105b7dc2017-11-04 20:28:14 -07003477 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003478 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003479 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003480
Brian Andersond0010582017-03-07 13:20:31 -08003481 // Use phase of 0 since phase is not known.
3482 // Use latency of 0, which will snap to the ideal latency.
3483 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003484}
3485
3486void SurfaceFlinger::initializeDisplays() {
3487 class MessageScreenInitialized : public MessageBase {
3488 SurfaceFlinger* flinger;
3489 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003490 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003491 virtual bool handler() {
3492 flinger->onInitializeDisplays();
3493 return true;
3494 }
3495 };
3496 sp<MessageBase> msg = new MessageScreenInitialized(this);
3497 postMessageAsync(msg); // we may be called from main thread, use async message
3498}
3499
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003500void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003501 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003502 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3503 this);
3504 int32_t type = hw->getDisplayType();
3505 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003506
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003507 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003508 return;
3509 }
3510
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003511 hw->setPowerMode(mode);
3512 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3513 ALOGW("Trying to set power mode for virtual display");
3514 return;
3515 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003516
Irvelffc9efc2016-07-27 15:16:37 -07003517 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003518 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003519 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3520 if (idx < 0) {
3521 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3522 return;
3523 }
3524 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3525 }
3526
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003527 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003528 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003529 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003530 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3531 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003532 // FIXME: eventthread only knows about the main display right now
3533 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003534 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003537 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003538 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003539 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003540
3541 struct sched_param param = {0};
3542 param.sched_priority = 1;
3543 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3544 ALOGW("Couldn't set SCHED_FIFO on display on");
3545 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003547 // Turn off the display
3548 struct sched_param param = {0};
3549 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3550 ALOGW("Couldn't set SCHED_OTHER on display off");
3551 }
3552
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003553 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3554 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003555 disableHardwareVsync(true); // also cancels any in-progress resync
3556
Mathias Agopiancde87a32012-09-13 14:09:01 -07003557 // FIXME: eventthread only knows about the main display right now
3558 mEventThread->onScreenReleased();
3559 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003560
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003561 getHwComposer().setPowerMode(type, mode);
3562 mVisibleRegionsDirty = true;
3563 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003564 } else if (mode == HWC_POWER_MODE_DOZE ||
3565 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003566 // Update display while dozing
3567 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003568 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3569 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003570 // FIXME: eventthread only knows about the main display right now
3571 mEventThread->onScreenAcquired();
3572 resyncToHardwareVsync(true);
3573 }
3574 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3575 // Leave display going to doze
3576 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3577 disableHardwareVsync(true); // also cancels any in-progress resync
3578 // FIXME: eventthread only knows about the main display right now
3579 mEventThread->onScreenReleased();
3580 }
3581 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003582 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003583 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003584 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003585 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003586}
3587
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003588void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3589 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003590 SurfaceFlinger& mFlinger;
3591 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003592 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003593 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003594 MessageSetPowerMode(SurfaceFlinger& flinger,
3595 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3596 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003597 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003598 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003599 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003601 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003602 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003603 ALOGW("Attempt to set power mode = %d for virtual display",
3604 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003605 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003606 mFlinger.setPowerModeInternal(
3607 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003608 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003609 return true;
3610 }
3611 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003612 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003613 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003614}
3615
3616// ---------------------------------------------------------------------------
3617
Lloyd Pique755e3192018-01-31 16:46:15 -08003618status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3619 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003620 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003621
Mathias Agopianbd115332013-04-18 16:41:04 -07003622 IPCThreadState* ipc = IPCThreadState::self();
3623 const int pid = ipc->getCallingPid();
3624 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003625
Mathias Agopianbd115332013-04-18 16:41:04 -07003626 if ((uid != AID_SHELL) &&
3627 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003628 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003629 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003630 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003631 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003632 // (this would indicate SF is stuck, but we want to be able to
3633 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003634 status_t err = mStateLock.timedLock(s2ns(1));
3635 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003636 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003637 result.appendFormat(
3638 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3639 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003640 }
3641
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003642 bool dumpAll = true;
3643 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003644 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003645
3646 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003647 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003648 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3649 dumpAll = false;
3650 }
3651
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003652 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003653 if ((index < numArgs) &&
3654 (args[index] == String16("--list"))) {
3655 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003656 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003657 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003658 }
3659
3660 if ((index < numArgs) &&
3661 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003662 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003663 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003664 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003665 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003666
3667 if ((index < numArgs) &&
3668 (args[index] == String16("--latency-clear"))) {
3669 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003670 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003671 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003672 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003673
3674 if ((index < numArgs) &&
3675 (args[index] == String16("--dispsync"))) {
3676 index++;
3677 mPrimaryDispSync.dump(result);
3678 dumpAll = false;
3679 }
Dan Stozab90cf072015-03-05 11:05:59 -08003680
3681 if ((index < numArgs) &&
3682 (args[index] == String16("--static-screen"))) {
3683 index++;
3684 dumpStaticScreenStats(result);
3685 dumpAll = false;
3686 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003687
3688 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003689 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003690 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003691 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003692 dumpAll = false;
3693 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003694
3695 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3696 index++;
3697 dumpWideColorInfo(result);
3698 dumpAll = false;
3699 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003701
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003702 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003703 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003704 }
3705
Mathias Agopian9795c422009-08-26 16:36:26 -07003706 if (locked) {
3707 mStateLock.unlock();
3708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003709 }
3710 write(fd, result.string(), result.size());
3711 return NO_ERROR;
3712}
3713
Dan Stozac7014012014-02-14 15:03:43 -08003714void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3715 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003716{
Robert Carr2047fae2016-11-28 14:09:09 -08003717 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003718 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003719 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003720}
3721
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003722void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003723 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003724{
3725 String8 name;
3726 if (index < args.size()) {
3727 name = String8(args[index]);
3728 index++;
3729 }
3730
David Sodman105b7dc2017-11-04 20:28:14 -07003731 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003732 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003733 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003734
3735 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003736 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003737 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003738 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003739 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003740 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003741 }
Robert Carr2047fae2016-11-28 14:09:09 -08003742 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003743 }
3744}
3745
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003746void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003747 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003748{
3749 String8 name;
3750 if (index < args.size()) {
3751 name = String8(args[index]);
3752 index++;
3753 }
3754
Robert Carr2047fae2016-11-28 14:09:09 -08003755 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003756 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003757 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003758 }
Robert Carr2047fae2016-11-28 14:09:09 -08003759 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003760
Svetoslavd85084b2014-03-20 10:28:31 -07003761 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003762}
3763
Jamie Gennis6547ff42013-07-16 20:12:42 -07003764// This should only be called from the main thread. Otherwise it would need
3765// the lock and should use mCurrentState rather than mDrawingState.
3766void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003767 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003768 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003769 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003770
3771 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3772}
3773
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003774void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003775{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003776 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003777
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003778 if (isLayerTripleBufferingDisabled())
3779 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003780
3781 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003782 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003783 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003784 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003785 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3786 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003787 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003788}
3789
Dan Stozab90cf072015-03-05 11:05:59 -08003790void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3791{
3792 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003793 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3794 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003795 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003796 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003797 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3798 b + 1, bucketTimeSec, percent);
3799 }
David Sodman4a36e932017-11-07 14:29:47 -08003800 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003801 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003802 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003803 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003804 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003805}
3806
Dan Stozae77c7662016-05-13 11:37:28 -07003807void SurfaceFlinger::recordBufferingStats(const char* layerName,
3808 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003809 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3810 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003811 for (const auto& segment : history) {
3812 if (!segment.usedThirdBuffer) {
3813 stats.twoBufferTime += segment.totalTime;
3814 }
3815 if (segment.occupancyAverage < 1.0f) {
3816 stats.doubleBufferedTime += segment.totalTime;
3817 } else if (segment.occupancyAverage < 2.0f) {
3818 stats.tripleBufferedTime += segment.totalTime;
3819 }
3820 ++stats.numSegments;
3821 stats.totalTime += segment.totalTime;
3822 }
3823}
3824
Brian Andersond6927fb2016-07-23 23:37:30 -07003825void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3826 result.appendFormat("Layer frame timestamps:\n");
3827
3828 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3829 const size_t count = currentLayers.size();
3830 for (size_t i=0 ; i<count ; i++) {
3831 currentLayers[i]->dumpFrameEvents(result);
3832 }
3833}
3834
Dan Stozae77c7662016-05-13 11:37:28 -07003835void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3836 result.append("Buffering stats:\n");
3837 result.append(" [Layer name] <Active time> <Two buffer> "
3838 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003839 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003840 typedef std::tuple<std::string, float, float, float> BufferTuple;
3841 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003842 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003843 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003844 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003845 if (stats.numSegments == 0) {
3846 continue;
3847 }
3848 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3849 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3850 stats.totalTime;
3851 float doubleBufferRatio = static_cast<float>(
3852 stats.doubleBufferedTime) / stats.totalTime;
3853 float tripleBufferRatio = static_cast<float>(
3854 stats.tripleBufferedTime) / stats.totalTime;
3855 sorted.insert({activeTime, {name, twoBufferRatio,
3856 doubleBufferRatio, tripleBufferRatio}});
3857 }
3858 for (const auto& sortedPair : sorted) {
3859 float activeTime = sortedPair.first;
3860 const BufferTuple& values = sortedPair.second;
3861 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3862 std::get<0>(values).c_str(), activeTime,
3863 std::get<1>(values), std::get<2>(values),
3864 std::get<3>(values));
3865 }
3866 result.append("\n");
3867}
3868
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003869void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3870 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003871 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003872
3873 // TODO: print out if wide-color mode is active or not
3874
3875 for (size_t d = 0; d < mDisplays.size(); d++) {
3876 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3877 int32_t hwcId = displayDevice->getHwcDisplayId();
3878 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3879 continue;
3880 }
3881
3882 result.appendFormat("Display %d color modes:\n", hwcId);
3883 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3884 for (auto&& mode : modes) {
3885 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3886 }
3887
3888 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3889 result.appendFormat(" Current color mode: %s (%d)\n",
3890 decodeColorMode(currentMode).c_str(), currentMode);
3891 }
3892 result.append("\n");
3893}
3894
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003895LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003896 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003897 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3898 const State& state = useDrawing ? mDrawingState : mCurrentState;
3899 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003900 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003901 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003902 });
3903
3904 return layersProto;
3905}
3906
Mathias Agopian74d211a2013-04-22 16:55:35 +02003907void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3908 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003910 bool colorize = false;
3911 if (index < args.size()
3912 && (args[index] == String16("--color"))) {
3913 colorize = true;
3914 index++;
3915 }
3916
3917 Colorizer colorizer(colorize);
3918
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003919 // figure out if we're stuck somewhere
3920 const nsecs_t now = systemTime();
3921 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3922 const nsecs_t inTransaction(mDebugInTransaction);
3923 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3924 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3925
3926 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003927 * Dump library configuration.
3928 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003929
3930 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003931 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003932 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003933 appendSfConfigString(result);
3934 appendUiConfigString(result);
3935 appendGuiConfigString(result);
3936 result.append("\n");
3937
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003938 result.append("\nWide-Color information:\n");
3939 dumpWideColorInfo(result);
3940
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003941 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003942 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003943 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003944 result.append(SyncFeatures::getInstance().toString());
3945 result.append("\n");
3946
David Sodman105b7dc2017-11-04 20:28:14 -07003947 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003948
Andy McFadden41d67d72014-04-25 16:58:34 -07003949 colorizer.bold(result);
3950 result.append("DispSync configuration: ");
3951 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003952 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003953 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003954 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003955 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003956 result.append("\n");
3957
Dan Stozab90cf072015-03-05 11:05:59 -08003958 // Dump static screen stats
3959 result.append("\n");
3960 dumpStaticScreenStats(result);
3961 result.append("\n");
3962
Dan Stozae77c7662016-05-13 11:37:28 -07003963 dumpBufferingStats(result);
3964
Andy McFadden4803b742012-09-24 19:07:20 -07003965 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966 * Dump the visible layer list
3967 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003968 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003969 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003970 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003971
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003972 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003973 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3974 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975
3976 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003977 * Dump Display state
3978 */
3979
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003980 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003981 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003982 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003983 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3984 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003985 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003986 }
3987
3988 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003989 * Dump SurfaceFlinger global state
3990 */
3991
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003992 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003993 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003994 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003995
Mathias Agopian888c8222012-08-04 21:10:38 -07003996 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003997 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003998
David Sodmanbc815282017-11-05 18:57:52 -08003999 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004001 if (hw) {
4002 hw->undefinedRegion.dump(result, "undefinedRegion");
4003 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4004 hw->getOrientation(), hw->isDisplayOn());
4005 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004006 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004007 " last eglSwapBuffers() time: %f us\n"
4008 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004009 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004010 " refresh-rate : %f fps\n"
4011 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004012 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004013 " gpu_to_cpu_unsupported : %d\n"
4014 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004015 mLastSwapBufferTime/1000.0,
4016 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004017 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004018 1e9 / activeConfig->getVsyncPeriod(),
4019 activeConfig->getDpiX(),
4020 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004021 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004022
Mathias Agopian74d211a2013-04-22 16:55:35 +02004023 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004024 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004025
Mathias Agopian74d211a2013-04-22 16:55:35 +02004026 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004027 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004028
4029 /*
4030 * VSYNC state
4031 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004032 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004033 result.append("\n");
4034
4035 /*
4036 * HWC layer minidump
4037 */
4038 for (size_t d = 0; d < mDisplays.size(); d++) {
4039 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4040 int32_t hwcId = displayDevice->getHwcDisplayId();
4041 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4042 continue;
4043 }
4044
4045 result.appendFormat("Display %d HWC layers:\n", hwcId);
4046 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004047 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004048 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004049 });
Dan Stozae22aec72016-08-01 13:20:59 -07004050 result.append("\n");
4051 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004052
4053 /*
4054 * Dump HWComposer state
4055 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004056 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004057 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004058 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004059 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004060 result.appendFormat(" h/w composer %s\n",
4061 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004063
4064 /*
4065 * Dump gralloc state
4066 */
4067 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4068 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004069
4070 /*
4071 * Dump VrFlinger state if in use.
4072 */
4073 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4074 result.append("VrFlinger state:\n");
4075 result.append(mVrFlinger->Dump().c_str());
4076 result.append("\n");
4077 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004078}
4079
Mathias Agopian13127d82013-03-05 17:47:11 -08004080const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004081SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004082 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004083 wp<IBinder> dpy;
4084 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4085 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4086 dpy = mDisplays.keyAt(i);
4087 break;
4088 }
4089 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004090 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004091 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4092 // Just use the primary display so we have something to return
4093 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4094 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004095 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004096}
4097
Keun young Park63f165f2012-08-31 10:53:36 -07004098bool SurfaceFlinger::startDdmConnection()
4099{
4100 void* libddmconnection_dso =
4101 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4102 if (!libddmconnection_dso) {
4103 return false;
4104 }
4105 void (*DdmConnection_start)(const char* name);
4106 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004107 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004108 if (!DdmConnection_start) {
4109 dlclose(libddmconnection_dso);
4110 return false;
4111 }
4112 (*DdmConnection_start)(getServiceName());
4113 return true;
4114}
4115
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004116status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 switch (code) {
4118 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004119 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004121 case CLEAR_ANIMATION_FRAME_STATS:
4122 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004123 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004124 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004125 case ENABLE_VSYNC_INJECTIONS:
4126 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 {
4128 // codes that require permission check
4129 IPCThreadState* ipc = IPCThreadState::self();
4130 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004131 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004132 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004133 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004134 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004135 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004137 break;
4138 }
Robert Carr1db73f62016-12-21 12:58:51 -08004139 /*
4140 * Calling setTransactionState is safe, because you need to have been
4141 * granted a reference to Client* and Handle* to do anything with it.
4142 *
4143 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4144 */
4145 case SET_TRANSACTION_STATE:
4146 case CREATE_SCOPED_CONNECTION:
4147 {
4148 return OK;
4149 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004150 case CAPTURE_SCREEN:
4151 {
4152 // codes that require permission check
4153 IPCThreadState* ipc = IPCThreadState::self();
4154 const int pid = ipc->getCallingPid();
4155 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004156 if ((uid != AID_GRAPHICS) &&
4157 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004158 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004159 return PERMISSION_DENIED;
4160 }
4161 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004162 }
chaviwa76b2712017-09-20 12:02:26 -07004163 case CAPTURE_LAYERS: {
4164 IPCThreadState* ipc = IPCThreadState::self();
4165 const int pid = ipc->getCallingPid();
4166 const int uid = ipc->getCallingUid();
4167 if ((uid != AID_GRAPHICS) &&
4168 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4169 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4170 return PERMISSION_DENIED;
4171 }
4172 break;
4173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004175 return OK;
4176}
4177
4178status_t SurfaceFlinger::onTransact(
4179 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4180{
4181 status_t credentialCheck = CheckTransactCodeCredentials(code);
4182 if (credentialCheck != OK) {
4183 return credentialCheck;
4184 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4187 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004188 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004189 IPCThreadState* ipc = IPCThreadState::self();
4190 const int uid = ipc->getCallingUid();
4191 if (CC_UNLIKELY(uid != AID_SYSTEM
4192 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004193 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004194 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004195 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004196 return PERMISSION_DENIED;
4197 }
4198 int n;
4199 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004200 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004201 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 return NO_ERROR;
4203 case 1002: // SHOW_UPDATES
4204 n = data.readInt32();
4205 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004206 invalidateHwcGeometry();
4207 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004210 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004211 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004212 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004213 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004214 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004215 setTransactionFlags(
4216 eTransactionNeeded|
4217 eDisplayTransactionNeeded|
4218 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004219 return NO_ERROR;
4220 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004221 case 1006:{ // send empty update
4222 signalRefresh();
4223 return NO_ERROR;
4224 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004225 case 1008: // toggle use of hw composer
4226 n = data.readInt32();
4227 mDebugDisableHWC = n ? 1 : 0;
4228 invalidateHwcGeometry();
4229 repaintEverything();
4230 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004231 case 1009: // toggle use of transform hint
4232 n = data.readInt32();
4233 mDebugDisableTransformHint = n ? 1 : 0;
4234 invalidateHwcGeometry();
4235 repaintEverything();
4236 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004237 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004238 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004239 reply->writeInt32(0);
4240 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004241 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004242 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 return NO_ERROR;
4244 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004245 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004246 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004247 return NO_ERROR;
4248 }
4249 case 1014: {
4250 // daltonize
4251 n = data.readInt32();
4252 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004253 case 1:
4254 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4255 break;
4256 case 2:
4257 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4258 break;
4259 case 3:
4260 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4261 break;
4262 default:
4263 mDaltonizer.setType(ColorBlindnessType::None);
4264 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004265 }
4266 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004267 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004268 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004269 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004270 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004271 invalidateHwcGeometry();
4272 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004273 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004275 case 1015: {
4276 // apply a color matrix
4277 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004278 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004279 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004280 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004281 for (size_t j = 0; j < 4; j++) {
4282 mColorMatrix[i][j] = data.readFloat();
4283 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004284 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004285 } else {
4286 mColorMatrix = mat4();
4287 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004288
4289 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4290 // the division by w in the fragment shader
4291 float4 lastRow(transpose(mColorMatrix)[3]);
4292 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4293 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4294 }
4295
Alan Viverette9c5a3332013-09-12 20:04:35 -07004296 invalidateHwcGeometry();
4297 repaintEverything();
4298 return NO_ERROR;
4299 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004300 // This is an experimental interface
4301 // Needs to be shifted to proper binder interface when we productize
4302 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004303 n = data.readInt32();
4304 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004305 return NO_ERROR;
4306 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004307 case 1017: {
4308 n = data.readInt32();
4309 mForceFullDamage = static_cast<bool>(n);
4310 return NO_ERROR;
4311 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004312 case 1018: { // Modify Choreographer's phase offset
4313 n = data.readInt32();
4314 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4315 return NO_ERROR;
4316 }
4317 case 1019: { // Modify SurfaceFlinger's phase offset
4318 n = data.readInt32();
4319 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4320 return NO_ERROR;
4321 }
Irvel468051e2016-06-13 16:44:44 -07004322 case 1020: { // Layer updates interceptor
4323 n = data.readInt32();
4324 if (n) {
4325 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004326 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004327 }
4328 else{
4329 ALOGV("Interceptor disabled");
4330 mInterceptor.disable();
4331 }
4332 return NO_ERROR;
4333 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004334 case 1021: { // Disable HWC virtual displays
4335 n = data.readInt32();
4336 mUseHwcVirtualDisplays = !n;
4337 return NO_ERROR;
4338 }
Romain Guy0147a172017-06-01 13:53:56 -07004339 case 1022: { // Set saturation boost
4340 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4341
4342 invalidateHwcGeometry();
4343 repaintEverything();
4344 return NO_ERROR;
4345 }
Romain Guy54f154a2017-10-24 21:40:32 +01004346 case 1023: { // Set native mode
4347 mForceNativeColorMode = data.readInt32() == 1;
4348
4349 invalidateHwcGeometry();
4350 repaintEverything();
4351 return NO_ERROR;
4352 }
4353 case 1024: { // Is wide color gamut rendering/color management supported?
4354 reply->writeBool(hasWideColorDisplay);
4355 return NO_ERROR;
4356 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004357 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004358 n = data.readInt32();
4359 if (n) {
4360 ALOGV("LayerTracing enabled");
4361 mTracing.enable();
4362 doTracing("tracing.enable");
4363 reply->writeInt32(NO_ERROR);
4364 } else {
4365 ALOGV("LayerTracing disabled");
4366 status_t err = mTracing.disable();
4367 reply->writeInt32(err);
4368 }
4369 return NO_ERROR;
4370 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004371 case 1026: { // Get layer tracing status
4372 reply->writeBool(mTracing.isEnabled());
4373 return NO_ERROR;
4374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004375 }
4376 }
4377 return err;
4378}
4379
Steven Thomas6d8110b2017-08-31 18:24:21 -07004380void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004381 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004382 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004383}
4384
Steven Thomas6d8110b2017-08-31 18:24:21 -07004385void SurfaceFlinger::repaintEverything() {
4386 ConditionalLock _l(mStateLock,
4387 std::this_thread::get_id() != mMainThreadId);
4388 repaintEverythingLocked();
4389}
4390
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004391// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4392class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004393public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004394 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4395 ~WindowDisconnector() {
4396 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004397 }
4398
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004399private:
4400 ANativeWindow* mWindow;
4401 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004402};
4403
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004404status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4405 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4406 int32_t minLayerZ, int32_t maxLayerZ,
4407 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004408 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004409 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004410
chaviwa76b2712017-09-20 12:02:26 -07004411 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4412
4413 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4414 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4415
4416 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4417 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004418 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004419}
4420
4421status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004422 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004423 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004424 ATRACE_CALL();
4425
4426 class LayerRenderArea : public RenderArea {
4427 public:
chaviw7206d492017-11-10 16:16:12 -08004428 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004429 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004430 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004431 const Transform& getTransform() const override {
4432 // Make the top level transform the inverse the transform and it's parent so it sets
4433 // the whole capture back to 0,0
4434 return *new Transform(mLayer->getTransform().inverse());
4435 }
4436 Rect getBounds() const override {
4437 const Layer::State& layerState(mLayer->getDrawingState());
4438 return Rect(layerState.active.w, layerState.active.h);
4439 }
4440 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4441 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4442 bool isSecure() const override { return false; }
4443 bool needsFiltering() const override { return false; }
4444
chaviw7206d492017-11-10 16:16:12 -08004445 Rect getSourceCrop() const override {
4446 if (mCrop.isEmpty()) {
4447 return getBounds();
4448 } else {
4449 return mCrop;
4450 }
4451 }
chaviwa76b2712017-09-20 12:02:26 -07004452 bool getWideColorSupport() const override { return false; }
4453 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4454
4455 private:
chaviw7206d492017-11-10 16:16:12 -08004456 const sp<Layer> mLayer;
4457 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004458 };
4459
4460 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4461 auto parent = layerHandle->owner.promote();
4462
chaviw7206d492017-11-10 16:16:12 -08004463 if (parent == nullptr || parent->isPendingRemoval()) {
4464 ALOGE("captureLayers called with a removed parent");
4465 return NAME_NOT_FOUND;
4466 }
4467
4468 Rect crop(sourceCrop);
4469 if (sourceCrop.width() <= 0) {
4470 crop.left = 0;
4471 crop.right = parent->getCurrentState().active.w;
4472 }
4473
4474 if (sourceCrop.height() <= 0) {
4475 crop.top = 0;
4476 crop.bottom = parent->getCurrentState().active.h;
4477 }
4478
4479 int32_t reqWidth = crop.width() * frameScale;
4480 int32_t reqHeight = crop.height() * frameScale;
4481
4482 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4483
chaviwa76b2712017-09-20 12:02:26 -07004484 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4485 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4486 if (!layer->isVisible()) {
4487 return;
4488 }
4489 visitor(layer);
4490 });
4491 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004492 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004493}
4494
4495status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4496 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004497 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004498 bool useIdentityTransform) {
4499 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004500
chaviwa76b2712017-09-20 12:02:26 -07004501 renderArea.updateDimensions();
4502
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004503 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4504 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4505 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4506 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004507
4508 // This mutex protects syncFd and captureResult for communication of the return values from the
4509 // main thread back to this Binder thread
4510 std::mutex captureMutex;
4511 std::condition_variable captureCondition;
4512 std::unique_lock<std::mutex> captureLock(captureMutex);
4513 int syncFd = -1;
4514 std::optional<status_t> captureResult;
4515
Robert Carr03480e22018-01-04 16:02:06 -08004516 const int uid = IPCThreadState::self()->getCallingUid();
4517 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004519 sp<LambdaMessage> message = new LambdaMessage([&]() {
4520 // If there is a refresh pending, bug out early and tell the binder thread to try again
4521 // after the refresh.
4522 if (mRefreshPending) {
4523 ATRACE_NAME("Skipping screenshot for now");
4524 std::unique_lock<std::mutex> captureLock(captureMutex);
4525 captureResult = std::make_optional<status_t>(EAGAIN);
4526 captureCondition.notify_one();
4527 return;
4528 }
4529
4530 status_t result = NO_ERROR;
4531 int fd = -1;
4532 {
4533 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004534 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004535 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004536 }
4537
4538 {
4539 std::unique_lock<std::mutex> captureLock(captureMutex);
4540 syncFd = fd;
4541 captureResult = std::make_optional<status_t>(result);
4542 captureCondition.notify_one();
4543 }
4544 });
4545
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004546 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004547 if (result == NO_ERROR) {
4548 captureCondition.wait(captureLock, [&]() { return captureResult; });
4549 while (*captureResult == EAGAIN) {
4550 captureResult.reset();
4551 result = postMessageAsync(message);
4552 if (result != NO_ERROR) {
4553 return result;
4554 }
4555 captureCondition.wait(captureLock, [&]() { return captureResult; });
4556 }
4557 result = *captureResult;
4558 }
4559
4560 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004561 sync_wait(syncFd, -1);
4562 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004563 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004564
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004565 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004566}
4567
chaviwa76b2712017-09-20 12:02:26 -07004568void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4569 TraverseLayersFunction traverseLayers, bool yswap,
4570 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004571 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004572
Lloyd Pique144e1162017-12-20 16:44:52 -08004573 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004574
4575 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004576 const auto raWidth = renderArea.getWidth();
4577 const auto raHeight = renderArea.getHeight();
4578
4579 const auto reqWidth = renderArea.getReqWidth();
4580 const auto reqHeight = renderArea.getReqHeight();
4581 Rect sourceCrop = renderArea.getSourceCrop();
4582
4583 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4584 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004585
Dan Stozac1879002014-05-22 15:59:05 -07004586 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004587 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004588 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004589 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004590 }
4591
4592 // ensure that sourceCrop is inside screen
4593 if (sourceCrop.left < 0) {
4594 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4595 }
chaviwa76b2712017-09-20 12:02:26 -07004596 if (sourceCrop.right > raWidth) {
4597 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004598 }
4599 if (sourceCrop.top < 0) {
4600 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4601 }
chaviwa76b2712017-09-20 12:02:26 -07004602 if (sourceCrop.bottom > raHeight) {
4603 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004604 }
4605
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004606 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004607 if (renderArea.getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004608 renderArea.getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
4609 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4610 }
4611 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004612
Mathias Agopian180f10d2013-04-10 22:55:41 -07004613 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004614 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004615
4616 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004617 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4618 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004619 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004620
4621 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004622 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004623
chaviwa76b2712017-09-20 12:02:26 -07004624 traverseLayers([&](Layer* layer) {
4625 if (filtering) layer->setFiltering(true);
4626 layer->draw(renderArea, useIdentityTransform);
4627 if (filtering) layer->setFiltering(false);
4628 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004629}
4630
chaviwa76b2712017-09-20 12:02:26 -07004631status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4632 TraverseLayersFunction traverseLayers,
4633 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004634 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004635 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004636 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004637 ATRACE_CALL();
4638
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004639 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004640
4641 traverseLayers([&](Layer* layer) {
4642 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4643 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004644
Robert Carr03480e22018-01-04 16:02:06 -08004645 // We allow the system server to take screenshots of secure layers for
4646 // use in situations like the Screen-rotation animation and place
4647 // the impetus on WindowManager to not persist them.
4648 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004649 ALOGW("FB is protected: PERMISSION_DENIED");
4650 return PERMISSION_DENIED;
4651 }
4652
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004653 // this binds the given EGLImage as a framebuffer for the
4654 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004655 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004656 if (bufferBond.getStatus() != NO_ERROR) {
4657 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004658 return INVALID_OPERATION;
4659 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004660
Dan Stozaabcda352017-06-01 14:37:39 -07004661 // this will in fact render into our dequeued buffer
4662 // via an FBO, which means we didn't have to create
4663 // an EGLSurface and therefore we're not
4664 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004665 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004666
Dan Stozaabcda352017-06-01 14:37:39 -07004667 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004668 getRenderEngine().finish();
4669 *outSyncFd = -1;
4670
chaviwa76b2712017-09-20 12:02:26 -07004671 const auto reqWidth = renderArea.getReqWidth();
4672 const auto reqHeight = renderArea.getReqHeight();
4673
Dan Stozaabcda352017-06-01 14:37:39 -07004674 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4675 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004676 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004677 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004678 } else {
4679 base::unique_fd syncFd = getRenderEngine().flush();
4680 if (syncFd < 0) {
4681 getRenderEngine().finish();
4682 }
4683 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004684 }
4685
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004686 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004687}
4688
Mathias Agopiand5556842013-09-19 17:08:37 -07004689void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004690 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004691 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004692 for (size_t y = 0; y < h; y++) {
4693 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4694 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004695 if (p[x] != 0xFF000000) return;
4696 }
4697 }
chaviwa76b2712017-09-20 12:02:26 -07004698 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004699
Robert Carr2047fae2016-11-28 14:09:09 -08004700 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004701 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004702 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004703 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4704 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4705 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4706 static_cast<float>(state.color.a));
4707 i++;
4708 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004709 }
4710}
4711
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004712// ---------------------------------------------------------------------------
4713
Dan Stoza412903f2017-04-27 13:42:17 -07004714void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4715 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004716}
4717
Dan Stoza412903f2017-04-27 13:42:17 -07004718void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4719 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004720}
4721
chaviwa76b2712017-09-20 12:02:26 -07004722void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4723 int32_t maxLayerZ,
4724 const LayerVector::Visitor& visitor) {
4725 // We loop through the first level of layers without traversing,
4726 // as we need to interpret min/max layer Z in the top level Z space.
4727 for (const auto& layer : mDrawingState.layersSortedByZ) {
4728 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4729 continue;
4730 }
4731 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004732 // relative layers are traversed in Layer::traverseInZOrder
4733 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004734 continue;
4735 }
4736 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004737 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4738 return;
4739 }
chaviwa76b2712017-09-20 12:02:26 -07004740 if (!layer->isVisible()) {
4741 return;
4742 }
4743 visitor(layer);
4744 });
4745 }
4746}
4747
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004748}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004749
4750
4751#if defined(__gl_h_)
4752#error "don't include gl/gl.h in this file"
4753#endif
4754
4755#if defined(__gl2_h_)
4756#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004757#endif