blob: a91525d8d0b96baf7e063857217d34c46eb42601 [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()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700166 : 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),
David Sodman105b7dc2017-11-04 20:28:14 -0700196 mMainThreadId(std::this_thread::get_id())
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
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 {
Mathias Agopian3f844832013-08-07 21:24:32 -0700413 RenderEngine& engine;
414 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700415 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700416 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
417 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 }
419 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 return true;
422 }
423 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425}
426
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427class DispSyncSource : public VSyncSource, private DispSync::Callback {
428public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* name) :
431 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
435 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 mDispSync(dispSync),
437 mCallbackMutex(),
438 mCallback(),
439 mVsyncMutex(),
440 mPhaseOffset(phaseOffset),
441 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700442
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 virtual ~DispSyncSource() {}
444
445 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 static_cast<DispSync::Callback*>(this));
450 if (err != NO_ERROR) {
451 ALOGE("error registering vsync callback: %s (%d)",
452 strerror(-err), err);
453 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 } else {
456 status_t err = mDispSync->removeEventListener(
457 static_cast<DispSync::Callback*>(this));
458 if (err != NO_ERROR) {
459 ALOGE("error unregistering vsync callback: %s (%d)",
460 strerror(-err), err);
461 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700462 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700464 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 }
466
467 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 mCallback = callback;
470 }
471
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 virtual void setPhaseOffset(nsecs_t phaseOffset) {
473 Mutex::Autolock lock(mVsyncMutex);
474
475 // Normalize phaseOffset to [0, period)
476 auto period = mDispSync->getPeriod();
477 phaseOffset %= period;
478 if (phaseOffset < 0) {
479 // If we're here, then phaseOffset is in (-period, 0). After this
480 // operation, it will be in (0, period)
481 phaseOffset += period;
482 }
483 mPhaseOffset = phaseOffset;
484
485 // If we're not enabled, we don't need to mess with the listeners
486 if (!mEnabled) {
487 return;
488 }
489
490 // Remove the listener with the old offset
491 status_t err = mDispSync->removeEventListener(
492 static_cast<DispSync::Callback*>(this));
493 if (err != NO_ERROR) {
494 ALOGE("error unregistering vsync callback: %s (%d)",
495 strerror(-err), err);
496 }
497
498 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 static_cast<DispSync::Callback*>(this));
501 if (err != NO_ERROR) {
502 ALOGE("error registering vsync callback: %s (%d)",
503 strerror(-err), err);
504 }
505 }
506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507private:
508 virtual void onDispSyncEvent(nsecs_t when) {
509 sp<VSyncSource::Callback> callback;
510 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 callback = mCallback;
513
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514 if (mTraceVsync) {
515 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700516 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700517 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 }
519
Peiyong Lin566a3b42018-01-09 18:22:43 -0800520 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 callback->onVSyncEvent(when);
522 }
523 }
524
Tim Murray4a4e4a22016-04-19 16:29:23 +0000525 const char* const mName;
526
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 int mValue;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 const String8 mVsyncOnLabel;
531 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534
535 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537
538 Mutex mVsyncMutex; // Protects the following
539 nsecs_t mPhaseOffset;
540 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541};
542
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700543class InjectVSyncSource : public VSyncSource {
544public:
545 InjectVSyncSource() {}
546
547 virtual ~InjectVSyncSource() {}
548
549 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
550 std::lock_guard<std::mutex> lock(mCallbackMutex);
551 mCallback = callback;
552 }
553
554 virtual void onInjectSyncEvent(nsecs_t when) {
555 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700556 if (mCallback) {
557 mCallback->onVSyncEvent(when);
558 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700559 }
560
561 virtual void setVSyncEnabled(bool) {}
562 virtual void setPhaseOffset(nsecs_t) {}
563
564private:
565 std::mutex mCallbackMutex; // Protects the following
566 sp<VSyncSource::Callback> mCallback;
567};
568
Wei Wangf9b05ee2017-07-19 20:59:39 -0700569// Do not call property_set on main thread which will be blocked by init
570// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700572 ALOGI( "SurfaceFlinger's main thread ready to run. "
573 "Initializing graphics H/W...");
574
Thierry Strudel2924d012017-08-14 15:19:37 -0700575 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 // start the EventThread
David Sodman99974d22017-11-28 12:04:33 -0800580 sp<VSyncSource> vsyncSrc =
581 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 mEventThread = new EventThread(vsyncSrc, *this, false);
David Sodman99974d22017-11-28 12:04:33 -0800583 sp<VSyncSource> sfVsyncSrc =
584 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
586 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
589 struct sched_param param = {0};
590 param.sched_priority = 2;
591 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
592 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
593 }
594 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
595 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596 }
597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800599 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800601 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700602
603 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
604 "Starting with vr flinger active is not currently supported.");
David Sodmanbc815282017-11-05 18:57:52 -0800605 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700606 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800607 // Process any initial hotplug and resulting display changes.
608 processDisplayHotplugEventsLocked();
609 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
610 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800611
Lloyd Piquefcd86612017-12-14 17:15:36 -0800612 // make the default display GLContext current so that we can create textures
613 // when creating Layers (which may happens before we render something)
614 getDefaultDisplayDeviceLocked()->makeCurrent();
615
Steven Thomas050b2c82017-03-06 11:45:16 -0800616 if (useVrFlinger) {
617 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700618 // This callback is called from the vr flinger dispatch thread. We
619 // need to call signalTransaction(), which requires holding
620 // mStateLock when we're not on the main thread. Acquiring
621 // mStateLock from the vr flinger dispatch thread might trigger a
622 // deadlock in surface flinger (see b/66916578), so post a message
623 // to be handled on the main thread instead.
624 sp<LambdaMessage> message = new LambdaMessage([=]() {
625 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
626 mVrFlingerRequestsDisplay = requestDisplay;
627 signalTransaction();
628 });
629 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 };
David Sodman105b7dc2017-11-04 20:28:14 -0700631 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
632 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800633 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 if (!mVrFlinger) {
635 ALOGE("Failed to start vrflinger");
636 }
637 }
638
Jamie Gennisd1700752013-10-14 12:22:52 -0700639 mEventControlThread = new EventControlThread(this);
640 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
641
Mathias Agopian92a979a2012-08-02 18:32:23 -0700642 // initialize our drawing state
643 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700644
Andy McFadden13a082e2012-08-24 10:16:42 -0700645 // set initial conditions (e.g. unblank default device)
646 initializeDisplays();
647
David Sodmanbc815282017-11-05 18:57:52 -0800648 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700649
Wei Wangf9b05ee2017-07-19 20:59:39 -0700650 // Inform native graphics APIs whether the present timestamp is supported:
651 if (getHwComposer().hasCapability(
652 HWC2::Capability::PresentFenceIsNotReliable)) {
653 mStartPropertySetThread = new StartPropertySetThread(false);
654 } else {
655 mStartPropertySetThread = new StartPropertySetThread(true);
656 }
657
658 if (mStartPropertySetThread->Start() != NO_ERROR) {
659 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800660 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800661
Dan Stoza9e56aa02015-11-02 13:00:03 -0800662 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700663}
664
Romain Guy11d63f42017-07-20 12:47:14 -0700665void SurfaceFlinger::readPersistentProperties() {
666 char value[PROPERTY_VALUE_MAX];
667
668 property_get("persist.sys.sf.color_saturation", value, "1.0");
669 mSaturation = atof(value);
670 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100671
672 property_get("persist.sys.sf.native_mode", value, "0");
673 mForceNativeColorMode = atoi(value) == 1;
674 if (mForceNativeColorMode) {
675 ALOGV("Forcing native color mode");
676 }
Romain Guy11d63f42017-07-20 12:47:14 -0700677}
678
Mathias Agopiana67e4182012-06-19 17:26:12 -0700679void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Start boot animation service by setting a property mailbox
681 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 if (mStartPropertySetThread->join() != NO_ERROR) {
685 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800686 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687}
688
Mathias Agopian875d8e12013-06-07 15:35:48 -0700689size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800690 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700691}
692
Mathias Agopian875d8e12013-06-07 15:35:48 -0700693size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800694 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700695}
696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800698
Jamie Gennis582270d2011-08-17 18:19:00 -0700699bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800700 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800701 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800702 return authenticateSurfaceTextureLocked(bufferProducer);
703}
704
705bool SurfaceFlinger::authenticateSurfaceTextureLocked(
706 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800707 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700708 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800709}
710
Brian Anderson6b376712017-04-04 10:51:39 -0700711status_t SurfaceFlinger::getSupportedFrameTimestamps(
712 std::vector<FrameEvent>* outSupported) const {
713 *outSupported = {
714 FrameEvent::REQUESTED_PRESENT,
715 FrameEvent::ACQUIRE,
716 FrameEvent::LATCH,
717 FrameEvent::FIRST_REFRESH_START,
718 FrameEvent::LAST_REFRESH_START,
719 FrameEvent::GPU_COMPOSITION_DONE,
720 FrameEvent::DEQUEUE_READY,
721 FrameEvent::RELEASE,
722 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700723 ConditionalLock _l(mStateLock,
724 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700725 if (!getHwComposer().hasCapability(
726 HWC2::Capability::PresentFenceIsNotReliable)) {
727 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
728 }
729 return NO_ERROR;
730}
731
Dan Stoza7f7da322014-05-02 15:26:25 -0700732status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
733 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800734 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700735 return BAD_VALUE;
736 }
737
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500738 if (!display.get())
739 return NAME_NOT_FOUND;
740
Jesse Hall692c7232012-11-08 15:41:56 -0800741 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700742 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800743 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700744 type = i;
745 break;
746 }
747 }
748
749 if (type < 0) {
750 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700751 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753 // TODO: Not sure if display density should handled by SF any longer
754 class Density {
755 static int getDensityFromProperty(char const* propName) {
756 char property[PROPERTY_VALUE_MAX];
757 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800758 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 density = atoi(property);
760 }
761 return density;
762 }
763 public:
764 static int getEmuDensity() {
765 return getDensityFromProperty("qemu.sf.lcd_density"); }
766 static int getBuildDensity() {
767 return getDensityFromProperty("ro.sf.lcd_density"); }
768 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700769
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700771
Steven Thomas6d8110b2017-08-31 18:24:21 -0700772 ConditionalLock _l(mStateLock,
773 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800774 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 DisplayInfo info = DisplayInfo();
776
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 float xdpi = hwConfig->getDpiX();
778 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700779
780 if (type == DisplayDevice::DISPLAY_PRIMARY) {
781 // The density of the device is provided by a build property
782 float density = Density::getBuildDensity() / 160.0f;
783 if (density == 0) {
784 // the build doesn't provide a density -- this is wrong!
785 // use xdpi instead
786 ALOGE("ro.sf.lcd_density must be defined as a build property");
787 density = xdpi / 160.0f;
788 }
789 if (Density::getEmuDensity()) {
790 // if "qemu.sf.lcd_density" is specified, it overrides everything
791 xdpi = ydpi = density = Density::getEmuDensity();
792 density /= 160.0f;
793 }
794 info.density = density;
795
796 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700797 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800798 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 } else {
800 // TODO: where should this value come from?
801 static const int TV_DENSITY = 213;
802 info.density = TV_DENSITY / 160.0f;
803 info.orientation = 0;
804 }
805
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 info.w = hwConfig->getWidth();
807 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 info.xdpi = xdpi;
809 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900811 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812
Andy McFadden91b2ca82014-06-13 14:04:23 -0700813 // This is how far in advance a buffer must be queued for
814 // presentation at a given time. If you want a buffer to appear
815 // on the screen at time N, you must submit the buffer before
816 // (N - presentationDeadline).
817 //
818 // Normally it's one full refresh period (to give SF a chance to
819 // latch the buffer), but this can be reduced by configuring a
820 // DispSync offset. Any additional delays introduced by the hardware
821 // composer or panel must be accounted for here.
822 //
823 // We add an additional 1ms to allow for processing time and
824 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800826 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
828 // All non-virtual displays are currently considered secure.
829 info.secure = true;
830
Michael Wright28f24d02016-07-12 13:30:53 -0700831 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 }
833
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 return NO_ERROR;
835}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700836
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800837status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700838 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800839 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700840 return BAD_VALUE;
841 }
842
843 // FIXME for now we always return stats for the primary display
844 memset(stats, 0, sizeof(*stats));
845 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
846 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
847 return NO_ERROR;
848}
849
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700850int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800851 if (display == nullptr) {
852 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800853 return BAD_VALUE;
854 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700855
856 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800857 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700858 return device->getActiveConfig();
859 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700860
Dan Stoza24a42e92015-03-09 10:04:11 -0700861 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700862}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700863
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700864void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
865 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
866 this);
867 int32_t type = hw->getDisplayType();
868 int currentMode = hw->getActiveConfig();
869
870 if (mode == currentMode) {
871 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
872 return;
873 }
874
875 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
876 ALOGW("Trying to set config for virtual display");
877 return;
878 }
879
880 hw->setActiveConfig(mode);
881 getHwComposer().setActiveConfig(type, mode);
882}
883
884status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
885 class MessageSetActiveConfig: public MessageBase {
886 SurfaceFlinger& mFlinger;
887 sp<IBinder> mDisplay;
888 int mMode;
889 public:
890 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
891 int mode) :
892 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
893 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700894 Vector<DisplayInfo> configs;
895 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700896 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700897 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700898 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700899 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700900 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700901 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800902 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700903 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700904 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700905 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
906 ALOGW("Attempt to set active config = %d for virtual display",
907 mMode);
908 } else {
909 mFlinger.setActiveConfigInternal(hw, mMode);
910 }
911 return true;
912 }
913 };
914 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
915 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700916 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700917}
Michael Wright28f24d02016-07-12 13:30:53 -0700918status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
919 Vector<android_color_mode_t>* outColorModes) {
920 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
921 return BAD_VALUE;
922 }
923
924 if (!display.get()) {
925 return NAME_NOT_FOUND;
926 }
927
928 int32_t type = NAME_NOT_FOUND;
929 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
930 if (display == mBuiltinDisplays[i]) {
931 type = i;
932 break;
933 }
934 }
935
936 if (type < 0) {
937 return type;
938 }
939
Steven Thomas6d8110b2017-08-31 18:24:21 -0700940 std::vector<android_color_mode_t> modes;
941 {
942 ConditionalLock _l(mStateLock,
943 std::this_thread::get_id() != mMainThreadId);
944 modes = getHwComposer().getColorModes(type);
945 }
Michael Wright28f24d02016-07-12 13:30:53 -0700946 outColorModes->clear();
947 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
948
949 return NO_ERROR;
950}
951
952android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700954 if (device != nullptr) {
955 return device->getActiveColorMode();
956 }
957 return static_cast<android_color_mode_t>(BAD_VALUE);
958}
959
960void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
961 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 int32_t type = hw->getDisplayType();
963 android_color_mode_t currentMode = hw->getActiveColorMode();
964
965 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700966 return;
967 }
968
969 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
970 ALOGW("Trying to set config for virtual display");
971 return;
972 }
973
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600974 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
975 hw->getDisplayType());
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 hw->setActiveColorMode(mode);
978 getHwComposer().setActiveColorMode(type, mode);
979}
980
981
982status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
983 android_color_mode_t colorMode) {
984 class MessageSetActiveColorMode: public MessageBase {
985 SurfaceFlinger& mFlinger;
986 sp<IBinder> mDisplay;
987 android_color_mode_t mMode;
988 public:
989 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
990 android_color_mode_t mode) :
991 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
992 virtual bool handler() {
993 Vector<android_color_mode_t> modes;
994 mFlinger.getDisplayColorModes(mDisplay, &modes);
995 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
996 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600997 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
998 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700999 return true;
1000 }
1001 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1002 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1004 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001005 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGW("Attempt to set active color mode %s %d for virtual display",
1007 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else {
1009 mFlinger.setActiveColorModeInternal(hw, mMode);
1010 }
1011 return true;
1012 }
1013 };
1014 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1015 postMessageSync(msg);
1016 return NO_ERROR;
1017}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001018
Svetoslavd85084b2014-03-20 10:28:31 -07001019status_t SurfaceFlinger::clearAnimationFrameStats() {
1020 Mutex::Autolock _l(mStateLock);
1021 mAnimFrameTracker.clearStats();
1022 return NO_ERROR;
1023}
1024
1025status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1026 Mutex::Autolock _l(mStateLock);
1027 mAnimFrameTracker.getStats(outStats);
1028 return NO_ERROR;
1029}
1030
Dan Stozac4f471e2016-03-24 09:31:08 -07001031status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1032 HdrCapabilities* outCapabilities) const {
1033 Mutex::Autolock _l(mStateLock);
1034
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001035 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001036 if (displayDevice == nullptr) {
1037 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1038 return BAD_VALUE;
1039 }
1040
1041 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001042 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001043 if (capabilities) {
1044 std::swap(*outCapabilities, *capabilities);
1045 } else {
1046 return BAD_VALUE;
1047 }
1048
1049 return NO_ERROR;
1050}
1051
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001052status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001053 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1054 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001055
Chia-I Wu90f669f2017-10-05 14:24:41 -07001056 if (mInjectVSyncs == enable) {
1057 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001058 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001059
1060 if (enable) {
1061 ALOGV("VSync Injections enabled");
1062 if (mVSyncInjector.get() == nullptr) {
1063 mVSyncInjector = new InjectVSyncSource();
1064 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1065 }
1066 mEventQueue.setEventThread(mInjectorEventThread);
1067 } else {
1068 ALOGV("VSync Injections disabled");
1069 mEventQueue.setEventThread(mSFEventThread);
1070 }
1071
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073 });
1074 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001075 return NO_ERROR;
1076}
1077
1078status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079 Mutex::Autolock _l(mStateLock);
1080
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081 if (!mInjectVSyncs) {
1082 ALOGE("VSync Injections not enabled");
1083 return BAD_VALUE;
1084 }
1085 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1086 ALOGV("Injecting VSync inside SurfaceFlinger");
1087 mVSyncInjector->onInjectSyncEvent(when);
1088 }
1089 return NO_ERROR;
1090}
1091
Kalle Raitaa099a242017-01-11 11:17:29 -08001092status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1093 IPCThreadState* ipc = IPCThreadState::self();
1094 const int pid = ipc->getCallingPid();
1095 const int uid = ipc->getCallingUid();
1096 if ((uid != AID_SHELL) &&
1097 !PermissionCache::checkPermission(sDump, pid, uid)) {
1098 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1099 return PERMISSION_DENIED;
1100 }
1101
1102 // Try to acquire a lock for 1s, fail gracefully
1103 const status_t err = mStateLock.timedLock(s2ns(1));
1104 const bool locked = (err == NO_ERROR);
1105 if (!locked) {
1106 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1107 return TIMED_OUT;
1108 }
1109
1110 outLayers->clear();
1111 mCurrentState.traverseInZOrder([&](Layer* layer) {
1112 outLayers->push_back(layer->getLayerDebugInfo());
1113 });
1114
1115 mStateLock.unlock();
1116 return NO_ERROR;
1117}
1118
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001119// ----------------------------------------------------------------------------
1120
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001121sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1122 ISurfaceComposer::VsyncSource vsyncSource) {
1123 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1124 return mSFEventThread->createEventConnection();
1125 } else {
1126 return mEventThread->createEventConnection();
1127 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001128}
1129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001130// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001131
1132void SurfaceFlinger::waitForEvent() {
1133 mEventQueue.waitMessage();
1134}
1135
1136void SurfaceFlinger::signalTransaction() {
1137 mEventQueue.invalidate();
1138}
1139
1140void SurfaceFlinger::signalLayerUpdate() {
1141 mEventQueue.invalidate();
1142}
1143
1144void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001145 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001146 mEventQueue.refresh();
1147}
1148
1149status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001150 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151 return mEventQueue.postMessage(msg, reltime);
1152}
1153
1154status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001155 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156 status_t res = mEventQueue.postMessage(msg, reltime);
1157 if (res == NO_ERROR) {
1158 msg->wait();
1159 }
1160 return res;
1161}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001162
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001163void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001164 do {
1165 waitForEvent();
1166 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001167}
1168
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169void SurfaceFlinger::enableHardwareVsync() {
1170 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001171 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001173 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1174 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001176 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001177}
1178
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180 Mutex::Autolock _l(mHWVsyncLock);
1181
Jesse Hall948fe0c2013-10-14 12:56:09 -07001182 if (makeAvailable) {
1183 mHWVsyncAvailable = true;
1184 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001185 // Hardware vsync is not currently available, so abort the resync
1186 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001187 return;
1188 }
1189
David Sodman105b7dc2017-11-04 20:28:14 -07001190 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001191 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192
1193 mPrimaryDispSync.reset();
1194 mPrimaryDispSync.setPeriod(period);
1195
1196 if (!mPrimaryHWVsyncEnabled) {
1197 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001198 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1199 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001200 mPrimaryHWVsyncEnabled = true;
1201 }
1202}
1203
Jesse Hall948fe0c2013-10-14 12:56:09 -07001204void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205 Mutex::Autolock _l(mHWVsyncLock);
1206 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001207 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1208 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 mPrimaryDispSync.endResync();
1210 mPrimaryHWVsyncEnabled = false;
1211 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001212 if (makeUnavailable) {
1213 mHWVsyncAvailable = false;
1214 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215}
1216
Tim Murray4a4e4a22016-04-19 16:29:23 +00001217void SurfaceFlinger::resyncWithRateLimit() {
1218 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001219
1220 // No explicit locking is needed here since EventThread holds a lock while calling this method
1221 static nsecs_t sLastResyncAttempted = 0;
1222 const nsecs_t now = systemTime();
1223 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001224 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001225 }
Dan Stoza57164302017-05-08 14:03:54 -07001226 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227}
1228
Steven Thomasb02664d2017-07-26 18:48:28 -07001229void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1230 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001231 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001232 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001233 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001234 return;
1235 }
1236
1237 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001238 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001239 return;
1240 }
1241
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 { // Scope for the lock
1245 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001247 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001249 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001250
1251 if (needsHwVsync) {
1252 enableHardwareVsync();
1253 } else {
1254 disableHardwareVsync(false);
1255 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001256}
1257
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001258void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001259 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1260 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001261}
1262
Lloyd Pique715a2c12017-12-14 17:18:08 -08001263void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1264 HWC2::Connection connection) {
1265 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1266 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001267
Lloyd Piqueba04e622017-12-14 17:11:26 -08001268 // Ignore events that do not have the right sequenceId.
1269 if (sequenceId != getBE().mComposerSequenceId) {
1270 return;
1271 }
1272
Steven Thomasb02664d2017-07-26 18:48:28 -07001273 // Only lock if we're not on the main thread. This function is normally
1274 // called on a hwbinder thread, but for the primary display it's called on
1275 // the main thread with the state lock already held, so don't attempt to
1276 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001277 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001278
Lloyd Pique715a2c12017-12-14 17:18:08 -08001279 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001280
Lloyd Piqueba04e622017-12-14 17:11:26 -08001281 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001282}
1283
Steven Thomasb02664d2017-07-26 18:48:28 -07001284void SurfaceFlinger::onRefreshReceived(int sequenceId,
1285 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001286 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001287 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001288 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001289 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001290 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001291}
1292
Dan Stoza9e56aa02015-11-02 13:00:03 -08001293void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001295 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296 getHwComposer().setVsyncEnabled(disp,
1297 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001298}
1299
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001301void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001302 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001303 // Clear the drawing state so that the logic inside of
1304 // handleTransactionLocked will fire. It will determine the delta between
1305 // mCurrentState and mDrawingState and re-apply all changes when we make the
1306 // transition.
1307 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001308 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 mDisplays.clear();
1310}
1311
Steven Thomas050b2c82017-03-06 11:45:16 -08001312void SurfaceFlinger::updateVrFlinger() {
1313 if (!mVrFlinger)
1314 return;
1315 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001316 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001317 return;
1318 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 ALOGE("Vr flinger is only supported for remote hardware composer"
1322 " service connections. Ignoring request to transition to vr"
1323 " flinger.");
1324 mVrFlingerRequestsDisplay = false;
1325 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001326 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001329
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 int currentDisplayPowerMode = getDisplayDeviceLocked(
1331 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001335 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001338 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001339 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001340 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
David Sodman105b7dc2017-11-04 20:28:14 -07001342 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1343 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001344
1345 if (vrFlingerRequestsDisplay) {
1346 mVrFlinger->GrantDisplayOwnership();
1347 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001348 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350
1351 mVisibleRegionsDirty = true;
1352 invalidateHwcGeometry();
1353
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001354 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1356 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1357 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001360 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 const nsecs_t period = activeConfig->getVsyncPeriod();
1362 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001363
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 // Use phase of 0 since phase is not known.
1365 // Use latency of 0, which will snap to the ideal latency.
1366 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001367
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368 android_atomic_or(1, &mRepaintEverything);
1369 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001370}
1371
Mathias Agopian4fec8732012-06-29 14:12:52 -07001372void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001373 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001374 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001375 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001376 bool frameMissed = !mHadClientComposition &&
1377 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001378 (mPreviousPresentFence->getSignalTime() ==
1379 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001380 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001381 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001382 signalLayerUpdate();
1383 break;
1384 }
1385
Steven Thomas050b2c82017-03-06 11:45:16 -08001386 // Now that we're going to make it to the handleMessageTransaction()
1387 // call below it's safe to call updateVrFlinger(), which will
1388 // potentially trigger a display handoff.
1389 updateVrFlinger();
1390
Dan Stoza6b9454d2014-11-07 16:00:59 -08001391 bool refreshNeeded = handleMessageTransaction();
1392 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001393 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001395 // Signal a refresh if a transaction modified the window state,
1396 // a new buffer was latched, or if HWC has requested a full
1397 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001398 signalRefresh();
1399 }
1400 break;
1401 }
1402 case MessageQueue::REFRESH: {
1403 handleMessageRefresh();
1404 break;
1405 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406 }
1407}
1408
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001410 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001411 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001412 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001413 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001414 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001416}
1417
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001420 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001421}
1422
1423void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001424 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001425
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001426 mRefreshPending = false;
1427
Pablo Ceballos40845df2016-01-25 17:41:15 -08001428 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001429
Brian Andersond6927fb2016-07-23 23:37:30 -07001430 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001431 rebuildLayerStacks();
1432 setUpHWComposer();
1433 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001434 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001435 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001436 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001437
David Sodman105b7dc2017-11-04 20:28:14 -07001438 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001439
1440 mHadClientComposition = false;
1441 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1442 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1443 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001444 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001445 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001446
Dan Stoza9e56aa02015-11-02 13:00:03 -08001447 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001448}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001449
Mathias Agopiancd60f992012-08-16 16:28:27 -07001450void SurfaceFlinger::doDebugFlashRegions()
1451{
1452 // is debugging enabled
1453 if (CC_LIKELY(!mDebugRegion))
1454 return;
1455
1456 const bool repaintEverything = mRepaintEverything;
1457 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1458 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001459 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460 // transform the dirty region into this screen's coordinate space
1461 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1462 if (!dirtyRegion.isEmpty()) {
1463 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001464 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465
1466 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001468 RenderEngine& engine(getRenderEngine());
1469 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1470
Mathias Agopianda27af92012-09-13 18:17:13 -07001471 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 }
1473 }
1474 }
1475
1476 postFramebuffer();
1477
1478 if (mDebugRegion > 1) {
1479 usleep(mDebugRegion * 1000);
1480 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001481
Dan Stoza9e56aa02015-11-02 13:00:03 -08001482 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001483 auto& displayDevice = mDisplays[displayId];
1484 if (!displayDevice->isDisplayOn()) {
1485 continue;
1486 }
1487
David Sodman105b7dc2017-11-04 20:28:14 -07001488 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1489 ALOGE_IF(result != NO_ERROR,
1490 "prepareFrame for display %zd failed:"
1491 " %d (%s)",
1492 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001493 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494}
1495
Adrian Roos1e1a1282017-11-01 19:05:31 +01001496void SurfaceFlinger::doTracing(const char* where) {
1497 ATRACE_CALL();
1498 ATRACE_NAME(where);
1499 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001500 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001501 }
1502}
1503
Brian Andersond6927fb2016-07-23 23:37:30 -07001504void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 ATRACE_CALL();
1507 ALOGV("preComposition");
1508
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001510 mDrawingState.traverseInZOrder([&](Layer* layer) {
1511 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 needExtraInvalidate = true;
1513 }
Robert Carr2047fae2016-11-28 14:09:09 -08001514 });
1515
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 if (needExtraInvalidate) {
1517 signalLayerUpdate();
1518 }
1519}
1520
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521void SurfaceFlinger::updateCompositorTiming(
1522 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1523 std::shared_ptr<FenceTime>& presentFenceTime) {
1524 // Update queue of past composite+present times and determine the
1525 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001526 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001528 while (!getBE().mCompositePresentTimes.empty()) {
1529 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001530 // Cached values should have been updated before calling this method,
1531 // which helps avoid duplicate syscalls.
1532 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1533 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1534 break;
1535 }
1536 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001537 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538 }
1539
1540 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001541 while (getBE().mCompositePresentTimes.size() > 16) {
1542 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001543 }
1544
Brian Andersond0010582017-03-07 13:20:31 -08001545 setCompositorTimingSnapped(
1546 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1547}
1548
1549void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1550 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 // Integer division and modulo round toward 0 not -inf, so we need to
1552 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001553 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001554 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1555 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1556
Brian Andersond0010582017-03-07 13:20:31 -08001557 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1558 if (idealLatency <= 0) {
1559 idealLatency = vsyncInterval;
1560 }
1561
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562 // Snap the latency to a value that removes scheduling jitter from the
1563 // composition and present times, which often have >1ms of jitter.
1564 // Reducing jitter is important if an app attempts to extrapolate
1565 // something (such as user input) to an accurate diasplay time.
1566 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1567 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001568 nsecs_t bias = vsyncInterval / 2;
1569 int64_t extraVsyncs =
1570 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1571 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1572 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573
David Sodman99974d22017-11-28 12:04:33 -08001574 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1575 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1576 getBE().mCompositorTiming.interval = vsyncInterval;
1577 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001578}
1579
1580void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 ATRACE_CALL();
1583 ALOGV("postComposition");
1584
Brian Anderson3546a3f2016-07-14 11:51:14 -07001585 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001586 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001587 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001588 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001589 }
1590
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591 // |mStateLock| not needed as we are on the main thread
1592 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001593
David Sodman73beded2017-11-15 11:56:06 -08001594 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001595 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001596 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001597 glCompositionDoneFenceTime =
1598 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001599 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001600 } else {
1601 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1602 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603
David Sodman73beded2017-11-15 11:56:06 -08001604 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001605 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001606 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001607 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001608
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1610 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1611
1612 // We use the refreshStartTime which might be sampled a little later than
1613 // when we started doing work for this frame, but that should be okay
1614 // since updateCompositorTiming has snapping logic.
1615 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001616 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001617 CompositorTiming compositorTiming;
1618 {
David Sodman99974d22017-11-28 12:04:33 -08001619 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1620 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001621 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622
Robert Carr2047fae2016-11-28 14:09:09 -08001623 mDrawingState.traverseInZOrder([&](Layer* layer) {
1624 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001625 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001626 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001627 recordBufferingStats(layer->getName().string(),
1628 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001629 }
Robert Carr2047fae2016-11-28 14:09:09 -08001630 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001631
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001632 if (presentFenceTime->isValid()) {
1633 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001634 enableHardwareVsync();
1635 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001636 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001637 }
1638 }
1639
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001640 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001641 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001642 enableHardwareVsync();
1643 }
1644 }
1645
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001646 if (mAnimCompositionPending) {
1647 mAnimCompositionPending = false;
1648
Brian Anderson4e606e32017-03-16 15:34:57 -07001649 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001650 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001651 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001652 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001653 // The HWC doesn't support present fences, so use the refresh
1654 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001656 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001657 mAnimFrameTracker.setActualPresentTime(presentTime);
1658 }
1659 mAnimFrameTracker.advanceFrame();
1660 }
Dan Stozab90cf072015-03-05 11:05:59 -08001661
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001662 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1663 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001664 return;
1665 }
1666
1667 nsecs_t currentTime = systemTime();
1668 if (mHasPoweredOff) {
1669 mHasPoweredOff = false;
1670 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001671 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001673 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1674 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001675 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001676 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001677 }
David Sodman4a36e932017-11-07 14:29:47 -08001678 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001679 }
David Sodman4a36e932017-11-07 14:29:47 -08001680 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681}
1682
1683void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001684 ATRACE_CALL();
1685 ALOGV("rebuildLayerStacks");
1686
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001688 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001689 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001690 mVisibleRegionsDirty = false;
1691 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001692
Jeff Sharkey76488112017-02-27 14:15:18 -07001693 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1694 Region opaqueRegion;
1695 Region dirtyRegion;
1696 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001697 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001698 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1699 const Transform& tr(displayDevice->getTransform());
1700 const Rect bounds(displayDevice->getBounds());
1701 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001702 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001703
Jeff Sharkey76488112017-02-27 14:15:18 -07001704 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001705 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001706 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1707 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001708 Region drawRegion(tr.transform(
1709 layer->visibleNonTransparentRegion));
1710 drawRegion.andSelf(bounds);
1711 if (!drawRegion.isEmpty()) {
1712 layersSortedByZ.add(layer);
1713 } else {
1714 // Clear out the HWC layer if this layer was
1715 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001716 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001717 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001718 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001719 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001720 // WM changes displayDevice->layerStack upon sleep/awake.
1721 // Here we make sure we delete the HWC layers even if
1722 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001723 hwcLayerDestroyed = layer->destroyHwcLayer(
1724 displayDevice->getHwcDisplayId());
1725 }
1726
1727 // If a layer is not going to get a release fence because
1728 // it is invisible, but it is also going to release its
1729 // old buffer, add it to the list of layers needing
1730 // fences.
1731 if (hwcLayerDestroyed) {
1732 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1733 mLayersWithQueuedFrames.cend(), layer);
1734 if (found != mLayersWithQueuedFrames.cend()) {
1735 layersNeedingFences.add(layer);
1736 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001737 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001738 });
1739 }
1740 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001741 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001742 displayDevice->undefinedRegion.set(bounds);
1743 displayDevice->undefinedRegion.subtractSelf(
1744 tr.transform(opaqueRegion));
1745 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001746 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001747 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001749
Romain Guy0147a172017-06-01 13:53:56 -07001750mat4 SurfaceFlinger::computeSaturationMatrix() const {
1751 if (mSaturation == 1.0f) {
1752 return mat4();
1753 }
1754
1755 // Rec.709 luma coefficients
1756 float3 luminance{0.213f, 0.715f, 0.072f};
1757 luminance *= 1.0f - mSaturation;
1758 return mat4(
1759 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1760 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1761 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1762 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1763 );
1764}
1765
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001766// pickColorMode translates a given dataspace into the best available color mode.
1767// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001768android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001769 if (mForceNativeColorMode) {
1770 return HAL_COLOR_MODE_NATIVE;
1771 }
1772
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001773 switch (dataSpace) {
1774 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1775 // system expects.
1776 case HAL_DATASPACE_UNKNOWN:
1777 case HAL_DATASPACE_SRGB:
1778 case HAL_DATASPACE_V0_SRGB:
1779 return HAL_COLOR_MODE_SRGB;
1780 break;
1781
1782 case HAL_DATASPACE_DISPLAY_P3:
1783 return HAL_COLOR_MODE_DISPLAY_P3;
1784 break;
1785
1786 default:
1787 // TODO (courtneygo): Do we want to assert an error here?
1788 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1789 dataSpace);
1790 return HAL_COLOR_MODE_SRGB;
1791 break;
1792 }
1793}
1794
Romain Guy0147a172017-06-01 13:53:56 -07001795android_dataspace SurfaceFlinger::bestTargetDataSpace(
1796 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001797 // Only support sRGB and Display-P3 right now.
1798 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1799 return HAL_DATASPACE_DISPLAY_P3;
1800 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001801 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1802 return HAL_DATASPACE_DISPLAY_P3;
1803 }
1804 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1805 return HAL_DATASPACE_DISPLAY_P3;
1806 }
1807
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001808 return HAL_DATASPACE_V0_SRGB;
1809}
1810
Mathias Agopiancd60f992012-08-16 16:28:27 -07001811void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 ATRACE_CALL();
1813 ALOGV("setUpHWComposer");
1814
Jesse Hall028dc8f2013-08-20 16:35:32 -07001815 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001816 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1817 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1818 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1819
1820 // If nothing has changed (!dirty), don't recompose.
1821 // If something changed, but we don't currently have any visible layers,
1822 // and didn't when we last did a composition, then skip it this time.
1823 // The second rule does two things:
1824 // - When all layers are removed from a display, we'll emit one black
1825 // frame, then nothing more until we get new layers.
1826 // - When a display is created with a private layer stack, we won't
1827 // emit any black frames until a layer is added to the layer stack.
1828 bool mustRecompose = dirty && !(empty && wasEmpty);
1829
1830 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1831 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1832 mustRecompose ? "doing" : "skipping",
1833 dirty ? "+" : "-",
1834 empty ? "+" : "-",
1835 wasEmpty ? "+" : "-");
1836
Dan Stoza71433162014-02-04 16:22:36 -08001837 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001838
1839 if (mustRecompose) {
1840 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1841 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001842 }
1843
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 // build the h/w work list
1845 if (CC_UNLIKELY(mGeometryInvalid)) {
1846 mGeometryInvalid = false;
1847 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1848 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1849 const auto hwcId = displayDevice->getHwcDisplayId();
1850 if (hwcId >= 0) {
1851 const Vector<sp<Layer>>& currentLayers(
1852 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001853 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001854 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001856 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001859 }
1860 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001861
Robert Carrae060832016-11-28 10:51:00 -08001862 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001863 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001864 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001865 }
1866 }
1867 }
1868 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001869 }
Riley Andrews03414a12014-07-01 14:22:59 -07001870
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001871
Romain Guy0147a172017-06-01 13:53:56 -07001872 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001873
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 // Set the per-frame data
1875 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1876 auto& displayDevice = mDisplays[displayId];
1877 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001878
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 if (hwcId < 0) {
1880 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001881 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001882 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001883 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001884 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1885 "display %zd: %d", displayId, result);
1886 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001888 if (layer->getForceClientComposition(hwcId)) {
1889 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1890 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1891 continue;
1892 }
1893
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 layer->setPerFrameData(displayDevice);
1895 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896
1897 if (hasWideColorDisplay) {
1898 android_color_mode newColorMode;
1899 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1900
1901 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1902 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1903 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1904 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1905 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1906 }
1907 newColorMode = pickColorMode(newDataSpace);
1908
Thierry Strudel2924d012017-08-14 15:19:37 -07001909 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001910 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001911 }
1912
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001913 mPreviousColorMatrix = colorMatrix;
1914
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001916 auto& displayDevice = mDisplays[displayId];
1917 if (!displayDevice->isDisplayOn()) {
1918 continue;
1919 }
1920
David Sodman105b7dc2017-11-04 20:28:14 -07001921 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1923 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001924 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001925}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001926
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927void SurfaceFlinger::doComposition() {
1928 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 ALOGV("doComposition");
1930
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001931 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001932 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001933 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001934 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935 // transform the dirty region into this screen's coordinate space
1936 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001937
1938 // repaint the framebuffer (if needed)
1939 doDisplayComposition(hw, dirtyRegion);
1940
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001942 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001943 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001944 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001945 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001946}
1947
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001948void SurfaceFlinger::postFramebuffer()
1949{
Mathias Agopian841cde52012-03-01 15:44:37 -08001950 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001952
Mathias Agopiana44b0412011-10-16 18:46:35 -07001953 const nsecs_t now = systemTime();
1954 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1957 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001958 if (!displayDevice->isDisplayOn()) {
1959 continue;
1960 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 const auto hwcId = displayDevice->getHwcDisplayId();
1962 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001963 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001964 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001965 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001966 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001968 // The layer buffer from the previous frame (if any) is released
1969 // by HWC only when the release fence from this frame (if any) is
1970 // signaled. Always get the release fence from HWC first.
1971 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001972 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08001973
1974 // If the layer was client composited in the previous frame, we
1975 // need to merge with the previous client target acquire fence.
1976 // Since we do not track that, always merge with the current
1977 // client target acquire fence when it is available, even though
1978 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001980 releaseFence = Fence::merge("LayerRelease", releaseFence,
1981 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001982 }
Chia-I Wu7b549592017-11-15 09:14:57 -08001983
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 layer->onLayerDisplayed(releaseFence);
1985 }
Chia-I Wu83806892017-11-16 10:50:20 -08001986
1987 // We've got a list of layers needing fences, that are disjoint with
1988 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
1989 // supply them with the present fence.
1990 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07001991 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08001992 for (auto& layer : displayDevice->getLayersNeedingFences()) {
1993 layer->onLayerDisplayed(presentFence);
1994 }
1995 }
1996
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001998 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001999 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002000 }
2001
Mathias Agopiana44b0412011-10-16 18:46:35 -07002002 mLastSwapBufferTime = systemTime() - now;
2003 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002004
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002005 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002006 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2007 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2008 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2009 logFrameStats();
2010 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002011 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012}
2013
Mathias Agopian87baae12012-07-31 12:38:26 -07002014void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015{
Mathias Agopian841cde52012-03-01 15:44:37 -08002016 ATRACE_CALL();
2017
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002018 // here we keep a copy of the drawing state (that is the state that's
2019 // going to be overwritten by handleTransactionLocked()) outside of
2020 // mStateLock so that the side-effects of the State assignment
2021 // don't happen with mStateLock held (which can cause deadlocks).
2022 State drawingState(mDrawingState);
2023
Mathias Agopianca4d3602011-05-19 15:38:14 -07002024 Mutex::Autolock _l(mStateLock);
2025 const nsecs_t now = systemTime();
2026 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002027
Mathias Agopianca4d3602011-05-19 15:38:14 -07002028 // Here we're guaranteed that some transaction flags are set
2029 // so we can call handleTransactionLocked() unconditionally.
2030 // We call getTransactionFlags(), which will also clear the flags,
2031 // with mStateLock held to guarantee that mCurrentState won't change
2032 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002033
Mathias Agopiane57f2922012-08-09 16:29:12 -07002034 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002035 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002036
Mathias Agopianca4d3602011-05-19 15:38:14 -07002037 mLastTransactionTime = systemTime() - now;
2038 mDebugInTransaction = 0;
2039 invalidateHwcGeometry();
2040 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002041}
2042
Lloyd Pique715a2c12017-12-14 17:18:08 -08002043DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2044 HWC2::Connection connection) const {
2045 // Figure out whether the event is for the primary display or an
2046 // external display by matching the Hwc display id against one for a
2047 // connected display. If we did not find a match, we then check what
2048 // displays are not already connected to determine the type. If we don't
2049 // have a connected primary display, we assume the new display is meant to
2050 // be the primary display, and then if we don't have an external display,
2051 // we assume it is that.
2052 const auto primaryDisplayId =
2053 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2054 const auto externalDisplayId =
2055 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2056 if (primaryDisplayId && primaryDisplayId == display) {
2057 return DisplayDevice::DISPLAY_PRIMARY;
2058 } else if (externalDisplayId && externalDisplayId == display) {
2059 return DisplayDevice::DISPLAY_EXTERNAL;
2060 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2061 return DisplayDevice::DISPLAY_PRIMARY;
2062 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2063 return DisplayDevice::DISPLAY_EXTERNAL;
2064 }
2065
2066 return DisplayDevice::DISPLAY_ID_INVALID;
2067}
2068
Lloyd Piqueba04e622017-12-14 17:11:26 -08002069void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2070 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002071 auto displayType = determineDisplayType(event.display, event.connection);
2072 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2073 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2074 continue;
2075 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002076
2077 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2078 ALOGE("External displays are not supported by the vr hardware composer.");
2079 continue;
2080 }
2081
Lloyd Pique715a2c12017-12-14 17:18:08 -08002082 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002083
2084 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002085 ALOGV("Creating built in display %d", displayType);
2086 ALOGW_IF(mBuiltinDisplays[displayType],
2087 "Overwriting display token for display type %d", displayType);
2088 mBuiltinDisplays[displayType] = new BBinder();
2089 // All non-virtual displays are currently considered secure.
2090 DisplayDeviceState info(displayType, true);
2091 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2092 "Built-in Screen" : "External Screen";
2093 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2094 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002095 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002096 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002097
Lloyd Piquefcd86612017-12-14 17:15:36 -08002098 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2099 if (idx >= 0) {
2100 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2101 mInterceptor.saveDisplayDeletion(info.displayId);
2102 mCurrentState.displays.removeItemsAt(idx);
2103 }
2104 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002105 }
2106
2107 processDisplayChangesLocked();
2108 }
2109
2110 mPendingHotplugEvents.clear();
2111}
2112
Lloyd Pique347200f2017-12-14 17:00:15 -08002113void SurfaceFlinger::processDisplayChangesLocked() {
2114 // here we take advantage of Vector's copy-on-write semantics to
2115 // improve performance by skipping the transaction entirely when
2116 // know that the lists are identical
2117 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2118 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2119 if (!curr.isIdenticalTo(draw)) {
2120 mVisibleRegionsDirty = true;
2121 const size_t cc = curr.size();
2122 size_t dc = draw.size();
2123
2124 // find the displays that were removed
2125 // (ie: in drawing state but not in current state)
2126 // also handle displays that changed
2127 // (ie: displays that are in both lists)
2128 for (size_t i = 0; i < dc;) {
2129 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2130 if (j < 0) {
2131 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002132 // Call makeCurrent() on the primary display so we can
2133 // be sure that nothing associated with this display
2134 // is current.
2135 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2136 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2137 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2138 if (hw != nullptr) hw->disconnect(getHwComposer());
2139 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2140 mEventThread->onHotplugReceived(draw[i].type, false);
2141 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002142 } else {
2143 // this display is in both lists. see if something changed.
2144 const DisplayDeviceState& state(curr[j]);
2145 const wp<IBinder>& display(curr.keyAt(j));
2146 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2147 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2148 if (state_binder != draw_binder) {
2149 // changing the surface is like destroying and
2150 // recreating the DisplayDevice, so we just remove it
2151 // from the drawing state, so that it get re-added
2152 // below.
2153 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2154 if (hw != nullptr) hw->disconnect(getHwComposer());
2155 mDisplays.removeItem(display);
2156 mDrawingState.displays.removeItemsAt(i);
2157 dc--;
2158 // at this point we must loop to the next item
2159 continue;
2160 }
2161
2162 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2163 if (disp != nullptr) {
2164 if (state.layerStack != draw[i].layerStack) {
2165 disp->setLayerStack(state.layerStack);
2166 }
2167 if ((state.orientation != draw[i].orientation) ||
2168 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2169 disp->setProjection(state.orientation, state.viewport, state.frame);
2170 }
2171 if (state.width != draw[i].width || state.height != draw[i].height) {
2172 disp->setDisplaySize(state.width, state.height);
2173 }
2174 }
2175 }
2176 ++i;
2177 }
2178
2179 // find displays that were added
2180 // (ie: in current state but not in drawing state)
2181 for (size_t i = 0; i < cc; i++) {
2182 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2183 const DisplayDeviceState& state(curr[i]);
2184
2185 sp<DisplaySurface> dispSurface;
2186 sp<IGraphicBufferProducer> producer;
2187 sp<IGraphicBufferProducer> bqProducer;
2188 sp<IGraphicBufferConsumer> bqConsumer;
2189 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2190
2191 int32_t hwcId = -1;
2192 if (state.isVirtualDisplay()) {
2193 // Virtual displays without a surface are dormant:
2194 // they have external state (layer stack, projection,
2195 // etc.) but no internal state (i.e. a DisplayDevice).
2196 if (state.surface != nullptr) {
2197 // Allow VR composer to use virtual displays.
2198 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2199 int width = 0;
2200 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2201 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2202 int height = 0;
2203 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2204 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2205 int intFormat = 0;
2206 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2207 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2208 auto format = static_cast<android_pixel_format_t>(intFormat);
2209
2210 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2211 }
2212
2213 // TODO: Plumb requested format back up to consumer
2214
2215 sp<VirtualDisplaySurface> vds =
2216 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2217 bqProducer, bqConsumer,
2218 state.displayName);
2219
2220 dispSurface = vds;
2221 producer = vds;
2222 }
2223 } else {
2224 ALOGE_IF(state.surface != nullptr,
2225 "adding a supported display, but rendering "
2226 "surface is provided (%p), ignoring it",
2227 state.surface.get());
2228
2229 hwcId = state.type;
2230 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2231 producer = bqProducer;
2232 }
2233
2234 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002235
Lloyd Pique347200f2017-12-14 17:00:15 -08002236 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002237 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002238 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002239 bool hasWideColorModes = false;
2240 std::vector<android_color_mode_t> modes =
2241 getHwComposer().getColorModes(state.type);
2242 for (android_color_mode_t colorMode : modes) {
2243 switch (colorMode) {
2244 case HAL_COLOR_MODE_DISPLAY_P3:
2245 case HAL_COLOR_MODE_ADOBE_RGB:
2246 case HAL_COLOR_MODE_DCI_P3:
2247 hasWideColorModes = true;
2248 break;
2249 default:
2250 break;
2251 }
2252 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002253 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002254 }
2255
Lloyd Pique347200f2017-12-14 17:00:15 -08002256 sp<DisplayDevice> hw =
2257 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Lloyd Piquefcd86612017-12-14 17:15:36 -08002258 dispSurface, producer, useWideColorMode);
2259
Lloyd Piquec5208312018-01-08 17:59:02 -08002260 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2261 if (useWideColorMode) {
2262 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002263 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002264 setActiveColorModeInternal(hw, defaultColorMode);
2265 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002266 hw->setLayerStack(state.layerStack);
2267 hw->setProjection(state.orientation, state.viewport, state.frame);
2268 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002269
Lloyd Pique347200f2017-12-14 17:00:15 -08002270 mDisplays.add(display, hw);
2271 if (!state.isVirtualDisplay()) {
2272 mEventThread->onHotplugReceived(state.type, true);
2273 }
2274 }
2275 }
2276 }
2277 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278
2279 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002280}
2281
Mathias Agopian87baae12012-07-31 12:38:26 -07002282void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002283{
Dan Stoza7dde5992015-05-22 09:51:44 -07002284 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002285 mCurrentState.traverseInZOrder([](Layer* layer) {
2286 layer->notifyAvailableFrames();
2287 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289 /*
2290 * Traversal of the children
2291 * (perform the transaction for each of them if needed)
2292 */
2293
Mathias Agopian3559b072012-08-15 13:46:03 -07002294 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002295 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002297 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298
2299 const uint32_t flags = layer->doTransaction(0);
2300 if (flags & Layer::eVisibleRegion)
2301 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002302 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303 }
2304
2305 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002306 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 */
2308
Mathias Agopiane57f2922012-08-09 16:29:12 -07002309 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002310 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313
Mathias Agopian84300952012-11-21 16:02:13 -08002314 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2315 // The transform hint might have changed for some layers
2316 // (either because a display has changed, or because a layer
2317 // as changed).
2318 //
2319 // Walk through all the layers in currentLayers,
2320 // and update their transform hint.
2321 //
2322 // If a layer is visible only on a single display, then that
2323 // display is used to calculate the hint, otherwise we use the
2324 // default display.
2325 //
2326 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2327 // the hint is set before we acquire a buffer from the surface texture.
2328 //
2329 // NOTE: layer transactions have taken place already, so we use their
2330 // drawing state. However, SurfaceFlinger's own transaction has not
2331 // happened yet, so we must use the current state layer list
2332 // (soon to become the drawing state list).
2333 //
2334 sp<const DisplayDevice> disp;
2335 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002336 bool first = true;
2337 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002338 // NOTE: we rely on the fact that layers are sorted by
2339 // layerStack first (so we don't have to traverse the list
2340 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002341 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002342 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002343 currentlayerStack = layerStack;
2344 // figure out if this layerstack is mirrored
2345 // (more than one display) if so, pick the default display,
2346 // if not, pick the only display it's on.
2347 disp.clear();
2348 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2349 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002350 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002351 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002352 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002353 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002354 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002355 break;
2356 }
2357 }
2358 }
2359 }
Chet Haase91d25932013-04-11 15:24:55 -07002360
Robert Carr56a0b9a2017-12-04 16:06:13 -08002361 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002362 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002363 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2364 // redraw after transform hint changes. See bug 8508397.
2365
2366 // could be null when this layer is using a layerStack
2367 // that is not visible on any display. Also can occur at
2368 // screen off/on times.
2369 disp = getDefaultDisplayDeviceLocked();
2370 }
2371 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002372 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002373 if (disp != nullptr) {
2374 layer->updateTransformHint(disp);
2375 }
Robert Carr2047fae2016-11-28 14:09:09 -08002376
2377 first = false;
2378 });
Mathias Agopian84300952012-11-21 16:02:13 -08002379 }
2380
2381
Mathias Agopian3559b072012-08-15 13:46:03 -07002382 /*
2383 * Perform our own transaction if needed
2384 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002385
2386 if (mLayersAdded) {
2387 mLayersAdded = false;
2388 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002389 mVisibleRegionsDirty = true;
2390 }
2391
2392 // some layers might have been removed, so
2393 // we need to update the regions they're exposing.
2394 if (mLayersRemoved) {
2395 mLayersRemoved = false;
2396 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002397 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002399 // this layer is not visible anymore
2400 // TODO: we could traverse the tree from front to back and
2401 // compute the actual visible region
2402 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002403 Region visibleReg;
2404 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002405 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002406 }
Robert Carr2047fae2016-11-28 14:09:09 -08002407 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408 }
2409
2410 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002411
2412 updateCursorAsync();
2413}
2414
2415void SurfaceFlinger::updateCursorAsync()
2416{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2418 auto& displayDevice = mDisplays[displayId];
2419 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002420 continue;
2421 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002422
2423 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2424 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002425 }
2426 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427}
2428
2429void SurfaceFlinger::commitTransaction()
2430{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002431 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002432 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002433 for (const auto& l : mLayersPendingRemoval) {
2434 recordBufferingStats(l->getName().string(),
2435 l->getOccupancyHistory(true));
2436 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002437 }
2438 mLayersPendingRemoval.clear();
2439 }
2440
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002441 // If this transaction is part of a window animation then the next frame
2442 // we composite should be considered an animation as well.
2443 mAnimCompositionPending = mAnimTransactionPending;
2444
Mathias Agopian4fec8732012-06-29 14:12:52 -07002445 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002446 mDrawingState.traverseInZOrder([](Layer* layer) {
2447 layer->commitChildList();
2448 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002449 mTransactionPending = false;
2450 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452}
2453
Chia-I Wuab0c3192017-08-01 11:29:00 -07002454void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002455 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456{
Mathias Agopian841cde52012-03-01 15:44:37 -08002457 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002459
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460 Region aboveOpaqueLayers;
2461 Region aboveCoveredLayers;
2462 Region dirty;
2463
Mathias Agopian87baae12012-07-31 12:38:26 -07002464 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
Robert Carr2047fae2016-11-28 14:09:09 -08002466 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002468 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469
Jesse Hall01e29052013-02-19 16:13:35 -08002470 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002471 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002472 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002473
Mathias Agopianab028732010-03-16 16:41:46 -07002474 /*
2475 * opaqueRegion: area of a surface that is fully opaque.
2476 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002478
2479 /*
2480 * visibleRegion: area of a surface that is visible on screen
2481 * and not fully transparent. This is essentially the layer's
2482 * footprint minus the opaque regions above it.
2483 * Areas covered by a translucent surface are considered visible.
2484 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002486
2487 /*
2488 * coveredRegion: area of a surface that is covered by all
2489 * visible regions above it (which includes the translucent areas).
2490 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002492
Jesse Halla8026d22012-09-25 13:25:04 -07002493 /*
2494 * transparentRegion: area of a surface that is hinted to be completely
2495 * transparent. This is only used to tell when the layer has no visible
2496 * non-transparent regions and can be removed from the layer list. It
2497 * does not affect the visibleRegion of this layer or any layers
2498 * beneath it. The hint may not be correct if apps don't respect the
2499 * SurfaceView restrictions (which, sadly, some don't).
2500 */
2501 Region transparentRegion;
2502
Mathias Agopianab028732010-03-16 16:41:46 -07002503
2504 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002505 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002506 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002507 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002509 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002510 if (!visibleRegion.isEmpty()) {
2511 // Remove the transparent area from the visible region
2512 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002513 if (tr.preserveRects()) {
2514 // transform the transparent region
2515 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002516 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002517 // transformation too complex, can't do the
2518 // transparent region optimization.
2519 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002520 }
Mathias Agopianab028732010-03-16 16:41:46 -07002521 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002522
Mathias Agopianab028732010-03-16 16:41:46 -07002523 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002525 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002526 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2527 // the opaque region is the layer's footprint
2528 opaqueRegion = visibleRegion;
2529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530 }
2531 }
2532
Robert Carre5f4f692018-01-12 13:12:28 -08002533 if (visibleRegion.isEmpty()) {
2534 layer->clearVisibilityRegions();
2535 return;
2536 }
2537
Mathias Agopianab028732010-03-16 16:41:46 -07002538 // Clip the covered region to the visible region
2539 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2540
2541 // Update aboveCoveredLayers for next (lower) layer
2542 aboveCoveredLayers.orSelf(visibleRegion);
2543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544 // subtract the opaque region covered by the layers above us
2545 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546
2547 // compute this layer's dirty region
2548 if (layer->contentDirty) {
2549 // we need to invalidate the whole region
2550 dirty = visibleRegion;
2551 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002552 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 layer->contentDirty = false;
2554 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002555 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002556 * the exposed region consists of two components:
2557 * 1) what's VISIBLE now and was COVERED before
2558 * 2) what's EXPOSED now less what was EXPOSED before
2559 *
2560 * note that (1) is conservative, we start with the whole
2561 * visible region but only keep what used to be covered by
2562 * something -- which mean it may have been exposed.
2563 *
2564 * (2) handles areas that were not covered by anything but got
2565 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002566 */
Mathias Agopianab028732010-03-16 16:41:46 -07002567 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002568 const Region oldVisibleRegion = layer->visibleRegion;
2569 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002570 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2571 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 }
2573 dirty.subtractSelf(aboveOpaqueLayers);
2574
2575 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002576 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577
Mathias Agopianab028732010-03-16 16:41:46 -07002578 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002580
Jesse Halla8026d22012-09-25 13:25:04 -07002581 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 layer->setVisibleRegion(visibleRegion);
2583 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002584 layer->setVisibleNonTransparentRegion(
2585 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002586 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587
Mathias Agopian87baae12012-07-31 12:38:26 -07002588 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589}
2590
Chia-I Wuab0c3192017-08-01 11:29:00 -07002591void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002592 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002593 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002594 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002595 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002596 }
2597 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002598}
2599
Dan Stoza6b9454d2014-11-07 16:00:59 -08002600bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 ALOGV("handlePageFlip");
2603
Brian Andersond6927fb2016-07-23 23:37:30 -07002604 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605
Mathias Agopian4fec8732012-06-29 14:12:52 -07002606 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002607 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002608 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002609
2610 // Store the set of layers that need updates. This set must not change as
2611 // buffers are being latched, as this could result in a deadlock.
2612 // Example: Two producers share the same command stream and:
2613 // 1.) Layer 0 is latched
2614 // 2.) Layer 0 gets a new frame
2615 // 2.) Layer 1 gets a new frame
2616 // 3.) Layer 1 is latched.
2617 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2618 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002619 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002620 if (layer->hasQueuedFrame()) {
2621 frameQueued = true;
2622 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002623 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002624 } else {
2625 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002626 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002627 } else {
2628 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002629 }
Robert Carr2047fae2016-11-28 14:09:09 -08002630 });
2631
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002633 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002634 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002635 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002636 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002637 newDataLatched = true;
2638 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002639 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002640
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002641 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002642
2643 // If we will need to wake up at some time in the future to deal with a
2644 // queued frame that shouldn't be displayed during this vsync period, wake
2645 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002646 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002647 signalLayerUpdate();
2648 }
2649
2650 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002651 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652}
2653
Mathias Agopianad456f92011-01-13 17:53:01 -08002654void SurfaceFlinger::invalidateHwcGeometry()
2655{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002657}
2658
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002659
Fabien Sanglard830b8472016-11-30 16:35:58 -08002660void SurfaceFlinger::doDisplayComposition(
2661 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002662 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663{
Dan Stoza71433162014-02-04 16:22:36 -08002664 // We only need to actually compose the display if:
2665 // 1) It is being handled by hardware composer, which may need this to
2666 // keep its virtual display state machine in sync, or
2667 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002668 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002669 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002671 return;
2672 }
2673
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002675 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002676
2677 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002678 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679}
2680
Chia-I Wub02087d2017-11-09 10:19:54 -08002681bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002682{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002683 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002684
Chia-I Wub02087d2017-11-09 10:19:54 -08002685 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002686 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002688
2689 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002690 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2691 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002692 if (applyColorMatrix) {
2693 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2694 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2695 }
2696
David Sodman105b7dc2017-11-04 20:28:14 -07002697 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 if (hasClientComposition) {
2699 ALOGV("hasClientComposition");
2700
David Sodmanbc815282017-11-05 18:57:52 -08002701 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002702 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002703 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002704 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002705 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002706 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002708 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002709
2710 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002711 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002712 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2713 }
2714 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002715 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002716
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002717 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002718 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002719 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002720 // when using overlays, we assume a fully transparent framebuffer
2721 // NOTE: we could reduce how much we need to clear, for instance
2722 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002723 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002724 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002725 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002726 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002727 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002728 // we're left with the letterbox region
2729 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002731
2732 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002734
Mathias Agopianb9494d52012-04-18 02:28:45 -07002735 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002736 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002737 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002738 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002739 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002740 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002741
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002743 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002744 // scissor on the main display. It should never be needed
2745 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 const Rect& bounds(displayDevice->getBounds());
2747 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002748 if (scissor != bounds) {
2749 // scissor doesn't match the screen's dimensions, so we
2750 // need to clear everything outside of it and enable
2751 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002752
Mathias Agopianf45c5102012-10-24 16:29:17 -07002753 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002755 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002756 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002757 }
2758 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002759 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002760
Mathias Agopian85d751c2012-08-29 16:59:24 -07002761 /*
2762 * and then, render the layers targeted at the framebuffer
2763 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002764
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 ALOGV("Rendering client layers");
2766 const Transform& displayTransform = displayDevice->getTransform();
2767 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002768 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 bool firstLayer = true;
2770 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002771 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772 displayTransform.transform(layer->visibleRegion)));
2773 ALOGV("Layer: %s", layer->getName().string());
2774 ALOGV(" Composition type: %s",
2775 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002776 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 switch (layer->getCompositionType(hwcId)) {
2778 case HWC2::Composition::Cursor:
2779 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002780 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002782 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002784 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002786 // never clear the very first layer since we're
2787 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002788 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002789 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002790 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002791 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002793 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002794 break;
2795 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002797 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002798 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002799 } else {
2800 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002801 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002803 }
2804 } else {
2805 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002807 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002809 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002810 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002811 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002812 }
2813 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002814
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002815 if (applyColorMatrix) {
2816 getRenderEngine().setupColorTransform(oldColorMatrix);
2817 }
2818
Mathias Agopianf45c5102012-10-24 16:29:17 -07002819 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002820 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002821 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822}
2823
Fabien Sanglard830b8472016-11-30 16:35:58 -08002824void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2825 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002826 RenderEngine& engine(getRenderEngine());
2827 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828}
2829
Dan Stoza7d89d062015-04-30 13:29:25 -07002830status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002831 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002832 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 const sp<Layer>& lbc,
2834 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002835{
Dan Stoza7d89d062015-04-30 13:29:25 -07002836 // add this layer to the current state list
2837 {
2838 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002840 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2841 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002842 return NO_MEMORY;
2843 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002844 if (parent == nullptr) {
2845 mCurrentState.layersSortedByZ.add(lbc);
2846 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002847 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002848 ALOGE("addClientLayer called with a removed parent");
2849 return NAME_NOT_FOUND;
2850 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851 parent->addChild(lbc);
2852 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002853
Dan Stoza7d89d062015-04-30 13:29:25 -07002854 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002855 mLayersAdded = true;
2856 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002857 }
2858
Mathias Agopian96f08192010-06-02 23:28:45 -07002859 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002860 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002861
Dan Stoza7d89d062015-04-30 13:29:25 -07002862 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002863}
2864
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002865status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002866 Mutex::Autolock _l(mStateLock);
2867
chaviw8b3871a2017-11-01 17:41:01 -07002868 if (layer->isPendingRemoval()) {
2869 return NO_ERROR;
2870 }
2871
Robert Carr1f0a16a2016-10-24 16:27:39 -07002872 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002873 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002874 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002875 if (topLevelOnly) {
2876 return NO_ERROR;
2877 }
2878
Chia-I Wu98f1c102017-05-30 14:54:08 -07002879 sp<Layer> ancestor = p;
2880 while (ancestor->getParent() != nullptr) {
2881 ancestor = ancestor->getParent();
2882 }
2883 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2884 ALOGE("removeLayer called with a layer whose parent has been removed");
2885 return NAME_NOT_FOUND;
2886 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002887
2888 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002889 } else {
2890 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002891 }
2892
Robert Carr136e2f62017-02-08 17:54:29 -08002893 // As a matter of normal operation, the LayerCleaner will produce a second
2894 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2895 // so we will succeed in promoting it, but it's already been removed
2896 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2897 // otherwise something has gone wrong and we are leaking the layer.
2898 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002899 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2900 layer->getName().string(),
2901 (p != nullptr) ? p->getName().string() : "no-parent");
2902 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002903 } else if (index < 0) {
2904 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002905 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906
Chia-I Wuc6657022017-08-15 11:18:17 -07002907 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002908 mLayersPendingRemoval.add(layer);
2909 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002910 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002911 setTransactionFlags(eTransactionNeeded);
2912 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913}
2914
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002915uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002916 return android_atomic_release_load(&mTransactionFlags);
2917}
2918
Mathias Agopian3f844832013-08-07 21:24:32 -07002919uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2921}
2922
Mathias Agopian3f844832013-08-07 21:24:32 -07002923uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2925 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002926 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927 }
2928 return old;
2929}
2930
Mathias Agopian8b33f032012-07-24 20:43:54 -07002931void SurfaceFlinger::setTransactionState(
2932 const Vector<ComposerState>& state,
2933 const Vector<DisplayState>& displays,
2934 uint32_t flags)
2935{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002936 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002937 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002938 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002939
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002940 if (flags & eAnimation) {
2941 // For window updates that are part of an animation we must wait for
2942 // previous animation "frames" to be handled.
2943 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002944 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002945 if (CC_UNLIKELY(err != NO_ERROR)) {
2946 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002947 // caller after a few seconds.
2948 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2949 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002950 mAnimTransactionPending = false;
2951 break;
2952 }
2953 }
2954 }
2955
Mathias Agopiane57f2922012-08-09 16:29:12 -07002956 size_t count = displays.size();
2957 for (size_t i=0 ; i<count ; i++) {
2958 const DisplayState& s(displays[i]);
2959 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002960 }
2961
Mathias Agopiane57f2922012-08-09 16:29:12 -07002962 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002963 for (size_t i=0 ; i<count ; i++) {
2964 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002965 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08002966 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002967 // IInterface, or one of its own or even one of our own but a
2968 // different type. All these situations would cause us to crash.
2969 //
2970 // NOTE: it would be better to use RTTI as we could directly check
2971 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08002972 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002973 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08002974 if (binder != nullptr) {
2975 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002976 sp<Client> client( static_cast<Client *>(s.client.get()) );
2977 transactionFlags |= setClientStateLocked(client, s.state);
2978 }
2979 }
2980 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002981 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002982
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002983 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2984 // anyway. This can be used as a flush mechanism for previous async transactions.
2985 // Empty animation transaction can be used to simulate back-pressure, so also force a
2986 // transaction for empty animation transactions.
2987 if (transactionFlags == 0 &&
2988 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002989 transactionFlags = eTransactionNeeded;
2990 }
2991
Mathias Agopian386aa982011-11-07 21:58:03 -08002992 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002993 if (mInterceptor.isEnabled()) {
2994 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2995 }
Irvel468051e2016-06-13 16:44:44 -07002996
Mathias Agopian386aa982011-11-07 21:58:03 -08002997 // this triggers the transaction
2998 setTransactionFlags(transactionFlags);
2999
3000 // if this is a synchronous transaction, wait for it to take effect
3001 // before returning.
3002 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003003 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003004 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003005 if (flags & eAnimation) {
3006 mAnimTransactionPending = true;
3007 }
3008 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003009 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3010 if (CC_UNLIKELY(err != NO_ERROR)) {
3011 // just in case something goes wrong in SF, return to the
3012 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003013 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3014 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003015 break;
3016 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018 }
3019}
3020
Mathias Agopiane57f2922012-08-09 16:29:12 -07003021uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3022{
Jesse Hall9a143922012-10-04 16:29:19 -07003023 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3024 if (dpyIdx < 0)
3025 return 0;
3026
Mathias Agopiane57f2922012-08-09 16:29:12 -07003027 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003028 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003029 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003030 const uint32_t what = s.what;
3031 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003032 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003033 disp.surface = s.surface;
3034 flags |= eDisplayTransactionNeeded;
3035 }
3036 }
3037 if (what & DisplayState::eLayerStackChanged) {
3038 if (disp.layerStack != s.layerStack) {
3039 disp.layerStack = s.layerStack;
3040 flags |= eDisplayTransactionNeeded;
3041 }
3042 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003043 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003044 if (disp.orientation != s.orientation) {
3045 disp.orientation = s.orientation;
3046 flags |= eDisplayTransactionNeeded;
3047 }
3048 if (disp.frame != s.frame) {
3049 disp.frame = s.frame;
3050 flags |= eDisplayTransactionNeeded;
3051 }
3052 if (disp.viewport != s.viewport) {
3053 disp.viewport = s.viewport;
3054 flags |= eDisplayTransactionNeeded;
3055 }
3056 }
Michael Lentine47e45402014-07-18 15:34:25 -07003057 if (what & DisplayState::eDisplaySizeChanged) {
3058 if (disp.width != s.width) {
3059 disp.width = s.width;
3060 flags |= eDisplayTransactionNeeded;
3061 }
3062 if (disp.height != s.height) {
3063 disp.height = s.height;
3064 flags |= eDisplayTransactionNeeded;
3065 }
3066 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003067 }
3068 return flags;
3069}
3070
3071uint32_t SurfaceFlinger::setClientStateLocked(
3072 const sp<Client>& client,
3073 const layer_state_t& s)
3074{
Mathias Agopian13127d82013-03-05 17:47:11 -08003075 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003076 if (layer == nullptr) {
3077 return 0;
3078 }
3079
3080 if (layer->isPendingRemoval()) {
3081 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3082 return 0;
3083 }
3084
3085 uint32_t flags = 0;
3086
3087 const uint32_t what = s.what;
3088 bool geometryAppliesWithResize =
3089 what & layer_state_t::eGeometryAppliesWithResize;
3090 if (what & layer_state_t::ePositionChanged) {
3091 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3092 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003093 }
chaviw8b3871a2017-11-01 17:41:01 -07003094 }
3095 if (what & layer_state_t::eLayerChanged) {
3096 // NOTE: index needs to be calculated before we update the state
3097 const auto& p = layer->getParent();
3098 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003099 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003100 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003101 mCurrentState.layersSortedByZ.removeAt(idx);
3102 mCurrentState.layersSortedByZ.add(layer);
3103 // we need traversal (state changed)
3104 // AND transaction (list changed)
3105 flags |= eTransactionNeeded|eTraversalNeeded;
3106 }
chaviw8b3871a2017-11-01 17:41:01 -07003107 } else {
3108 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003109 flags |= eTransactionNeeded|eTraversalNeeded;
3110 }
3111 }
chaviw8b3871a2017-11-01 17:41:01 -07003112 }
3113 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003114 // NOTE: index needs to be calculated before we update the state
3115 const auto& p = layer->getParent();
3116 if (p == nullptr) {
3117 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3118 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3119 mCurrentState.layersSortedByZ.removeAt(idx);
3120 mCurrentState.layersSortedByZ.add(layer);
3121 // we need traversal (state changed)
3122 // AND transaction (list changed)
3123 flags |= eTransactionNeeded|eTraversalNeeded;
3124 }
3125 } else {
3126 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3127 flags |= eTransactionNeeded|eTraversalNeeded;
3128 }
chaviw8b3871a2017-11-01 17:41:01 -07003129 }
3130 }
3131 if (what & layer_state_t::eSizeChanged) {
3132 if (layer->setSize(s.w, s.h)) {
3133 flags |= eTraversalNeeded;
3134 }
3135 }
3136 if (what & layer_state_t::eAlphaChanged) {
3137 if (layer->setAlpha(s.alpha))
3138 flags |= eTraversalNeeded;
3139 }
3140 if (what & layer_state_t::eColorChanged) {
3141 if (layer->setColor(s.color))
3142 flags |= eTraversalNeeded;
3143 }
3144 if (what & layer_state_t::eMatrixChanged) {
3145 if (layer->setMatrix(s.matrix))
3146 flags |= eTraversalNeeded;
3147 }
3148 if (what & layer_state_t::eTransparentRegionChanged) {
3149 if (layer->setTransparentRegionHint(s.transparentRegion))
3150 flags |= eTraversalNeeded;
3151 }
3152 if (what & layer_state_t::eFlagsChanged) {
3153 if (layer->setFlags(s.flags, s.mask))
3154 flags |= eTraversalNeeded;
3155 }
3156 if (what & layer_state_t::eCropChanged) {
3157 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3158 flags |= eTraversalNeeded;
3159 }
3160 if (what & layer_state_t::eFinalCropChanged) {
3161 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3162 flags |= eTraversalNeeded;
3163 }
3164 if (what & layer_state_t::eLayerStackChanged) {
3165 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3166 // We only allow setting layer stacks for top level layers,
3167 // everything else inherits layer stack from its parent.
3168 if (layer->hasParent()) {
3169 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3170 layer->getName().string());
3171 } else if (idx < 0) {
3172 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3173 "that also does not appear in the top level layer list. Something"
3174 " has gone wrong.", layer->getName().string());
3175 } else if (layer->setLayerStack(s.layerStack)) {
3176 mCurrentState.layersSortedByZ.removeAt(idx);
3177 mCurrentState.layersSortedByZ.add(layer);
3178 // we need traversal (state changed)
3179 // AND transaction (list changed)
3180 flags |= eTransactionNeeded|eTraversalNeeded;
3181 }
3182 }
3183 if (what & layer_state_t::eDeferTransaction) {
3184 if (s.barrierHandle != nullptr) {
3185 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3186 } else if (s.barrierGbp != nullptr) {
3187 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3188 if (authenticateSurfaceTextureLocked(gbp)) {
3189 const auto& otherLayer =
3190 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3191 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3192 } else {
3193 ALOGE("Attempt to defer transaction to to an"
3194 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003195 }
3196 }
chaviw8b3871a2017-11-01 17:41:01 -07003197 // We don't trigger a traversal here because if no other state is
3198 // changed, we don't want this to cause any more work
3199 }
3200 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003201 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003202 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003203 if (!hadParent) {
3204 mCurrentState.layersSortedByZ.remove(layer);
3205 }
chaviw8b3871a2017-11-01 17:41:01 -07003206 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003207 }
chaviw8b3871a2017-11-01 17:41:01 -07003208 }
3209 if (what & layer_state_t::eReparentChildren) {
3210 if (layer->reparentChildren(s.reparentHandle)) {
3211 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003212 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003213 }
chaviw8b3871a2017-11-01 17:41:01 -07003214 if (what & layer_state_t::eDetachChildren) {
3215 layer->detachChildren();
3216 }
3217 if (what & layer_state_t::eOverrideScalingModeChanged) {
3218 layer->setOverrideScalingMode(s.overrideScalingMode);
3219 // We don't trigger a traversal here because if no other state is
3220 // changed, we don't want this to cause any more work
3221 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003222 return flags;
3223}
3224
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003225status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003226 const String8& name,
3227 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003228 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003229 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3230 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003232 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003233 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003234 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003235 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003236 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003237
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003238 status_t result = NO_ERROR;
3239
3240 sp<Layer> layer;
3241
Cody Northropbc755282017-03-31 12:00:08 -06003242 String8 uniqueName = getUniqueLayerName(name);
3243
Mathias Agopian3165cc22012-08-08 19:42:09 -07003244 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3245 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003246 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003247 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003248 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003249
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250 break;
chaviw13fdc492017-06-27 12:40:18 -07003251 case ISurfaceComposerClient::eFXSurfaceColor:
3252 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003253 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003254 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003255 break;
3256 default:
3257 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 break;
3259 }
3260
Dan Stoza7d89d062015-04-30 13:29:25 -07003261 if (result != NO_ERROR) {
3262 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003264
Chia-I Wuab0c3192017-08-01 11:29:00 -07003265 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3266 // TODO b/64227542
3267 if (windowType == 441731) {
3268 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3269 layer->setPrimaryDisplayOnly();
3270 }
3271
Albert Chaulk479c60c2017-01-27 14:21:34 -05003272 layer->setInfo(windowType, ownerUid);
3273
Robert Carr1f0a16a2016-10-24 16:27:39 -07003274 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003275 if (result != NO_ERROR) {
3276 return result;
3277 }
Irvelffc9efc2016-07-27 15:16:37 -07003278 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003279
3280 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003281 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282}
3283
Cody Northropbc755282017-03-31 12:00:08 -06003284String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3285{
3286 bool matchFound = true;
3287 uint32_t dupeCounter = 0;
3288
3289 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3290 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3291
3292 // Loop over layers until we're sure there is no matching name
3293 while (matchFound) {
3294 matchFound = false;
3295 mDrawingState.traverseInZOrder([&](Layer* layer) {
3296 if (layer->getName() == uniqueName) {
3297 matchFound = true;
3298 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3299 }
3300 });
3301 }
3302
3303 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3304
3305 return uniqueName;
3306}
3307
David Sodman0c69cad2017-08-21 12:12:51 -07003308status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003309 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3310 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003311{
3312 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003313 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314 case PIXEL_FORMAT_TRANSPARENT:
3315 case PIXEL_FORMAT_TRANSLUCENT:
3316 format = PIXEL_FORMAT_RGBA_8888;
3317 break;
3318 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003319 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003320 break;
3321 }
3322
David Sodman0c69cad2017-08-21 12:12:51 -07003323 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3324 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003325 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003326 *handle = layer->getHandle();
3327 *gbp = layer->getProducer();
3328 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003330
David Sodman0c69cad2017-08-21 12:12:51 -07003331 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003332 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003333}
3334
chaviw13fdc492017-06-27 12:40:18 -07003335status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003336 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003337 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338{
chaviw13fdc492017-06-27 12:40:18 -07003339 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003340 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003341 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003342}
3343
Mathias Agopianac9fa422013-02-11 16:40:36 -08003344status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003345{
Robert Carr9524cb32017-02-13 11:32:32 -08003346 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003347 status_t err = NO_ERROR;
3348 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003349 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003350 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003351 err = removeLayer(l);
3352 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3353 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003354 }
3355 return err;
3356}
3357
Mathias Agopian13127d82013-03-05 17:47:11 -08003358status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003359{
Mathias Agopian67106042013-03-14 19:18:13 -07003360 // called by ~LayerCleaner() when all references to the IBinder (handle)
3361 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003362 sp<Layer> l = layer.promote();
3363 if (l == nullptr) {
3364 // The layer has already been removed, carry on
3365 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003366 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003367 // If we have a parent, then we can continue to live as long as it does.
3368 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369}
3370
Mathias Agopianb60314a2012-04-10 22:09:54 -07003371// ---------------------------------------------------------------------------
3372
Andy McFadden13a082e2012-08-24 10:16:42 -07003373void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003374 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003375 Vector<ComposerState> state;
3376 Vector<DisplayState> displays;
3377 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003378 d.what = DisplayState::eDisplayProjectionChanged |
3379 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003380 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003381 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003382 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003383 d.frame.makeInvalid();
3384 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003385 d.width = 0;
3386 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003387 displays.add(d);
3388 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003389 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3390 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003391
David Sodman105b7dc2017-11-04 20:28:14 -07003392 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003393 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003394 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003395
Brian Andersond0010582017-03-07 13:20:31 -08003396 // Use phase of 0 since phase is not known.
3397 // Use latency of 0, which will snap to the ideal latency.
3398 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003399}
3400
3401void SurfaceFlinger::initializeDisplays() {
3402 class MessageScreenInitialized : public MessageBase {
3403 SurfaceFlinger* flinger;
3404 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003405 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003406 virtual bool handler() {
3407 flinger->onInitializeDisplays();
3408 return true;
3409 }
3410 };
3411 sp<MessageBase> msg = new MessageScreenInitialized(this);
3412 postMessageAsync(msg); // we may be called from main thread, use async message
3413}
3414
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003415void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003416 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003417 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3418 this);
3419 int32_t type = hw->getDisplayType();
3420 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003421
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003422 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003423 return;
3424 }
3425
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003426 hw->setPowerMode(mode);
3427 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3428 ALOGW("Trying to set power mode for virtual display");
3429 return;
3430 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003431
Irvelffc9efc2016-07-27 15:16:37 -07003432 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003433 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003434 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3435 if (idx < 0) {
3436 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3437 return;
3438 }
3439 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3440 }
3441
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003442 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003443 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003444 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003445 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3446 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003447 // FIXME: eventthread only knows about the main display right now
3448 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003449 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003450 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003451
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003452 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003453 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003454 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003455
3456 struct sched_param param = {0};
3457 param.sched_priority = 1;
3458 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3459 ALOGW("Couldn't set SCHED_FIFO on display on");
3460 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003461 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003462 // Turn off the display
3463 struct sched_param param = {0};
3464 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3465 ALOGW("Couldn't set SCHED_OTHER on display off");
3466 }
3467
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003468 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3469 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003470 disableHardwareVsync(true); // also cancels any in-progress resync
3471
Mathias Agopiancde87a32012-09-13 14:09:01 -07003472 // FIXME: eventthread only knows about the main display right now
3473 mEventThread->onScreenReleased();
3474 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003475
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003476 getHwComposer().setPowerMode(type, mode);
3477 mVisibleRegionsDirty = true;
3478 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003479 } else if (mode == HWC_POWER_MODE_DOZE ||
3480 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003481 // Update display while dozing
3482 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003483 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3484 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003485 // FIXME: eventthread only knows about the main display right now
3486 mEventThread->onScreenAcquired();
3487 resyncToHardwareVsync(true);
3488 }
3489 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3490 // Leave display going to doze
3491 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3492 disableHardwareVsync(true); // also cancels any in-progress resync
3493 // FIXME: eventthread only knows about the main display right now
3494 mEventThread->onScreenReleased();
3495 }
3496 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003497 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003498 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003499 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003500 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003501}
3502
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003503void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3504 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003505 SurfaceFlinger& mFlinger;
3506 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003507 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003508 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003509 MessageSetPowerMode(SurfaceFlinger& flinger,
3510 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3511 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003512 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003513 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003514 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003515 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003516 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003517 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003518 ALOGW("Attempt to set power mode = %d for virtual display",
3519 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003520 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003521 mFlinger.setPowerModeInternal(
3522 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003523 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003524 return true;
3525 }
3526 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003527 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003528 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003529}
3530
3531// ---------------------------------------------------------------------------
3532
Vishnu Nair6a408532017-10-24 09:11:27 -07003533status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003535
Mathias Agopianbd115332013-04-18 16:41:04 -07003536 IPCThreadState* ipc = IPCThreadState::self();
3537 const int pid = ipc->getCallingPid();
3538 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003539
Mathias Agopianbd115332013-04-18 16:41:04 -07003540 if ((uid != AID_SHELL) &&
3541 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003542 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003543 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003545 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003546 // (this would indicate SF is stuck, but we want to be able to
3547 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003548 status_t err = mStateLock.timedLock(s2ns(1));
3549 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003550 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003551 result.appendFormat(
3552 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3553 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003554 }
3555
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003556 bool dumpAll = true;
3557 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003558 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003559
3560 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003561 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003562 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3563 dumpAll = false;
3564 }
3565
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003566 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003567 if ((index < numArgs) &&
3568 (args[index] == String16("--list"))) {
3569 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003570 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003571 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003572 }
3573
3574 if ((index < numArgs) &&
3575 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003576 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003577 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003578 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003579 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003580
3581 if ((index < numArgs) &&
3582 (args[index] == String16("--latency-clear"))) {
3583 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003584 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003585 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003586 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003587
3588 if ((index < numArgs) &&
3589 (args[index] == String16("--dispsync"))) {
3590 index++;
3591 mPrimaryDispSync.dump(result);
3592 dumpAll = false;
3593 }
Dan Stozab90cf072015-03-05 11:05:59 -08003594
3595 if ((index < numArgs) &&
3596 (args[index] == String16("--static-screen"))) {
3597 index++;
3598 dumpStaticScreenStats(result);
3599 dumpAll = false;
3600 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003601
3602 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003603 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003604 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003605 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003606 dumpAll = false;
3607 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003608
3609 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3610 index++;
3611 dumpWideColorInfo(result);
3612 dumpAll = false;
3613 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003615
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003616 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003617 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003618 }
3619
Mathias Agopian9795c422009-08-26 16:36:26 -07003620 if (locked) {
3621 mStateLock.unlock();
3622 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623 }
3624 write(fd, result.string(), result.size());
3625 return NO_ERROR;
3626}
3627
Dan Stozac7014012014-02-14 15:03:43 -08003628void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3629 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003630{
Robert Carr2047fae2016-11-28 14:09:09 -08003631 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003632 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003633 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003634}
3635
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003636void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003637 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003638{
3639 String8 name;
3640 if (index < args.size()) {
3641 name = String8(args[index]);
3642 index++;
3643 }
3644
David Sodman105b7dc2017-11-04 20:28:14 -07003645 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003646 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003647 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003648
3649 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003650 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003651 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003652 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003653 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003654 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003655 }
Robert Carr2047fae2016-11-28 14:09:09 -08003656 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003657 }
3658}
3659
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003660void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003661 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003662{
3663 String8 name;
3664 if (index < args.size()) {
3665 name = String8(args[index]);
3666 index++;
3667 }
3668
Robert Carr2047fae2016-11-28 14:09:09 -08003669 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003670 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003671 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003672 }
Robert Carr2047fae2016-11-28 14:09:09 -08003673 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003674
Svetoslavd85084b2014-03-20 10:28:31 -07003675 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003676}
3677
Jamie Gennis6547ff42013-07-16 20:12:42 -07003678// This should only be called from the main thread. Otherwise it would need
3679// the lock and should use mCurrentState rather than mDrawingState.
3680void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003681 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003682 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003683 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003684
3685 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3686}
3687
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003688void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003689{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003690 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003691
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003692 if (isLayerTripleBufferingDisabled())
3693 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003694
3695 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003696 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003697 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003698 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003699 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3700 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003701 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003702}
3703
Dan Stozab90cf072015-03-05 11:05:59 -08003704void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3705{
3706 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003707 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3708 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003709 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003710 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003711 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3712 b + 1, bucketTimeSec, percent);
3713 }
David Sodman4a36e932017-11-07 14:29:47 -08003714 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003715 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003716 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003717 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003718 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003719}
3720
Dan Stozae77c7662016-05-13 11:37:28 -07003721void SurfaceFlinger::recordBufferingStats(const char* layerName,
3722 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003723 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3724 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003725 for (const auto& segment : history) {
3726 if (!segment.usedThirdBuffer) {
3727 stats.twoBufferTime += segment.totalTime;
3728 }
3729 if (segment.occupancyAverage < 1.0f) {
3730 stats.doubleBufferedTime += segment.totalTime;
3731 } else if (segment.occupancyAverage < 2.0f) {
3732 stats.tripleBufferedTime += segment.totalTime;
3733 }
3734 ++stats.numSegments;
3735 stats.totalTime += segment.totalTime;
3736 }
3737}
3738
Brian Andersond6927fb2016-07-23 23:37:30 -07003739void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3740 result.appendFormat("Layer frame timestamps:\n");
3741
3742 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3743 const size_t count = currentLayers.size();
3744 for (size_t i=0 ; i<count ; i++) {
3745 currentLayers[i]->dumpFrameEvents(result);
3746 }
3747}
3748
Dan Stozae77c7662016-05-13 11:37:28 -07003749void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3750 result.append("Buffering stats:\n");
3751 result.append(" [Layer name] <Active time> <Two buffer> "
3752 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003753 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003754 typedef std::tuple<std::string, float, float, float> BufferTuple;
3755 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003756 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003757 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003758 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003759 if (stats.numSegments == 0) {
3760 continue;
3761 }
3762 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3763 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3764 stats.totalTime;
3765 float doubleBufferRatio = static_cast<float>(
3766 stats.doubleBufferedTime) / stats.totalTime;
3767 float tripleBufferRatio = static_cast<float>(
3768 stats.tripleBufferedTime) / stats.totalTime;
3769 sorted.insert({activeTime, {name, twoBufferRatio,
3770 doubleBufferRatio, tripleBufferRatio}});
3771 }
3772 for (const auto& sortedPair : sorted) {
3773 float activeTime = sortedPair.first;
3774 const BufferTuple& values = sortedPair.second;
3775 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3776 std::get<0>(values).c_str(), activeTime,
3777 std::get<1>(values), std::get<2>(values),
3778 std::get<3>(values));
3779 }
3780 result.append("\n");
3781}
3782
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003783void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3784 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003785 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003786
3787 // TODO: print out if wide-color mode is active or not
3788
3789 for (size_t d = 0; d < mDisplays.size(); d++) {
3790 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3791 int32_t hwcId = displayDevice->getHwcDisplayId();
3792 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3793 continue;
3794 }
3795
3796 result.appendFormat("Display %d color modes:\n", hwcId);
3797 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3798 for (auto&& mode : modes) {
3799 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3800 }
3801
3802 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3803 result.appendFormat(" Current color mode: %s (%d)\n",
3804 decodeColorMode(currentMode).c_str(), currentMode);
3805 }
3806 result.append("\n");
3807}
3808
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003809LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003810 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003811 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3812 const State& state = useDrawing ? mDrawingState : mCurrentState;
3813 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003814 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003815 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003816 });
3817
3818 return layersProto;
3819}
3820
Mathias Agopian74d211a2013-04-22 16:55:35 +02003821void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3822 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003823{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 bool colorize = false;
3825 if (index < args.size()
3826 && (args[index] == String16("--color"))) {
3827 colorize = true;
3828 index++;
3829 }
3830
3831 Colorizer colorizer(colorize);
3832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 // figure out if we're stuck somewhere
3834 const nsecs_t now = systemTime();
3835 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3836 const nsecs_t inTransaction(mDebugInTransaction);
3837 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3838 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3839
3840 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003841 * Dump library configuration.
3842 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003843
3844 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003845 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003846 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003847 appendSfConfigString(result);
3848 appendUiConfigString(result);
3849 appendGuiConfigString(result);
3850 result.append("\n");
3851
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003852 result.append("\nWide-Color information:\n");
3853 dumpWideColorInfo(result);
3854
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003855 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003856 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003857 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003858 result.append(SyncFeatures::getInstance().toString());
3859 result.append("\n");
3860
David Sodman105b7dc2017-11-04 20:28:14 -07003861 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003862
Andy McFadden41d67d72014-04-25 16:58:34 -07003863 colorizer.bold(result);
3864 result.append("DispSync configuration: ");
3865 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003866 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003867 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003868 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003869 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003870 result.append("\n");
3871
Dan Stozab90cf072015-03-05 11:05:59 -08003872 // Dump static screen stats
3873 result.append("\n");
3874 dumpStaticScreenStats(result);
3875 result.append("\n");
3876
Dan Stozae77c7662016-05-13 11:37:28 -07003877 dumpBufferingStats(result);
3878
Andy McFadden4803b742012-09-24 19:07:20 -07003879 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003880 * Dump the visible layer list
3881 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003882 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003883 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003884 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003885
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003886 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003887 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3888 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003889
3890 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003891 * Dump Display state
3892 */
3893
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003894 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003895 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003896 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3898 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003899 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003900 }
3901
3902 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003903 * Dump SurfaceFlinger global state
3904 */
3905
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003906 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003907 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003908 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909
Mathias Agopian888c8222012-08-04 21:10:38 -07003910 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003911 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003912
David Sodmanbc815282017-11-05 18:57:52 -08003913 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003914
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003915 if (hw) {
3916 hw->undefinedRegion.dump(result, "undefinedRegion");
3917 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3918 hw->getOrientation(), hw->isDisplayOn());
3919 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921 " last eglSwapBuffers() time: %f us\n"
3922 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003923 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924 " refresh-rate : %f fps\n"
3925 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003926 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003927 " gpu_to_cpu_unsupported : %d\n"
3928 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929 mLastSwapBufferTime/1000.0,
3930 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003931 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003932 1e9 / activeConfig->getVsyncPeriod(),
3933 activeConfig->getDpiX(),
3934 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003935 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003936
Mathias Agopian74d211a2013-04-22 16:55:35 +02003937 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939
Mathias Agopian74d211a2013-04-22 16:55:35 +02003940 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003941 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003942
3943 /*
3944 * VSYNC state
3945 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003946 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003947 result.append("\n");
3948
3949 /*
3950 * HWC layer minidump
3951 */
3952 for (size_t d = 0; d < mDisplays.size(); d++) {
3953 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3954 int32_t hwcId = displayDevice->getHwcDisplayId();
3955 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3956 continue;
3957 }
3958
3959 result.appendFormat("Display %d HWC layers:\n", hwcId);
3960 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003961 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003962 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003963 });
Dan Stozae22aec72016-08-01 13:20:59 -07003964 result.append("\n");
3965 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966
3967 /*
3968 * Dump HWComposer state
3969 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003970 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003971 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003972 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003973 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003974 result.appendFormat(" h/w composer %s\n",
3975 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003976 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003977
3978 /*
3979 * Dump gralloc state
3980 */
3981 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3982 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003983
3984 /*
3985 * Dump VrFlinger state if in use.
3986 */
3987 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3988 result.append("VrFlinger state:\n");
3989 result.append(mVrFlinger->Dump().c_str());
3990 result.append("\n");
3991 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992}
3993
Mathias Agopian13127d82013-03-05 17:47:11 -08003994const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003995SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003996 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003997 wp<IBinder> dpy;
3998 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3999 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4000 dpy = mDisplays.keyAt(i);
4001 break;
4002 }
4003 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004004 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004005 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4006 // Just use the primary display so we have something to return
4007 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004009 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004010}
4011
Keun young Park63f165f2012-08-31 10:53:36 -07004012bool SurfaceFlinger::startDdmConnection()
4013{
4014 void* libddmconnection_dso =
4015 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4016 if (!libddmconnection_dso) {
4017 return false;
4018 }
4019 void (*DdmConnection_start)(const char* name);
4020 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004021 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004022 if (!DdmConnection_start) {
4023 dlclose(libddmconnection_dso);
4024 return false;
4025 }
4026 (*DdmConnection_start)(getServiceName());
4027 return true;
4028}
4029
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004030status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 switch (code) {
4032 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004033 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004034 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004035 case CLEAR_ANIMATION_FRAME_STATS:
4036 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004037 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004038 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004039 case ENABLE_VSYNC_INJECTIONS:
4040 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041 {
4042 // codes that require permission check
4043 IPCThreadState* ipc = IPCThreadState::self();
4044 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004045 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004046 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004047 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004048 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004049 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004051 break;
4052 }
Robert Carr1db73f62016-12-21 12:58:51 -08004053 /*
4054 * Calling setTransactionState is safe, because you need to have been
4055 * granted a reference to Client* and Handle* to do anything with it.
4056 *
4057 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4058 */
4059 case SET_TRANSACTION_STATE:
4060 case CREATE_SCOPED_CONNECTION:
4061 {
4062 return OK;
4063 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004064 case CAPTURE_SCREEN:
4065 {
4066 // codes that require permission check
4067 IPCThreadState* ipc = IPCThreadState::self();
4068 const int pid = ipc->getCallingPid();
4069 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004070 if ((uid != AID_GRAPHICS) &&
4071 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004072 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004073 return PERMISSION_DENIED;
4074 }
4075 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004076 }
chaviwa76b2712017-09-20 12:02:26 -07004077 case CAPTURE_LAYERS: {
4078 IPCThreadState* ipc = IPCThreadState::self();
4079 const int pid = ipc->getCallingPid();
4080 const int uid = ipc->getCallingUid();
4081 if ((uid != AID_GRAPHICS) &&
4082 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4083 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4084 return PERMISSION_DENIED;
4085 }
4086 break;
4087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004089 return OK;
4090}
4091
4092status_t SurfaceFlinger::onTransact(
4093 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4094{
4095 status_t credentialCheck = CheckTransactCodeCredentials(code);
4096 if (credentialCheck != OK) {
4097 return credentialCheck;
4098 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004099
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004100 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4101 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004102 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004103 IPCThreadState* ipc = IPCThreadState::self();
4104 const int uid = ipc->getCallingUid();
4105 if (CC_UNLIKELY(uid != AID_SYSTEM
4106 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004107 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004108 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004109 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 return PERMISSION_DENIED;
4111 }
4112 int n;
4113 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004114 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004115 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 return NO_ERROR;
4117 case 1002: // SHOW_UPDATES
4118 n = data.readInt32();
4119 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004120 invalidateHwcGeometry();
4121 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004124 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004125 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004127 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004128 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004129 setTransactionFlags(
4130 eTransactionNeeded|
4131 eDisplayTransactionNeeded|
4132 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004133 return NO_ERROR;
4134 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004135 case 1006:{ // send empty update
4136 signalRefresh();
4137 return NO_ERROR;
4138 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004139 case 1008: // toggle use of hw composer
4140 n = data.readInt32();
4141 mDebugDisableHWC = n ? 1 : 0;
4142 invalidateHwcGeometry();
4143 repaintEverything();
4144 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004145 case 1009: // toggle use of transform hint
4146 n = data.readInt32();
4147 mDebugDisableTransformHint = n ? 1 : 0;
4148 invalidateHwcGeometry();
4149 repaintEverything();
4150 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004151 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004152 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 reply->writeInt32(0);
4154 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004155 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004156 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157 return NO_ERROR;
4158 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004159 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004160 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004161 return NO_ERROR;
4162 }
4163 case 1014: {
4164 // daltonize
4165 n = data.readInt32();
4166 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004167 case 1:
4168 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4169 break;
4170 case 2:
4171 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4172 break;
4173 case 3:
4174 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4175 break;
4176 default:
4177 mDaltonizer.setType(ColorBlindnessType::None);
4178 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004179 }
4180 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004181 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004182 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004183 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004184 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004185 invalidateHwcGeometry();
4186 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004187 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004189 case 1015: {
4190 // apply a color matrix
4191 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004192 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004193 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004194 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004195 for (size_t j = 0; j < 4; j++) {
4196 mColorMatrix[i][j] = data.readFloat();
4197 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004198 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004199 } else {
4200 mColorMatrix = mat4();
4201 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004202
4203 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4204 // the division by w in the fragment shader
4205 float4 lastRow(transpose(mColorMatrix)[3]);
4206 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4207 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4208 }
4209
Alan Viverette9c5a3332013-09-12 20:04:35 -07004210 invalidateHwcGeometry();
4211 repaintEverything();
4212 return NO_ERROR;
4213 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004214 // This is an experimental interface
4215 // Needs to be shifted to proper binder interface when we productize
4216 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004217 n = data.readInt32();
4218 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004219 return NO_ERROR;
4220 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004221 case 1017: {
4222 n = data.readInt32();
4223 mForceFullDamage = static_cast<bool>(n);
4224 return NO_ERROR;
4225 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004226 case 1018: { // Modify Choreographer's phase offset
4227 n = data.readInt32();
4228 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4229 return NO_ERROR;
4230 }
4231 case 1019: { // Modify SurfaceFlinger's phase offset
4232 n = data.readInt32();
4233 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4234 return NO_ERROR;
4235 }
Irvel468051e2016-06-13 16:44:44 -07004236 case 1020: { // Layer updates interceptor
4237 n = data.readInt32();
4238 if (n) {
4239 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004240 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004241 }
4242 else{
4243 ALOGV("Interceptor disabled");
4244 mInterceptor.disable();
4245 }
4246 return NO_ERROR;
4247 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004248 case 1021: { // Disable HWC virtual displays
4249 n = data.readInt32();
4250 mUseHwcVirtualDisplays = !n;
4251 return NO_ERROR;
4252 }
Romain Guy0147a172017-06-01 13:53:56 -07004253 case 1022: { // Set saturation boost
4254 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4255
4256 invalidateHwcGeometry();
4257 repaintEverything();
4258 return NO_ERROR;
4259 }
Romain Guy54f154a2017-10-24 21:40:32 +01004260 case 1023: { // Set native mode
4261 mForceNativeColorMode = data.readInt32() == 1;
4262
4263 invalidateHwcGeometry();
4264 repaintEverything();
4265 return NO_ERROR;
4266 }
4267 case 1024: { // Is wide color gamut rendering/color management supported?
4268 reply->writeBool(hasWideColorDisplay);
4269 return NO_ERROR;
4270 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004271 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004272 n = data.readInt32();
4273 if (n) {
4274 ALOGV("LayerTracing enabled");
4275 mTracing.enable();
4276 doTracing("tracing.enable");
4277 reply->writeInt32(NO_ERROR);
4278 } else {
4279 ALOGV("LayerTracing disabled");
4280 status_t err = mTracing.disable();
4281 reply->writeInt32(err);
4282 }
4283 return NO_ERROR;
4284 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004285 case 1026: { // Get layer tracing status
4286 reply->writeBool(mTracing.isEnabled());
4287 return NO_ERROR;
4288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 }
4290 }
4291 return err;
4292}
4293
Steven Thomas6d8110b2017-08-31 18:24:21 -07004294void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004295 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004296 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004297}
4298
Steven Thomas6d8110b2017-08-31 18:24:21 -07004299void SurfaceFlinger::repaintEverything() {
4300 ConditionalLock _l(mStateLock,
4301 std::this_thread::get_id() != mMainThreadId);
4302 repaintEverythingLocked();
4303}
4304
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004305// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4306class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004307public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004308 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4309 ~WindowDisconnector() {
4310 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004311 }
4312
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004313private:
4314 ANativeWindow* mWindow;
4315 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004316};
4317
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004318status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4319 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4320 int32_t minLayerZ, int32_t maxLayerZ,
4321 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004322 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004323 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004324
chaviwa76b2712017-09-20 12:02:26 -07004325 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4326
4327 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4328 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4329
4330 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4331 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004332 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004333}
4334
4335status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004336 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004337 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004338 ATRACE_CALL();
4339
4340 class LayerRenderArea : public RenderArea {
4341 public:
chaviw7206d492017-11-10 16:16:12 -08004342 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004343 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004344 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004345 const Transform& getTransform() const override {
4346 // Make the top level transform the inverse the transform and it's parent so it sets
4347 // the whole capture back to 0,0
4348 return *new Transform(mLayer->getTransform().inverse());
4349 }
4350 Rect getBounds() const override {
4351 const Layer::State& layerState(mLayer->getDrawingState());
4352 return Rect(layerState.active.w, layerState.active.h);
4353 }
4354 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4355 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4356 bool isSecure() const override { return false; }
4357 bool needsFiltering() const override { return false; }
4358
chaviw7206d492017-11-10 16:16:12 -08004359 Rect getSourceCrop() const override {
4360 if (mCrop.isEmpty()) {
4361 return getBounds();
4362 } else {
4363 return mCrop;
4364 }
4365 }
chaviwa76b2712017-09-20 12:02:26 -07004366 bool getWideColorSupport() const override { return false; }
4367 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4368
4369 private:
chaviw7206d492017-11-10 16:16:12 -08004370 const sp<Layer> mLayer;
4371 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004372 };
4373
4374 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4375 auto parent = layerHandle->owner.promote();
4376
chaviw7206d492017-11-10 16:16:12 -08004377 if (parent == nullptr || parent->isPendingRemoval()) {
4378 ALOGE("captureLayers called with a removed parent");
4379 return NAME_NOT_FOUND;
4380 }
4381
4382 Rect crop(sourceCrop);
4383 if (sourceCrop.width() <= 0) {
4384 crop.left = 0;
4385 crop.right = parent->getCurrentState().active.w;
4386 }
4387
4388 if (sourceCrop.height() <= 0) {
4389 crop.top = 0;
4390 crop.bottom = parent->getCurrentState().active.h;
4391 }
4392
4393 int32_t reqWidth = crop.width() * frameScale;
4394 int32_t reqHeight = crop.height() * frameScale;
4395
4396 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4397
chaviwa76b2712017-09-20 12:02:26 -07004398 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4399 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4400 if (!layer->isVisible()) {
4401 return;
4402 }
4403 visitor(layer);
4404 });
4405 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004406 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004407}
4408
4409status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4410 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004411 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004412 bool useIdentityTransform) {
4413 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004414
chaviwa76b2712017-09-20 12:02:26 -07004415 renderArea.updateDimensions();
4416
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004417 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4418 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4419 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4420 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004421
4422 // This mutex protects syncFd and captureResult for communication of the return values from the
4423 // main thread back to this Binder thread
4424 std::mutex captureMutex;
4425 std::condition_variable captureCondition;
4426 std::unique_lock<std::mutex> captureLock(captureMutex);
4427 int syncFd = -1;
4428 std::optional<status_t> captureResult;
4429
Robert Carr03480e22018-01-04 16:02:06 -08004430 const int uid = IPCThreadState::self()->getCallingUid();
4431 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4432
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004433 sp<LambdaMessage> message = new LambdaMessage([&]() {
4434 // If there is a refresh pending, bug out early and tell the binder thread to try again
4435 // after the refresh.
4436 if (mRefreshPending) {
4437 ATRACE_NAME("Skipping screenshot for now");
4438 std::unique_lock<std::mutex> captureLock(captureMutex);
4439 captureResult = std::make_optional<status_t>(EAGAIN);
4440 captureCondition.notify_one();
4441 return;
4442 }
4443
4444 status_t result = NO_ERROR;
4445 int fd = -1;
4446 {
4447 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004448 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004449 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004450 }
4451
4452 {
4453 std::unique_lock<std::mutex> captureLock(captureMutex);
4454 syncFd = fd;
4455 captureResult = std::make_optional<status_t>(result);
4456 captureCondition.notify_one();
4457 }
4458 });
4459
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004460 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004461 if (result == NO_ERROR) {
4462 captureCondition.wait(captureLock, [&]() { return captureResult; });
4463 while (*captureResult == EAGAIN) {
4464 captureResult.reset();
4465 result = postMessageAsync(message);
4466 if (result != NO_ERROR) {
4467 return result;
4468 }
4469 captureCondition.wait(captureLock, [&]() { return captureResult; });
4470 }
4471 result = *captureResult;
4472 }
4473
4474 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004475 sync_wait(syncFd, -1);
4476 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004477 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004478
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004479 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004480}
4481
chaviwa76b2712017-09-20 12:02:26 -07004482void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4483 TraverseLayersFunction traverseLayers, bool yswap,
4484 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004485 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004486
Mathias Agopian3f844832013-08-07 21:24:32 -07004487 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004488
4489 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004490 const auto raWidth = renderArea.getWidth();
4491 const auto raHeight = renderArea.getHeight();
4492
4493 const auto reqWidth = renderArea.getReqWidth();
4494 const auto reqHeight = renderArea.getReqHeight();
4495 Rect sourceCrop = renderArea.getSourceCrop();
4496
4497 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4498 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004499
Dan Stozac1879002014-05-22 15:59:05 -07004500 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004501 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004502 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004503 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004504 }
4505
4506 // ensure that sourceCrop is inside screen
4507 if (sourceCrop.left < 0) {
4508 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4509 }
chaviwa76b2712017-09-20 12:02:26 -07004510 if (sourceCrop.right > raWidth) {
4511 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004512 }
4513 if (sourceCrop.top < 0) {
4514 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4515 }
chaviwa76b2712017-09-20 12:02:26 -07004516 if (sourceCrop.bottom > raHeight) {
4517 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004518 }
4519
chaviwa76b2712017-09-20 12:02:26 -07004520 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004521 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4522 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004523
Mathias Agopian180f10d2013-04-10 22:55:41 -07004524 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004525 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004526
4527 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004528 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4529 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004530 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004531
4532 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004533 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004534
chaviwa76b2712017-09-20 12:02:26 -07004535 traverseLayers([&](Layer* layer) {
4536 if (filtering) layer->setFiltering(true);
4537 layer->draw(renderArea, useIdentityTransform);
4538 if (filtering) layer->setFiltering(false);
4539 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004540}
4541
chaviwa76b2712017-09-20 12:02:26 -07004542status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4543 TraverseLayersFunction traverseLayers,
4544 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004545 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004546 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004547 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004548 ATRACE_CALL();
4549
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004550 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004551
4552 traverseLayers([&](Layer* layer) {
4553 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4554 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004555
Robert Carr03480e22018-01-04 16:02:06 -08004556 // We allow the system server to take screenshots of secure layers for
4557 // use in situations like the Screen-rotation animation and place
4558 // the impetus on WindowManager to not persist them.
4559 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004560 ALOGW("FB is protected: PERMISSION_DENIED");
4561 return PERMISSION_DENIED;
4562 }
4563
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004564 // this binds the given EGLImage as a framebuffer for the
4565 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004566 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4567 if (bufferBond.getStatus() != NO_ERROR) {
4568 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004569 return INVALID_OPERATION;
4570 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004571
Dan Stozaabcda352017-06-01 14:37:39 -07004572 // this will in fact render into our dequeued buffer
4573 // via an FBO, which means we didn't have to create
4574 // an EGLSurface and therefore we're not
4575 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004576 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004577
Dan Stozaabcda352017-06-01 14:37:39 -07004578 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004579 getRenderEngine().finish();
4580 *outSyncFd = -1;
4581
chaviwa76b2712017-09-20 12:02:26 -07004582 const auto reqWidth = renderArea.getReqWidth();
4583 const auto reqHeight = renderArea.getReqHeight();
4584
Dan Stozaabcda352017-06-01 14:37:39 -07004585 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4586 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004587 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004588 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004589 } else {
4590 base::unique_fd syncFd = getRenderEngine().flush();
4591 if (syncFd < 0) {
4592 getRenderEngine().finish();
4593 }
4594 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004595 }
4596
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004597 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004598}
4599
Mathias Agopiand5556842013-09-19 17:08:37 -07004600void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004601 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004602 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004603 for (size_t y = 0; y < h; y++) {
4604 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4605 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004606 if (p[x] != 0xFF000000) return;
4607 }
4608 }
chaviwa76b2712017-09-20 12:02:26 -07004609 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004610
Robert Carr2047fae2016-11-28 14:09:09 -08004611 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004612 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004613 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004614 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4615 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4616 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4617 static_cast<float>(state.color.a));
4618 i++;
4619 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004620 }
4621}
4622
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004623// ---------------------------------------------------------------------------
4624
Dan Stoza412903f2017-04-27 13:42:17 -07004625void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4626 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004627}
4628
Dan Stoza412903f2017-04-27 13:42:17 -07004629void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4630 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004631}
4632
chaviwa76b2712017-09-20 12:02:26 -07004633void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4634 int32_t maxLayerZ,
4635 const LayerVector::Visitor& visitor) {
4636 // We loop through the first level of layers without traversing,
4637 // as we need to interpret min/max layer Z in the top level Z space.
4638 for (const auto& layer : mDrawingState.layersSortedByZ) {
4639 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4640 continue;
4641 }
4642 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004643 // relative layers are traversed in Layer::traverseInZOrder
4644 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004645 continue;
4646 }
4647 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004648 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4649 return;
4650 }
chaviwa76b2712017-09-20 12:02:26 -07004651 if (!layer->isVisible()) {
4652 return;
4653 }
4654 visitor(layer);
4655 });
4656 }
4657}
4658
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004660
4661
4662#if defined(__gl_h_)
4663#error "don't include gl/gl.h in this file"
4664#endif
4665
4666#if defined(__gl2_h_)
4667#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004668#endif