blob: 29c1ee23eee4351ef1515bb11a98dd1ce77161ea [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165SurfaceFlinger::SurfaceFlinger()
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()),
197 mCreateBufferQueue(&BufferQueue::createBufferQueue) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
211
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
214
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800215 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
217
Steven Thomas050b2c82017-03-06 11:45:16 -0800218 // Vr flinger is only enabled on Daydream ready devices.
219 useVrFlinger = getBool< ISurfaceFlingerConfigs,
220 &ISurfaceFlingerConfigs::useVrFlinger>(false);
221
Fabien Sanglard1971b632017-03-10 14:50:03 -0800222 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
224
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600225 hasWideColorDisplay =
226 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
227
David Sodman99974d22017-11-28 12:04:33 -0800228 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 // debugging stuff...
231 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700232
Mathias Agopianb4b17302013-03-20 18:36:41 -0700233 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700234 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 property_get("debug.sf.showupdates", value, "0");
237 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700238
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239 property_get("debug.sf.ddms", value, "0");
240 mDebugDDMS = atoi(value);
241 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700242 if (!startDdmConnection()) {
243 // start failed, and DDMS debugging not enabled
244 mDebugDDMS = 0;
245 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700246 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700247 ALOGI_IF(mDebugRegion, "showupdates enabled");
248 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700249
250 property_get("debug.sf.disable_backpressure", value, "0");
251 mPropagateBackpressure = !atoi(value);
252 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700253
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800254 property_get("debug.sf.enable_hwc_vds", value, "0");
255 mUseHwcVirtualDisplays = atoi(value);
256 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800257
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800258 property_get("ro.sf.disable_triple_buffer", value, "1");
259 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700261
Romain Guy11d63f42017-07-20 12:47:14 -0700262 // We should be reading 'persist.sys.sf.color_saturation' here
263 // but since /data may be encrypted, we need to wait until after vold
264 // comes online to attempt to read the property. The property is
265 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800266
267 if (useTrebleTestingOverride()) {
268 // Without the override SurfaceFlinger cannot connect to HIDL
269 // services that are not listed in the manifests. Considered
270 // deriving the setting from the set service name, but it
271 // would be brittle if the name that's not 'default' is used
272 // for production purposes later on.
273 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800277void SurfaceFlinger::onFirstRef()
278{
279 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280}
281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282SurfaceFlinger::~SurfaceFlinger()
283{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Dan Stozac7014012014-02-14 15:03:43 -0800286void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800287{
288 // the window manager died on us. prepare its eulogy.
289
Andy McFadden13a082e2012-08-24 10:16:42 -0700290 // restore initial conditions (default device unblank, etc)
291 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800292
293 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700294 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295}
296
Robert Carr1db73f62016-12-21 12:58:51 -0800297static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700298 status_t err = client->initCheck();
299 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800300 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 }
Robert Carr1db73f62016-12-21 12:58:51 -0800302 return nullptr;
303}
304
305sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
306 return initClient(new Client(this));
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
310 const sp<IGraphicBufferProducer>& gbp) {
311 if (authenticateSurfaceTexture(gbp) == false) {
312 return nullptr;
313 }
314 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
315 if (layer == nullptr) {
316 return nullptr;
317 }
318
319 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700322sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
323 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324{
325 class DisplayToken : public BBinder {
326 sp<SurfaceFlinger> flinger;
327 virtual ~DisplayToken() {
328 // no more references, this display must be terminated
329 Mutex::Autolock _l(flinger->mStateLock);
330 flinger->mCurrentState.displays.removeItem(this);
331 flinger->setTransactionFlags(eDisplayTransactionNeeded);
332 }
333 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700334 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335 : flinger(flinger) {
336 }
337 };
338
339 sp<BBinder> token = new DisplayToken(this);
340
341 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700342 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700343 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700344 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700345 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346 return token;
347}
348
Jesse Hall6c913be2013-08-08 12:15:49 -0700349void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
350 Mutex::Autolock _l(mStateLock);
351
352 ssize_t idx = mCurrentState.displays.indexOfKey(display);
353 if (idx < 0) {
354 ALOGW("destroyDisplay: invalid display token");
355 return;
356 }
357
358 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
359 if (!info.isVirtualDisplay()) {
360 ALOGE("destroyDisplay called for non-virtual display");
361 return;
362 }
Irvelffc9efc2016-07-27 15:16:37 -0700363 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700364 mCurrentState.displays.removeItemsAt(idx);
365 setTransactionFlags(eDisplayTransactionNeeded);
366}
367
Mathias Agopiane57f2922012-08-09 16:29:12 -0700368sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700369 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700370 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800371 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700372 }
Jesse Hall692c7232012-11-08 15:41:56 -0800373 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376void SurfaceFlinger::bootFinished()
377{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700378 if (mStartPropertySetThread->join() != NO_ERROR) {
379 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 const nsecs_t now = systemTime();
382 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000383 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700384
385 // wait patiently for the window manager death
386 const String16 name("window");
387 sp<IBinder> window(defaultServiceManager()->getService(name));
388 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700390 }
391
Steven Thomas050b2c82017-03-06 11:45:16 -0800392 if (mVrFlinger) {
393 mVrFlinger->OnBootFinished();
394 }
395
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700396 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700397 // formerly we would just kill the process, but we now ask it to exit so it
398 // can choose where to stop the animation.
399 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700400
401 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
402 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
403 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700404
Thierry Strudel2924d012017-08-14 15:19:37 -0700405 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700406 readPersistentProperties();
407 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700408 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Mathias Agopian3f844832013-08-07 21:24:32 -0700411void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700412 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800413 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700414 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700415 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800416 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
417 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700419 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700420 return true;
421 }
422 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700423 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424}
425
Lloyd Piquee83f9312018-02-01 12:53:17 -0800426class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000429 const char* name) :
430 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700431 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
434 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 mDispSync(dispSync),
436 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 mVsyncMutex(),
438 mPhaseOffset(phaseOffset),
439 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700440
Lloyd Piquee83f9312018-02-01 12:53:17 -0800441 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442
Lloyd Piquee83f9312018-02-01 12:53:17 -0800443 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700444 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000446 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 static_cast<DispSync::Callback*>(this));
448 if (err != NO_ERROR) {
449 ALOGE("error registering vsync callback: %s (%d)",
450 strerror(-err), err);
451 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700452 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 } else {
454 status_t err = mDispSync->removeEventListener(
455 static_cast<DispSync::Callback*>(this));
456 if (err != NO_ERROR) {
457 ALOGE("error unregistering vsync callback: %s (%d)",
458 strerror(-err), err);
459 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700460 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
464
Lloyd Piquee83f9312018-02-01 12:53:17 -0800465 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700466 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 mCallback = callback;
468 }
469
Lloyd Piquee83f9312018-02-01 12:53:17 -0800470 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 Mutex::Autolock lock(mVsyncMutex);
472
473 // Normalize phaseOffset to [0, period)
474 auto period = mDispSync->getPeriod();
475 phaseOffset %= period;
476 if (phaseOffset < 0) {
477 // If we're here, then phaseOffset is in (-period, 0). After this
478 // operation, it will be in (0, period)
479 phaseOffset += period;
480 }
481 mPhaseOffset = phaseOffset;
482
483 // If we're not enabled, we don't need to mess with the listeners
484 if (!mEnabled) {
485 return;
486 }
487
488 // Remove the listener with the old offset
489 status_t err = mDispSync->removeEventListener(
490 static_cast<DispSync::Callback*>(this));
491 if (err != NO_ERROR) {
492 ALOGE("error unregistering vsync callback: %s (%d)",
493 strerror(-err), err);
494 }
495
496 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000497 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700498 static_cast<DispSync::Callback*>(this));
499 if (err != NO_ERROR) {
500 ALOGE("error registering vsync callback: %s (%d)",
501 strerror(-err), err);
502 }
503 }
504
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505private:
506 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800507 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700509 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 callback = mCallback;
511
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700512 if (mTraceVsync) {
513 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700514 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700515 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 }
517
Peiyong Lin566a3b42018-01-09 18:22:43 -0800518 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519 callback->onVSyncEvent(when);
520 }
521 }
522
Tim Murray4a4e4a22016-04-19 16:29:23 +0000523 const char* const mName;
524
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 int mValue;
526
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700527 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700528 const String8 mVsyncOnLabel;
529 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700530
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700532
533 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800534 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700535
536 Mutex mVsyncMutex; // Protects the following
537 nsecs_t mPhaseOffset;
538 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539};
540
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700542public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800543 InjectVSyncSource() = default;
544 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700545
Lloyd Piquee83f9312018-02-01 12:53:17 -0800546 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700547 std::lock_guard<std::mutex> lock(mCallbackMutex);
548 mCallback = callback;
549 }
550
Lloyd Piquee83f9312018-02-01 12:53:17 -0800551 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700552 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700553 if (mCallback) {
554 mCallback->onVSyncEvent(when);
555 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700556 }
557
Lloyd Piquee83f9312018-02-01 12:53:17 -0800558 void setVSyncEnabled(bool) override {}
559 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700560
561private:
562 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800563 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700564};
565
Wei Wangf9b05ee2017-07-19 20:59:39 -0700566// Do not call property_set on main thread which will be blocked by init
567// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700569 ALOGI( "SurfaceFlinger's main thread ready to run. "
570 "Initializing graphics H/W...");
571
Thierry Strudel2924d012017-08-14 15:19:37 -0700572 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900573
Steven Thomasb02664d2017-07-26 18:48:28 -0700574 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575
Steven Thomasb02664d2017-07-26 18:48:28 -0700576 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800577 mEventThreadSource =
578 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
579 true, "app");
580 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
581 "appEventThread");
582 mSfEventThreadSource =
583 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
584 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
585 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
586 "sfEventThread");
Lloyd Piquee83f9312018-02-01 12:53:17 -0800587 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588
Steven Thomasb02664d2017-07-26 18:48:28 -0700589 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800590 getBE().mRenderEngine =
591 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
592 hasWideColorDisplay
593 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
594 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800595 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700596
597 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
598 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800599 getBE().mHwc.reset(
600 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700601 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800602 // Process any initial hotplug and resulting display changes.
603 processDisplayHotplugEventsLocked();
604 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
605 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800606
Lloyd Piquefcd86612017-12-14 17:15:36 -0800607 // make the default display GLContext current so that we can create textures
608 // when creating Layers (which may happens before we render something)
609 getDefaultDisplayDeviceLocked()->makeCurrent();
610
Steven Thomas050b2c82017-03-06 11:45:16 -0800611 if (useVrFlinger) {
612 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700613 // This callback is called from the vr flinger dispatch thread. We
614 // need to call signalTransaction(), which requires holding
615 // mStateLock when we're not on the main thread. Acquiring
616 // mStateLock from the vr flinger dispatch thread might trigger a
617 // deadlock in surface flinger (see b/66916578), so post a message
618 // to be handled on the main thread instead.
619 sp<LambdaMessage> message = new LambdaMessage([=]() {
620 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
621 mVrFlingerRequestsDisplay = requestDisplay;
622 signalTransaction();
623 });
624 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 };
David Sodman105b7dc2017-11-04 20:28:14 -0700626 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
627 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800628 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800629 if (!mVrFlinger) {
630 ALOGE("Failed to start vrflinger");
631 }
632 }
633
Lloyd Pique755e3192018-01-31 16:46:15 -0800634 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
635 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
636 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700637
Mathias Agopian92a979a2012-08-02 18:32:23 -0700638 // initialize our drawing state
639 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700640
Andy McFadden13a082e2012-08-24 10:16:42 -0700641 // set initial conditions (e.g. unblank default device)
642 initializeDisplays();
643
David Sodmanbc815282017-11-05 18:57:52 -0800644 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700645
Wei Wangf9b05ee2017-07-19 20:59:39 -0700646 // Inform native graphics APIs whether the present timestamp is supported:
647 if (getHwComposer().hasCapability(
648 HWC2::Capability::PresentFenceIsNotReliable)) {
649 mStartPropertySetThread = new StartPropertySetThread(false);
650 } else {
651 mStartPropertySetThread = new StartPropertySetThread(true);
652 }
653
654 if (mStartPropertySetThread->Start() != NO_ERROR) {
655 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657
Dan Stoza9e56aa02015-11-02 13:00:03 -0800658 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700659}
660
Romain Guy11d63f42017-07-20 12:47:14 -0700661void SurfaceFlinger::readPersistentProperties() {
662 char value[PROPERTY_VALUE_MAX];
663
664 property_get("persist.sys.sf.color_saturation", value, "1.0");
665 mSaturation = atof(value);
666 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100667
668 property_get("persist.sys.sf.native_mode", value, "0");
669 mForceNativeColorMode = atoi(value) == 1;
670 if (mForceNativeColorMode) {
671 ALOGV("Forcing native color mode");
672 }
Romain Guy11d63f42017-07-20 12:47:14 -0700673}
674
Mathias Agopiana67e4182012-06-19 17:26:12 -0700675void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800676 // Start boot animation service by setting a property mailbox
677 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700678 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800679 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 if (mStartPropertySetThread->join() != NO_ERROR) {
681 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800682 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700683}
684
Mathias Agopian875d8e12013-06-07 15:35:48 -0700685size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800686 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700687}
688
Mathias Agopian875d8e12013-06-07 15:35:48 -0700689size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800690 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700691}
692
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800693// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800694
Jamie Gennis582270d2011-08-17 18:19:00 -0700695bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800696 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800697 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800698 return authenticateSurfaceTextureLocked(bufferProducer);
699}
700
701bool SurfaceFlinger::authenticateSurfaceTextureLocked(
702 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800703 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800704 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800705}
706
Brian Anderson6b376712017-04-04 10:51:39 -0700707status_t SurfaceFlinger::getSupportedFrameTimestamps(
708 std::vector<FrameEvent>* outSupported) const {
709 *outSupported = {
710 FrameEvent::REQUESTED_PRESENT,
711 FrameEvent::ACQUIRE,
712 FrameEvent::LATCH,
713 FrameEvent::FIRST_REFRESH_START,
714 FrameEvent::LAST_REFRESH_START,
715 FrameEvent::GPU_COMPOSITION_DONE,
716 FrameEvent::DEQUEUE_READY,
717 FrameEvent::RELEASE,
718 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700719 ConditionalLock _l(mStateLock,
720 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700721 if (!getHwComposer().hasCapability(
722 HWC2::Capability::PresentFenceIsNotReliable)) {
723 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
724 }
725 return NO_ERROR;
726}
727
Dan Stoza7f7da322014-05-02 15:26:25 -0700728status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
729 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800730 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700731 return BAD_VALUE;
732 }
733
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500734 if (!display.get())
735 return NAME_NOT_FOUND;
736
Jesse Hall692c7232012-11-08 15:41:56 -0800737 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700738 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800739 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700740 type = i;
741 break;
742 }
743 }
744
745 if (type < 0) {
746 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700747 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700748
Mathias Agopian8b736f12012-08-13 17:54:26 -0700749 // TODO: Not sure if display density should handled by SF any longer
750 class Density {
751 static int getDensityFromProperty(char const* propName) {
752 char property[PROPERTY_VALUE_MAX];
753 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800754 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755 density = atoi(property);
756 }
757 return density;
758 }
759 public:
760 static int getEmuDensity() {
761 return getDensityFromProperty("qemu.sf.lcd_density"); }
762 static int getBuildDensity() {
763 return getDensityFromProperty("ro.sf.lcd_density"); }
764 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700765
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700767
Steven Thomas6d8110b2017-08-31 18:24:21 -0700768 ConditionalLock _l(mStateLock,
769 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700771 DisplayInfo info = DisplayInfo();
772
Dan Stoza9e56aa02015-11-02 13:00:03 -0800773 float xdpi = hwConfig->getDpiX();
774 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700775
776 if (type == DisplayDevice::DISPLAY_PRIMARY) {
777 // The density of the device is provided by a build property
778 float density = Density::getBuildDensity() / 160.0f;
779 if (density == 0) {
780 // the build doesn't provide a density -- this is wrong!
781 // use xdpi instead
782 ALOGE("ro.sf.lcd_density must be defined as a build property");
783 density = xdpi / 160.0f;
784 }
785 if (Density::getEmuDensity()) {
786 // if "qemu.sf.lcd_density" is specified, it overrides everything
787 xdpi = ydpi = density = Density::getEmuDensity();
788 density /= 160.0f;
789 }
790 info.density = density;
791
792 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800794 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700795 } else {
796 // TODO: where should this value come from?
797 static const int TV_DENSITY = 213;
798 info.density = TV_DENSITY / 160.0f;
799 info.orientation = 0;
800 }
801
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 info.w = hwConfig->getWidth();
803 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700804 info.xdpi = xdpi;
805 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900807 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808
Andy McFadden91b2ca82014-06-13 14:04:23 -0700809 // This is how far in advance a buffer must be queued for
810 // presentation at a given time. If you want a buffer to appear
811 // on the screen at time N, you must submit the buffer before
812 // (N - presentationDeadline).
813 //
814 // Normally it's one full refresh period (to give SF a chance to
815 // latch the buffer), but this can be reduced by configuring a
816 // DispSync offset. Any additional delays introduced by the hardware
817 // composer or panel must be accounted for here.
818 //
819 // We add an additional 1ms to allow for processing time and
820 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800822 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700823
824 // All non-virtual displays are currently considered secure.
825 info.secure = true;
826
Michael Wright28f24d02016-07-12 13:30:53 -0700827 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 }
829
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 return NO_ERROR;
831}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700832
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800833status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700834 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800835 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700836 return BAD_VALUE;
837 }
838
839 // FIXME for now we always return stats for the primary display
840 memset(stats, 0, sizeof(*stats));
841 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
842 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
843 return NO_ERROR;
844}
845
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700846int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800847 if (display == nullptr) {
848 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800849 return BAD_VALUE;
850 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700851
852 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800853 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700854 return device->getActiveConfig();
855 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700856
Dan Stoza24a42e92015-03-09 10:04:11 -0700857 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700859
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700860void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
861 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
862 this);
863 int32_t type = hw->getDisplayType();
864 int currentMode = hw->getActiveConfig();
865
866 if (mode == currentMode) {
867 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
868 return;
869 }
870
871 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
872 ALOGW("Trying to set config for virtual display");
873 return;
874 }
875
876 hw->setActiveConfig(mode);
877 getHwComposer().setActiveConfig(type, mode);
878}
879
880status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
881 class MessageSetActiveConfig: public MessageBase {
882 SurfaceFlinger& mFlinger;
883 sp<IBinder> mDisplay;
884 int mMode;
885 public:
886 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
887 int mode) :
888 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
889 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700890 Vector<DisplayInfo> configs;
891 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700892 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700893 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700894 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700895 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700896 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700897 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800898 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700899 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700900 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700901 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
902 ALOGW("Attempt to set active config = %d for virtual display",
903 mMode);
904 } else {
905 mFlinger.setActiveConfigInternal(hw, mMode);
906 }
907 return true;
908 }
909 };
910 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
911 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700912 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700913}
Michael Wright28f24d02016-07-12 13:30:53 -0700914status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
915 Vector<android_color_mode_t>* outColorModes) {
916 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
917 return BAD_VALUE;
918 }
919
920 if (!display.get()) {
921 return NAME_NOT_FOUND;
922 }
923
924 int32_t type = NAME_NOT_FOUND;
925 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
926 if (display == mBuiltinDisplays[i]) {
927 type = i;
928 break;
929 }
930 }
931
932 if (type < 0) {
933 return type;
934 }
935
Steven Thomas6d8110b2017-08-31 18:24:21 -0700936 std::vector<android_color_mode_t> modes;
937 {
938 ConditionalLock _l(mStateLock,
939 std::this_thread::get_id() != mMainThreadId);
940 modes = getHwComposer().getColorModes(type);
941 }
Michael Wright28f24d02016-07-12 13:30:53 -0700942 outColorModes->clear();
943 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
944
945 return NO_ERROR;
946}
947
948android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700949 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700950 if (device != nullptr) {
951 return device->getActiveColorMode();
952 }
953 return static_cast<android_color_mode_t>(BAD_VALUE);
954}
955
956void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
957 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700958 int32_t type = hw->getDisplayType();
959 android_color_mode_t currentMode = hw->getActiveColorMode();
960
961 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 return;
963 }
964
965 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
966 ALOGW("Trying to set config for virtual display");
967 return;
968 }
969
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600970 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
971 hw->getDisplayType());
972
Michael Wright28f24d02016-07-12 13:30:53 -0700973 hw->setActiveColorMode(mode);
974 getHwComposer().setActiveColorMode(type, mode);
975}
976
977
978status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
979 android_color_mode_t colorMode) {
980 class MessageSetActiveColorMode: public MessageBase {
981 SurfaceFlinger& mFlinger;
982 sp<IBinder> mDisplay;
983 android_color_mode_t mMode;
984 public:
985 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
986 android_color_mode_t mode) :
987 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
988 virtual bool handler() {
989 Vector<android_color_mode_t> modes;
990 mFlinger.getDisplayColorModes(mDisplay, &modes);
991 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
992 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600993 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
994 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700995 return true;
996 }
997 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
998 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600999 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1000 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001001 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001002 ALOGW("Attempt to set active color mode %s %d for virtual display",
1003 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001004 } else {
1005 mFlinger.setActiveColorModeInternal(hw, mMode);
1006 }
1007 return true;
1008 }
1009 };
1010 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1011 postMessageSync(msg);
1012 return NO_ERROR;
1013}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001014
Svetoslavd85084b2014-03-20 10:28:31 -07001015status_t SurfaceFlinger::clearAnimationFrameStats() {
1016 Mutex::Autolock _l(mStateLock);
1017 mAnimFrameTracker.clearStats();
1018 return NO_ERROR;
1019}
1020
1021status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1022 Mutex::Autolock _l(mStateLock);
1023 mAnimFrameTracker.getStats(outStats);
1024 return NO_ERROR;
1025}
1026
Dan Stozac4f471e2016-03-24 09:31:08 -07001027status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1028 HdrCapabilities* outCapabilities) const {
1029 Mutex::Autolock _l(mStateLock);
1030
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001031 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001032 if (displayDevice == nullptr) {
1033 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1034 return BAD_VALUE;
1035 }
1036
1037 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001038 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001039 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001040 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1041 // insert HDR10 as we will force client composition for HDR10
1042 // layers
1043 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1044 types.push_back(HAL_HDR_HDR10);
1045
1046 *outCapabilities = HdrCapabilities(types,
1047 capabilities->getDesiredMaxLuminance(),
1048 capabilities->getDesiredMaxAverageLuminance(),
1049 capabilities->getDesiredMinLuminance());
1050 } else {
1051 *outCapabilities = std::move(*capabilities);
1052 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001053 } else {
1054 return BAD_VALUE;
1055 }
1056
1057 return NO_ERROR;
1058}
1059
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001060status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001061 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1062 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063
Chia-I Wu90f669f2017-10-05 14:24:41 -07001064 if (mInjectVSyncs == enable) {
1065 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067
1068 if (enable) {
1069 ALOGV("VSync Injections enabled");
1070 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001071 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001072 mInjectorEventThread =
1073 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1074 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001075 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001076 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077 } else {
1078 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001079 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001080 }
1081
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001082 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 });
1084 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089 Mutex::Autolock _l(mStateLock);
1090
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 if (!mInjectVSyncs) {
1092 ALOGE("VSync Injections not enabled");
1093 return BAD_VALUE;
1094 }
1095 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1096 ALOGV("Injecting VSync inside SurfaceFlinger");
1097 mVSyncInjector->onInjectSyncEvent(when);
1098 }
1099 return NO_ERROR;
1100}
1101
Lloyd Pique755e3192018-01-31 16:46:15 -08001102status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1103 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001104 IPCThreadState* ipc = IPCThreadState::self();
1105 const int pid = ipc->getCallingPid();
1106 const int uid = ipc->getCallingUid();
1107 if ((uid != AID_SHELL) &&
1108 !PermissionCache::checkPermission(sDump, pid, uid)) {
1109 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1110 return PERMISSION_DENIED;
1111 }
1112
1113 // Try to acquire a lock for 1s, fail gracefully
1114 const status_t err = mStateLock.timedLock(s2ns(1));
1115 const bool locked = (err == NO_ERROR);
1116 if (!locked) {
1117 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1118 return TIMED_OUT;
1119 }
1120
1121 outLayers->clear();
1122 mCurrentState.traverseInZOrder([&](Layer* layer) {
1123 outLayers->push_back(layer->getLayerDebugInfo());
1124 });
1125
1126 mStateLock.unlock();
1127 return NO_ERROR;
1128}
1129
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001130// ----------------------------------------------------------------------------
1131
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001132sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1133 ISurfaceComposer::VsyncSource vsyncSource) {
1134 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1135 return mSFEventThread->createEventConnection();
1136 } else {
1137 return mEventThread->createEventConnection();
1138 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001139}
1140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001141// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001142
1143void SurfaceFlinger::waitForEvent() {
1144 mEventQueue.waitMessage();
1145}
1146
1147void SurfaceFlinger::signalTransaction() {
1148 mEventQueue.invalidate();
1149}
1150
1151void SurfaceFlinger::signalLayerUpdate() {
1152 mEventQueue.invalidate();
1153}
1154
1155void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001156 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001157 mEventQueue.refresh();
1158}
1159
1160status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001161 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162 return mEventQueue.postMessage(msg, reltime);
1163}
1164
1165status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001166 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167 status_t res = mEventQueue.postMessage(msg, reltime);
1168 if (res == NO_ERROR) {
1169 msg->wait();
1170 }
1171 return res;
1172}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001173
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001174void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001175 do {
1176 waitForEvent();
1177 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178}
1179
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180void SurfaceFlinger::enableHardwareVsync() {
1181 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001182 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001184 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1185 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001187 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188}
1189
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191 Mutex::Autolock _l(mHWVsyncLock);
1192
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193 if (makeAvailable) {
1194 mHWVsyncAvailable = true;
1195 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001196 // Hardware vsync is not currently available, so abort the resync
1197 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198 return;
1199 }
1200
David Sodman105b7dc2017-11-04 20:28:14 -07001201 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001202 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203
1204 mPrimaryDispSync.reset();
1205 mPrimaryDispSync.setPeriod(period);
1206
1207 if (!mPrimaryHWVsyncEnabled) {
1208 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001209 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1210 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryHWVsyncEnabled = true;
1212 }
1213}
1214
Jesse Hall948fe0c2013-10-14 12:56:09 -07001215void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216 Mutex::Autolock _l(mHWVsyncLock);
1217 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1219 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryDispSync.endResync();
1221 mPrimaryHWVsyncEnabled = false;
1222 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (makeUnavailable) {
1224 mHWVsyncAvailable = false;
1225 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226}
1227
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228void SurfaceFlinger::resyncWithRateLimit() {
1229 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001230
1231 // No explicit locking is needed here since EventThread holds a lock while calling this method
1232 static nsecs_t sLastResyncAttempted = 0;
1233 const nsecs_t now = systemTime();
1234 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001235 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236 }
Dan Stoza57164302017-05-08 14:03:54 -07001237 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001238}
1239
Steven Thomasb02664d2017-07-26 18:48:28 -07001240void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1241 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001242 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001243 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001244 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001245 return;
1246 }
1247
1248 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001249 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001250 return;
1251 }
1252
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 { // Scope for the lock
1256 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001257 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001260 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001261
1262 if (needsHwVsync) {
1263 enableHardwareVsync();
1264 } else {
1265 disableHardwareVsync(false);
1266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267}
1268
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001269void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001270 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1271 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001272}
1273
Lloyd Pique715a2c12017-12-14 17:18:08 -08001274void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1275 HWC2::Connection connection) {
1276 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1277 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001278
Lloyd Piqueba04e622017-12-14 17:11:26 -08001279 // Ignore events that do not have the right sequenceId.
1280 if (sequenceId != getBE().mComposerSequenceId) {
1281 return;
1282 }
1283
Steven Thomasb02664d2017-07-26 18:48:28 -07001284 // Only lock if we're not on the main thread. This function is normally
1285 // called on a hwbinder thread, but for the primary display it's called on
1286 // the main thread with the state lock already held, so don't attempt to
1287 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001288 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001289
Lloyd Pique715a2c12017-12-14 17:18:08 -08001290 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001291
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001292 if (std::this_thread::get_id() == mMainThreadId) {
1293 // Process all pending hot plug events immediately if we are on the main thread.
1294 processDisplayHotplugEventsLocked();
1295 }
1296
Lloyd Piqueba04e622017-12-14 17:11:26 -08001297 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001298}
1299
Steven Thomasb02664d2017-07-26 18:48:28 -07001300void SurfaceFlinger::onRefreshReceived(int sequenceId,
1301 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001302 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001303 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001304 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001305 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001306 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001307}
1308
Dan Stoza9e56aa02015-11-02 13:00:03 -08001309void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001312 getHwComposer().setVsyncEnabled(disp,
1313 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001314}
1315
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001316// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001317void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001318 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001319 // Clear the drawing state so that the logic inside of
1320 // handleTransactionLocked will fire. It will determine the delta between
1321 // mCurrentState and mDrawingState and re-apply all changes when we make the
1322 // transition.
1323 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001324 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 mDisplays.clear();
1326}
1327
Steven Thomas050b2c82017-03-06 11:45:16 -08001328void SurfaceFlinger::updateVrFlinger() {
1329 if (!mVrFlinger)
1330 return;
1331 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001332 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001333 return;
1334 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001335
David Sodman105b7dc2017-11-04 20:28:14 -07001336 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001337 ALOGE("Vr flinger is only supported for remote hardware composer"
1338 " service connections. Ignoring request to transition to vr"
1339 " flinger.");
1340 mVrFlingerRequestsDisplay = false;
1341 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001342 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001344 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001345
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 int currentDisplayPowerMode = getDisplayDeviceLocked(
1347 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352
Steven Thomasb02664d2017-07-26 18:48:28 -07001353 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001354 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001355 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1356 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001357 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358
David Sodman105b7dc2017-11-04 20:28:14 -07001359 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1360 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001361
1362 if (vrFlingerRequestsDisplay) {
1363 mVrFlinger->GrantDisplayOwnership();
1364 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001366 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001367
1368 mVisibleRegionsDirty = true;
1369 invalidateHwcGeometry();
1370
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001371 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1373 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1374 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001377 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 const nsecs_t period = activeConfig->getVsyncPeriod();
1379 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 // Use phase of 0 since phase is not known.
1382 // Use latency of 0, which will snap to the ideal latency.
1383 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001384
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 android_atomic_or(1, &mRepaintEverything);
1386 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387}
1388
Mathias Agopian4fec8732012-06-29 14:12:52 -07001389void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001390 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001393 bool frameMissed = !mHadClientComposition &&
1394 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395 (mPreviousPresentFence->getSignalTime() ==
1396 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001397 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001398 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001399 signalLayerUpdate();
1400 break;
1401 }
1402
Steven Thomas050b2c82017-03-06 11:45:16 -08001403 // Now that we're going to make it to the handleMessageTransaction()
1404 // call below it's safe to call updateVrFlinger(), which will
1405 // potentially trigger a display handoff.
1406 updateVrFlinger();
1407
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408 bool refreshNeeded = handleMessageTransaction();
1409 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001410 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001411 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001412 // Signal a refresh if a transaction modified the window state,
1413 // a new buffer was latched, or if HWC has requested a full
1414 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 signalRefresh();
1416 }
1417 break;
1418 }
1419 case MessageQueue::REFRESH: {
1420 handleMessageRefresh();
1421 break;
1422 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423 }
1424}
1425
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001427 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001428 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001429 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001430 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001431 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001433}
1434
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001437 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001438}
1439
1440void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001442
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001443 mRefreshPending = false;
1444
Pablo Ceballos40845df2016-01-25 17:41:15 -08001445 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001446
Brian Andersond6927fb2016-07-23 23:37:30 -07001447 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001448 rebuildLayerStacks();
1449 setUpHWComposer();
1450 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001451 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001452 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001453 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001454 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001455
David Sodman105b7dc2017-11-04 20:28:14 -07001456 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001457
1458 mHadClientComposition = false;
1459 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1460 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1461 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001462 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001463 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001464
Dan Stoza9e56aa02015-11-02 13:00:03 -08001465 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468void SurfaceFlinger::doDebugFlashRegions()
1469{
1470 // is debugging enabled
1471 if (CC_LIKELY(!mDebugRegion))
1472 return;
1473
1474 const bool repaintEverything = mRepaintEverything;
1475 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1476 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001477 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001478 // transform the dirty region into this screen's coordinate space
1479 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1480 if (!dirtyRegion.isEmpty()) {
1481 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001482 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483
1484 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001486 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001487 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1488
Mathias Agopianda27af92012-09-13 18:17:13 -07001489 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490 }
1491 }
1492 }
1493
1494 postFramebuffer();
1495
1496 if (mDebugRegion > 1) {
1497 usleep(mDebugRegion * 1000);
1498 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001499
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001501 auto& displayDevice = mDisplays[displayId];
1502 if (!displayDevice->isDisplayOn()) {
1503 continue;
1504 }
1505
David Sodman105b7dc2017-11-04 20:28:14 -07001506 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1507 ALOGE_IF(result != NO_ERROR,
1508 "prepareFrame for display %zd failed:"
1509 " %d (%s)",
1510 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001511 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512}
1513
Adrian Roos1e1a1282017-11-01 19:05:31 +01001514void SurfaceFlinger::doTracing(const char* where) {
1515 ATRACE_CALL();
1516 ATRACE_NAME(where);
1517 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001518 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001519 }
1520}
1521
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001522void SurfaceFlinger::logLayerStats() {
1523 ATRACE_CALL();
1524 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1525 int32_t hwcId = -1;
1526 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1527 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1528 if (displayDevice->isPrimary()) {
1529 hwcId = displayDevice->getHwcDisplayId();
1530 break;
1531 }
1532 }
1533 if (hwcId < 0) {
1534 ALOGE("LayerStats: Hmmm, no primary display?");
1535 return;
1536 }
1537 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1538 }
1539}
1540
Brian Andersond6927fb2016-07-23 23:37:30 -07001541void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001543 ATRACE_CALL();
1544 ALOGV("preComposition");
1545
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001547 mDrawingState.traverseInZOrder([&](Layer* layer) {
1548 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549 needExtraInvalidate = true;
1550 }
Robert Carr2047fae2016-11-28 14:09:09 -08001551 });
1552
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 if (needExtraInvalidate) {
1554 signalLayerUpdate();
1555 }
1556}
1557
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001558void SurfaceFlinger::updateCompositorTiming(
1559 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1560 std::shared_ptr<FenceTime>& presentFenceTime) {
1561 // Update queue of past composite+present times and determine the
1562 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001563 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001565 while (!getBE().mCompositePresentTimes.empty()) {
1566 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001567 // Cached values should have been updated before calling this method,
1568 // which helps avoid duplicate syscalls.
1569 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1570 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1571 break;
1572 }
1573 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001574 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001575 }
1576
1577 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001578 while (getBE().mCompositePresentTimes.size() > 16) {
1579 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001580 }
1581
Brian Andersond0010582017-03-07 13:20:31 -08001582 setCompositorTimingSnapped(
1583 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1584}
1585
1586void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1587 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588 // Integer division and modulo round toward 0 not -inf, so we need to
1589 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001590 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001591 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1592 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1593
Brian Andersond0010582017-03-07 13:20:31 -08001594 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1595 if (idealLatency <= 0) {
1596 idealLatency = vsyncInterval;
1597 }
1598
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 // Snap the latency to a value that removes scheduling jitter from the
1600 // composition and present times, which often have >1ms of jitter.
1601 // Reducing jitter is important if an app attempts to extrapolate
1602 // something (such as user input) to an accurate diasplay time.
1603 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1604 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001605 nsecs_t bias = vsyncInterval / 2;
1606 int64_t extraVsyncs =
1607 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1608 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1609 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610
David Sodman99974d22017-11-28 12:04:33 -08001611 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1612 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1613 getBE().mCompositorTiming.interval = vsyncInterval;
1614 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615}
1616
1617void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001619 ATRACE_CALL();
1620 ALOGV("postComposition");
1621
Brian Anderson3546a3f2016-07-14 11:51:14 -07001622 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001623 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001624 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001625 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001626 }
1627
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001628 // |mStateLock| not needed as we are on the main thread
1629 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001630
David Sodman73beded2017-11-15 11:56:06 -08001631 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001632 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001633 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001634 glCompositionDoneFenceTime =
1635 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001636 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001637 } else {
1638 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1639 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001640
David Sodman73beded2017-11-15 11:56:06 -08001641 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001642 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001643 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001644 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001645
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1647 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1648
1649 // We use the refreshStartTime which might be sampled a little later than
1650 // when we started doing work for this frame, but that should be okay
1651 // since updateCompositorTiming has snapping logic.
1652 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001653 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001654 CompositorTiming compositorTiming;
1655 {
David Sodman99974d22017-11-28 12:04:33 -08001656 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1657 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001658 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659
Robert Carr2047fae2016-11-28 14:09:09 -08001660 mDrawingState.traverseInZOrder([&](Layer* layer) {
1661 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001662 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001663 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001664 recordBufferingStats(layer->getName().string(),
1665 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001666 }
Robert Carr2047fae2016-11-28 14:09:09 -08001667 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001668
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001669 if (presentFenceTime->isValid()) {
1670 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001671 enableHardwareVsync();
1672 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001673 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001674 }
1675 }
1676
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001677 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001678 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001679 enableHardwareVsync();
1680 }
1681 }
1682
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001683 if (mAnimCompositionPending) {
1684 mAnimCompositionPending = false;
1685
Brian Anderson4e606e32017-03-16 15:34:57 -07001686 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001687 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001688 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001689 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001690 // The HWC doesn't support present fences, so use the refresh
1691 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001693 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001694 mAnimFrameTracker.setActualPresentTime(presentTime);
1695 }
1696 mAnimFrameTracker.advanceFrame();
1697 }
Dan Stozab90cf072015-03-05 11:05:59 -08001698
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001699 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1700 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001701 return;
1702 }
1703
1704 nsecs_t currentTime = systemTime();
1705 if (mHasPoweredOff) {
1706 mHasPoweredOff = false;
1707 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001708 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001710 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1711 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001712 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001713 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001714 }
David Sodman4a36e932017-11-07 14:29:47 -08001715 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001716 }
David Sodman4a36e932017-11-07 14:29:47 -08001717 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718}
1719
1720void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721 ATRACE_CALL();
1722 ALOGV("rebuildLayerStacks");
1723
Mathias Agopiancd60f992012-08-16 16:28:27 -07001724 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001725 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001726 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001727 mVisibleRegionsDirty = false;
1728 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001729
Jeff Sharkey76488112017-02-27 14:15:18 -07001730 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1731 Region opaqueRegion;
1732 Region dirtyRegion;
1733 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001734 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001735 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1736 const Transform& tr(displayDevice->getTransform());
1737 const Rect bounds(displayDevice->getBounds());
1738 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001739 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001740
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001742 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001743 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1744 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001745 Region drawRegion(tr.transform(
1746 layer->visibleNonTransparentRegion));
1747 drawRegion.andSelf(bounds);
1748 if (!drawRegion.isEmpty()) {
1749 layersSortedByZ.add(layer);
1750 } else {
1751 // Clear out the HWC layer if this layer was
1752 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001753 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001754 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001755 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001756 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001757 // WM changes displayDevice->layerStack upon sleep/awake.
1758 // Here we make sure we delete the HWC layers even if
1759 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001760 hwcLayerDestroyed = layer->destroyHwcLayer(
1761 displayDevice->getHwcDisplayId());
1762 }
1763
1764 // If a layer is not going to get a release fence because
1765 // it is invisible, but it is also going to release its
1766 // old buffer, add it to the list of layers needing
1767 // fences.
1768 if (hwcLayerDestroyed) {
1769 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1770 mLayersWithQueuedFrames.cend(), layer);
1771 if (found != mLayersWithQueuedFrames.cend()) {
1772 layersNeedingFences.add(layer);
1773 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001774 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 });
1776 }
1777 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001778 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001779 displayDevice->undefinedRegion.set(bounds);
1780 displayDevice->undefinedRegion.subtractSelf(
1781 tr.transform(opaqueRegion));
1782 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001783 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001784 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001786
Romain Guy0147a172017-06-01 13:53:56 -07001787mat4 SurfaceFlinger::computeSaturationMatrix() const {
1788 if (mSaturation == 1.0f) {
1789 return mat4();
1790 }
1791
1792 // Rec.709 luma coefficients
1793 float3 luminance{0.213f, 0.715f, 0.072f};
1794 luminance *= 1.0f - mSaturation;
1795 return mat4(
1796 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1797 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1798 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1799 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1800 );
1801}
1802
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001803// pickColorMode translates a given dataspace into the best available color mode.
1804// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001805android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001806 if (mForceNativeColorMode) {
1807 return HAL_COLOR_MODE_NATIVE;
1808 }
1809
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001810 switch (dataSpace) {
1811 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1812 // system expects.
1813 case HAL_DATASPACE_UNKNOWN:
1814 case HAL_DATASPACE_SRGB:
1815 case HAL_DATASPACE_V0_SRGB:
1816 return HAL_COLOR_MODE_SRGB;
1817 break;
1818
1819 case HAL_DATASPACE_DISPLAY_P3:
1820 return HAL_COLOR_MODE_DISPLAY_P3;
1821 break;
1822
1823 default:
1824 // TODO (courtneygo): Do we want to assert an error here?
1825 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1826 dataSpace);
1827 return HAL_COLOR_MODE_SRGB;
1828 break;
1829 }
1830}
1831
Romain Guy0147a172017-06-01 13:53:56 -07001832android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001833 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001834 // Only support sRGB and Display-P3 right now.
1835 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1836 return HAL_DATASPACE_DISPLAY_P3;
1837 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001838 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1839 return HAL_DATASPACE_DISPLAY_P3;
1840 }
1841 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1842 return HAL_DATASPACE_DISPLAY_P3;
1843 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001844 if (!hasHdr) {
1845 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1846 return HAL_DATASPACE_DISPLAY_P3;
1847 }
1848 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1849 return HAL_DATASPACE_DISPLAY_P3;
1850 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001851 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001852
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001853 return HAL_DATASPACE_V0_SRGB;
1854}
1855
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 ATRACE_CALL();
1858 ALOGV("setUpHWComposer");
1859
Jesse Hall028dc8f2013-08-20 16:35:32 -07001860 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001861 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1862 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1863 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1864
1865 // If nothing has changed (!dirty), don't recompose.
1866 // If something changed, but we don't currently have any visible layers,
1867 // and didn't when we last did a composition, then skip it this time.
1868 // The second rule does two things:
1869 // - When all layers are removed from a display, we'll emit one black
1870 // frame, then nothing more until we get new layers.
1871 // - When a display is created with a private layer stack, we won't
1872 // emit any black frames until a layer is added to the layer stack.
1873 bool mustRecompose = dirty && !(empty && wasEmpty);
1874
1875 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1876 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1877 mustRecompose ? "doing" : "skipping",
1878 dirty ? "+" : "-",
1879 empty ? "+" : "-",
1880 wasEmpty ? "+" : "-");
1881
Dan Stoza71433162014-02-04 16:22:36 -08001882 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001883
1884 if (mustRecompose) {
1885 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1886 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001887 }
1888
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 // build the h/w work list
1890 if (CC_UNLIKELY(mGeometryInvalid)) {
1891 mGeometryInvalid = false;
1892 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1893 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1894 const auto hwcId = displayDevice->getHwcDisplayId();
1895 if (hwcId >= 0) {
1896 const Vector<sp<Layer>>& currentLayers(
1897 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001898 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001899 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001901 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001904 }
1905 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001906
Robert Carrae060832016-11-28 10:51:00 -08001907 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001908 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001910 }
1911 }
1912 }
1913 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 }
Riley Andrews03414a12014-07-01 14:22:59 -07001915
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001916
Romain Guy0147a172017-06-01 13:53:56 -07001917 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001918
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 // Set the per-frame data
1920 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1921 auto& displayDevice = mDisplays[displayId];
1922 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001923
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 if (hwcId < 0) {
1925 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001926 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001927 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001928 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001929 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1930 "display %zd: %d", displayId, result);
1931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001933 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1934 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001935 !displayDevice->getHdrSupport()) {
1936 layer->forceClientComposition(hwcId);
1937 }
1938
chaviwc9232ed2017-11-14 15:31:15 -08001939 if (layer->getForceClientComposition(hwcId)) {
1940 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1941 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1942 continue;
1943 }
1944
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 layer->setPerFrameData(displayDevice);
1946 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001947
1948 if (hasWideColorDisplay) {
1949 android_color_mode newColorMode;
1950 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1951
1952 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001953 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1954 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001955 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1956 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1957 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1958 }
1959 newColorMode = pickColorMode(newDataSpace);
1960
Thierry Strudel2924d012017-08-14 15:19:37 -07001961 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001962 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 }
1964
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001965 mPreviousColorMatrix = colorMatrix;
1966
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001968 auto& displayDevice = mDisplays[displayId];
1969 if (!displayDevice->isDisplayOn()) {
1970 continue;
1971 }
1972
David Sodman105b7dc2017-11-04 20:28:14 -07001973 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1975 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001976 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001977}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001978
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979void SurfaceFlinger::doComposition() {
1980 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 ALOGV("doComposition");
1982
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001983 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001984 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001985 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001986 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001987 // transform the dirty region into this screen's coordinate space
1988 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001989
1990 // repaint the framebuffer (if needed)
1991 doDisplayComposition(hw, dirtyRegion);
1992
Mathias Agopiancd60f992012-08-16 16:28:27 -07001993 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001994 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001995 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001996 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001997 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001998}
1999
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002000void SurfaceFlinger::postFramebuffer()
2001{
Mathias Agopian841cde52012-03-01 15:44:37 -08002002 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002004
Mathias Agopiana44b0412011-10-16 18:46:35 -07002005 const nsecs_t now = systemTime();
2006 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002007
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2009 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002010 if (!displayDevice->isDisplayOn()) {
2011 continue;
2012 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 const auto hwcId = displayDevice->getHwcDisplayId();
2014 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002015 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002016 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002017 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002018 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002020 // The layer buffer from the previous frame (if any) is released
2021 // by HWC only when the release fence from this frame (if any) is
2022 // signaled. Always get the release fence from HWC first.
2023 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002024 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002025
2026 // If the layer was client composited in the previous frame, we
2027 // need to merge with the previous client target acquire fence.
2028 // Since we do not track that, always merge with the current
2029 // client target acquire fence when it is available, even though
2030 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002032 releaseFence = Fence::merge("LayerRelease", releaseFence,
2033 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002034 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002035
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 layer->onLayerDisplayed(releaseFence);
2037 }
Chia-I Wu83806892017-11-16 10:50:20 -08002038
2039 // We've got a list of layers needing fences, that are disjoint with
2040 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2041 // supply them with the present fence.
2042 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002043 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002044 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2045 layer->onLayerDisplayed(presentFence);
2046 }
2047 }
2048
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002050 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002051 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002052 }
2053
Mathias Agopiana44b0412011-10-16 18:46:35 -07002054 mLastSwapBufferTime = systemTime() - now;
2055 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002056
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002057 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002058 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2059 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2060 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2061 logFrameStats();
2062 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064}
2065
Mathias Agopian87baae12012-07-31 12:38:26 -07002066void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002067{
Mathias Agopian841cde52012-03-01 15:44:37 -08002068 ATRACE_CALL();
2069
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002070 // here we keep a copy of the drawing state (that is the state that's
2071 // going to be overwritten by handleTransactionLocked()) outside of
2072 // mStateLock so that the side-effects of the State assignment
2073 // don't happen with mStateLock held (which can cause deadlocks).
2074 State drawingState(mDrawingState);
2075
Mathias Agopianca4d3602011-05-19 15:38:14 -07002076 Mutex::Autolock _l(mStateLock);
2077 const nsecs_t now = systemTime();
2078 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079
Mathias Agopianca4d3602011-05-19 15:38:14 -07002080 // Here we're guaranteed that some transaction flags are set
2081 // so we can call handleTransactionLocked() unconditionally.
2082 // We call getTransactionFlags(), which will also clear the flags,
2083 // with mStateLock held to guarantee that mCurrentState won't change
2084 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002085
Mathias Agopiane57f2922012-08-09 16:29:12 -07002086 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002087 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002088
Mathias Agopianca4d3602011-05-19 15:38:14 -07002089 mLastTransactionTime = systemTime() - now;
2090 mDebugInTransaction = 0;
2091 invalidateHwcGeometry();
2092 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002093}
2094
Lloyd Pique715a2c12017-12-14 17:18:08 -08002095DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2096 HWC2::Connection connection) const {
2097 // Figure out whether the event is for the primary display or an
2098 // external display by matching the Hwc display id against one for a
2099 // connected display. If we did not find a match, we then check what
2100 // displays are not already connected to determine the type. If we don't
2101 // have a connected primary display, we assume the new display is meant to
2102 // be the primary display, and then if we don't have an external display,
2103 // we assume it is that.
2104 const auto primaryDisplayId =
2105 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2106 const auto externalDisplayId =
2107 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2108 if (primaryDisplayId && primaryDisplayId == display) {
2109 return DisplayDevice::DISPLAY_PRIMARY;
2110 } else if (externalDisplayId && externalDisplayId == display) {
2111 return DisplayDevice::DISPLAY_EXTERNAL;
2112 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2113 return DisplayDevice::DISPLAY_PRIMARY;
2114 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2115 return DisplayDevice::DISPLAY_EXTERNAL;
2116 }
2117
2118 return DisplayDevice::DISPLAY_ID_INVALID;
2119}
2120
Lloyd Piqueba04e622017-12-14 17:11:26 -08002121void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2122 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002123 auto displayType = determineDisplayType(event.display, event.connection);
2124 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2125 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2126 continue;
2127 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002128
2129 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2130 ALOGE("External displays are not supported by the vr hardware composer.");
2131 continue;
2132 }
2133
Lloyd Pique715a2c12017-12-14 17:18:08 -08002134 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002135
2136 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002137 ALOGV("Creating built in display %d", displayType);
2138 ALOGW_IF(mBuiltinDisplays[displayType],
2139 "Overwriting display token for display type %d", displayType);
2140 mBuiltinDisplays[displayType] = new BBinder();
2141 // All non-virtual displays are currently considered secure.
2142 DisplayDeviceState info(displayType, true);
2143 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2144 "Built-in Screen" : "External Screen";
2145 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2146 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002147 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002148 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002149
Lloyd Piquefcd86612017-12-14 17:15:36 -08002150 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2151 if (idx >= 0) {
2152 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2153 mInterceptor.saveDisplayDeletion(info.displayId);
2154 mCurrentState.displays.removeItemsAt(idx);
2155 }
2156 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002157 }
2158
2159 processDisplayChangesLocked();
2160 }
2161
2162 mPendingHotplugEvents.clear();
2163}
2164
Lloyd Pique347200f2017-12-14 17:00:15 -08002165void SurfaceFlinger::processDisplayChangesLocked() {
2166 // here we take advantage of Vector's copy-on-write semantics to
2167 // improve performance by skipping the transaction entirely when
2168 // know that the lists are identical
2169 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2170 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2171 if (!curr.isIdenticalTo(draw)) {
2172 mVisibleRegionsDirty = true;
2173 const size_t cc = curr.size();
2174 size_t dc = draw.size();
2175
2176 // find the displays that were removed
2177 // (ie: in drawing state but not in current state)
2178 // also handle displays that changed
2179 // (ie: displays that are in both lists)
2180 for (size_t i = 0; i < dc;) {
2181 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2182 if (j < 0) {
2183 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002184 // Call makeCurrent() on the primary display so we can
2185 // be sure that nothing associated with this display
2186 // is current.
2187 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2188 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2189 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2190 if (hw != nullptr) hw->disconnect(getHwComposer());
2191 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2192 mEventThread->onHotplugReceived(draw[i].type, false);
2193 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002194 } else {
2195 // this display is in both lists. see if something changed.
2196 const DisplayDeviceState& state(curr[j]);
2197 const wp<IBinder>& display(curr.keyAt(j));
2198 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2199 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2200 if (state_binder != draw_binder) {
2201 // changing the surface is like destroying and
2202 // recreating the DisplayDevice, so we just remove it
2203 // from the drawing state, so that it get re-added
2204 // below.
2205 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2206 if (hw != nullptr) hw->disconnect(getHwComposer());
2207 mDisplays.removeItem(display);
2208 mDrawingState.displays.removeItemsAt(i);
2209 dc--;
2210 // at this point we must loop to the next item
2211 continue;
2212 }
2213
2214 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2215 if (disp != nullptr) {
2216 if (state.layerStack != draw[i].layerStack) {
2217 disp->setLayerStack(state.layerStack);
2218 }
2219 if ((state.orientation != draw[i].orientation) ||
2220 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2221 disp->setProjection(state.orientation, state.viewport, state.frame);
2222 }
2223 if (state.width != draw[i].width || state.height != draw[i].height) {
2224 disp->setDisplaySize(state.width, state.height);
2225 }
2226 }
2227 }
2228 ++i;
2229 }
2230
2231 // find displays that were added
2232 // (ie: in current state but not in drawing state)
2233 for (size_t i = 0; i < cc; i++) {
2234 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2235 const DisplayDeviceState& state(curr[i]);
2236
2237 sp<DisplaySurface> dispSurface;
2238 sp<IGraphicBufferProducer> producer;
2239 sp<IGraphicBufferProducer> bqProducer;
2240 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002241 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002242
2243 int32_t hwcId = -1;
2244 if (state.isVirtualDisplay()) {
2245 // Virtual displays without a surface are dormant:
2246 // they have external state (layer stack, projection,
2247 // etc.) but no internal state (i.e. a DisplayDevice).
2248 if (state.surface != nullptr) {
2249 // Allow VR composer to use virtual displays.
2250 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2251 int width = 0;
2252 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2253 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2254 int height = 0;
2255 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2256 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2257 int intFormat = 0;
2258 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2259 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2260 auto format = static_cast<android_pixel_format_t>(intFormat);
2261
2262 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2263 }
2264
2265 // TODO: Plumb requested format back up to consumer
2266
2267 sp<VirtualDisplaySurface> vds =
2268 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2269 bqProducer, bqConsumer,
2270 state.displayName);
2271
2272 dispSurface = vds;
2273 producer = vds;
2274 }
2275 } else {
2276 ALOGE_IF(state.surface != nullptr,
2277 "adding a supported display, but rendering "
2278 "surface is provided (%p), ignoring it",
2279 state.surface.get());
2280
2281 hwcId = state.type;
2282 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2283 producer = bqProducer;
2284 }
2285
2286 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002287
Lloyd Pique347200f2017-12-14 17:00:15 -08002288 if (dispSurface != nullptr) {
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002289 bool hasWideColorSupport = false;
2290 if (hasWideColorDisplay) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002291 std::vector<android_color_mode_t> modes =
2292 getHwComposer().getColorModes(state.type);
2293 for (android_color_mode_t colorMode : modes) {
2294 switch (colorMode) {
2295 case HAL_COLOR_MODE_DISPLAY_P3:
2296 case HAL_COLOR_MODE_ADOBE_RGB:
2297 case HAL_COLOR_MODE_DCI_P3:
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002298 hasWideColorSupport = true;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002299 break;
2300 default:
2301 break;
2302 }
2303 }
Lloyd Piquefcd86612017-12-14 17:15:36 -08002304 }
2305
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002306 bool hasHdrSupport = false;
2307 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2308 getHwComposer().getHdrCapabilities(state.type);
2309 if (hdrCapabilities) {
2310 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2311 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2312 hasHdrSupport = iter != types.cend();
2313 }
2314
Lloyd Pique347200f2017-12-14 17:00:15 -08002315 sp<DisplayDevice> hw =
2316 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002317 dispSurface, producer, hasWideColorSupport,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002318 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002319
Lloyd Piquec5208312018-01-08 17:59:02 -08002320 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Chia-I Wu4b0e4dd2018-02-20 13:04:55 -08002321 if (hasWideColorSupport) {
Lloyd Piquec5208312018-01-08 17:59:02 -08002322 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002323 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002324 setActiveColorModeInternal(hw, defaultColorMode);
2325 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 hw->setLayerStack(state.layerStack);
2327 hw->setProjection(state.orientation, state.viewport, state.frame);
2328 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002329
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 mDisplays.add(display, hw);
2331 if (!state.isVirtualDisplay()) {
2332 mEventThread->onHotplugReceived(state.type, true);
2333 }
2334 }
2335 }
2336 }
2337 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002338
2339 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002340}
2341
Mathias Agopian87baae12012-07-31 12:38:26 -07002342void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002343{
Dan Stoza7dde5992015-05-22 09:51:44 -07002344 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002345 mCurrentState.traverseInZOrder([](Layer* layer) {
2346 layer->notifyAvailableFrames();
2347 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 /*
2350 * Traversal of the children
2351 * (perform the transaction for each of them if needed)
2352 */
2353
Mathias Agopian3559b072012-08-15 13:46:03 -07002354 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002355 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002357 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358
2359 const uint32_t flags = layer->doTransaction(0);
2360 if (flags & Layer::eVisibleRegion)
2361 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002362 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363 }
2364
2365 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002366 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367 */
2368
Mathias Agopiane57f2922012-08-09 16:29:12 -07002369 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002371 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002372 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373
Mathias Agopian84300952012-11-21 16:02:13 -08002374 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2375 // The transform hint might have changed for some layers
2376 // (either because a display has changed, or because a layer
2377 // as changed).
2378 //
2379 // Walk through all the layers in currentLayers,
2380 // and update their transform hint.
2381 //
2382 // If a layer is visible only on a single display, then that
2383 // display is used to calculate the hint, otherwise we use the
2384 // default display.
2385 //
2386 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2387 // the hint is set before we acquire a buffer from the surface texture.
2388 //
2389 // NOTE: layer transactions have taken place already, so we use their
2390 // drawing state. However, SurfaceFlinger's own transaction has not
2391 // happened yet, so we must use the current state layer list
2392 // (soon to become the drawing state list).
2393 //
2394 sp<const DisplayDevice> disp;
2395 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002396 bool first = true;
2397 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002398 // NOTE: we rely on the fact that layers are sorted by
2399 // layerStack first (so we don't have to traverse the list
2400 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002401 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002402 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002403 currentlayerStack = layerStack;
2404 // figure out if this layerstack is mirrored
2405 // (more than one display) if so, pick the default display,
2406 // if not, pick the only display it's on.
2407 disp.clear();
2408 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2409 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002410 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002411 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002412 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002413 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002414 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002415 break;
2416 }
2417 }
2418 }
2419 }
Chet Haase91d25932013-04-11 15:24:55 -07002420
Robert Carr56a0b9a2017-12-04 16:06:13 -08002421 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002422 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002423 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2424 // redraw after transform hint changes. See bug 8508397.
2425
2426 // could be null when this layer is using a layerStack
2427 // that is not visible on any display. Also can occur at
2428 // screen off/on times.
2429 disp = getDefaultDisplayDeviceLocked();
2430 }
2431 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002432 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002433 if (disp != nullptr) {
2434 layer->updateTransformHint(disp);
2435 }
Robert Carr2047fae2016-11-28 14:09:09 -08002436
2437 first = false;
2438 });
Mathias Agopian84300952012-11-21 16:02:13 -08002439 }
2440
2441
Mathias Agopian3559b072012-08-15 13:46:03 -07002442 /*
2443 * Perform our own transaction if needed
2444 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002445
2446 if (mLayersAdded) {
2447 mLayersAdded = false;
2448 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002449 mVisibleRegionsDirty = true;
2450 }
2451
2452 // some layers might have been removed, so
2453 // we need to update the regions they're exposing.
2454 if (mLayersRemoved) {
2455 mLayersRemoved = false;
2456 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002457 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002458 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002459 // this layer is not visible anymore
2460 // TODO: we could traverse the tree from front to back and
2461 // compute the actual visible region
2462 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002463 Region visibleReg;
2464 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002465 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002466 }
Robert Carr2047fae2016-11-28 14:09:09 -08002467 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468 }
2469
2470 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002471
2472 updateCursorAsync();
2473}
2474
2475void SurfaceFlinger::updateCursorAsync()
2476{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2478 auto& displayDevice = mDisplays[displayId];
2479 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002480 continue;
2481 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482
2483 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2484 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002485 }
2486 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002487}
2488
2489void SurfaceFlinger::commitTransaction()
2490{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002491 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002493 for (const auto& l : mLayersPendingRemoval) {
2494 recordBufferingStats(l->getName().string(),
2495 l->getOccupancyHistory(true));
2496 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002497 }
2498 mLayersPendingRemoval.clear();
2499 }
2500
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002501 // If this transaction is part of a window animation then the next frame
2502 // we composite should be considered an animation as well.
2503 mAnimCompositionPending = mAnimTransactionPending;
2504
Mathias Agopian4fec8732012-06-29 14:12:52 -07002505 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002506 mDrawingState.traverseInZOrder([](Layer* layer) {
2507 layer->commitChildList();
2508 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002509 mTransactionPending = false;
2510 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002511 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512}
2513
Chia-I Wuab0c3192017-08-01 11:29:00 -07002514void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002515 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516{
Mathias Agopian841cde52012-03-01 15:44:37 -08002517 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002518 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 Region aboveOpaqueLayers;
2521 Region aboveCoveredLayers;
2522 Region dirty;
2523
Mathias Agopian87baae12012-07-31 12:38:26 -07002524 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525
Robert Carr2047fae2016-11-28 14:09:09 -08002526 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002528 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529
Jesse Hall01e29052013-02-19 16:13:35 -08002530 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002531 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002532 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002533
Mathias Agopianab028732010-03-16 16:41:46 -07002534 /*
2535 * opaqueRegion: area of a surface that is fully opaque.
2536 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002538
2539 /*
2540 * visibleRegion: area of a surface that is visible on screen
2541 * and not fully transparent. This is essentially the layer's
2542 * footprint minus the opaque regions above it.
2543 * Areas covered by a translucent surface are considered visible.
2544 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002546
2547 /*
2548 * coveredRegion: area of a surface that is covered by all
2549 * visible regions above it (which includes the translucent areas).
2550 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002552
Jesse Halla8026d22012-09-25 13:25:04 -07002553 /*
2554 * transparentRegion: area of a surface that is hinted to be completely
2555 * transparent. This is only used to tell when the layer has no visible
2556 * non-transparent regions and can be removed from the layer list. It
2557 * does not affect the visibleRegion of this layer or any layers
2558 * beneath it. The hint may not be correct if apps don't respect the
2559 * SurfaceView restrictions (which, sadly, some don't).
2560 */
2561 Region transparentRegion;
2562
Mathias Agopianab028732010-03-16 16:41:46 -07002563
2564 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002565 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002566 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002569 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002570 if (!visibleRegion.isEmpty()) {
2571 // Remove the transparent area from the visible region
2572 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002573 if (tr.preserveRects()) {
2574 // transform the transparent region
2575 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002576 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002577 // transformation too complex, can't do the
2578 // transparent region optimization.
2579 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002580 }
Mathias Agopianab028732010-03-16 16:41:46 -07002581 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582
Mathias Agopianab028732010-03-16 16:41:46 -07002583 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002584 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002585 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002586 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2587 // the opaque region is the layer's footprint
2588 opaqueRegion = visibleRegion;
2589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 }
2591 }
2592
Robert Carre5f4f692018-01-12 13:12:28 -08002593 if (visibleRegion.isEmpty()) {
2594 layer->clearVisibilityRegions();
2595 return;
2596 }
2597
Mathias Agopianab028732010-03-16 16:41:46 -07002598 // Clip the covered region to the visible region
2599 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2600
2601 // Update aboveCoveredLayers for next (lower) layer
2602 aboveCoveredLayers.orSelf(visibleRegion);
2603
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604 // subtract the opaque region covered by the layers above us
2605 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
2607 // compute this layer's dirty region
2608 if (layer->contentDirty) {
2609 // we need to invalidate the whole region
2610 dirty = visibleRegion;
2611 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002612 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 layer->contentDirty = false;
2614 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002615 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002616 * the exposed region consists of two components:
2617 * 1) what's VISIBLE now and was COVERED before
2618 * 2) what's EXPOSED now less what was EXPOSED before
2619 *
2620 * note that (1) is conservative, we start with the whole
2621 * visible region but only keep what used to be covered by
2622 * something -- which mean it may have been exposed.
2623 *
2624 * (2) handles areas that were not covered by anything but got
2625 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002626 */
Mathias Agopianab028732010-03-16 16:41:46 -07002627 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628 const Region oldVisibleRegion = layer->visibleRegion;
2629 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002630 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2631 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 }
2633 dirty.subtractSelf(aboveOpaqueLayers);
2634
2635 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002636 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
Mathias Agopianab028732010-03-16 16:41:46 -07002638 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002640
Jesse Halla8026d22012-09-25 13:25:04 -07002641 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 layer->setVisibleRegion(visibleRegion);
2643 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002644 layer->setVisibleNonTransparentRegion(
2645 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002646 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647
Mathias Agopian87baae12012-07-31 12:38:26 -07002648 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649}
2650
Chia-I Wuab0c3192017-08-01 11:29:00 -07002651void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002652 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002653 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002654 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002655 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002656 }
2657 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002658}
2659
Dan Stoza6b9454d2014-11-07 16:00:59 -08002660bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 ALOGV("handlePageFlip");
2663
Brian Andersond6927fb2016-07-23 23:37:30 -07002664 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Mathias Agopian4fec8732012-06-29 14:12:52 -07002666 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002667 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002668 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002669
2670 // Store the set of layers that need updates. This set must not change as
2671 // buffers are being latched, as this could result in a deadlock.
2672 // Example: Two producers share the same command stream and:
2673 // 1.) Layer 0 is latched
2674 // 2.) Layer 0 gets a new frame
2675 // 2.) Layer 1 gets a new frame
2676 // 3.) Layer 1 is latched.
2677 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2678 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002679 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002680 if (layer->hasQueuedFrame()) {
2681 frameQueued = true;
2682 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002683 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002684 } else {
2685 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002686 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002687 } else {
2688 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689 }
Robert Carr2047fae2016-11-28 14:09:09 -08002690 });
2691
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002693 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002694 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002695 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002696 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002697 newDataLatched = true;
2698 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002699 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002700
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002701 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002702
2703 // If we will need to wake up at some time in the future to deal with a
2704 // queued frame that shouldn't be displayed during this vsync period, wake
2705 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002706 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002707 signalLayerUpdate();
2708 }
2709
2710 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002711 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Mathias Agopianad456f92011-01-13 17:53:01 -08002714void SurfaceFlinger::invalidateHwcGeometry()
2715{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002717}
2718
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002719
Fabien Sanglard830b8472016-11-30 16:35:58 -08002720void SurfaceFlinger::doDisplayComposition(
2721 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002722 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723{
Dan Stoza71433162014-02-04 16:22:36 -08002724 // We only need to actually compose the display if:
2725 // 1) It is being handled by hardware composer, which may need this to
2726 // keep its virtual display state machine in sync, or
2727 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002728 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002729 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002731 return;
2732 }
2733
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002735 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002736
2737 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002738 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739}
2740
Chia-I Wub02087d2017-11-09 10:19:54 -08002741bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002742{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002744
Chia-I Wub02087d2017-11-09 10:19:54 -08002745 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002746 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002748
2749 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002750 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2751 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002752 if (applyColorMatrix) {
2753 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2754 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2755 }
2756
David Sodman105b7dc2017-11-04 20:28:14 -07002757 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 if (hasClientComposition) {
2759 ALOGV("hasClientComposition");
2760
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002761 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002762 if (displayDevice->getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002763 displayDevice->getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
2764 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2765 }
2766 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2767
Chia-I Wu7f402902017-11-09 12:51:10 -08002768 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002769 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002771 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002772
2773 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002774 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002775 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2776 }
2777 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002778 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002779
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002780 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002781 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002783 // when using overlays, we assume a fully transparent framebuffer
2784 // NOTE: we could reduce how much we need to clear, for instance
2785 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002786 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002787 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002788 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002789 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002790 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002791 // we're left with the letterbox region
2792 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002794
2795 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002797
Mathias Agopianb9494d52012-04-18 02:28:45 -07002798 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002799 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002800 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002802 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002803 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002804
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002806 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002807 // scissor on the main display. It should never be needed
2808 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 const Rect& bounds(displayDevice->getBounds());
2810 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002811 if (scissor != bounds) {
2812 // scissor doesn't match the screen's dimensions, so we
2813 // need to clear everything outside of it and enable
2814 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002815
Mathias Agopianf45c5102012-10-24 16:29:17 -07002816 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002818 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002819 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002820 }
2821 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002822 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002823
Mathias Agopian85d751c2012-08-29 16:59:24 -07002824 /*
2825 * and then, render the layers targeted at the framebuffer
2826 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002827
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 ALOGV("Rendering client layers");
2829 const Transform& displayTransform = displayDevice->getTransform();
2830 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002831 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 bool firstLayer = true;
2833 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002834 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 displayTransform.transform(layer->visibleRegion)));
2836 ALOGV("Layer: %s", layer->getName().string());
2837 ALOGV(" Composition type: %s",
2838 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002839 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002840 switch (layer->getCompositionType(hwcId)) {
2841 case HWC2::Composition::Cursor:
2842 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002843 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002845 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002847 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002849 // never clear the very first layer since we're
2850 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002851 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002852 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002853 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002854 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002856 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002857 break;
2858 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002859 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002860 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002861 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002862 } else {
2863 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002864 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002866 }
2867 } else {
2868 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002870 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002871 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002872 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002873 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002874 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002875 }
2876 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002877
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002878 if (applyColorMatrix) {
2879 getRenderEngine().setupColorTransform(oldColorMatrix);
2880 }
2881
Mathias Agopianf45c5102012-10-24 16:29:17 -07002882 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002883 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002884 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885}
2886
Fabien Sanglard830b8472016-11-30 16:35:58 -08002887void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2888 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002889 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002890 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Dan Stoza7d89d062015-04-30 13:29:25 -07002893status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002894 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002895 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 const sp<Layer>& lbc,
2897 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002898{
Dan Stoza7d89d062015-04-30 13:29:25 -07002899 // add this layer to the current state list
2900 {
2901 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002902 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002903 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2904 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002905 return NO_MEMORY;
2906 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002907 if (parent == nullptr) {
2908 mCurrentState.layersSortedByZ.add(lbc);
2909 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002910 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002911 ALOGE("addClientLayer called with a removed parent");
2912 return NAME_NOT_FOUND;
2913 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 parent->addChild(lbc);
2915 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002916
Dan Stoza101d8dc2018-02-27 15:42:25 -08002917 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2918 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() > MAX_LAYERS,
2919 "Suspected IGBP leak");
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 mLayersAdded = true;
2921 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002922 }
2923
Mathias Agopian96f08192010-06-02 23:28:45 -07002924 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002925 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002926
Dan Stoza7d89d062015-04-30 13:29:25 -07002927 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002928}
2929
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002930status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002931 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002932 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2933}
Robert Carr7f9b8992017-03-10 11:08:39 -08002934
chaviwca27f252018-02-06 16:46:39 -08002935status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2936 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002937 if (layer->isPendingRemoval()) {
2938 return NO_ERROR;
2939 }
2940
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002942 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002943 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002944 if (topLevelOnly) {
2945 return NO_ERROR;
2946 }
2947
Chia-I Wu98f1c102017-05-30 14:54:08 -07002948 sp<Layer> ancestor = p;
2949 while (ancestor->getParent() != nullptr) {
2950 ancestor = ancestor->getParent();
2951 }
2952 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2953 ALOGE("removeLayer called with a layer whose parent has been removed");
2954 return NAME_NOT_FOUND;
2955 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002956
2957 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002958 } else {
2959 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002960 }
2961
Robert Carr136e2f62017-02-08 17:54:29 -08002962 // As a matter of normal operation, the LayerCleaner will produce a second
2963 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2964 // so we will succeed in promoting it, but it's already been removed
2965 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2966 // otherwise something has gone wrong and we are leaking the layer.
2967 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2969 layer->getName().string(),
2970 (p != nullptr) ? p->getName().string() : "no-parent");
2971 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002972 } else if (index < 0) {
2973 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002974 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002975
Chia-I Wuc6657022017-08-15 11:18:17 -07002976 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002977 mLayersPendingRemoval.add(layer);
2978 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002979 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002980 setTransactionFlags(eTransactionNeeded);
2981 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002984uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002985 return android_atomic_release_load(&mTransactionFlags);
2986}
2987
Mathias Agopian3f844832013-08-07 21:24:32 -07002988uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2990}
2991
Mathias Agopian3f844832013-08-07 21:24:32 -07002992uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2994 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002995 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996 }
2997 return old;
2998}
2999
chaviwca27f252018-02-06 16:46:39 -08003000bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3001 for (const ComposerState& state : states) {
3002 // Here we need to check that the interface we're given is indeed
3003 // one of our own. A malicious client could give us a nullptr
3004 // IInterface, or one of its own or even one of our own but a
3005 // different type. All these situations would cause us to crash.
3006 if (state.client == nullptr) {
3007 return true;
3008 }
3009
3010 sp<IBinder> binder = IInterface::asBinder(state.client);
3011 if (binder == nullptr) {
3012 return true;
3013 }
3014
3015 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3016 return true;
3017 }
3018 }
3019 return false;
3020}
3021
Mathias Agopian8b33f032012-07-24 20:43:54 -07003022void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003023 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003024 const Vector<DisplayState>& displays,
3025 uint32_t flags)
3026{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003027 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003028 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003029 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003030
chaviwca27f252018-02-06 16:46:39 -08003031 if (containsAnyInvalidClientState(states)) {
3032 return;
3033 }
3034
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003035 if (flags & eAnimation) {
3036 // For window updates that are part of an animation we must wait for
3037 // previous animation "frames" to be handled.
3038 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003039 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003040 if (CC_UNLIKELY(err != NO_ERROR)) {
3041 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003042 // caller after a few seconds.
3043 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3044 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003045 mAnimTransactionPending = false;
3046 break;
3047 }
3048 }
3049 }
3050
chaviwca27f252018-02-06 16:46:39 -08003051 for (const DisplayState& display : displays) {
3052 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003053 }
3054
chaviwca27f252018-02-06 16:46:39 -08003055 for (const ComposerState& state : states) {
3056 transactionFlags |= setClientStateLocked(state);
3057 }
3058
3059 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3060 // as destroyed should only occur after setting all other states. This is to allow for a
3061 // child re-parent to happen before marking its original parent as destroyed (which would
3062 // then mark the child as destroyed).
3063 for (const ComposerState& state : states) {
3064 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003065 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003066
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003067 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3068 // anyway. This can be used as a flush mechanism for previous async transactions.
3069 // Empty animation transaction can be used to simulate back-pressure, so also force a
3070 // transaction for empty animation transactions.
3071 if (transactionFlags == 0 &&
3072 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003073 transactionFlags = eTransactionNeeded;
3074 }
3075
Mathias Agopian386aa982011-11-07 21:58:03 -08003076 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003077 if (mInterceptor.isEnabled()) {
chaviwca27f252018-02-06 16:46:39 -08003078 mInterceptor.saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003079 }
Irvel468051e2016-06-13 16:44:44 -07003080
Mathias Agopian386aa982011-11-07 21:58:03 -08003081 // this triggers the transaction
3082 setTransactionFlags(transactionFlags);
3083
3084 // if this is a synchronous transaction, wait for it to take effect
3085 // before returning.
3086 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003087 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003088 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003089 if (flags & eAnimation) {
3090 mAnimTransactionPending = true;
3091 }
3092 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003093 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3094 if (CC_UNLIKELY(err != NO_ERROR)) {
3095 // just in case something goes wrong in SF, return to the
3096 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003097 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3098 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003099 break;
3100 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 }
3103}
3104
Mathias Agopiane57f2922012-08-09 16:29:12 -07003105uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3106{
Jesse Hall9a143922012-10-04 16:29:19 -07003107 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3108 if (dpyIdx < 0)
3109 return 0;
3110
Mathias Agopiane57f2922012-08-09 16:29:12 -07003111 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003112 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003113 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003114 const uint32_t what = s.what;
3115 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003116 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003117 disp.surface = s.surface;
3118 flags |= eDisplayTransactionNeeded;
3119 }
3120 }
3121 if (what & DisplayState::eLayerStackChanged) {
3122 if (disp.layerStack != s.layerStack) {
3123 disp.layerStack = s.layerStack;
3124 flags |= eDisplayTransactionNeeded;
3125 }
3126 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003127 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003128 if (disp.orientation != s.orientation) {
3129 disp.orientation = s.orientation;
3130 flags |= eDisplayTransactionNeeded;
3131 }
3132 if (disp.frame != s.frame) {
3133 disp.frame = s.frame;
3134 flags |= eDisplayTransactionNeeded;
3135 }
3136 if (disp.viewport != s.viewport) {
3137 disp.viewport = s.viewport;
3138 flags |= eDisplayTransactionNeeded;
3139 }
3140 }
Michael Lentine47e45402014-07-18 15:34:25 -07003141 if (what & DisplayState::eDisplaySizeChanged) {
3142 if (disp.width != s.width) {
3143 disp.width = s.width;
3144 flags |= eDisplayTransactionNeeded;
3145 }
3146 if (disp.height != s.height) {
3147 disp.height = s.height;
3148 flags |= eDisplayTransactionNeeded;
3149 }
3150 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003151 }
3152 return flags;
3153}
3154
chaviwca27f252018-02-06 16:46:39 -08003155uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3156 const layer_state_t& s = composerState.state;
3157 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3158
Mathias Agopian13127d82013-03-05 17:47:11 -08003159 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003160 if (layer == nullptr) {
3161 return 0;
3162 }
3163
3164 if (layer->isPendingRemoval()) {
3165 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3166 return 0;
3167 }
3168
3169 uint32_t flags = 0;
3170
3171 const uint32_t what = s.what;
3172 bool geometryAppliesWithResize =
3173 what & layer_state_t::eGeometryAppliesWithResize;
3174 if (what & layer_state_t::ePositionChanged) {
3175 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3176 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003177 }
chaviw8b3871a2017-11-01 17:41:01 -07003178 }
3179 if (what & layer_state_t::eLayerChanged) {
3180 // NOTE: index needs to be calculated before we update the state
3181 const auto& p = layer->getParent();
3182 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003183 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003184 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003185 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 }
chaviw8b3871a2017-11-01 17:41:01 -07003191 } else {
3192 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003193 flags |= eTransactionNeeded|eTraversalNeeded;
3194 }
3195 }
chaviw8b3871a2017-11-01 17:41:01 -07003196 }
3197 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003198 // NOTE: index needs to be calculated before we update the state
3199 const auto& p = layer->getParent();
3200 if (p == nullptr) {
3201 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3202 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3203 mCurrentState.layersSortedByZ.removeAt(idx);
3204 mCurrentState.layersSortedByZ.add(layer);
3205 // we need traversal (state changed)
3206 // AND transaction (list changed)
3207 flags |= eTransactionNeeded|eTraversalNeeded;
3208 }
3209 } else {
3210 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3211 flags |= eTransactionNeeded|eTraversalNeeded;
3212 }
chaviw8b3871a2017-11-01 17:41:01 -07003213 }
3214 }
3215 if (what & layer_state_t::eSizeChanged) {
3216 if (layer->setSize(s.w, s.h)) {
3217 flags |= eTraversalNeeded;
3218 }
3219 }
3220 if (what & layer_state_t::eAlphaChanged) {
3221 if (layer->setAlpha(s.alpha))
3222 flags |= eTraversalNeeded;
3223 }
3224 if (what & layer_state_t::eColorChanged) {
3225 if (layer->setColor(s.color))
3226 flags |= eTraversalNeeded;
3227 }
3228 if (what & layer_state_t::eMatrixChanged) {
3229 if (layer->setMatrix(s.matrix))
3230 flags |= eTraversalNeeded;
3231 }
3232 if (what & layer_state_t::eTransparentRegionChanged) {
3233 if (layer->setTransparentRegionHint(s.transparentRegion))
3234 flags |= eTraversalNeeded;
3235 }
3236 if (what & layer_state_t::eFlagsChanged) {
3237 if (layer->setFlags(s.flags, s.mask))
3238 flags |= eTraversalNeeded;
3239 }
3240 if (what & layer_state_t::eCropChanged) {
3241 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3242 flags |= eTraversalNeeded;
3243 }
3244 if (what & layer_state_t::eFinalCropChanged) {
3245 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3246 flags |= eTraversalNeeded;
3247 }
3248 if (what & layer_state_t::eLayerStackChanged) {
3249 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3250 // We only allow setting layer stacks for top level layers,
3251 // everything else inherits layer stack from its parent.
3252 if (layer->hasParent()) {
3253 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3254 layer->getName().string());
3255 } else if (idx < 0) {
3256 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3257 "that also does not appear in the top level layer list. Something"
3258 " has gone wrong.", layer->getName().string());
3259 } else if (layer->setLayerStack(s.layerStack)) {
3260 mCurrentState.layersSortedByZ.removeAt(idx);
3261 mCurrentState.layersSortedByZ.add(layer);
3262 // we need traversal (state changed)
3263 // AND transaction (list changed)
3264 flags |= eTransactionNeeded|eTraversalNeeded;
3265 }
3266 }
3267 if (what & layer_state_t::eDeferTransaction) {
3268 if (s.barrierHandle != nullptr) {
3269 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3270 } else if (s.barrierGbp != nullptr) {
3271 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3272 if (authenticateSurfaceTextureLocked(gbp)) {
3273 const auto& otherLayer =
3274 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3275 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3276 } else {
3277 ALOGE("Attempt to defer transaction to to an"
3278 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003279 }
3280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 // We don't trigger a traversal here because if no other state is
3282 // changed, we don't want this to cause any more work
3283 }
3284 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003285 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003286 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003287 if (!hadParent) {
3288 mCurrentState.layersSortedByZ.remove(layer);
3289 }
chaviw8b3871a2017-11-01 17:41:01 -07003290 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003291 }
chaviw8b3871a2017-11-01 17:41:01 -07003292 }
3293 if (what & layer_state_t::eReparentChildren) {
3294 if (layer->reparentChildren(s.reparentHandle)) {
3295 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003296 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003297 }
chaviw8b3871a2017-11-01 17:41:01 -07003298 if (what & layer_state_t::eDetachChildren) {
3299 layer->detachChildren();
3300 }
3301 if (what & layer_state_t::eOverrideScalingModeChanged) {
3302 layer->setOverrideScalingMode(s.overrideScalingMode);
3303 // We don't trigger a traversal here because if no other state is
3304 // changed, we don't want this to cause any more work
3305 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003306 return flags;
3307}
3308
chaviwca27f252018-02-06 16:46:39 -08003309void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3310 const layer_state_t& state = composerState.state;
3311 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3312
3313 sp<Layer> layer(client->getLayerUser(state.surface));
3314 if (layer == nullptr) {
3315 return;
3316 }
3317
3318 if (layer->isPendingRemoval()) {
3319 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3320 return;
3321 }
3322
3323 if (state.what & layer_state_t::eDestroySurface) {
3324 removeLayerLocked(mStateLock, layer);
3325 }
3326}
3327
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003328status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003329 const String8& name,
3330 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003331 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003332 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3333 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003335 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003336 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003337 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003338 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003339 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003340
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003341 status_t result = NO_ERROR;
3342
3343 sp<Layer> layer;
3344
Cody Northropbc755282017-03-31 12:00:08 -06003345 String8 uniqueName = getUniqueLayerName(name);
3346
Mathias Agopian3165cc22012-08-08 19:42:09 -07003347 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3348 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003349 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003350 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003351 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003352
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 break;
chaviw13fdc492017-06-27 12:40:18 -07003354 case ISurfaceComposerClient::eFXSurfaceColor:
3355 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003356 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003357 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003358 break;
3359 default:
3360 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361 break;
3362 }
3363
Dan Stoza7d89d062015-04-30 13:29:25 -07003364 if (result != NO_ERROR) {
3365 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003367
Chia-I Wuab0c3192017-08-01 11:29:00 -07003368 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3369 // TODO b/64227542
3370 if (windowType == 441731) {
3371 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3372 layer->setPrimaryDisplayOnly();
3373 }
3374
Albert Chaulk479c60c2017-01-27 14:21:34 -05003375 layer->setInfo(windowType, ownerUid);
3376
Robert Carr1f0a16a2016-10-24 16:27:39 -07003377 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003378 if (result != NO_ERROR) {
3379 return result;
3380 }
Irvelffc9efc2016-07-27 15:16:37 -07003381 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003382
3383 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003384 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003385}
3386
Cody Northropbc755282017-03-31 12:00:08 -06003387String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3388{
3389 bool matchFound = true;
3390 uint32_t dupeCounter = 0;
3391
3392 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3393 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3394
3395 // Loop over layers until we're sure there is no matching name
3396 while (matchFound) {
3397 matchFound = false;
3398 mDrawingState.traverseInZOrder([&](Layer* layer) {
3399 if (layer->getName() == uniqueName) {
3400 matchFound = true;
3401 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3402 }
3403 });
3404 }
3405
3406 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3407
3408 return uniqueName;
3409}
3410
David Sodman0c69cad2017-08-21 12:12:51 -07003411status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003412 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3413 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414{
3415 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003416 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003417 case PIXEL_FORMAT_TRANSPARENT:
3418 case PIXEL_FORMAT_TRANSLUCENT:
3419 format = PIXEL_FORMAT_RGBA_8888;
3420 break;
3421 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003422 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423 break;
3424 }
3425
David Sodman0c69cad2017-08-21 12:12:51 -07003426 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3427 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003428 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003429 *handle = layer->getHandle();
3430 *gbp = layer->getProducer();
3431 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003432 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003433
David Sodman0c69cad2017-08-21 12:12:51 -07003434 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003435 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003436}
3437
chaviw13fdc492017-06-27 12:40:18 -07003438status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003439 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003440 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003441{
chaviw13fdc492017-06-27 12:40:18 -07003442 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003443 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003444 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003445}
3446
Mathias Agopianac9fa422013-02-11 16:40:36 -08003447status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003448{
Robert Carr9524cb32017-02-13 11:32:32 -08003449 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003450 status_t err = NO_ERROR;
3451 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003452 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003453 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003454 err = removeLayer(l);
3455 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3456 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003457 }
3458 return err;
3459}
3460
Mathias Agopian13127d82013-03-05 17:47:11 -08003461status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003462{
Mathias Agopian67106042013-03-14 19:18:13 -07003463 // called by ~LayerCleaner() when all references to the IBinder (handle)
3464 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003465 sp<Layer> l = layer.promote();
3466 if (l == nullptr) {
3467 // The layer has already been removed, carry on
3468 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003469 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003470 // If we have a parent, then we can continue to live as long as it does.
3471 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472}
3473
Mathias Agopianb60314a2012-04-10 22:09:54 -07003474// ---------------------------------------------------------------------------
3475
Andy McFadden13a082e2012-08-24 10:16:42 -07003476void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003477 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003478 Vector<ComposerState> state;
3479 Vector<DisplayState> displays;
3480 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003481 d.what = DisplayState::eDisplayProjectionChanged |
3482 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003483 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003484 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003485 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003486 d.frame.makeInvalid();
3487 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003488 d.width = 0;
3489 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003490 displays.add(d);
3491 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003492 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3493 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003494
David Sodman105b7dc2017-11-04 20:28:14 -07003495 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003496 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003497 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003498
Brian Andersond0010582017-03-07 13:20:31 -08003499 // Use phase of 0 since phase is not known.
3500 // Use latency of 0, which will snap to the ideal latency.
3501 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003502}
3503
3504void SurfaceFlinger::initializeDisplays() {
3505 class MessageScreenInitialized : public MessageBase {
3506 SurfaceFlinger* flinger;
3507 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003508 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003509 virtual bool handler() {
3510 flinger->onInitializeDisplays();
3511 return true;
3512 }
3513 };
3514 sp<MessageBase> msg = new MessageScreenInitialized(this);
3515 postMessageAsync(msg); // we may be called from main thread, use async message
3516}
3517
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003518void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003519 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003520 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3521 this);
3522 int32_t type = hw->getDisplayType();
3523 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003524
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003525 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003526 return;
3527 }
3528
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003529 hw->setPowerMode(mode);
3530 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3531 ALOGW("Trying to set power mode for virtual display");
3532 return;
3533 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003534
Irvelffc9efc2016-07-27 15:16:37 -07003535 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003536 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003537 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3538 if (idx < 0) {
3539 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3540 return;
3541 }
3542 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3543 }
3544
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003545 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003546 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003547 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003548 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3549 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003550 // FIXME: eventthread only knows about the main display right now
3551 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003552 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003555 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003556 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003557 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003558
3559 struct sched_param param = {0};
3560 param.sched_priority = 1;
3561 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3562 ALOGW("Couldn't set SCHED_FIFO on display on");
3563 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003564 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003565 // Turn off the display
3566 struct sched_param param = {0};
3567 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3568 ALOGW("Couldn't set SCHED_OTHER on display off");
3569 }
3570
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003571 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3572 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003573 disableHardwareVsync(true); // also cancels any in-progress resync
3574
Mathias Agopiancde87a32012-09-13 14:09:01 -07003575 // FIXME: eventthread only knows about the main display right now
3576 mEventThread->onScreenReleased();
3577 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003578
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003579 getHwComposer().setPowerMode(type, mode);
3580 mVisibleRegionsDirty = true;
3581 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003582 } else if (mode == HWC_POWER_MODE_DOZE ||
3583 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003584 // Update display while dozing
3585 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003586 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3587 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003588 // FIXME: eventthread only knows about the main display right now
3589 mEventThread->onScreenAcquired();
3590 resyncToHardwareVsync(true);
3591 }
3592 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3593 // Leave display going to doze
3594 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3595 disableHardwareVsync(true); // also cancels any in-progress resync
3596 // FIXME: eventthread only knows about the main display right now
3597 mEventThread->onScreenReleased();
3598 }
3599 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003601 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003602 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003603 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003604}
3605
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003606void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3607 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003608 SurfaceFlinger& mFlinger;
3609 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003610 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003611 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003612 MessageSetPowerMode(SurfaceFlinger& flinger,
3613 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3614 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003615 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003616 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003617 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003618 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003619 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003620 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003621 ALOGW("Attempt to set power mode = %d for virtual display",
3622 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003623 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003624 mFlinger.setPowerModeInternal(
3625 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003626 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003627 return true;
3628 }
3629 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003630 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003631 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003632}
3633
3634// ---------------------------------------------------------------------------
3635
Lloyd Pique755e3192018-01-31 16:46:15 -08003636status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3637 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003639
Mathias Agopianbd115332013-04-18 16:41:04 -07003640 IPCThreadState* ipc = IPCThreadState::self();
3641 const int pid = ipc->getCallingPid();
3642 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003643
Mathias Agopianbd115332013-04-18 16:41:04 -07003644 if ((uid != AID_SHELL) &&
3645 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003646 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003647 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003649 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003650 // (this would indicate SF is stuck, but we want to be able to
3651 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003652 status_t err = mStateLock.timedLock(s2ns(1));
3653 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003654 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003655 result.appendFormat(
3656 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3657 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003658 }
3659
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003660 bool dumpAll = true;
3661 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003662 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003663
3664 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003665 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003666 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3667 dumpAll = false;
3668 }
3669
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003670 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003671 if ((index < numArgs) &&
3672 (args[index] == String16("--list"))) {
3673 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003674 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003675 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003676 }
3677
3678 if ((index < numArgs) &&
3679 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003680 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003681 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003682 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003683 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003684
3685 if ((index < numArgs) &&
3686 (args[index] == String16("--latency-clear"))) {
3687 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003688 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003689 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003690 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003691
3692 if ((index < numArgs) &&
3693 (args[index] == String16("--dispsync"))) {
3694 index++;
3695 mPrimaryDispSync.dump(result);
3696 dumpAll = false;
3697 }
Dan Stozab90cf072015-03-05 11:05:59 -08003698
3699 if ((index < numArgs) &&
3700 (args[index] == String16("--static-screen"))) {
3701 index++;
3702 dumpStaticScreenStats(result);
3703 dumpAll = false;
3704 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003705
3706 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003707 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003708 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003709 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003710 dumpAll = false;
3711 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003712
3713 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3714 index++;
3715 dumpWideColorInfo(result);
3716 dumpAll = false;
3717 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003718
3719 if ((index < numArgs) &&
3720 (args[index] == String16("--enable-layer-stats"))) {
3721 index++;
3722 mLayerStats.enable();
3723 dumpAll = false;
3724 }
3725
3726 if ((index < numArgs) &&
3727 (args[index] == String16("--disable-layer-stats"))) {
3728 index++;
3729 mLayerStats.disable();
3730 dumpAll = false;
3731 }
3732
3733 if ((index < numArgs) &&
3734 (args[index] == String16("--clear-layer-stats"))) {
3735 index++;
3736 mLayerStats.clear();
3737 dumpAll = false;
3738 }
3739
3740 if ((index < numArgs) &&
3741 (args[index] == String16("--dump-layer-stats"))) {
3742 index++;
3743 mLayerStats.dump(result);
3744 dumpAll = false;
3745 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003747
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003748 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003749 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003750 }
3751
Mathias Agopian9795c422009-08-26 16:36:26 -07003752 if (locked) {
3753 mStateLock.unlock();
3754 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 }
3756 write(fd, result.string(), result.size());
3757 return NO_ERROR;
3758}
3759
Dan Stozac7014012014-02-14 15:03:43 -08003760void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3761 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003762{
Robert Carr2047fae2016-11-28 14:09:09 -08003763 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003764 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003765 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003766}
3767
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003768void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003769 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770{
3771 String8 name;
3772 if (index < args.size()) {
3773 name = String8(args[index]);
3774 index++;
3775 }
3776
David Sodman105b7dc2017-11-04 20:28:14 -07003777 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003778 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003779 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003780
3781 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003782 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003783 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003784 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003785 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003786 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003787 }
Robert Carr2047fae2016-11-28 14:09:09 -08003788 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003789 }
3790}
3791
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003792void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003793 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003794{
3795 String8 name;
3796 if (index < args.size()) {
3797 name = String8(args[index]);
3798 index++;
3799 }
3800
Robert Carr2047fae2016-11-28 14:09:09 -08003801 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003802 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003803 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003804 }
Robert Carr2047fae2016-11-28 14:09:09 -08003805 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003806
Svetoslavd85084b2014-03-20 10:28:31 -07003807 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003808}
3809
Jamie Gennis6547ff42013-07-16 20:12:42 -07003810// This should only be called from the main thread. Otherwise it would need
3811// the lock and should use mCurrentState rather than mDrawingState.
3812void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003813 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003814 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003815 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003816
3817 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3818}
3819
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003820void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003821{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003822 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003823
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003824 if (isLayerTripleBufferingDisabled())
3825 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003826
3827 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003828 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003829 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003830 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003831 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3832 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003833 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003834}
3835
Dan Stozab90cf072015-03-05 11:05:59 -08003836void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3837{
3838 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003839 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3840 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003841 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003842 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003843 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3844 b + 1, bucketTimeSec, percent);
3845 }
David Sodman4a36e932017-11-07 14:29:47 -08003846 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003847 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003848 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003849 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003850 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003851}
3852
Dan Stozae77c7662016-05-13 11:37:28 -07003853void SurfaceFlinger::recordBufferingStats(const char* layerName,
3854 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003855 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3856 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003857 for (const auto& segment : history) {
3858 if (!segment.usedThirdBuffer) {
3859 stats.twoBufferTime += segment.totalTime;
3860 }
3861 if (segment.occupancyAverage < 1.0f) {
3862 stats.doubleBufferedTime += segment.totalTime;
3863 } else if (segment.occupancyAverage < 2.0f) {
3864 stats.tripleBufferedTime += segment.totalTime;
3865 }
3866 ++stats.numSegments;
3867 stats.totalTime += segment.totalTime;
3868 }
3869}
3870
Brian Andersond6927fb2016-07-23 23:37:30 -07003871void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3872 result.appendFormat("Layer frame timestamps:\n");
3873
3874 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3875 const size_t count = currentLayers.size();
3876 for (size_t i=0 ; i<count ; i++) {
3877 currentLayers[i]->dumpFrameEvents(result);
3878 }
3879}
3880
Dan Stozae77c7662016-05-13 11:37:28 -07003881void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3882 result.append("Buffering stats:\n");
3883 result.append(" [Layer name] <Active time> <Two buffer> "
3884 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003885 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003886 typedef std::tuple<std::string, float, float, float> BufferTuple;
3887 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003888 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003889 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003890 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003891 if (stats.numSegments == 0) {
3892 continue;
3893 }
3894 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3895 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3896 stats.totalTime;
3897 float doubleBufferRatio = static_cast<float>(
3898 stats.doubleBufferedTime) / stats.totalTime;
3899 float tripleBufferRatio = static_cast<float>(
3900 stats.tripleBufferedTime) / stats.totalTime;
3901 sorted.insert({activeTime, {name, twoBufferRatio,
3902 doubleBufferRatio, tripleBufferRatio}});
3903 }
3904 for (const auto& sortedPair : sorted) {
3905 float activeTime = sortedPair.first;
3906 const BufferTuple& values = sortedPair.second;
3907 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3908 std::get<0>(values).c_str(), activeTime,
3909 std::get<1>(values), std::get<2>(values),
3910 std::get<3>(values));
3911 }
3912 result.append("\n");
3913}
3914
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003915void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3916 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003917 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003918
3919 // TODO: print out if wide-color mode is active or not
3920
3921 for (size_t d = 0; d < mDisplays.size(); d++) {
3922 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3923 int32_t hwcId = displayDevice->getHwcDisplayId();
3924 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3925 continue;
3926 }
3927
3928 result.appendFormat("Display %d color modes:\n", hwcId);
3929 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3930 for (auto&& mode : modes) {
3931 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3932 }
3933
3934 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3935 result.appendFormat(" Current color mode: %s (%d)\n",
3936 decodeColorMode(currentMode).c_str(), currentMode);
3937 }
3938 result.append("\n");
3939}
3940
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003941LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003942 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003943 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3944 const State& state = useDrawing ? mDrawingState : mCurrentState;
3945 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003946 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003947 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003948 });
3949
3950 return layersProto;
3951}
3952
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003953LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
3954 LayersProto layersProto;
3955
3956 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
3957 SizeProto* resolution = layersProto.mutable_resolution();
3958 resolution->set_w(displayDevice->getWidth());
3959 resolution->set_h(displayDevice->getHeight());
3960
3961 mDrawingState.traverseInZOrder([&](Layer* layer) {
3962 if (!layer->visibleRegion.isEmpty() &&
3963 layer->getBE().mHwcLayers.count(hwcId)) {
3964 LayerProto* layerProto = layersProto.add_layers();
3965 layer->writeToProto(layerProto, hwcId);
3966 }
3967 });
3968
3969 return layersProto;
3970}
3971
Mathias Agopian74d211a2013-04-22 16:55:35 +02003972void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3973 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003975 bool colorize = false;
3976 if (index < args.size()
3977 && (args[index] == String16("--color"))) {
3978 colorize = true;
3979 index++;
3980 }
3981
3982 Colorizer colorizer(colorize);
3983
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003984 // figure out if we're stuck somewhere
3985 const nsecs_t now = systemTime();
3986 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3987 const nsecs_t inTransaction(mDebugInTransaction);
3988 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3989 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3990
3991 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003992 * Dump library configuration.
3993 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003994
3995 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003996 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003997 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003998 appendSfConfigString(result);
3999 appendUiConfigString(result);
4000 appendGuiConfigString(result);
4001 result.append("\n");
4002
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004003 result.append("\nWide-Color information:\n");
4004 dumpWideColorInfo(result);
4005
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004006 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004007 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004008 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004009 result.append(SyncFeatures::getInstance().toString());
4010 result.append("\n");
4011
David Sodman105b7dc2017-11-04 20:28:14 -07004012 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004013
Andy McFadden41d67d72014-04-25 16:58:34 -07004014 colorizer.bold(result);
4015 result.append("DispSync configuration: ");
4016 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004017 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004018 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004019 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004020 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004021 result.append("\n");
4022
Dan Stozab90cf072015-03-05 11:05:59 -08004023 // Dump static screen stats
4024 result.append("\n");
4025 dumpStaticScreenStats(result);
4026 result.append("\n");
4027
Dan Stozae77c7662016-05-13 11:37:28 -07004028 dumpBufferingStats(result);
4029
Andy McFadden4803b742012-09-24 19:07:20 -07004030 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004031 * Dump the visible layer list
4032 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004033 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004034 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004035 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004036
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004037 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004038 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4039 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040
4041 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004042 * Dump Display state
4043 */
4044
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004045 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004046 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004047 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004048 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4049 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004050 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004051 }
4052
4053 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004054 * Dump SurfaceFlinger global state
4055 */
4056
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004057 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004058 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004059 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004060
Mathias Agopian888c8222012-08-04 21:10:38 -07004061 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004062 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004063
David Sodmanbc815282017-11-05 18:57:52 -08004064 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004065
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004066 if (hw) {
4067 hw->undefinedRegion.dump(result, "undefinedRegion");
4068 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4069 hw->getOrientation(), hw->isDisplayOn());
4070 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004071 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004072 " last eglSwapBuffers() time: %f us\n"
4073 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004074 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004075 " refresh-rate : %f fps\n"
4076 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004077 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004078 " gpu_to_cpu_unsupported : %d\n"
4079 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004080 mLastSwapBufferTime/1000.0,
4081 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004082 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004083 1e9 / activeConfig->getVsyncPeriod(),
4084 activeConfig->getDpiX(),
4085 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004086 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004087
Mathias Agopian74d211a2013-04-22 16:55:35 +02004088 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004089 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004090
Mathias Agopian74d211a2013-04-22 16:55:35 +02004091 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004092 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004093
4094 /*
4095 * VSYNC state
4096 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004097 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004098 result.append("\n");
4099
4100 /*
4101 * HWC layer minidump
4102 */
4103 for (size_t d = 0; d < mDisplays.size(); d++) {
4104 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4105 int32_t hwcId = displayDevice->getHwcDisplayId();
4106 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4107 continue;
4108 }
4109
4110 result.appendFormat("Display %d HWC layers:\n", hwcId);
4111 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004112 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004113 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004114 });
Dan Stozae22aec72016-08-01 13:20:59 -07004115 result.append("\n");
4116 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004117
4118 /*
4119 * Dump HWComposer state
4120 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004121 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004122 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004123 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004124 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004125 result.appendFormat(" h/w composer %s\n",
4126 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004127 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004128
4129 /*
4130 * Dump gralloc state
4131 */
4132 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4133 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004134
4135 /*
4136 * Dump VrFlinger state if in use.
4137 */
4138 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4139 result.append("VrFlinger state:\n");
4140 result.append(mVrFlinger->Dump().c_str());
4141 result.append("\n");
4142 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004143}
4144
Mathias Agopian13127d82013-03-05 17:47:11 -08004145const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004146SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004147 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004148 wp<IBinder> dpy;
4149 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4150 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4151 dpy = mDisplays.keyAt(i);
4152 break;
4153 }
4154 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004155 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004156 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4157 // Just use the primary display so we have something to return
4158 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4159 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004160 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004161}
4162
Keun young Park63f165f2012-08-31 10:53:36 -07004163bool SurfaceFlinger::startDdmConnection()
4164{
4165 void* libddmconnection_dso =
4166 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4167 if (!libddmconnection_dso) {
4168 return false;
4169 }
4170 void (*DdmConnection_start)(const char* name);
4171 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004172 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004173 if (!DdmConnection_start) {
4174 dlclose(libddmconnection_dso);
4175 return false;
4176 }
4177 (*DdmConnection_start)(getServiceName());
4178 return true;
4179}
4180
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004181status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 switch (code) {
4183 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004184 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004186 case CLEAR_ANIMATION_FRAME_STATS:
4187 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004188 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004189 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004190 case ENABLE_VSYNC_INJECTIONS:
4191 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192 {
4193 // codes that require permission check
4194 IPCThreadState* ipc = IPCThreadState::self();
4195 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004196 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004197 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004198 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004199 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004200 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004201 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004202 break;
4203 }
Robert Carr1db73f62016-12-21 12:58:51 -08004204 /*
4205 * Calling setTransactionState is safe, because you need to have been
4206 * granted a reference to Client* and Handle* to do anything with it.
4207 *
4208 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4209 */
4210 case SET_TRANSACTION_STATE:
4211 case CREATE_SCOPED_CONNECTION:
4212 {
4213 return OK;
4214 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004215 case CAPTURE_SCREEN:
4216 {
4217 // codes that require permission check
4218 IPCThreadState* ipc = IPCThreadState::self();
4219 const int pid = ipc->getCallingPid();
4220 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004221 if ((uid != AID_GRAPHICS) &&
4222 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004223 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004224 return PERMISSION_DENIED;
4225 }
4226 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004227 }
chaviwa76b2712017-09-20 12:02:26 -07004228 case CAPTURE_LAYERS: {
4229 IPCThreadState* ipc = IPCThreadState::self();
4230 const int pid = ipc->getCallingPid();
4231 const int uid = ipc->getCallingUid();
4232 if ((uid != AID_GRAPHICS) &&
4233 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4234 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4235 return PERMISSION_DENIED;
4236 }
4237 break;
4238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004239 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004240 return OK;
4241}
4242
4243status_t SurfaceFlinger::onTransact(
4244 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4245{
4246 status_t credentialCheck = CheckTransactCodeCredentials(code);
4247 if (credentialCheck != OK) {
4248 return credentialCheck;
4249 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004250
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4252 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004253 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004254 IPCThreadState* ipc = IPCThreadState::self();
4255 const int uid = ipc->getCallingUid();
4256 if (CC_UNLIKELY(uid != AID_SYSTEM
4257 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004258 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004259 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004260 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004261 return PERMISSION_DENIED;
4262 }
4263 int n;
4264 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004265 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004266 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004267 return NO_ERROR;
4268 case 1002: // SHOW_UPDATES
4269 n = data.readInt32();
4270 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004271 invalidateHwcGeometry();
4272 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004275 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004276 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004277 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004278 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004279 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004280 setTransactionFlags(
4281 eTransactionNeeded|
4282 eDisplayTransactionNeeded|
4283 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004284 return NO_ERROR;
4285 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004286 case 1006:{ // send empty update
4287 signalRefresh();
4288 return NO_ERROR;
4289 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004290 case 1008: // toggle use of hw composer
4291 n = data.readInt32();
4292 mDebugDisableHWC = n ? 1 : 0;
4293 invalidateHwcGeometry();
4294 repaintEverything();
4295 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004296 case 1009: // toggle use of transform hint
4297 n = data.readInt32();
4298 mDebugDisableTransformHint = n ? 1 : 0;
4299 invalidateHwcGeometry();
4300 repaintEverything();
4301 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004303 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004304 reply->writeInt32(0);
4305 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004306 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004307 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 return NO_ERROR;
4309 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004310 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004311 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004312 return NO_ERROR;
4313 }
4314 case 1014: {
4315 // daltonize
4316 n = data.readInt32();
4317 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004318 case 1:
4319 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4320 break;
4321 case 2:
4322 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4323 break;
4324 case 3:
4325 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4326 break;
4327 default:
4328 mDaltonizer.setType(ColorBlindnessType::None);
4329 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004330 }
4331 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004332 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004333 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004334 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004335 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004336 invalidateHwcGeometry();
4337 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004338 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004339 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004340 case 1015: {
4341 // apply a color matrix
4342 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004343 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004344 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004345 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004346 for (size_t j = 0; j < 4; j++) {
4347 mColorMatrix[i][j] = data.readFloat();
4348 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004349 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004350 } else {
4351 mColorMatrix = mat4();
4352 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004353
4354 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4355 // the division by w in the fragment shader
4356 float4 lastRow(transpose(mColorMatrix)[3]);
4357 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4358 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4359 }
4360
Alan Viverette9c5a3332013-09-12 20:04:35 -07004361 invalidateHwcGeometry();
4362 repaintEverything();
4363 return NO_ERROR;
4364 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004365 // This is an experimental interface
4366 // Needs to be shifted to proper binder interface when we productize
4367 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004368 n = data.readInt32();
4369 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004370 return NO_ERROR;
4371 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004372 case 1017: {
4373 n = data.readInt32();
4374 mForceFullDamage = static_cast<bool>(n);
4375 return NO_ERROR;
4376 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004377 case 1018: { // Modify Choreographer's phase offset
4378 n = data.readInt32();
4379 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4380 return NO_ERROR;
4381 }
4382 case 1019: { // Modify SurfaceFlinger's phase offset
4383 n = data.readInt32();
4384 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4385 return NO_ERROR;
4386 }
Irvel468051e2016-06-13 16:44:44 -07004387 case 1020: { // Layer updates interceptor
4388 n = data.readInt32();
4389 if (n) {
4390 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004391 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004392 }
4393 else{
4394 ALOGV("Interceptor disabled");
4395 mInterceptor.disable();
4396 }
4397 return NO_ERROR;
4398 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004399 case 1021: { // Disable HWC virtual displays
4400 n = data.readInt32();
4401 mUseHwcVirtualDisplays = !n;
4402 return NO_ERROR;
4403 }
Romain Guy0147a172017-06-01 13:53:56 -07004404 case 1022: { // Set saturation boost
4405 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4406
4407 invalidateHwcGeometry();
4408 repaintEverything();
4409 return NO_ERROR;
4410 }
Romain Guy54f154a2017-10-24 21:40:32 +01004411 case 1023: { // Set native mode
4412 mForceNativeColorMode = data.readInt32() == 1;
4413
4414 invalidateHwcGeometry();
4415 repaintEverything();
4416 return NO_ERROR;
4417 }
4418 case 1024: { // Is wide color gamut rendering/color management supported?
4419 reply->writeBool(hasWideColorDisplay);
4420 return NO_ERROR;
4421 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004422 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004423 n = data.readInt32();
4424 if (n) {
4425 ALOGV("LayerTracing enabled");
4426 mTracing.enable();
4427 doTracing("tracing.enable");
4428 reply->writeInt32(NO_ERROR);
4429 } else {
4430 ALOGV("LayerTracing disabled");
4431 status_t err = mTracing.disable();
4432 reply->writeInt32(err);
4433 }
4434 return NO_ERROR;
4435 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004436 case 1026: { // Get layer tracing status
4437 reply->writeBool(mTracing.isEnabled());
4438 return NO_ERROR;
4439 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004440 }
4441 }
4442 return err;
4443}
4444
Steven Thomas6d8110b2017-08-31 18:24:21 -07004445void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004446 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004447 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004448}
4449
Steven Thomas6d8110b2017-08-31 18:24:21 -07004450void SurfaceFlinger::repaintEverything() {
4451 ConditionalLock _l(mStateLock,
4452 std::this_thread::get_id() != mMainThreadId);
4453 repaintEverythingLocked();
4454}
4455
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004456// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4457class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004458public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004459 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4460 ~WindowDisconnector() {
4461 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004462 }
4463
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004464private:
4465 ANativeWindow* mWindow;
4466 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004467};
4468
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004469status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4470 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4471 int32_t minLayerZ, int32_t maxLayerZ,
4472 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004473 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004474 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004475
chaviwa76b2712017-09-20 12:02:26 -07004476 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4477
4478 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4479 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4480
4481 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4482 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004483 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004484}
4485
4486status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004487 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004488 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004489 ATRACE_CALL();
4490
4491 class LayerRenderArea : public RenderArea {
4492 public:
chaviw7206d492017-11-10 16:16:12 -08004493 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004494 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004495 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004496 const Transform& getTransform() const override {
4497 // Make the top level transform the inverse the transform and it's parent so it sets
4498 // the whole capture back to 0,0
4499 return *new Transform(mLayer->getTransform().inverse());
4500 }
4501 Rect getBounds() const override {
4502 const Layer::State& layerState(mLayer->getDrawingState());
4503 return Rect(layerState.active.w, layerState.active.h);
4504 }
4505 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4506 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4507 bool isSecure() const override { return false; }
4508 bool needsFiltering() const override { return false; }
4509
chaviw7206d492017-11-10 16:16:12 -08004510 Rect getSourceCrop() const override {
4511 if (mCrop.isEmpty()) {
4512 return getBounds();
4513 } else {
4514 return mCrop;
4515 }
4516 }
chaviwa76b2712017-09-20 12:02:26 -07004517 bool getWideColorSupport() const override { return false; }
4518 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4519
4520 private:
chaviw7206d492017-11-10 16:16:12 -08004521 const sp<Layer> mLayer;
4522 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004523 };
4524
4525 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4526 auto parent = layerHandle->owner.promote();
4527
chaviw7206d492017-11-10 16:16:12 -08004528 if (parent == nullptr || parent->isPendingRemoval()) {
4529 ALOGE("captureLayers called with a removed parent");
4530 return NAME_NOT_FOUND;
4531 }
4532
4533 Rect crop(sourceCrop);
4534 if (sourceCrop.width() <= 0) {
4535 crop.left = 0;
4536 crop.right = parent->getCurrentState().active.w;
4537 }
4538
4539 if (sourceCrop.height() <= 0) {
4540 crop.top = 0;
4541 crop.bottom = parent->getCurrentState().active.h;
4542 }
4543
4544 int32_t reqWidth = crop.width() * frameScale;
4545 int32_t reqHeight = crop.height() * frameScale;
4546
4547 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4548
chaviwa76b2712017-09-20 12:02:26 -07004549 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4550 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4551 if (!layer->isVisible()) {
4552 return;
4553 }
4554 visitor(layer);
4555 });
4556 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004557 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004558}
4559
4560status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4561 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004562 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004563 bool useIdentityTransform) {
4564 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004565
chaviwa76b2712017-09-20 12:02:26 -07004566 renderArea.updateDimensions();
4567
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004568 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4569 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4570 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4571 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004572
4573 // This mutex protects syncFd and captureResult for communication of the return values from the
4574 // main thread back to this Binder thread
4575 std::mutex captureMutex;
4576 std::condition_variable captureCondition;
4577 std::unique_lock<std::mutex> captureLock(captureMutex);
4578 int syncFd = -1;
4579 std::optional<status_t> captureResult;
4580
Robert Carr03480e22018-01-04 16:02:06 -08004581 const int uid = IPCThreadState::self()->getCallingUid();
4582 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4583
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004584 sp<LambdaMessage> message = new LambdaMessage([&]() {
4585 // If there is a refresh pending, bug out early and tell the binder thread to try again
4586 // after the refresh.
4587 if (mRefreshPending) {
4588 ATRACE_NAME("Skipping screenshot for now");
4589 std::unique_lock<std::mutex> captureLock(captureMutex);
4590 captureResult = std::make_optional<status_t>(EAGAIN);
4591 captureCondition.notify_one();
4592 return;
4593 }
4594
4595 status_t result = NO_ERROR;
4596 int fd = -1;
4597 {
4598 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004599 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004600 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004601 }
4602
4603 {
4604 std::unique_lock<std::mutex> captureLock(captureMutex);
4605 syncFd = fd;
4606 captureResult = std::make_optional<status_t>(result);
4607 captureCondition.notify_one();
4608 }
4609 });
4610
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004611 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004612 if (result == NO_ERROR) {
4613 captureCondition.wait(captureLock, [&]() { return captureResult; });
4614 while (*captureResult == EAGAIN) {
4615 captureResult.reset();
4616 result = postMessageAsync(message);
4617 if (result != NO_ERROR) {
4618 return result;
4619 }
4620 captureCondition.wait(captureLock, [&]() { return captureResult; });
4621 }
4622 result = *captureResult;
4623 }
4624
4625 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004626 sync_wait(syncFd, -1);
4627 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004628 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004629
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004630 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004631}
4632
chaviwa76b2712017-09-20 12:02:26 -07004633void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4634 TraverseLayersFunction traverseLayers, bool yswap,
4635 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004636 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004637
Lloyd Pique144e1162017-12-20 16:44:52 -08004638 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004639
4640 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004641 const auto raWidth = renderArea.getWidth();
4642 const auto raHeight = renderArea.getHeight();
4643
4644 const auto reqWidth = renderArea.getReqWidth();
4645 const auto reqHeight = renderArea.getReqHeight();
4646 Rect sourceCrop = renderArea.getSourceCrop();
4647
4648 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4649 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004650
Dan Stozac1879002014-05-22 15:59:05 -07004651 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004652 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004653 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004654 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004655 }
4656
4657 // ensure that sourceCrop is inside screen
4658 if (sourceCrop.left < 0) {
4659 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4660 }
chaviwa76b2712017-09-20 12:02:26 -07004661 if (sourceCrop.right > raWidth) {
4662 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004663 }
4664 if (sourceCrop.top < 0) {
4665 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4666 }
chaviwa76b2712017-09-20 12:02:26 -07004667 if (sourceCrop.bottom > raHeight) {
4668 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004669 }
4670
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004671 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004672 if (renderArea.getWideColorSupport() &&
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004673 renderArea.getActiveColorMode() == HAL_COLOR_MODE_DISPLAY_P3) {
4674 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4675 }
4676 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004677
Mathias Agopian180f10d2013-04-10 22:55:41 -07004678 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004679 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004680
4681 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004682 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4683 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004684 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004685
4686 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004687 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004688
chaviwa76b2712017-09-20 12:02:26 -07004689 traverseLayers([&](Layer* layer) {
4690 if (filtering) layer->setFiltering(true);
4691 layer->draw(renderArea, useIdentityTransform);
4692 if (filtering) layer->setFiltering(false);
4693 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004694}
4695
chaviwa76b2712017-09-20 12:02:26 -07004696status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4697 TraverseLayersFunction traverseLayers,
4698 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004699 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004700 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004701 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004702 ATRACE_CALL();
4703
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004704 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004705
4706 traverseLayers([&](Layer* layer) {
4707 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4708 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004709
Robert Carr03480e22018-01-04 16:02:06 -08004710 // We allow the system server to take screenshots of secure layers for
4711 // use in situations like the Screen-rotation animation and place
4712 // the impetus on WindowManager to not persist them.
4713 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004714 ALOGW("FB is protected: PERMISSION_DENIED");
4715 return PERMISSION_DENIED;
4716 }
4717
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004718 // this binds the given EGLImage as a framebuffer for the
4719 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004720 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004721 if (bufferBond.getStatus() != NO_ERROR) {
4722 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004723 return INVALID_OPERATION;
4724 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004725
Dan Stozaabcda352017-06-01 14:37:39 -07004726 // this will in fact render into our dequeued buffer
4727 // via an FBO, which means we didn't have to create
4728 // an EGLSurface and therefore we're not
4729 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004730 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004731
Dan Stozaabcda352017-06-01 14:37:39 -07004732 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004733 getRenderEngine().finish();
4734 *outSyncFd = -1;
4735
chaviwa76b2712017-09-20 12:02:26 -07004736 const auto reqWidth = renderArea.getReqWidth();
4737 const auto reqHeight = renderArea.getReqHeight();
4738
Dan Stozaabcda352017-06-01 14:37:39 -07004739 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4740 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004741 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004742 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004743 } else {
4744 base::unique_fd syncFd = getRenderEngine().flush();
4745 if (syncFd < 0) {
4746 getRenderEngine().finish();
4747 }
4748 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004749 }
4750
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004751 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004752}
4753
Mathias Agopiand5556842013-09-19 17:08:37 -07004754void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004755 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004756 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004757 for (size_t y = 0; y < h; y++) {
4758 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4759 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004760 if (p[x] != 0xFF000000) return;
4761 }
4762 }
chaviwa76b2712017-09-20 12:02:26 -07004763 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004764
Robert Carr2047fae2016-11-28 14:09:09 -08004765 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004766 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004767 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004768 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4769 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4770 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4771 static_cast<float>(state.color.a));
4772 i++;
4773 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004774 }
4775}
4776
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004777// ---------------------------------------------------------------------------
4778
Dan Stoza412903f2017-04-27 13:42:17 -07004779void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4780 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004781}
4782
Dan Stoza412903f2017-04-27 13:42:17 -07004783void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4784 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004785}
4786
chaviwa76b2712017-09-20 12:02:26 -07004787void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4788 int32_t maxLayerZ,
4789 const LayerVector::Visitor& visitor) {
4790 // We loop through the first level of layers without traversing,
4791 // as we need to interpret min/max layer Z in the top level Z space.
4792 for (const auto& layer : mDrawingState.layersSortedByZ) {
4793 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4794 continue;
4795 }
4796 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004797 // relative layers are traversed in Layer::traverseInZOrder
4798 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004799 continue;
4800 }
4801 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004802 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4803 return;
4804 }
chaviwa76b2712017-09-20 12:02:26 -07004805 if (!layer->isVisible()) {
4806 return;
4807 }
4808 visitor(layer);
4809 });
4810 }
4811}
4812
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004813}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004814
4815
4816#if defined(__gl_h_)
4817#error "don't include gl/gl.h in this file"
4818#endif
4819
4820#if defined(__gl2_h_)
4821#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004822#endif