blob: 1380b01a1c8ff45ae4bd7633c85822c912fce537 [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
Lloyd Piquee83f9312018-02-01 12:53:17 -0800427class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428public:
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(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mVsyncMutex(),
439 mPhaseOffset(phaseOffset),
440 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700441
Lloyd Piquee83f9312018-02-01 12:53:17 -0800442 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443
Lloyd Piquee83f9312018-02-01 12:53:17 -0800444 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 static_cast<DispSync::Callback*>(this));
449 if (err != NO_ERROR) {
450 ALOGE("error registering vsync callback: %s (%d)",
451 strerror(-err), err);
452 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700453 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 } else {
455 status_t err = mDispSync->removeEventListener(
456 static_cast<DispSync::Callback*>(this));
457 if (err != NO_ERROR) {
458 ALOGE("error unregistering vsync callback: %s (%d)",
459 strerror(-err), err);
460 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700461 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 }
465
Lloyd Piquee83f9312018-02-01 12:53:17 -0800466 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 mCallback = callback;
469 }
470
Lloyd Piquee83f9312018-02-01 12:53:17 -0800471 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 Mutex::Autolock lock(mVsyncMutex);
473
474 // Normalize phaseOffset to [0, period)
475 auto period = mDispSync->getPeriod();
476 phaseOffset %= period;
477 if (phaseOffset < 0) {
478 // If we're here, then phaseOffset is in (-period, 0). After this
479 // operation, it will be in (0, period)
480 phaseOffset += period;
481 }
482 mPhaseOffset = phaseOffset;
483
484 // If we're not enabled, we don't need to mess with the listeners
485 if (!mEnabled) {
486 return;
487 }
488
489 // Remove the listener with the old offset
490 status_t err = mDispSync->removeEventListener(
491 static_cast<DispSync::Callback*>(this));
492 if (err != NO_ERROR) {
493 ALOGE("error unregistering vsync callback: %s (%d)",
494 strerror(-err), err);
495 }
496
497 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499 static_cast<DispSync::Callback*>(this));
500 if (err != NO_ERROR) {
501 ALOGE("error registering vsync callback: %s (%d)",
502 strerror(-err), err);
503 }
504 }
505
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506private:
507 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700510 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 callback = mCallback;
512
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 if (mTraceVsync) {
514 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700515 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700516 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 }
518
Peiyong Lin566a3b42018-01-09 18:22:43 -0800519 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 callback->onVSyncEvent(when);
521 }
522 }
523
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 const char* const mName;
525
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 int mValue;
527
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 const String8 mVsyncOnLabel;
530 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533
534 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800535 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536
537 Mutex mVsyncMutex; // Protects the following
538 nsecs_t mPhaseOffset;
539 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540};
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700543public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800544 InjectVSyncSource() = default;
545 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700546
Lloyd Piquee83f9312018-02-01 12:53:17 -0800547 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700548 std::lock_guard<std::mutex> lock(mCallbackMutex);
549 mCallback = callback;
550 }
551
Lloyd Piquee83f9312018-02-01 12:53:17 -0800552 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700553 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700554 if (mCallback) {
555 mCallback->onVSyncEvent(when);
556 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setVSyncEnabled(bool) override {}
560 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700561
562private:
563 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800564 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700565};
566
Wei Wangf9b05ee2017-07-19 20:59:39 -0700567// Do not call property_set on main thread which will be blocked by init
568// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700570 ALOGI( "SurfaceFlinger's main thread ready to run. "
571 "Initializing graphics H/W...");
572
Thierry Strudel2924d012017-08-14 15:19:37 -0700573 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900574
Steven Thomasb02664d2017-07-26 18:48:28 -0700575 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 // start the EventThread
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578
579 mEventThreadSource = std::make_unique<DispSyncSource>(
580 &mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
581 mEventThread = std::make_unique<EventThread>(
582 mEventThreadSource.get(), *this, false, "sfEventThread");
583 mSfEventThreadSource = std::make_unique<DispSyncSource>(
584 &mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
585 mSFEventThread = std::make_unique<EventThread>(
586 mSfEventThreadSource.get(), *this, true, "appEventThread");
587 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588
Steven Thomasb02664d2017-07-26 18:48:28 -0700589 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800590 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700591 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800592 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700593
594 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
595 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800596 getBE().mHwc.reset(
597 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700598 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800599 // Process any initial hotplug and resulting display changes.
600 processDisplayHotplugEventsLocked();
601 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
602 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800603
Lloyd Piquefcd86612017-12-14 17:15:36 -0800604 // make the default display GLContext current so that we can create textures
605 // when creating Layers (which may happens before we render something)
606 getDefaultDisplayDeviceLocked()->makeCurrent();
607
Steven Thomas050b2c82017-03-06 11:45:16 -0800608 if (useVrFlinger) {
609 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700610 // This callback is called from the vr flinger dispatch thread. We
611 // need to call signalTransaction(), which requires holding
612 // mStateLock when we're not on the main thread. Acquiring
613 // mStateLock from the vr flinger dispatch thread might trigger a
614 // deadlock in surface flinger (see b/66916578), so post a message
615 // to be handled on the main thread instead.
616 sp<LambdaMessage> message = new LambdaMessage([=]() {
617 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
618 mVrFlingerRequestsDisplay = requestDisplay;
619 signalTransaction();
620 });
621 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800622 };
David Sodman105b7dc2017-11-04 20:28:14 -0700623 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
624 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800625 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 if (!mVrFlinger) {
627 ALOGE("Failed to start vrflinger");
628 }
629 }
630
Lloyd Pique755e3192018-01-31 16:46:15 -0800631 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
632 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
633 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700634
Mathias Agopian92a979a2012-08-02 18:32:23 -0700635 // initialize our drawing state
636 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700637
Andy McFadden13a082e2012-08-24 10:16:42 -0700638 // set initial conditions (e.g. unblank default device)
639 initializeDisplays();
640
David Sodmanbc815282017-11-05 18:57:52 -0800641 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700642
Wei Wangf9b05ee2017-07-19 20:59:39 -0700643 // Inform native graphics APIs whether the present timestamp is supported:
644 if (getHwComposer().hasCapability(
645 HWC2::Capability::PresentFenceIsNotReliable)) {
646 mStartPropertySetThread = new StartPropertySetThread(false);
647 } else {
648 mStartPropertySetThread = new StartPropertySetThread(true);
649 }
650
651 if (mStartPropertySetThread->Start() != NO_ERROR) {
652 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700656}
657
Romain Guy11d63f42017-07-20 12:47:14 -0700658void SurfaceFlinger::readPersistentProperties() {
659 char value[PROPERTY_VALUE_MAX];
660
661 property_get("persist.sys.sf.color_saturation", value, "1.0");
662 mSaturation = atof(value);
663 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100664
665 property_get("persist.sys.sf.native_mode", value, "0");
666 mForceNativeColorMode = atoi(value) == 1;
667 if (mForceNativeColorMode) {
668 ALOGV("Forcing native color mode");
669 }
Romain Guy11d63f42017-07-20 12:47:14 -0700670}
671
Mathias Agopiana67e4182012-06-19 17:26:12 -0700672void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800673 // Start boot animation service by setting a property mailbox
674 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700675 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800676 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700677 if (mStartPropertySetThread->join() != NO_ERROR) {
678 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800679 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700680}
681
Mathias Agopian875d8e12013-06-07 15:35:48 -0700682size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800683 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700684}
685
Mathias Agopian875d8e12013-06-07 15:35:48 -0700686size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800687 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700688}
689
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800690// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800691
Jamie Gennis582270d2011-08-17 18:19:00 -0700692bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800693 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800694 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800695 return authenticateSurfaceTextureLocked(bufferProducer);
696}
697
698bool SurfaceFlinger::authenticateSurfaceTextureLocked(
699 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800700 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700701 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800702}
703
Brian Anderson6b376712017-04-04 10:51:39 -0700704status_t SurfaceFlinger::getSupportedFrameTimestamps(
705 std::vector<FrameEvent>* outSupported) const {
706 *outSupported = {
707 FrameEvent::REQUESTED_PRESENT,
708 FrameEvent::ACQUIRE,
709 FrameEvent::LATCH,
710 FrameEvent::FIRST_REFRESH_START,
711 FrameEvent::LAST_REFRESH_START,
712 FrameEvent::GPU_COMPOSITION_DONE,
713 FrameEvent::DEQUEUE_READY,
714 FrameEvent::RELEASE,
715 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700716 ConditionalLock _l(mStateLock,
717 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700718 if (!getHwComposer().hasCapability(
719 HWC2::Capability::PresentFenceIsNotReliable)) {
720 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
721 }
722 return NO_ERROR;
723}
724
Dan Stoza7f7da322014-05-02 15:26:25 -0700725status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
726 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800727 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700728 return BAD_VALUE;
729 }
730
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500731 if (!display.get())
732 return NAME_NOT_FOUND;
733
Jesse Hall692c7232012-11-08 15:41:56 -0800734 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700735 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800736 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700737 type = i;
738 break;
739 }
740 }
741
742 if (type < 0) {
743 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700744 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745
Mathias Agopian8b736f12012-08-13 17:54:26 -0700746 // TODO: Not sure if display density should handled by SF any longer
747 class Density {
748 static int getDensityFromProperty(char const* propName) {
749 char property[PROPERTY_VALUE_MAX];
750 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800751 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752 density = atoi(property);
753 }
754 return density;
755 }
756 public:
757 static int getEmuDensity() {
758 return getDensityFromProperty("qemu.sf.lcd_density"); }
759 static int getBuildDensity() {
760 return getDensityFromProperty("ro.sf.lcd_density"); }
761 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700764
Steven Thomas6d8110b2017-08-31 18:24:21 -0700765 ConditionalLock _l(mStateLock,
766 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700768 DisplayInfo info = DisplayInfo();
769
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 float xdpi = hwConfig->getDpiX();
771 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700772
773 if (type == DisplayDevice::DISPLAY_PRIMARY) {
774 // The density of the device is provided by a build property
775 float density = Density::getBuildDensity() / 160.0f;
776 if (density == 0) {
777 // the build doesn't provide a density -- this is wrong!
778 // use xdpi instead
779 ALOGE("ro.sf.lcd_density must be defined as a build property");
780 density = xdpi / 160.0f;
781 }
782 if (Density::getEmuDensity()) {
783 // if "qemu.sf.lcd_density" is specified, it overrides everything
784 xdpi = ydpi = density = Density::getEmuDensity();
785 density /= 160.0f;
786 }
787 info.density = density;
788
789 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700790 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800791 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700792 } else {
793 // TODO: where should this value come from?
794 static const int TV_DENSITY = 213;
795 info.density = TV_DENSITY / 160.0f;
796 info.orientation = 0;
797 }
798
Dan Stoza9e56aa02015-11-02 13:00:03 -0800799 info.w = hwConfig->getWidth();
800 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 info.xdpi = xdpi;
802 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900804 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805
Andy McFadden91b2ca82014-06-13 14:04:23 -0700806 // This is how far in advance a buffer must be queued for
807 // presentation at a given time. If you want a buffer to appear
808 // on the screen at time N, you must submit the buffer before
809 // (N - presentationDeadline).
810 //
811 // Normally it's one full refresh period (to give SF a chance to
812 // latch the buffer), but this can be reduced by configuring a
813 // DispSync offset. Any additional delays introduced by the hardware
814 // composer or panel must be accounted for here.
815 //
816 // We add an additional 1ms to allow for processing time and
817 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800818 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800819 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700820
821 // All non-virtual displays are currently considered secure.
822 info.secure = true;
823
Michael Wright28f24d02016-07-12 13:30:53 -0700824 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 return NO_ERROR;
828}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700829
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800830status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700831 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800832 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700833 return BAD_VALUE;
834 }
835
836 // FIXME for now we always return stats for the primary display
837 memset(stats, 0, sizeof(*stats));
838 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
839 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
840 return NO_ERROR;
841}
842
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700843int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800844 if (display == nullptr) {
845 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800846 return BAD_VALUE;
847 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700848
849 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800850 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700851 return device->getActiveConfig();
852 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700853
Dan Stoza24a42e92015-03-09 10:04:11 -0700854 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700855}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700856
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700857void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
858 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
859 this);
860 int32_t type = hw->getDisplayType();
861 int currentMode = hw->getActiveConfig();
862
863 if (mode == currentMode) {
864 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
865 return;
866 }
867
868 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
869 ALOGW("Trying to set config for virtual display");
870 return;
871 }
872
873 hw->setActiveConfig(mode);
874 getHwComposer().setActiveConfig(type, mode);
875}
876
877status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
878 class MessageSetActiveConfig: public MessageBase {
879 SurfaceFlinger& mFlinger;
880 sp<IBinder> mDisplay;
881 int mMode;
882 public:
883 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
884 int mode) :
885 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
886 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700887 Vector<DisplayInfo> configs;
888 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700889 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700890 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700891 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700892 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700893 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700894 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800895 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700896 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700897 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700898 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
899 ALOGW("Attempt to set active config = %d for virtual display",
900 mMode);
901 } else {
902 mFlinger.setActiveConfigInternal(hw, mMode);
903 }
904 return true;
905 }
906 };
907 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
908 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700909 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700910}
Michael Wright28f24d02016-07-12 13:30:53 -0700911status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
912 Vector<android_color_mode_t>* outColorModes) {
913 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
914 return BAD_VALUE;
915 }
916
917 if (!display.get()) {
918 return NAME_NOT_FOUND;
919 }
920
921 int32_t type = NAME_NOT_FOUND;
922 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
923 if (display == mBuiltinDisplays[i]) {
924 type = i;
925 break;
926 }
927 }
928
929 if (type < 0) {
930 return type;
931 }
932
Steven Thomas6d8110b2017-08-31 18:24:21 -0700933 std::vector<android_color_mode_t> modes;
934 {
935 ConditionalLock _l(mStateLock,
936 std::this_thread::get_id() != mMainThreadId);
937 modes = getHwComposer().getColorModes(type);
938 }
Michael Wright28f24d02016-07-12 13:30:53 -0700939 outColorModes->clear();
940 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
941
942 return NO_ERROR;
943}
944
945android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700946 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700947 if (device != nullptr) {
948 return device->getActiveColorMode();
949 }
950 return static_cast<android_color_mode_t>(BAD_VALUE);
951}
952
953void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
954 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700955 int32_t type = hw->getDisplayType();
956 android_color_mode_t currentMode = hw->getActiveColorMode();
957
958 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700959 return;
960 }
961
962 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
963 ALOGW("Trying to set config for virtual display");
964 return;
965 }
966
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600967 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
968 hw->getDisplayType());
969
Michael Wright28f24d02016-07-12 13:30:53 -0700970 hw->setActiveColorMode(mode);
971 getHwComposer().setActiveColorMode(type, mode);
972}
973
974
975status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
976 android_color_mode_t colorMode) {
977 class MessageSetActiveColorMode: public MessageBase {
978 SurfaceFlinger& mFlinger;
979 sp<IBinder> mDisplay;
980 android_color_mode_t mMode;
981 public:
982 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
983 android_color_mode_t mode) :
984 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
985 virtual bool handler() {
986 Vector<android_color_mode_t> modes;
987 mFlinger.getDisplayColorModes(mDisplay, &modes);
988 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
989 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600990 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
991 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700992 return true;
993 }
994 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
995 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600996 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
997 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700998 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600999 ALOGW("Attempt to set active color mode %s %d for virtual display",
1000 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001001 } else {
1002 mFlinger.setActiveColorModeInternal(hw, mMode);
1003 }
1004 return true;
1005 }
1006 };
1007 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1008 postMessageSync(msg);
1009 return NO_ERROR;
1010}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001011
Svetoslavd85084b2014-03-20 10:28:31 -07001012status_t SurfaceFlinger::clearAnimationFrameStats() {
1013 Mutex::Autolock _l(mStateLock);
1014 mAnimFrameTracker.clearStats();
1015 return NO_ERROR;
1016}
1017
1018status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1019 Mutex::Autolock _l(mStateLock);
1020 mAnimFrameTracker.getStats(outStats);
1021 return NO_ERROR;
1022}
1023
Dan Stozac4f471e2016-03-24 09:31:08 -07001024status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1025 HdrCapabilities* outCapabilities) const {
1026 Mutex::Autolock _l(mStateLock);
1027
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001028 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001029 if (displayDevice == nullptr) {
1030 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1031 return BAD_VALUE;
1032 }
1033
1034 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001035 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001036 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001037 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1038 // insert HDR10 as we will force client composition for HDR10
1039 // layers
1040 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1041 types.push_back(HAL_HDR_HDR10);
1042
1043 *outCapabilities = HdrCapabilities(types,
1044 capabilities->getDesiredMaxLuminance(),
1045 capabilities->getDesiredMaxAverageLuminance(),
1046 capabilities->getDesiredMinLuminance());
1047 } else {
1048 *outCapabilities = std::move(*capabilities);
1049 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001050 } else {
1051 return BAD_VALUE;
1052 }
1053
1054 return NO_ERROR;
1055}
1056
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001057status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001058 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1059 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001060
Chia-I Wu90f669f2017-10-05 14:24:41 -07001061 if (mInjectVSyncs == enable) {
1062 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001064
1065 if (enable) {
1066 ALOGV("VSync Injections enabled");
1067 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001068 mVSyncInjector = std::make_unique<InjectVSyncSource>();
1069 mInjectorEventThread = std::make_unique<EventThread>(
1070 mVSyncInjector.get(), *this, false, "injEvThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001072 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073 } else {
1074 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001075 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 }
1077
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079 });
1080 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081 return NO_ERROR;
1082}
1083
1084status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 Mutex::Autolock _l(mStateLock);
1086
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001087 if (!mInjectVSyncs) {
1088 ALOGE("VSync Injections not enabled");
1089 return BAD_VALUE;
1090 }
1091 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1092 ALOGV("Injecting VSync inside SurfaceFlinger");
1093 mVSyncInjector->onInjectSyncEvent(when);
1094 }
1095 return NO_ERROR;
1096}
1097
Lloyd Pique755e3192018-01-31 16:46:15 -08001098status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1099 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001100 IPCThreadState* ipc = IPCThreadState::self();
1101 const int pid = ipc->getCallingPid();
1102 const int uid = ipc->getCallingUid();
1103 if ((uid != AID_SHELL) &&
1104 !PermissionCache::checkPermission(sDump, pid, uid)) {
1105 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1106 return PERMISSION_DENIED;
1107 }
1108
1109 // Try to acquire a lock for 1s, fail gracefully
1110 const status_t err = mStateLock.timedLock(s2ns(1));
1111 const bool locked = (err == NO_ERROR);
1112 if (!locked) {
1113 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1114 return TIMED_OUT;
1115 }
1116
1117 outLayers->clear();
1118 mCurrentState.traverseInZOrder([&](Layer* layer) {
1119 outLayers->push_back(layer->getLayerDebugInfo());
1120 });
1121
1122 mStateLock.unlock();
1123 return NO_ERROR;
1124}
1125
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001126// ----------------------------------------------------------------------------
1127
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001128sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1129 ISurfaceComposer::VsyncSource vsyncSource) {
1130 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1131 return mSFEventThread->createEventConnection();
1132 } else {
1133 return mEventThread->createEventConnection();
1134 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001135}
1136
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001137// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001138
1139void SurfaceFlinger::waitForEvent() {
1140 mEventQueue.waitMessage();
1141}
1142
1143void SurfaceFlinger::signalTransaction() {
1144 mEventQueue.invalidate();
1145}
1146
1147void SurfaceFlinger::signalLayerUpdate() {
1148 mEventQueue.invalidate();
1149}
1150
1151void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001152 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001153 mEventQueue.refresh();
1154}
1155
1156status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001157 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158 return mEventQueue.postMessage(msg, reltime);
1159}
1160
1161status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001162 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 status_t res = mEventQueue.postMessage(msg, reltime);
1164 if (res == NO_ERROR) {
1165 msg->wait();
1166 }
1167 return res;
1168}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001169
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001170void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001171 do {
1172 waitForEvent();
1173 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174}
1175
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176void SurfaceFlinger::enableHardwareVsync() {
1177 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001178 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001180 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1181 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001183 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184}
1185
Jesse Hall948fe0c2013-10-14 12:56:09 -07001186void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 Mutex::Autolock _l(mHWVsyncLock);
1188
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189 if (makeAvailable) {
1190 mHWVsyncAvailable = true;
1191 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001192 // Hardware vsync is not currently available, so abort the resync
1193 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 return;
1195 }
1196
David Sodman105b7dc2017-11-04 20:28:14 -07001197 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001198 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199
1200 mPrimaryDispSync.reset();
1201 mPrimaryDispSync.setPeriod(period);
1202
1203 if (!mPrimaryHWVsyncEnabled) {
1204 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001205 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1206 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207 mPrimaryHWVsyncEnabled = true;
1208 }
1209}
1210
Jesse Hall948fe0c2013-10-14 12:56:09 -07001211void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 Mutex::Autolock _l(mHWVsyncLock);
1213 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001214 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1215 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216 mPrimaryDispSync.endResync();
1217 mPrimaryHWVsyncEnabled = false;
1218 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001219 if (makeUnavailable) {
1220 mHWVsyncAvailable = false;
1221 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222}
1223
Tim Murray4a4e4a22016-04-19 16:29:23 +00001224void SurfaceFlinger::resyncWithRateLimit() {
1225 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001226
1227 // No explicit locking is needed here since EventThread holds a lock while calling this method
1228 static nsecs_t sLastResyncAttempted = 0;
1229 const nsecs_t now = systemTime();
1230 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001232 }
Dan Stoza57164302017-05-08 14:03:54 -07001233 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001234}
1235
Steven Thomasb02664d2017-07-26 18:48:28 -07001236void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1237 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001238 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001239 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001240 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001241 return;
1242 }
1243
1244 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001245 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001246 return;
1247 }
1248
Jamie Gennisd1700752013-10-14 12:22:52 -07001249 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 { // Scope for the lock
1252 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001253 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001256 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001257
1258 if (needsHwVsync) {
1259 enableHardwareVsync();
1260 } else {
1261 disableHardwareVsync(false);
1262 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001263}
1264
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001265void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001266 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1267 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001268}
1269
Lloyd Pique715a2c12017-12-14 17:18:08 -08001270void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1271 HWC2::Connection connection) {
1272 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1273 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001274
Lloyd Piqueba04e622017-12-14 17:11:26 -08001275 // Ignore events that do not have the right sequenceId.
1276 if (sequenceId != getBE().mComposerSequenceId) {
1277 return;
1278 }
1279
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 // Only lock if we're not on the main thread. This function is normally
1281 // called on a hwbinder thread, but for the primary display it's called on
1282 // the main thread with the state lock already held, so don't attempt to
1283 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001284 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001285
Lloyd Pique715a2c12017-12-14 17:18:08 -08001286 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001287
Lloyd Piqueba04e622017-12-14 17:11:26 -08001288 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001289}
1290
Steven Thomasb02664d2017-07-26 18:48:28 -07001291void SurfaceFlinger::onRefreshReceived(int sequenceId,
1292 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001293 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001294 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001295 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001296 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001297 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001298}
1299
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001302 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 getHwComposer().setVsyncEnabled(disp,
1304 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001305}
1306
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001308void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001310 // Clear the drawing state so that the logic inside of
1311 // handleTransactionLocked will fire. It will determine the delta between
1312 // mCurrentState and mDrawingState and re-apply all changes when we make the
1313 // transition.
1314 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001315 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001316 mDisplays.clear();
1317}
1318
Steven Thomas050b2c82017-03-06 11:45:16 -08001319void SurfaceFlinger::updateVrFlinger() {
1320 if (!mVrFlinger)
1321 return;
1322 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001323 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001324 return;
1325 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001326
David Sodman105b7dc2017-11-04 20:28:14 -07001327 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 ALOGE("Vr flinger is only supported for remote hardware composer"
1329 " service connections. Ignoring request to transition to vr"
1330 " flinger.");
1331 mVrFlingerRequestsDisplay = false;
1332 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001333 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001334
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001335 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337 int currentDisplayPowerMode = getDisplayDeviceLocked(
1338 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001345 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001346 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1347 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001348 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349
David Sodman105b7dc2017-11-04 20:28:14 -07001350 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1351 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001352
1353 if (vrFlingerRequestsDisplay) {
1354 mVrFlinger->GrantDisplayOwnership();
1355 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001357 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358
1359 mVisibleRegionsDirty = true;
1360 invalidateHwcGeometry();
1361
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001362 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1364 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1365 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001366
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001368 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 const nsecs_t period = activeConfig->getVsyncPeriod();
1370 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 // Use phase of 0 since phase is not known.
1373 // Use latency of 0, which will snap to the ideal latency.
1374 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001375
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376 android_atomic_or(1, &mRepaintEverything);
1377 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378}
1379
Mathias Agopian4fec8732012-06-29 14:12:52 -07001380void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001381 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001382 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001383 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001384 bool frameMissed = !mHadClientComposition &&
1385 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001386 (mPreviousPresentFence->getSignalTime() ==
1387 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001388 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001389 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001390 signalLayerUpdate();
1391 break;
1392 }
1393
Steven Thomas050b2c82017-03-06 11:45:16 -08001394 // Now that we're going to make it to the handleMessageTransaction()
1395 // call below it's safe to call updateVrFlinger(), which will
1396 // potentially trigger a display handoff.
1397 updateVrFlinger();
1398
Dan Stoza6b9454d2014-11-07 16:00:59 -08001399 bool refreshNeeded = handleMessageTransaction();
1400 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001401 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001402 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001403 // Signal a refresh if a transaction modified the window state,
1404 // a new buffer was latched, or if HWC has requested a full
1405 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001406 signalRefresh();
1407 }
1408 break;
1409 }
1410 case MessageQueue::REFRESH: {
1411 handleMessageRefresh();
1412 break;
1413 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001414 }
1415}
1416
Dan Stoza6b9454d2014-11-07 16:00:59 -08001417bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001418 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001419 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001420 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001422 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424}
1425
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001427 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001428 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429}
1430
1431void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001432 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001433
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001434 mRefreshPending = false;
1435
Pablo Ceballos40845df2016-01-25 17:41:15 -08001436 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001437
Brian Andersond6927fb2016-07-23 23:37:30 -07001438 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001439 rebuildLayerStacks();
1440 setUpHWComposer();
1441 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001442 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001443 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001444 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001445
David Sodman105b7dc2017-11-04 20:28:14 -07001446 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001447
1448 mHadClientComposition = false;
1449 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1450 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1451 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001452 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001453 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001454
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001457
Mathias Agopiancd60f992012-08-16 16:28:27 -07001458void SurfaceFlinger::doDebugFlashRegions()
1459{
1460 // is debugging enabled
1461 if (CC_LIKELY(!mDebugRegion))
1462 return;
1463
1464 const bool repaintEverything = mRepaintEverything;
1465 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1466 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001467 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468 // transform the dirty region into this screen's coordinate space
1469 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1470 if (!dirtyRegion.isEmpty()) {
1471 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001472 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473
1474 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001476 RenderEngine& engine(getRenderEngine());
1477 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1478
Mathias Agopianda27af92012-09-13 18:17:13 -07001479 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001480 }
1481 }
1482 }
1483
1484 postFramebuffer();
1485
1486 if (mDebugRegion > 1) {
1487 usleep(mDebugRegion * 1000);
1488 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001489
Dan Stoza9e56aa02015-11-02 13:00:03 -08001490 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001491 auto& displayDevice = mDisplays[displayId];
1492 if (!displayDevice->isDisplayOn()) {
1493 continue;
1494 }
1495
David Sodman105b7dc2017-11-04 20:28:14 -07001496 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1497 ALOGE_IF(result != NO_ERROR,
1498 "prepareFrame for display %zd failed:"
1499 " %d (%s)",
1500 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001501 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502}
1503
Adrian Roos1e1a1282017-11-01 19:05:31 +01001504void SurfaceFlinger::doTracing(const char* where) {
1505 ATRACE_CALL();
1506 ATRACE_NAME(where);
1507 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001508 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001509 }
1510}
1511
Brian Andersond6927fb2016-07-23 23:37:30 -07001512void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001514 ATRACE_CALL();
1515 ALOGV("preComposition");
1516
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001518 mDrawingState.traverseInZOrder([&](Layer* layer) {
1519 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 needExtraInvalidate = true;
1521 }
Robert Carr2047fae2016-11-28 14:09:09 -08001522 });
1523
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 if (needExtraInvalidate) {
1525 signalLayerUpdate();
1526 }
1527}
1528
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001529void SurfaceFlinger::updateCompositorTiming(
1530 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1531 std::shared_ptr<FenceTime>& presentFenceTime) {
1532 // Update queue of past composite+present times and determine the
1533 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001534 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001536 while (!getBE().mCompositePresentTimes.empty()) {
1537 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538 // Cached values should have been updated before calling this method,
1539 // which helps avoid duplicate syscalls.
1540 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1541 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1542 break;
1543 }
1544 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001545 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 }
1547
1548 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001549 while (getBE().mCompositePresentTimes.size() > 16) {
1550 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 }
1552
Brian Andersond0010582017-03-07 13:20:31 -08001553 setCompositorTimingSnapped(
1554 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1555}
1556
1557void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1558 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559 // Integer division and modulo round toward 0 not -inf, so we need to
1560 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001561 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1563 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1564
Brian Andersond0010582017-03-07 13:20:31 -08001565 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1566 if (idealLatency <= 0) {
1567 idealLatency = vsyncInterval;
1568 }
1569
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570 // Snap the latency to a value that removes scheduling jitter from the
1571 // composition and present times, which often have >1ms of jitter.
1572 // Reducing jitter is important if an app attempts to extrapolate
1573 // something (such as user input) to an accurate diasplay time.
1574 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1575 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001576 nsecs_t bias = vsyncInterval / 2;
1577 int64_t extraVsyncs =
1578 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1579 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1580 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581
David Sodman99974d22017-11-28 12:04:33 -08001582 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1583 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1584 getBE().mCompositorTiming.interval = vsyncInterval;
1585 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001586}
1587
1588void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001590 ATRACE_CALL();
1591 ALOGV("postComposition");
1592
Brian Anderson3546a3f2016-07-14 11:51:14 -07001593 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001594 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001595 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001596 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001597 }
1598
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599 // |mStateLock| not needed as we are on the main thread
1600 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001601
David Sodman73beded2017-11-15 11:56:06 -08001602 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001604 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001605 glCompositionDoneFenceTime =
1606 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001607 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001608 } else {
1609 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1610 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001611
David Sodman73beded2017-11-15 11:56:06 -08001612 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001613 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001614 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001615 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001616
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1618 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1619
1620 // We use the refreshStartTime which might be sampled a little later than
1621 // when we started doing work for this frame, but that should be okay
1622 // since updateCompositorTiming has snapping logic.
1623 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001624 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001625 CompositorTiming compositorTiming;
1626 {
David Sodman99974d22017-11-28 12:04:33 -08001627 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1628 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001629 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630
Robert Carr2047fae2016-11-28 14:09:09 -08001631 mDrawingState.traverseInZOrder([&](Layer* layer) {
1632 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001633 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001634 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001635 recordBufferingStats(layer->getName().string(),
1636 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001637 }
Robert Carr2047fae2016-11-28 14:09:09 -08001638 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001639
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001640 if (presentFenceTime->isValid()) {
1641 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001642 enableHardwareVsync();
1643 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001644 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001645 }
1646 }
1647
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001648 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001649 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001650 enableHardwareVsync();
1651 }
1652 }
1653
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001654 if (mAnimCompositionPending) {
1655 mAnimCompositionPending = false;
1656
Brian Anderson4e606e32017-03-16 15:34:57 -07001657 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001658 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001659 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001660 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001661 // The HWC doesn't support present fences, so use the refresh
1662 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001664 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001665 mAnimFrameTracker.setActualPresentTime(presentTime);
1666 }
1667 mAnimFrameTracker.advanceFrame();
1668 }
Dan Stozab90cf072015-03-05 11:05:59 -08001669
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001670 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1671 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001672 return;
1673 }
1674
1675 nsecs_t currentTime = systemTime();
1676 if (mHasPoweredOff) {
1677 mHasPoweredOff = false;
1678 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001679 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001681 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1682 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001683 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001684 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001685 }
David Sodman4a36e932017-11-07 14:29:47 -08001686 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001687 }
David Sodman4a36e932017-11-07 14:29:47 -08001688 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689}
1690
1691void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692 ATRACE_CALL();
1693 ALOGV("rebuildLayerStacks");
1694
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001696 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001697 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001698 mVisibleRegionsDirty = false;
1699 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001700
Jeff Sharkey76488112017-02-27 14:15:18 -07001701 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1702 Region opaqueRegion;
1703 Region dirtyRegion;
1704 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001705 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001706 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1707 const Transform& tr(displayDevice->getTransform());
1708 const Rect bounds(displayDevice->getBounds());
1709 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001710 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001711
Jeff Sharkey76488112017-02-27 14:15:18 -07001712 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001713 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001714 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1715 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001716 Region drawRegion(tr.transform(
1717 layer->visibleNonTransparentRegion));
1718 drawRegion.andSelf(bounds);
1719 if (!drawRegion.isEmpty()) {
1720 layersSortedByZ.add(layer);
1721 } else {
1722 // Clear out the HWC layer if this layer was
1723 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001724 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001725 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001726 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001727 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001728 // WM changes displayDevice->layerStack upon sleep/awake.
1729 // Here we make sure we delete the HWC layers even if
1730 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001731 hwcLayerDestroyed = layer->destroyHwcLayer(
1732 displayDevice->getHwcDisplayId());
1733 }
1734
1735 // If a layer is not going to get a release fence because
1736 // it is invisible, but it is also going to release its
1737 // old buffer, add it to the list of layers needing
1738 // fences.
1739 if (hwcLayerDestroyed) {
1740 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1741 mLayersWithQueuedFrames.cend(), layer);
1742 if (found != mLayersWithQueuedFrames.cend()) {
1743 layersNeedingFences.add(layer);
1744 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001745 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001746 });
1747 }
1748 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001749 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 displayDevice->undefinedRegion.set(bounds);
1751 displayDevice->undefinedRegion.subtractSelf(
1752 tr.transform(opaqueRegion));
1753 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001754 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001755 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001756}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001757
Romain Guy0147a172017-06-01 13:53:56 -07001758mat4 SurfaceFlinger::computeSaturationMatrix() const {
1759 if (mSaturation == 1.0f) {
1760 return mat4();
1761 }
1762
1763 // Rec.709 luma coefficients
1764 float3 luminance{0.213f, 0.715f, 0.072f};
1765 luminance *= 1.0f - mSaturation;
1766 return mat4(
1767 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1768 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1769 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1770 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1771 );
1772}
1773
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001774// pickColorMode translates a given dataspace into the best available color mode.
1775// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001776android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001777 if (mForceNativeColorMode) {
1778 return HAL_COLOR_MODE_NATIVE;
1779 }
1780
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001781 switch (dataSpace) {
1782 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1783 // system expects.
1784 case HAL_DATASPACE_UNKNOWN:
1785 case HAL_DATASPACE_SRGB:
1786 case HAL_DATASPACE_V0_SRGB:
1787 return HAL_COLOR_MODE_SRGB;
1788 break;
1789
1790 case HAL_DATASPACE_DISPLAY_P3:
1791 return HAL_COLOR_MODE_DISPLAY_P3;
1792 break;
1793
1794 default:
1795 // TODO (courtneygo): Do we want to assert an error here?
1796 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1797 dataSpace);
1798 return HAL_COLOR_MODE_SRGB;
1799 break;
1800 }
1801}
1802
Romain Guy0147a172017-06-01 13:53:56 -07001803android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001804 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001805 // Only support sRGB and Display-P3 right now.
1806 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1807 return HAL_DATASPACE_DISPLAY_P3;
1808 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001809 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1810 return HAL_DATASPACE_DISPLAY_P3;
1811 }
1812 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1813 return HAL_DATASPACE_DISPLAY_P3;
1814 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001815 if (!hasHdr) {
1816 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1817 return HAL_DATASPACE_DISPLAY_P3;
1818 }
1819 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1820 return HAL_DATASPACE_DISPLAY_P3;
1821 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001822 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001823
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001824 return HAL_DATASPACE_V0_SRGB;
1825}
1826
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001828 ATRACE_CALL();
1829 ALOGV("setUpHWComposer");
1830
Jesse Hall028dc8f2013-08-20 16:35:32 -07001831 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001832 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1833 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1834 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1835
1836 // If nothing has changed (!dirty), don't recompose.
1837 // If something changed, but we don't currently have any visible layers,
1838 // and didn't when we last did a composition, then skip it this time.
1839 // The second rule does two things:
1840 // - When all layers are removed from a display, we'll emit one black
1841 // frame, then nothing more until we get new layers.
1842 // - When a display is created with a private layer stack, we won't
1843 // emit any black frames until a layer is added to the layer stack.
1844 bool mustRecompose = dirty && !(empty && wasEmpty);
1845
1846 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1847 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1848 mustRecompose ? "doing" : "skipping",
1849 dirty ? "+" : "-",
1850 empty ? "+" : "-",
1851 wasEmpty ? "+" : "-");
1852
Dan Stoza71433162014-02-04 16:22:36 -08001853 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001854
1855 if (mustRecompose) {
1856 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1857 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001858 }
1859
Dan Stoza9e56aa02015-11-02 13:00:03 -08001860 // build the h/w work list
1861 if (CC_UNLIKELY(mGeometryInvalid)) {
1862 mGeometryInvalid = false;
1863 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1864 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1865 const auto hwcId = displayDevice->getHwcDisplayId();
1866 if (hwcId >= 0) {
1867 const Vector<sp<Layer>>& currentLayers(
1868 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001869 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001870 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001872 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001875 }
1876 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001877
Robert Carrae060832016-11-28 10:51:00 -08001878 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001879 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001881 }
1882 }
1883 }
1884 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 }
Riley Andrews03414a12014-07-01 14:22:59 -07001886
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001887
Romain Guy0147a172017-06-01 13:53:56 -07001888 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001889
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 // Set the per-frame data
1891 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1892 auto& displayDevice = mDisplays[displayId];
1893 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001894
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 if (hwcId < 0) {
1896 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001897 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001898 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001899 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001900 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1901 "display %zd: %d", displayId, result);
1902 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001904 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1905 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001906 !displayDevice->getHdrSupport()) {
1907 layer->forceClientComposition(hwcId);
1908 }
1909
chaviwc9232ed2017-11-14 15:31:15 -08001910 if (layer->getForceClientComposition(hwcId)) {
1911 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1912 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1913 continue;
1914 }
1915
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 layer->setPerFrameData(displayDevice);
1917 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001918
1919 if (hasWideColorDisplay) {
1920 android_color_mode newColorMode;
1921 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1922
1923 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001924 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1925 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001926 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1927 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1928 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1929 }
1930 newColorMode = pickColorMode(newDataSpace);
1931
Thierry Strudel2924d012017-08-14 15:19:37 -07001932 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001933 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 }
1935
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001936 mPreviousColorMatrix = colorMatrix;
1937
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001939 auto& displayDevice = mDisplays[displayId];
1940 if (!displayDevice->isDisplayOn()) {
1941 continue;
1942 }
1943
David Sodman105b7dc2017-11-04 20:28:14 -07001944 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1946 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001947 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001949
Mathias Agopiancd60f992012-08-16 16:28:27 -07001950void SurfaceFlinger::doComposition() {
1951 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 ALOGV("doComposition");
1953
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001954 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001955 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001956 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001957 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958 // transform the dirty region into this screen's coordinate space
1959 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001960
1961 // repaint the framebuffer (if needed)
1962 doDisplayComposition(hw, dirtyRegion);
1963
Mathias Agopiancd60f992012-08-16 16:28:27 -07001964 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001965 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001966 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001967 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001968 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001969}
1970
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971void SurfaceFlinger::postFramebuffer()
1972{
Mathias Agopian841cde52012-03-01 15:44:37 -08001973 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001975
Mathias Agopiana44b0412011-10-16 18:46:35 -07001976 const nsecs_t now = systemTime();
1977 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001978
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1980 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001981 if (!displayDevice->isDisplayOn()) {
1982 continue;
1983 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 const auto hwcId = displayDevice->getHwcDisplayId();
1985 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001986 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001987 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001988 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001989 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001991 // The layer buffer from the previous frame (if any) is released
1992 // by HWC only when the release fence from this frame (if any) is
1993 // signaled. Always get the release fence from HWC first.
1994 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001995 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08001996
1997 // If the layer was client composited in the previous frame, we
1998 // need to merge with the previous client target acquire fence.
1999 // Since we do not track that, always merge with the current
2000 // client target acquire fence when it is available, even though
2001 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002003 releaseFence = Fence::merge("LayerRelease", releaseFence,
2004 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002005 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002006
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 layer->onLayerDisplayed(releaseFence);
2008 }
Chia-I Wu83806892017-11-16 10:50:20 -08002009
2010 // We've got a list of layers needing fences, that are disjoint with
2011 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2012 // supply them with the present fence.
2013 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002014 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002015 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2016 layer->onLayerDisplayed(presentFence);
2017 }
2018 }
2019
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002021 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002022 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002023 }
2024
Mathias Agopiana44b0412011-10-16 18:46:35 -07002025 mLastSwapBufferTime = systemTime() - now;
2026 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002027
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002028 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002029 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2030 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2031 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2032 logFrameStats();
2033 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035}
2036
Mathias Agopian87baae12012-07-31 12:38:26 -07002037void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038{
Mathias Agopian841cde52012-03-01 15:44:37 -08002039 ATRACE_CALL();
2040
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002041 // here we keep a copy of the drawing state (that is the state that's
2042 // going to be overwritten by handleTransactionLocked()) outside of
2043 // mStateLock so that the side-effects of the State assignment
2044 // don't happen with mStateLock held (which can cause deadlocks).
2045 State drawingState(mDrawingState);
2046
Mathias Agopianca4d3602011-05-19 15:38:14 -07002047 Mutex::Autolock _l(mStateLock);
2048 const nsecs_t now = systemTime();
2049 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050
Mathias Agopianca4d3602011-05-19 15:38:14 -07002051 // Here we're guaranteed that some transaction flags are set
2052 // so we can call handleTransactionLocked() unconditionally.
2053 // We call getTransactionFlags(), which will also clear the flags,
2054 // with mStateLock held to guarantee that mCurrentState won't change
2055 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002056
Mathias Agopiane57f2922012-08-09 16:29:12 -07002057 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002058 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002059
Mathias Agopianca4d3602011-05-19 15:38:14 -07002060 mLastTransactionTime = systemTime() - now;
2061 mDebugInTransaction = 0;
2062 invalidateHwcGeometry();
2063 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002064}
2065
Lloyd Pique715a2c12017-12-14 17:18:08 -08002066DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2067 HWC2::Connection connection) const {
2068 // Figure out whether the event is for the primary display or an
2069 // external display by matching the Hwc display id against one for a
2070 // connected display. If we did not find a match, we then check what
2071 // displays are not already connected to determine the type. If we don't
2072 // have a connected primary display, we assume the new display is meant to
2073 // be the primary display, and then if we don't have an external display,
2074 // we assume it is that.
2075 const auto primaryDisplayId =
2076 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2077 const auto externalDisplayId =
2078 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2079 if (primaryDisplayId && primaryDisplayId == display) {
2080 return DisplayDevice::DISPLAY_PRIMARY;
2081 } else if (externalDisplayId && externalDisplayId == display) {
2082 return DisplayDevice::DISPLAY_EXTERNAL;
2083 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2084 return DisplayDevice::DISPLAY_PRIMARY;
2085 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2086 return DisplayDevice::DISPLAY_EXTERNAL;
2087 }
2088
2089 return DisplayDevice::DISPLAY_ID_INVALID;
2090}
2091
Lloyd Piqueba04e622017-12-14 17:11:26 -08002092void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2093 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002094 auto displayType = determineDisplayType(event.display, event.connection);
2095 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2096 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2097 continue;
2098 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002099
2100 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2101 ALOGE("External displays are not supported by the vr hardware composer.");
2102 continue;
2103 }
2104
Lloyd Pique715a2c12017-12-14 17:18:08 -08002105 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002106
2107 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002108 ALOGV("Creating built in display %d", displayType);
2109 ALOGW_IF(mBuiltinDisplays[displayType],
2110 "Overwriting display token for display type %d", displayType);
2111 mBuiltinDisplays[displayType] = new BBinder();
2112 // All non-virtual displays are currently considered secure.
2113 DisplayDeviceState info(displayType, true);
2114 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2115 "Built-in Screen" : "External Screen";
2116 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2117 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002118 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002119 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002120
Lloyd Piquefcd86612017-12-14 17:15:36 -08002121 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2122 if (idx >= 0) {
2123 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2124 mInterceptor.saveDisplayDeletion(info.displayId);
2125 mCurrentState.displays.removeItemsAt(idx);
2126 }
2127 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002128 }
2129
2130 processDisplayChangesLocked();
2131 }
2132
2133 mPendingHotplugEvents.clear();
2134}
2135
Lloyd Pique347200f2017-12-14 17:00:15 -08002136void SurfaceFlinger::processDisplayChangesLocked() {
2137 // here we take advantage of Vector's copy-on-write semantics to
2138 // improve performance by skipping the transaction entirely when
2139 // know that the lists are identical
2140 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2141 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2142 if (!curr.isIdenticalTo(draw)) {
2143 mVisibleRegionsDirty = true;
2144 const size_t cc = curr.size();
2145 size_t dc = draw.size();
2146
2147 // find the displays that were removed
2148 // (ie: in drawing state but not in current state)
2149 // also handle displays that changed
2150 // (ie: displays that are in both lists)
2151 for (size_t i = 0; i < dc;) {
2152 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2153 if (j < 0) {
2154 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002155 // Call makeCurrent() on the primary display so we can
2156 // be sure that nothing associated with this display
2157 // is current.
2158 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2159 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2160 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2161 if (hw != nullptr) hw->disconnect(getHwComposer());
2162 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2163 mEventThread->onHotplugReceived(draw[i].type, false);
2164 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002165 } else {
2166 // this display is in both lists. see if something changed.
2167 const DisplayDeviceState& state(curr[j]);
2168 const wp<IBinder>& display(curr.keyAt(j));
2169 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2170 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2171 if (state_binder != draw_binder) {
2172 // changing the surface is like destroying and
2173 // recreating the DisplayDevice, so we just remove it
2174 // from the drawing state, so that it get re-added
2175 // below.
2176 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2177 if (hw != nullptr) hw->disconnect(getHwComposer());
2178 mDisplays.removeItem(display);
2179 mDrawingState.displays.removeItemsAt(i);
2180 dc--;
2181 // at this point we must loop to the next item
2182 continue;
2183 }
2184
2185 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2186 if (disp != nullptr) {
2187 if (state.layerStack != draw[i].layerStack) {
2188 disp->setLayerStack(state.layerStack);
2189 }
2190 if ((state.orientation != draw[i].orientation) ||
2191 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2192 disp->setProjection(state.orientation, state.viewport, state.frame);
2193 }
2194 if (state.width != draw[i].width || state.height != draw[i].height) {
2195 disp->setDisplaySize(state.width, state.height);
2196 }
2197 }
2198 }
2199 ++i;
2200 }
2201
2202 // find displays that were added
2203 // (ie: in current state but not in drawing state)
2204 for (size_t i = 0; i < cc; i++) {
2205 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2206 const DisplayDeviceState& state(curr[i]);
2207
2208 sp<DisplaySurface> dispSurface;
2209 sp<IGraphicBufferProducer> producer;
2210 sp<IGraphicBufferProducer> bqProducer;
2211 sp<IGraphicBufferConsumer> bqConsumer;
2212 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2213
2214 int32_t hwcId = -1;
2215 if (state.isVirtualDisplay()) {
2216 // Virtual displays without a surface are dormant:
2217 // they have external state (layer stack, projection,
2218 // etc.) but no internal state (i.e. a DisplayDevice).
2219 if (state.surface != nullptr) {
2220 // Allow VR composer to use virtual displays.
2221 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2222 int width = 0;
2223 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2224 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2225 int height = 0;
2226 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2227 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2228 int intFormat = 0;
2229 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2230 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2231 auto format = static_cast<android_pixel_format_t>(intFormat);
2232
2233 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2234 }
2235
2236 // TODO: Plumb requested format back up to consumer
2237
2238 sp<VirtualDisplaySurface> vds =
2239 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2240 bqProducer, bqConsumer,
2241 state.displayName);
2242
2243 dispSurface = vds;
2244 producer = vds;
2245 }
2246 } else {
2247 ALOGE_IF(state.surface != nullptr,
2248 "adding a supported display, but rendering "
2249 "surface is provided (%p), ignoring it",
2250 state.surface.get());
2251
2252 hwcId = state.type;
2253 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2254 producer = bqProducer;
2255 }
2256
2257 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002258
Lloyd Pique347200f2017-12-14 17:00:15 -08002259 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002260 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002261 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002262 bool hasWideColorModes = false;
2263 std::vector<android_color_mode_t> modes =
2264 getHwComposer().getColorModes(state.type);
2265 for (android_color_mode_t colorMode : modes) {
2266 switch (colorMode) {
2267 case HAL_COLOR_MODE_DISPLAY_P3:
2268 case HAL_COLOR_MODE_ADOBE_RGB:
2269 case HAL_COLOR_MODE_DCI_P3:
2270 hasWideColorModes = true;
2271 break;
2272 default:
2273 break;
2274 }
2275 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002276 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002277 }
2278
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002279 bool hasHdrSupport = false;
2280 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2281 getHwComposer().getHdrCapabilities(state.type);
2282 if (hdrCapabilities) {
2283 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2284 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2285 hasHdrSupport = iter != types.cend();
2286 }
2287
Lloyd Pique347200f2017-12-14 17:00:15 -08002288 sp<DisplayDevice> hw =
2289 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002290 dispSurface, producer, useWideColorMode,
2291 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002292
Lloyd Piquec5208312018-01-08 17:59:02 -08002293 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2294 if (useWideColorMode) {
2295 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002296 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002297 setActiveColorModeInternal(hw, defaultColorMode);
2298 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002299 hw->setLayerStack(state.layerStack);
2300 hw->setProjection(state.orientation, state.viewport, state.frame);
2301 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002302
Lloyd Pique347200f2017-12-14 17:00:15 -08002303 mDisplays.add(display, hw);
2304 if (!state.isVirtualDisplay()) {
2305 mEventThread->onHotplugReceived(state.type, true);
2306 }
2307 }
2308 }
2309 }
2310 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
2312 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002313}
2314
Mathias Agopian87baae12012-07-31 12:38:26 -07002315void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002316{
Dan Stoza7dde5992015-05-22 09:51:44 -07002317 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002318 mCurrentState.traverseInZOrder([](Layer* layer) {
2319 layer->notifyAvailableFrames();
2320 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322 /*
2323 * Traversal of the children
2324 * (perform the transaction for each of them if needed)
2325 */
2326
Mathias Agopian3559b072012-08-15 13:46:03 -07002327 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002328 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002329 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002330 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331
2332 const uint32_t flags = layer->doTransaction(0);
2333 if (flags & Layer::eVisibleRegion)
2334 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002335 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 }
2337
2338 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002339 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340 */
2341
Mathias Agopiane57f2922012-08-09 16:29:12 -07002342 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002343 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002344 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002345 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346
Mathias Agopian84300952012-11-21 16:02:13 -08002347 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2348 // The transform hint might have changed for some layers
2349 // (either because a display has changed, or because a layer
2350 // as changed).
2351 //
2352 // Walk through all the layers in currentLayers,
2353 // and update their transform hint.
2354 //
2355 // If a layer is visible only on a single display, then that
2356 // display is used to calculate the hint, otherwise we use the
2357 // default display.
2358 //
2359 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2360 // the hint is set before we acquire a buffer from the surface texture.
2361 //
2362 // NOTE: layer transactions have taken place already, so we use their
2363 // drawing state. However, SurfaceFlinger's own transaction has not
2364 // happened yet, so we must use the current state layer list
2365 // (soon to become the drawing state list).
2366 //
2367 sp<const DisplayDevice> disp;
2368 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002369 bool first = true;
2370 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002371 // NOTE: we rely on the fact that layers are sorted by
2372 // layerStack first (so we don't have to traverse the list
2373 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002374 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002375 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002376 currentlayerStack = layerStack;
2377 // figure out if this layerstack is mirrored
2378 // (more than one display) if so, pick the default display,
2379 // if not, pick the only display it's on.
2380 disp.clear();
2381 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2382 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002383 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002384 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002385 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002386 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002387 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002388 break;
2389 }
2390 }
2391 }
2392 }
Chet Haase91d25932013-04-11 15:24:55 -07002393
Robert Carr56a0b9a2017-12-04 16:06:13 -08002394 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002395 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002396 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2397 // redraw after transform hint changes. See bug 8508397.
2398
2399 // could be null when this layer is using a layerStack
2400 // that is not visible on any display. Also can occur at
2401 // screen off/on times.
2402 disp = getDefaultDisplayDeviceLocked();
2403 }
2404 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002405 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002406 if (disp != nullptr) {
2407 layer->updateTransformHint(disp);
2408 }
Robert Carr2047fae2016-11-28 14:09:09 -08002409
2410 first = false;
2411 });
Mathias Agopian84300952012-11-21 16:02:13 -08002412 }
2413
2414
Mathias Agopian3559b072012-08-15 13:46:03 -07002415 /*
2416 * Perform our own transaction if needed
2417 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002418
2419 if (mLayersAdded) {
2420 mLayersAdded = false;
2421 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002422 mVisibleRegionsDirty = true;
2423 }
2424
2425 // some layers might have been removed, so
2426 // we need to update the regions they're exposing.
2427 if (mLayersRemoved) {
2428 mLayersRemoved = false;
2429 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002430 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002431 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002432 // this layer is not visible anymore
2433 // TODO: we could traverse the tree from front to back and
2434 // compute the actual visible region
2435 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002436 Region visibleReg;
2437 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002438 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002439 }
Robert Carr2047fae2016-11-28 14:09:09 -08002440 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441 }
2442
2443 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002444
2445 updateCursorAsync();
2446}
2447
2448void SurfaceFlinger::updateCursorAsync()
2449{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002450 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2451 auto& displayDevice = mDisplays[displayId];
2452 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002453 continue;
2454 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455
2456 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2457 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002458 }
2459 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002460}
2461
2462void SurfaceFlinger::commitTransaction()
2463{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002464 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002465 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002466 for (const auto& l : mLayersPendingRemoval) {
2467 recordBufferingStats(l->getName().string(),
2468 l->getOccupancyHistory(true));
2469 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002470 }
2471 mLayersPendingRemoval.clear();
2472 }
2473
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002474 // If this transaction is part of a window animation then the next frame
2475 // we composite should be considered an animation as well.
2476 mAnimCompositionPending = mAnimTransactionPending;
2477
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002479 mDrawingState.traverseInZOrder([](Layer* layer) {
2480 layer->commitChildList();
2481 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002482 mTransactionPending = false;
2483 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002484 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485}
2486
Chia-I Wuab0c3192017-08-01 11:29:00 -07002487void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002488 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489{
Mathias Agopian841cde52012-03-01 15:44:37 -08002490 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493 Region aboveOpaqueLayers;
2494 Region aboveCoveredLayers;
2495 Region dirty;
2496
Mathias Agopian87baae12012-07-31 12:38:26 -07002497 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498
Robert Carr2047fae2016-11-28 14:09:09 -08002499 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002501 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502
Jesse Hall01e29052013-02-19 16:13:35 -08002503 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002504 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002505 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002506
Mathias Agopianab028732010-03-16 16:41:46 -07002507 /*
2508 * opaqueRegion: area of a surface that is fully opaque.
2509 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002511
2512 /*
2513 * visibleRegion: area of a surface that is visible on screen
2514 * and not fully transparent. This is essentially the layer's
2515 * footprint minus the opaque regions above it.
2516 * Areas covered by a translucent surface are considered visible.
2517 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002519
2520 /*
2521 * coveredRegion: area of a surface that is covered by all
2522 * visible regions above it (which includes the translucent areas).
2523 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002525
Jesse Halla8026d22012-09-25 13:25:04 -07002526 /*
2527 * transparentRegion: area of a surface that is hinted to be completely
2528 * transparent. This is only used to tell when the layer has no visible
2529 * non-transparent regions and can be removed from the layer list. It
2530 * does not affect the visibleRegion of this layer or any layers
2531 * beneath it. The hint may not be correct if apps don't respect the
2532 * SurfaceView restrictions (which, sadly, some don't).
2533 */
2534 Region transparentRegion;
2535
Mathias Agopianab028732010-03-16 16:41:46 -07002536
2537 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002538 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002539 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002542 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002543 if (!visibleRegion.isEmpty()) {
2544 // Remove the transparent area from the visible region
2545 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002546 if (tr.preserveRects()) {
2547 // transform the transparent region
2548 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002549 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002550 // transformation too complex, can't do the
2551 // transparent region optimization.
2552 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553 }
Mathias Agopianab028732010-03-16 16:41:46 -07002554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555
Mathias Agopianab028732010-03-16 16:41:46 -07002556 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002557 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002558 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002559 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2560 // the opaque region is the layer's footprint
2561 opaqueRegion = visibleRegion;
2562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 }
2564 }
2565
Robert Carre5f4f692018-01-12 13:12:28 -08002566 if (visibleRegion.isEmpty()) {
2567 layer->clearVisibilityRegions();
2568 return;
2569 }
2570
Mathias Agopianab028732010-03-16 16:41:46 -07002571 // Clip the covered region to the visible region
2572 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2573
2574 // Update aboveCoveredLayers for next (lower) layer
2575 aboveCoveredLayers.orSelf(visibleRegion);
2576
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 // subtract the opaque region covered by the layers above us
2578 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579
2580 // compute this layer's dirty region
2581 if (layer->contentDirty) {
2582 // we need to invalidate the whole region
2583 dirty = visibleRegion;
2584 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 layer->contentDirty = false;
2587 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002588 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002589 * the exposed region consists of two components:
2590 * 1) what's VISIBLE now and was COVERED before
2591 * 2) what's EXPOSED now less what was EXPOSED before
2592 *
2593 * note that (1) is conservative, we start with the whole
2594 * visible region but only keep what used to be covered by
2595 * something -- which mean it may have been exposed.
2596 *
2597 * (2) handles areas that were not covered by anything but got
2598 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002599 */
Mathias Agopianab028732010-03-16 16:41:46 -07002600 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002601 const Region oldVisibleRegion = layer->visibleRegion;
2602 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002603 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2604 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 }
2606 dirty.subtractSelf(aboveOpaqueLayers);
2607
2608 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002609 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610
Mathias Agopianab028732010-03-16 16:41:46 -07002611 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002613
Jesse Halla8026d22012-09-25 13:25:04 -07002614 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 layer->setVisibleRegion(visibleRegion);
2616 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002617 layer->setVisibleNonTransparentRegion(
2618 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002619 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620
Mathias Agopian87baae12012-07-31 12:38:26 -07002621 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622}
2623
Chia-I Wuab0c3192017-08-01 11:29:00 -07002624void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002625 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002626 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002627 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002628 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002629 }
2630 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002631}
2632
Dan Stoza6b9454d2014-11-07 16:00:59 -08002633bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 ALOGV("handlePageFlip");
2636
Brian Andersond6927fb2016-07-23 23:37:30 -07002637 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638
Mathias Agopian4fec8732012-06-29 14:12:52 -07002639 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002640 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002641 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002642
2643 // Store the set of layers that need updates. This set must not change as
2644 // buffers are being latched, as this could result in a deadlock.
2645 // Example: Two producers share the same command stream and:
2646 // 1.) Layer 0 is latched
2647 // 2.) Layer 0 gets a new frame
2648 // 2.) Layer 1 gets a new frame
2649 // 3.) Layer 1 is latched.
2650 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2651 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002652 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002653 if (layer->hasQueuedFrame()) {
2654 frameQueued = true;
2655 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002656 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002657 } else {
2658 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002659 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002660 } else {
2661 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002662 }
Robert Carr2047fae2016-11-28 14:09:09 -08002663 });
2664
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002666 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002667 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002668 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002669 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002670 newDataLatched = true;
2671 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002672 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002673
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002674 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002675
2676 // If we will need to wake up at some time in the future to deal with a
2677 // queued frame that shouldn't be displayed during this vsync period, wake
2678 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002679 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002680 signalLayerUpdate();
2681 }
2682
2683 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002684 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685}
2686
Mathias Agopianad456f92011-01-13 17:53:01 -08002687void SurfaceFlinger::invalidateHwcGeometry()
2688{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002690}
2691
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002692
Fabien Sanglard830b8472016-11-30 16:35:58 -08002693void SurfaceFlinger::doDisplayComposition(
2694 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002695 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696{
Dan Stoza71433162014-02-04 16:22:36 -08002697 // We only need to actually compose the display if:
2698 // 1) It is being handled by hardware composer, which may need this to
2699 // keep its virtual display state machine in sync, or
2700 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002701 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002702 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002704 return;
2705 }
2706
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002708 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002709
2710 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002711 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Chia-I Wub02087d2017-11-09 10:19:54 -08002714bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002715{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002717
Chia-I Wub02087d2017-11-09 10:19:54 -08002718 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002719 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002721
2722 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002723 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2724 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002725 if (applyColorMatrix) {
2726 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2727 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2728 }
2729
David Sodman105b7dc2017-11-04 20:28:14 -07002730 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731 if (hasClientComposition) {
2732 ALOGV("hasClientComposition");
2733
David Sodmanbc815282017-11-05 18:57:52 -08002734 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002735 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002736 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002737 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002738 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002739 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002741 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002742
2743 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002744 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002745 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2746 }
2747 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002748 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002749
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002750 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002751 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002753 // when using overlays, we assume a fully transparent framebuffer
2754 // NOTE: we could reduce how much we need to clear, for instance
2755 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002756 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002757 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002758 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002759 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002760 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002761 // we're left with the letterbox region
2762 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002764
2765 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002767
Mathias Agopianb9494d52012-04-18 02:28:45 -07002768 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002769 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002770 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002772 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002773 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002774
Dan Stoza9e56aa02015-11-02 13:00:03 -08002775 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002776 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002777 // scissor on the main display. It should never be needed
2778 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 const Rect& bounds(displayDevice->getBounds());
2780 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002781 if (scissor != bounds) {
2782 // scissor doesn't match the screen's dimensions, so we
2783 // need to clear everything outside of it and enable
2784 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002785
Mathias Agopianf45c5102012-10-24 16:29:17 -07002786 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002787 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002788 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002789 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002790 }
2791 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002792 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002793
Mathias Agopian85d751c2012-08-29 16:59:24 -07002794 /*
2795 * and then, render the layers targeted at the framebuffer
2796 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002797
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 ALOGV("Rendering client layers");
2799 const Transform& displayTransform = displayDevice->getTransform();
2800 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002801 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 bool firstLayer = true;
2803 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002804 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 displayTransform.transform(layer->visibleRegion)));
2806 ALOGV("Layer: %s", layer->getName().string());
2807 ALOGV(" Composition type: %s",
2808 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002809 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 switch (layer->getCompositionType(hwcId)) {
2811 case HWC2::Composition::Cursor:
2812 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002813 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002815 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002817 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002819 // never clear the very first layer since we're
2820 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002821 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002822 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002823 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002824 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002825 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002826 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002827 break;
2828 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002830 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002831 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 } else {
2833 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002834 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002836 }
2837 } else {
2838 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002840 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002842 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002843 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002844 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002845 }
2846 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002847
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002848 if (applyColorMatrix) {
2849 getRenderEngine().setupColorTransform(oldColorMatrix);
2850 }
2851
Mathias Agopianf45c5102012-10-24 16:29:17 -07002852 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002853 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002854 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855}
2856
Fabien Sanglard830b8472016-11-30 16:35:58 -08002857void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2858 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002859 RenderEngine& engine(getRenderEngine());
2860 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861}
2862
Dan Stoza7d89d062015-04-30 13:29:25 -07002863status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002864 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002865 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 const sp<Layer>& lbc,
2867 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002868{
Dan Stoza7d89d062015-04-30 13:29:25 -07002869 // add this layer to the current state list
2870 {
2871 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002872 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002873 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2874 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002875 return NO_MEMORY;
2876 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002877 if (parent == nullptr) {
2878 mCurrentState.layersSortedByZ.add(lbc);
2879 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002880 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002881 ALOGE("addClientLayer called with a removed parent");
2882 return NAME_NOT_FOUND;
2883 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002884 parent->addChild(lbc);
2885 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002886
Dan Stoza7d89d062015-04-30 13:29:25 -07002887 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 mLayersAdded = true;
2889 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002890 }
2891
Mathias Agopian96f08192010-06-02 23:28:45 -07002892 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002893 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002894
Dan Stoza7d89d062015-04-30 13:29:25 -07002895 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002896}
2897
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002898status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002899 Mutex::Autolock _l(mStateLock);
2900
chaviw8b3871a2017-11-01 17:41:01 -07002901 if (layer->isPendingRemoval()) {
2902 return NO_ERROR;
2903 }
2904
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002906 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002907 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002908 if (topLevelOnly) {
2909 return NO_ERROR;
2910 }
2911
Chia-I Wu98f1c102017-05-30 14:54:08 -07002912 sp<Layer> ancestor = p;
2913 while (ancestor->getParent() != nullptr) {
2914 ancestor = ancestor->getParent();
2915 }
2916 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2917 ALOGE("removeLayer called with a layer whose parent has been removed");
2918 return NAME_NOT_FOUND;
2919 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002920
2921 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002922 } else {
2923 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002924 }
2925
Robert Carr136e2f62017-02-08 17:54:29 -08002926 // As a matter of normal operation, the LayerCleaner will produce a second
2927 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2928 // so we will succeed in promoting it, but it's already been removed
2929 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2930 // otherwise something has gone wrong and we are leaking the layer.
2931 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002932 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2933 layer->getName().string(),
2934 (p != nullptr) ? p->getName().string() : "no-parent");
2935 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002936 } else if (index < 0) {
2937 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002938 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002939
Chia-I Wuc6657022017-08-15 11:18:17 -07002940 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941 mLayersPendingRemoval.add(layer);
2942 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002943 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002944 setTransactionFlags(eTransactionNeeded);
2945 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946}
2947
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002948uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002949 return android_atomic_release_load(&mTransactionFlags);
2950}
2951
Mathias Agopian3f844832013-08-07 21:24:32 -07002952uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2954}
2955
Mathias Agopian3f844832013-08-07 21:24:32 -07002956uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2958 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002959 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 }
2961 return old;
2962}
2963
Mathias Agopian8b33f032012-07-24 20:43:54 -07002964void SurfaceFlinger::setTransactionState(
2965 const Vector<ComposerState>& state,
2966 const Vector<DisplayState>& displays,
2967 uint32_t flags)
2968{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002969 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002970 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002971 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002972
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002973 if (flags & eAnimation) {
2974 // For window updates that are part of an animation we must wait for
2975 // previous animation "frames" to be handled.
2976 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002977 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002978 if (CC_UNLIKELY(err != NO_ERROR)) {
2979 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002980 // caller after a few seconds.
2981 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2982 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002983 mAnimTransactionPending = false;
2984 break;
2985 }
2986 }
2987 }
2988
Mathias Agopiane57f2922012-08-09 16:29:12 -07002989 size_t count = displays.size();
2990 for (size_t i=0 ; i<count ; i++) {
2991 const DisplayState& s(displays[i]);
2992 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002993 }
2994
Mathias Agopiane57f2922012-08-09 16:29:12 -07002995 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002996 for (size_t i=0 ; i<count ; i++) {
2997 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002998 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08002999 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003000 // IInterface, or one of its own or even one of our own but a
3001 // different type. All these situations would cause us to crash.
3002 //
3003 // NOTE: it would be better to use RTTI as we could directly check
3004 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08003005 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003006 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08003007 if (binder != nullptr) {
3008 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003009 sp<Client> client( static_cast<Client *>(s.client.get()) );
3010 transactionFlags |= setClientStateLocked(client, s.state);
3011 }
3012 }
3013 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003014 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003015
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003016 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3017 // anyway. This can be used as a flush mechanism for previous async transactions.
3018 // Empty animation transaction can be used to simulate back-pressure, so also force a
3019 // transaction for empty animation transactions.
3020 if (transactionFlags == 0 &&
3021 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003022 transactionFlags = eTransactionNeeded;
3023 }
3024
Mathias Agopian386aa982011-11-07 21:58:03 -08003025 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003026 if (mInterceptor.isEnabled()) {
3027 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3028 }
Irvel468051e2016-06-13 16:44:44 -07003029
Mathias Agopian386aa982011-11-07 21:58:03 -08003030 // this triggers the transaction
3031 setTransactionFlags(transactionFlags);
3032
3033 // if this is a synchronous transaction, wait for it to take effect
3034 // before returning.
3035 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003036 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003037 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003038 if (flags & eAnimation) {
3039 mAnimTransactionPending = true;
3040 }
3041 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003042 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3043 if (CC_UNLIKELY(err != NO_ERROR)) {
3044 // just in case something goes wrong in SF, return to the
3045 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003046 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3047 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003048 break;
3049 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003050 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051 }
3052}
3053
Mathias Agopiane57f2922012-08-09 16:29:12 -07003054uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3055{
Jesse Hall9a143922012-10-04 16:29:19 -07003056 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3057 if (dpyIdx < 0)
3058 return 0;
3059
Mathias Agopiane57f2922012-08-09 16:29:12 -07003060 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003061 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003062 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003063 const uint32_t what = s.what;
3064 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003065 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 disp.surface = s.surface;
3067 flags |= eDisplayTransactionNeeded;
3068 }
3069 }
3070 if (what & DisplayState::eLayerStackChanged) {
3071 if (disp.layerStack != s.layerStack) {
3072 disp.layerStack = s.layerStack;
3073 flags |= eDisplayTransactionNeeded;
3074 }
3075 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003076 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003077 if (disp.orientation != s.orientation) {
3078 disp.orientation = s.orientation;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 if (disp.frame != s.frame) {
3082 disp.frame = s.frame;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 if (disp.viewport != s.viewport) {
3086 disp.viewport = s.viewport;
3087 flags |= eDisplayTransactionNeeded;
3088 }
3089 }
Michael Lentine47e45402014-07-18 15:34:25 -07003090 if (what & DisplayState::eDisplaySizeChanged) {
3091 if (disp.width != s.width) {
3092 disp.width = s.width;
3093 flags |= eDisplayTransactionNeeded;
3094 }
3095 if (disp.height != s.height) {
3096 disp.height = s.height;
3097 flags |= eDisplayTransactionNeeded;
3098 }
3099 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 }
3101 return flags;
3102}
3103
3104uint32_t SurfaceFlinger::setClientStateLocked(
3105 const sp<Client>& client,
3106 const layer_state_t& s)
3107{
Mathias Agopian13127d82013-03-05 17:47:11 -08003108 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003109 if (layer == nullptr) {
3110 return 0;
3111 }
3112
3113 if (layer->isPendingRemoval()) {
3114 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3115 return 0;
3116 }
3117
3118 uint32_t flags = 0;
3119
3120 const uint32_t what = s.what;
3121 bool geometryAppliesWithResize =
3122 what & layer_state_t::eGeometryAppliesWithResize;
3123 if (what & layer_state_t::ePositionChanged) {
3124 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3125 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003126 }
chaviw8b3871a2017-11-01 17:41:01 -07003127 }
3128 if (what & layer_state_t::eLayerChanged) {
3129 // NOTE: index needs to be calculated before we update the state
3130 const auto& p = layer->getParent();
3131 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003132 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003133 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003134 mCurrentState.layersSortedByZ.removeAt(idx);
3135 mCurrentState.layersSortedByZ.add(layer);
3136 // we need traversal (state changed)
3137 // AND transaction (list changed)
3138 flags |= eTransactionNeeded|eTraversalNeeded;
3139 }
chaviw8b3871a2017-11-01 17:41:01 -07003140 } else {
3141 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003142 flags |= eTransactionNeeded|eTraversalNeeded;
3143 }
3144 }
chaviw8b3871a2017-11-01 17:41:01 -07003145 }
3146 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003147 // NOTE: index needs to be calculated before we update the state
3148 const auto& p = layer->getParent();
3149 if (p == nullptr) {
3150 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3151 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3152 mCurrentState.layersSortedByZ.removeAt(idx);
3153 mCurrentState.layersSortedByZ.add(layer);
3154 // we need traversal (state changed)
3155 // AND transaction (list changed)
3156 flags |= eTransactionNeeded|eTraversalNeeded;
3157 }
3158 } else {
3159 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3160 flags |= eTransactionNeeded|eTraversalNeeded;
3161 }
chaviw8b3871a2017-11-01 17:41:01 -07003162 }
3163 }
3164 if (what & layer_state_t::eSizeChanged) {
3165 if (layer->setSize(s.w, s.h)) {
3166 flags |= eTraversalNeeded;
3167 }
3168 }
3169 if (what & layer_state_t::eAlphaChanged) {
3170 if (layer->setAlpha(s.alpha))
3171 flags |= eTraversalNeeded;
3172 }
3173 if (what & layer_state_t::eColorChanged) {
3174 if (layer->setColor(s.color))
3175 flags |= eTraversalNeeded;
3176 }
3177 if (what & layer_state_t::eMatrixChanged) {
3178 if (layer->setMatrix(s.matrix))
3179 flags |= eTraversalNeeded;
3180 }
3181 if (what & layer_state_t::eTransparentRegionChanged) {
3182 if (layer->setTransparentRegionHint(s.transparentRegion))
3183 flags |= eTraversalNeeded;
3184 }
3185 if (what & layer_state_t::eFlagsChanged) {
3186 if (layer->setFlags(s.flags, s.mask))
3187 flags |= eTraversalNeeded;
3188 }
3189 if (what & layer_state_t::eCropChanged) {
3190 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3191 flags |= eTraversalNeeded;
3192 }
3193 if (what & layer_state_t::eFinalCropChanged) {
3194 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3195 flags |= eTraversalNeeded;
3196 }
3197 if (what & layer_state_t::eLayerStackChanged) {
3198 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3199 // We only allow setting layer stacks for top level layers,
3200 // everything else inherits layer stack from its parent.
3201 if (layer->hasParent()) {
3202 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3203 layer->getName().string());
3204 } else if (idx < 0) {
3205 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3206 "that also does not appear in the top level layer list. Something"
3207 " has gone wrong.", layer->getName().string());
3208 } else if (layer->setLayerStack(s.layerStack)) {
3209 mCurrentState.layersSortedByZ.removeAt(idx);
3210 mCurrentState.layersSortedByZ.add(layer);
3211 // we need traversal (state changed)
3212 // AND transaction (list changed)
3213 flags |= eTransactionNeeded|eTraversalNeeded;
3214 }
3215 }
3216 if (what & layer_state_t::eDeferTransaction) {
3217 if (s.barrierHandle != nullptr) {
3218 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3219 } else if (s.barrierGbp != nullptr) {
3220 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3221 if (authenticateSurfaceTextureLocked(gbp)) {
3222 const auto& otherLayer =
3223 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3224 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3225 } else {
3226 ALOGE("Attempt to defer transaction to to an"
3227 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003228 }
3229 }
chaviw8b3871a2017-11-01 17:41:01 -07003230 // We don't trigger a traversal here because if no other state is
3231 // changed, we don't want this to cause any more work
3232 }
3233 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003234 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003235 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003236 if (!hadParent) {
3237 mCurrentState.layersSortedByZ.remove(layer);
3238 }
chaviw8b3871a2017-11-01 17:41:01 -07003239 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003240 }
chaviw8b3871a2017-11-01 17:41:01 -07003241 }
3242 if (what & layer_state_t::eReparentChildren) {
3243 if (layer->reparentChildren(s.reparentHandle)) {
3244 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003245 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003246 }
chaviw8b3871a2017-11-01 17:41:01 -07003247 if (what & layer_state_t::eDetachChildren) {
3248 layer->detachChildren();
3249 }
3250 if (what & layer_state_t::eOverrideScalingModeChanged) {
3251 layer->setOverrideScalingMode(s.overrideScalingMode);
3252 // We don't trigger a traversal here because if no other state is
3253 // changed, we don't want this to cause any more work
3254 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003255 return flags;
3256}
3257
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003258status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003259 const String8& name,
3260 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003261 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003262 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3263 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003265 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003266 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003267 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003268 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003269 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003270
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003271 status_t result = NO_ERROR;
3272
3273 sp<Layer> layer;
3274
Cody Northropbc755282017-03-31 12:00:08 -06003275 String8 uniqueName = getUniqueLayerName(name);
3276
Mathias Agopian3165cc22012-08-08 19:42:09 -07003277 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3278 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003279 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003280 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003281 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 break;
chaviw13fdc492017-06-27 12:40:18 -07003284 case ISurfaceComposerClient::eFXSurfaceColor:
3285 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003286 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003287 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003288 break;
3289 default:
3290 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 break;
3292 }
3293
Dan Stoza7d89d062015-04-30 13:29:25 -07003294 if (result != NO_ERROR) {
3295 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003297
Chia-I Wuab0c3192017-08-01 11:29:00 -07003298 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3299 // TODO b/64227542
3300 if (windowType == 441731) {
3301 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3302 layer->setPrimaryDisplayOnly();
3303 }
3304
Albert Chaulk479c60c2017-01-27 14:21:34 -05003305 layer->setInfo(windowType, ownerUid);
3306
Robert Carr1f0a16a2016-10-24 16:27:39 -07003307 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003308 if (result != NO_ERROR) {
3309 return result;
3310 }
Irvelffc9efc2016-07-27 15:16:37 -07003311 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003312
3313 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003314 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315}
3316
Cody Northropbc755282017-03-31 12:00:08 -06003317String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3318{
3319 bool matchFound = true;
3320 uint32_t dupeCounter = 0;
3321
3322 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3323 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3324
3325 // Loop over layers until we're sure there is no matching name
3326 while (matchFound) {
3327 matchFound = false;
3328 mDrawingState.traverseInZOrder([&](Layer* layer) {
3329 if (layer->getName() == uniqueName) {
3330 matchFound = true;
3331 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3332 }
3333 });
3334 }
3335
3336 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3337
3338 return uniqueName;
3339}
3340
David Sodman0c69cad2017-08-21 12:12:51 -07003341status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003342 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3343 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344{
3345 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003346 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003347 case PIXEL_FORMAT_TRANSPARENT:
3348 case PIXEL_FORMAT_TRANSLUCENT:
3349 format = PIXEL_FORMAT_RGBA_8888;
3350 break;
3351 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003352 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 break;
3354 }
3355
David Sodman0c69cad2017-08-21 12:12:51 -07003356 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3357 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003358 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003359 *handle = layer->getHandle();
3360 *gbp = layer->getProducer();
3361 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003363
David Sodman0c69cad2017-08-21 12:12:51 -07003364 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003365 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366}
3367
chaviw13fdc492017-06-27 12:40:18 -07003368status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003369 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003370 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371{
chaviw13fdc492017-06-27 12:40:18 -07003372 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003373 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003374 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003375}
3376
Mathias Agopianac9fa422013-02-11 16:40:36 -08003377status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003378{
Robert Carr9524cb32017-02-13 11:32:32 -08003379 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003380 status_t err = NO_ERROR;
3381 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003382 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003383 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003384 err = removeLayer(l);
3385 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3386 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003387 }
3388 return err;
3389}
3390
Mathias Agopian13127d82013-03-05 17:47:11 -08003391status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003392{
Mathias Agopian67106042013-03-14 19:18:13 -07003393 // called by ~LayerCleaner() when all references to the IBinder (handle)
3394 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003395 sp<Layer> l = layer.promote();
3396 if (l == nullptr) {
3397 // The layer has already been removed, carry on
3398 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003399 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003400 // If we have a parent, then we can continue to live as long as it does.
3401 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003402}
3403
Mathias Agopianb60314a2012-04-10 22:09:54 -07003404// ---------------------------------------------------------------------------
3405
Andy McFadden13a082e2012-08-24 10:16:42 -07003406void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003407 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003408 Vector<ComposerState> state;
3409 Vector<DisplayState> displays;
3410 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003411 d.what = DisplayState::eDisplayProjectionChanged |
3412 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003413 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003414 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003415 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003416 d.frame.makeInvalid();
3417 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003418 d.width = 0;
3419 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003420 displays.add(d);
3421 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003422 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3423 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003424
David Sodman105b7dc2017-11-04 20:28:14 -07003425 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003426 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003427 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003428
Brian Andersond0010582017-03-07 13:20:31 -08003429 // Use phase of 0 since phase is not known.
3430 // Use latency of 0, which will snap to the ideal latency.
3431 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003432}
3433
3434void SurfaceFlinger::initializeDisplays() {
3435 class MessageScreenInitialized : public MessageBase {
3436 SurfaceFlinger* flinger;
3437 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003438 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003439 virtual bool handler() {
3440 flinger->onInitializeDisplays();
3441 return true;
3442 }
3443 };
3444 sp<MessageBase> msg = new MessageScreenInitialized(this);
3445 postMessageAsync(msg); // we may be called from main thread, use async message
3446}
3447
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003448void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003449 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003450 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3451 this);
3452 int32_t type = hw->getDisplayType();
3453 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003454
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003455 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003456 return;
3457 }
3458
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 hw->setPowerMode(mode);
3460 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3461 ALOGW("Trying to set power mode for virtual display");
3462 return;
3463 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003464
Irvelffc9efc2016-07-27 15:16:37 -07003465 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003466 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003467 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3468 if (idx < 0) {
3469 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3470 return;
3471 }
3472 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3473 }
3474
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003475 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003476 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003477 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003478 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3479 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003480 // FIXME: eventthread only knows about the main display right now
3481 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003482 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003485 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003486 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003487 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003488
3489 struct sched_param param = {0};
3490 param.sched_priority = 1;
3491 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3492 ALOGW("Couldn't set SCHED_FIFO on display on");
3493 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003494 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003495 // Turn off the display
3496 struct sched_param param = {0};
3497 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3498 ALOGW("Couldn't set SCHED_OTHER on display off");
3499 }
3500
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003501 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3502 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003503 disableHardwareVsync(true); // also cancels any in-progress resync
3504
Mathias Agopiancde87a32012-09-13 14:09:01 -07003505 // FIXME: eventthread only knows about the main display right now
3506 mEventThread->onScreenReleased();
3507 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003508
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003509 getHwComposer().setPowerMode(type, mode);
3510 mVisibleRegionsDirty = true;
3511 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003512 } else if (mode == HWC_POWER_MODE_DOZE ||
3513 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003514 // Update display while dozing
3515 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003516 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3517 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003518 // FIXME: eventthread only knows about the main display right now
3519 mEventThread->onScreenAcquired();
3520 resyncToHardwareVsync(true);
3521 }
3522 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3523 // Leave display going to doze
3524 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3525 disableHardwareVsync(true); // also cancels any in-progress resync
3526 // FIXME: eventthread only knows about the main display right now
3527 mEventThread->onScreenReleased();
3528 }
3529 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003531 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003532 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003533 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003534}
3535
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003536void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3537 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003538 SurfaceFlinger& mFlinger;
3539 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003540 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003541 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003542 MessageSetPowerMode(SurfaceFlinger& flinger,
3543 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3544 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003545 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003547 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003548 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003549 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003550 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003551 ALOGW("Attempt to set power mode = %d for virtual display",
3552 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003553 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003554 mFlinger.setPowerModeInternal(
3555 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003556 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003557 return true;
3558 }
3559 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003560 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003561 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003562}
3563
3564// ---------------------------------------------------------------------------
3565
Lloyd Pique755e3192018-01-31 16:46:15 -08003566status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3567 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003569
Mathias Agopianbd115332013-04-18 16:41:04 -07003570 IPCThreadState* ipc = IPCThreadState::self();
3571 const int pid = ipc->getCallingPid();
3572 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003573
Mathias Agopianbd115332013-04-18 16:41:04 -07003574 if ((uid != AID_SHELL) &&
3575 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003576 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003577 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003579 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003580 // (this would indicate SF is stuck, but we want to be able to
3581 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003582 status_t err = mStateLock.timedLock(s2ns(1));
3583 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003584 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003585 result.appendFormat(
3586 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3587 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003588 }
3589
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003590 bool dumpAll = true;
3591 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003592 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003593
3594 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003595 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003596 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3597 dumpAll = false;
3598 }
3599
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003600 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003601 if ((index < numArgs) &&
3602 (args[index] == String16("--list"))) {
3603 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003604 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003605 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003606 }
3607
3608 if ((index < numArgs) &&
3609 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003610 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003611 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003612 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003613 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003614
3615 if ((index < numArgs) &&
3616 (args[index] == String16("--latency-clear"))) {
3617 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003618 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003619 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003620 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003621
3622 if ((index < numArgs) &&
3623 (args[index] == String16("--dispsync"))) {
3624 index++;
3625 mPrimaryDispSync.dump(result);
3626 dumpAll = false;
3627 }
Dan Stozab90cf072015-03-05 11:05:59 -08003628
3629 if ((index < numArgs) &&
3630 (args[index] == String16("--static-screen"))) {
3631 index++;
3632 dumpStaticScreenStats(result);
3633 dumpAll = false;
3634 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003635
3636 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003637 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003638 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003639 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003640 dumpAll = false;
3641 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003642
3643 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3644 index++;
3645 dumpWideColorInfo(result);
3646 dumpAll = false;
3647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003649
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003650 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003651 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003652 }
3653
Mathias Agopian9795c422009-08-26 16:36:26 -07003654 if (locked) {
3655 mStateLock.unlock();
3656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657 }
3658 write(fd, result.string(), result.size());
3659 return NO_ERROR;
3660}
3661
Dan Stozac7014012014-02-14 15:03:43 -08003662void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3663 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003664{
Robert Carr2047fae2016-11-28 14:09:09 -08003665 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003666 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003667 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003668}
3669
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003670void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003671 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672{
3673 String8 name;
3674 if (index < args.size()) {
3675 name = String8(args[index]);
3676 index++;
3677 }
3678
David Sodman105b7dc2017-11-04 20:28:14 -07003679 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003680 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003681 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003682
3683 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003684 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003685 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003686 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003687 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003688 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003689 }
Robert Carr2047fae2016-11-28 14:09:09 -08003690 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003691 }
3692}
3693
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003694void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003695 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003696{
3697 String8 name;
3698 if (index < args.size()) {
3699 name = String8(args[index]);
3700 index++;
3701 }
3702
Robert Carr2047fae2016-11-28 14:09:09 -08003703 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003704 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003705 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003706 }
Robert Carr2047fae2016-11-28 14:09:09 -08003707 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003708
Svetoslavd85084b2014-03-20 10:28:31 -07003709 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003710}
3711
Jamie Gennis6547ff42013-07-16 20:12:42 -07003712// This should only be called from the main thread. Otherwise it would need
3713// the lock and should use mCurrentState rather than mDrawingState.
3714void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003715 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003716 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003717 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003718
3719 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3720}
3721
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003722void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003723{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003724 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003725
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003726 if (isLayerTripleBufferingDisabled())
3727 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003728
3729 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003730 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003731 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003732 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003733 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3734 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003735 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003736}
3737
Dan Stozab90cf072015-03-05 11:05:59 -08003738void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3739{
3740 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003741 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3742 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003743 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003744 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003745 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3746 b + 1, bucketTimeSec, percent);
3747 }
David Sodman4a36e932017-11-07 14:29:47 -08003748 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003749 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003750 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003751 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003752 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003753}
3754
Dan Stozae77c7662016-05-13 11:37:28 -07003755void SurfaceFlinger::recordBufferingStats(const char* layerName,
3756 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003757 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3758 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003759 for (const auto& segment : history) {
3760 if (!segment.usedThirdBuffer) {
3761 stats.twoBufferTime += segment.totalTime;
3762 }
3763 if (segment.occupancyAverage < 1.0f) {
3764 stats.doubleBufferedTime += segment.totalTime;
3765 } else if (segment.occupancyAverage < 2.0f) {
3766 stats.tripleBufferedTime += segment.totalTime;
3767 }
3768 ++stats.numSegments;
3769 stats.totalTime += segment.totalTime;
3770 }
3771}
3772
Brian Andersond6927fb2016-07-23 23:37:30 -07003773void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3774 result.appendFormat("Layer frame timestamps:\n");
3775
3776 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3777 const size_t count = currentLayers.size();
3778 for (size_t i=0 ; i<count ; i++) {
3779 currentLayers[i]->dumpFrameEvents(result);
3780 }
3781}
3782
Dan Stozae77c7662016-05-13 11:37:28 -07003783void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3784 result.append("Buffering stats:\n");
3785 result.append(" [Layer name] <Active time> <Two buffer> "
3786 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003787 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003788 typedef std::tuple<std::string, float, float, float> BufferTuple;
3789 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003790 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003791 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003792 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003793 if (stats.numSegments == 0) {
3794 continue;
3795 }
3796 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3797 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3798 stats.totalTime;
3799 float doubleBufferRatio = static_cast<float>(
3800 stats.doubleBufferedTime) / stats.totalTime;
3801 float tripleBufferRatio = static_cast<float>(
3802 stats.tripleBufferedTime) / stats.totalTime;
3803 sorted.insert({activeTime, {name, twoBufferRatio,
3804 doubleBufferRatio, tripleBufferRatio}});
3805 }
3806 for (const auto& sortedPair : sorted) {
3807 float activeTime = sortedPair.first;
3808 const BufferTuple& values = sortedPair.second;
3809 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3810 std::get<0>(values).c_str(), activeTime,
3811 std::get<1>(values), std::get<2>(values),
3812 std::get<3>(values));
3813 }
3814 result.append("\n");
3815}
3816
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003817void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3818 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003819 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003820
3821 // TODO: print out if wide-color mode is active or not
3822
3823 for (size_t d = 0; d < mDisplays.size(); d++) {
3824 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3825 int32_t hwcId = displayDevice->getHwcDisplayId();
3826 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3827 continue;
3828 }
3829
3830 result.appendFormat("Display %d color modes:\n", hwcId);
3831 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3832 for (auto&& mode : modes) {
3833 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3834 }
3835
3836 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3837 result.appendFormat(" Current color mode: %s (%d)\n",
3838 decodeColorMode(currentMode).c_str(), currentMode);
3839 }
3840 result.append("\n");
3841}
3842
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003843LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003844 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003845 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3846 const State& state = useDrawing ? mDrawingState : mCurrentState;
3847 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003848 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003849 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003850 });
3851
3852 return layersProto;
3853}
3854
Mathias Agopian74d211a2013-04-22 16:55:35 +02003855void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3856 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003858 bool colorize = false;
3859 if (index < args.size()
3860 && (args[index] == String16("--color"))) {
3861 colorize = true;
3862 index++;
3863 }
3864
3865 Colorizer colorizer(colorize);
3866
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003867 // figure out if we're stuck somewhere
3868 const nsecs_t now = systemTime();
3869 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3870 const nsecs_t inTransaction(mDebugInTransaction);
3871 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3872 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3873
3874 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003875 * Dump library configuration.
3876 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003877
3878 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003879 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003880 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003881 appendSfConfigString(result);
3882 appendUiConfigString(result);
3883 appendGuiConfigString(result);
3884 result.append("\n");
3885
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003886 result.append("\nWide-Color information:\n");
3887 dumpWideColorInfo(result);
3888
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003889 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003890 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003891 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003892 result.append(SyncFeatures::getInstance().toString());
3893 result.append("\n");
3894
David Sodman105b7dc2017-11-04 20:28:14 -07003895 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003896
Andy McFadden41d67d72014-04-25 16:58:34 -07003897 colorizer.bold(result);
3898 result.append("DispSync configuration: ");
3899 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003900 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003901 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003902 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003903 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003904 result.append("\n");
3905
Dan Stozab90cf072015-03-05 11:05:59 -08003906 // Dump static screen stats
3907 result.append("\n");
3908 dumpStaticScreenStats(result);
3909 result.append("\n");
3910
Dan Stozae77c7662016-05-13 11:37:28 -07003911 dumpBufferingStats(result);
3912
Andy McFadden4803b742012-09-24 19:07:20 -07003913 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003914 * Dump the visible layer list
3915 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003916 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003917 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003918 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003919
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003920 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003921 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3922 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003923
3924 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003925 * Dump Display state
3926 */
3927
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003928 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003929 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003930 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003931 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3932 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003933 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003934 }
3935
3936 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003937 * Dump SurfaceFlinger global state
3938 */
3939
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003940 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003941 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943
Mathias Agopian888c8222012-08-04 21:10:38 -07003944 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003945 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003946
David Sodmanbc815282017-11-05 18:57:52 -08003947 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003948
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003949 if (hw) {
3950 hw->undefinedRegion.dump(result, "undefinedRegion");
3951 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3952 hw->getOrientation(), hw->isDisplayOn());
3953 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955 " last eglSwapBuffers() time: %f us\n"
3956 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003957 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 " refresh-rate : %f fps\n"
3959 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003960 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003961 " gpu_to_cpu_unsupported : %d\n"
3962 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003963 mLastSwapBufferTime/1000.0,
3964 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003965 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003966 1e9 / activeConfig->getVsyncPeriod(),
3967 activeConfig->getDpiX(),
3968 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003969 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003970
Mathias Agopian74d211a2013-04-22 16:55:35 +02003971 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003972 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973
Mathias Agopian74d211a2013-04-22 16:55:35 +02003974 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976
3977 /*
3978 * VSYNC state
3979 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003980 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003981 result.append("\n");
3982
3983 /*
3984 * HWC layer minidump
3985 */
3986 for (size_t d = 0; d < mDisplays.size(); d++) {
3987 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3988 int32_t hwcId = displayDevice->getHwcDisplayId();
3989 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3990 continue;
3991 }
3992
3993 result.appendFormat("Display %d HWC layers:\n", hwcId);
3994 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003995 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003996 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003997 });
Dan Stozae22aec72016-08-01 13:20:59 -07003998 result.append("\n");
3999 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000
4001 /*
4002 * Dump HWComposer state
4003 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004005 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004006 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004007 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004008 result.appendFormat(" h/w composer %s\n",
4009 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004010 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004011
4012 /*
4013 * Dump gralloc state
4014 */
4015 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4016 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004017
4018 /*
4019 * Dump VrFlinger state if in use.
4020 */
4021 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4022 result.append("VrFlinger state:\n");
4023 result.append(mVrFlinger->Dump().c_str());
4024 result.append("\n");
4025 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004026}
4027
Mathias Agopian13127d82013-03-05 17:47:11 -08004028const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004029SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004030 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004031 wp<IBinder> dpy;
4032 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4033 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4034 dpy = mDisplays.keyAt(i);
4035 break;
4036 }
4037 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004038 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004039 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4040 // Just use the primary display so we have something to return
4041 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4042 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004043 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004044}
4045
Keun young Park63f165f2012-08-31 10:53:36 -07004046bool SurfaceFlinger::startDdmConnection()
4047{
4048 void* libddmconnection_dso =
4049 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4050 if (!libddmconnection_dso) {
4051 return false;
4052 }
4053 void (*DdmConnection_start)(const char* name);
4054 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004055 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004056 if (!DdmConnection_start) {
4057 dlclose(libddmconnection_dso);
4058 return false;
4059 }
4060 (*DdmConnection_start)(getServiceName());
4061 return true;
4062}
4063
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004064status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004065 switch (code) {
4066 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004067 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004069 case CLEAR_ANIMATION_FRAME_STATS:
4070 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004071 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004072 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004073 case ENABLE_VSYNC_INJECTIONS:
4074 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075 {
4076 // codes that require permission check
4077 IPCThreadState* ipc = IPCThreadState::self();
4078 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004079 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004080 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004081 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004082 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004083 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004085 break;
4086 }
Robert Carr1db73f62016-12-21 12:58:51 -08004087 /*
4088 * Calling setTransactionState is safe, because you need to have been
4089 * granted a reference to Client* and Handle* to do anything with it.
4090 *
4091 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4092 */
4093 case SET_TRANSACTION_STATE:
4094 case CREATE_SCOPED_CONNECTION:
4095 {
4096 return OK;
4097 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004098 case CAPTURE_SCREEN:
4099 {
4100 // codes that require permission check
4101 IPCThreadState* ipc = IPCThreadState::self();
4102 const int pid = ipc->getCallingPid();
4103 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004104 if ((uid != AID_GRAPHICS) &&
4105 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004106 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004107 return PERMISSION_DENIED;
4108 }
4109 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 }
chaviwa76b2712017-09-20 12:02:26 -07004111 case CAPTURE_LAYERS: {
4112 IPCThreadState* ipc = IPCThreadState::self();
4113 const int pid = ipc->getCallingPid();
4114 const int uid = ipc->getCallingUid();
4115 if ((uid != AID_GRAPHICS) &&
4116 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4117 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4118 return PERMISSION_DENIED;
4119 }
4120 break;
4121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004123 return OK;
4124}
4125
4126status_t SurfaceFlinger::onTransact(
4127 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4128{
4129 status_t credentialCheck = CheckTransactCodeCredentials(code);
4130 if (credentialCheck != OK) {
4131 return credentialCheck;
4132 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4135 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004136 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004137 IPCThreadState* ipc = IPCThreadState::self();
4138 const int uid = ipc->getCallingUid();
4139 if (CC_UNLIKELY(uid != AID_SYSTEM
4140 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004141 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004142 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004143 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 return PERMISSION_DENIED;
4145 }
4146 int n;
4147 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004148 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004149 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 return NO_ERROR;
4151 case 1002: // SHOW_UPDATES
4152 n = data.readInt32();
4153 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004154 invalidateHwcGeometry();
4155 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004158 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004159 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004161 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004162 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004163 setTransactionFlags(
4164 eTransactionNeeded|
4165 eDisplayTransactionNeeded|
4166 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004167 return NO_ERROR;
4168 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004169 case 1006:{ // send empty update
4170 signalRefresh();
4171 return NO_ERROR;
4172 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004173 case 1008: // toggle use of hw composer
4174 n = data.readInt32();
4175 mDebugDisableHWC = n ? 1 : 0;
4176 invalidateHwcGeometry();
4177 repaintEverything();
4178 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004179 case 1009: // toggle use of transform hint
4180 n = data.readInt32();
4181 mDebugDisableTransformHint = n ? 1 : 0;
4182 invalidateHwcGeometry();
4183 repaintEverything();
4184 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004186 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 reply->writeInt32(0);
4188 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004189 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004190 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004191 return NO_ERROR;
4192 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004193 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004194 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004195 return NO_ERROR;
4196 }
4197 case 1014: {
4198 // daltonize
4199 n = data.readInt32();
4200 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004201 case 1:
4202 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4203 break;
4204 case 2:
4205 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4206 break;
4207 case 3:
4208 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4209 break;
4210 default:
4211 mDaltonizer.setType(ColorBlindnessType::None);
4212 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004213 }
4214 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004215 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004216 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004217 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004218 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004219 invalidateHwcGeometry();
4220 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004221 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004223 case 1015: {
4224 // apply a color matrix
4225 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004226 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004227 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004228 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004229 for (size_t j = 0; j < 4; j++) {
4230 mColorMatrix[i][j] = data.readFloat();
4231 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004232 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004233 } else {
4234 mColorMatrix = mat4();
4235 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004236
4237 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4238 // the division by w in the fragment shader
4239 float4 lastRow(transpose(mColorMatrix)[3]);
4240 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4241 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4242 }
4243
Alan Viverette9c5a3332013-09-12 20:04:35 -07004244 invalidateHwcGeometry();
4245 repaintEverything();
4246 return NO_ERROR;
4247 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004248 // This is an experimental interface
4249 // Needs to be shifted to proper binder interface when we productize
4250 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004251 n = data.readInt32();
4252 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004253 return NO_ERROR;
4254 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004255 case 1017: {
4256 n = data.readInt32();
4257 mForceFullDamage = static_cast<bool>(n);
4258 return NO_ERROR;
4259 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004260 case 1018: { // Modify Choreographer's phase offset
4261 n = data.readInt32();
4262 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4263 return NO_ERROR;
4264 }
4265 case 1019: { // Modify SurfaceFlinger's phase offset
4266 n = data.readInt32();
4267 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4268 return NO_ERROR;
4269 }
Irvel468051e2016-06-13 16:44:44 -07004270 case 1020: { // Layer updates interceptor
4271 n = data.readInt32();
4272 if (n) {
4273 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004274 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004275 }
4276 else{
4277 ALOGV("Interceptor disabled");
4278 mInterceptor.disable();
4279 }
4280 return NO_ERROR;
4281 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004282 case 1021: { // Disable HWC virtual displays
4283 n = data.readInt32();
4284 mUseHwcVirtualDisplays = !n;
4285 return NO_ERROR;
4286 }
Romain Guy0147a172017-06-01 13:53:56 -07004287 case 1022: { // Set saturation boost
4288 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4289
4290 invalidateHwcGeometry();
4291 repaintEverything();
4292 return NO_ERROR;
4293 }
Romain Guy54f154a2017-10-24 21:40:32 +01004294 case 1023: { // Set native mode
4295 mForceNativeColorMode = data.readInt32() == 1;
4296
4297 invalidateHwcGeometry();
4298 repaintEverything();
4299 return NO_ERROR;
4300 }
4301 case 1024: { // Is wide color gamut rendering/color management supported?
4302 reply->writeBool(hasWideColorDisplay);
4303 return NO_ERROR;
4304 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004305 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004306 n = data.readInt32();
4307 if (n) {
4308 ALOGV("LayerTracing enabled");
4309 mTracing.enable();
4310 doTracing("tracing.enable");
4311 reply->writeInt32(NO_ERROR);
4312 } else {
4313 ALOGV("LayerTracing disabled");
4314 status_t err = mTracing.disable();
4315 reply->writeInt32(err);
4316 }
4317 return NO_ERROR;
4318 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004319 case 1026: { // Get layer tracing status
4320 reply->writeBool(mTracing.isEnabled());
4321 return NO_ERROR;
4322 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004323 }
4324 }
4325 return err;
4326}
4327
Steven Thomas6d8110b2017-08-31 18:24:21 -07004328void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004329 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004330 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004331}
4332
Steven Thomas6d8110b2017-08-31 18:24:21 -07004333void SurfaceFlinger::repaintEverything() {
4334 ConditionalLock _l(mStateLock,
4335 std::this_thread::get_id() != mMainThreadId);
4336 repaintEverythingLocked();
4337}
4338
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004339// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4340class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004341public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004342 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4343 ~WindowDisconnector() {
4344 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004345 }
4346
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004347private:
4348 ANativeWindow* mWindow;
4349 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004350};
4351
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004352status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4353 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4354 int32_t minLayerZ, int32_t maxLayerZ,
4355 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004356 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004357 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004358
chaviwa76b2712017-09-20 12:02:26 -07004359 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4360
4361 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4362 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4363
4364 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4365 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004366 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004367}
4368
4369status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004370 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004371 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004372 ATRACE_CALL();
4373
4374 class LayerRenderArea : public RenderArea {
4375 public:
chaviw7206d492017-11-10 16:16:12 -08004376 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004377 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004378 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004379 const Transform& getTransform() const override {
4380 // Make the top level transform the inverse the transform and it's parent so it sets
4381 // the whole capture back to 0,0
4382 return *new Transform(mLayer->getTransform().inverse());
4383 }
4384 Rect getBounds() const override {
4385 const Layer::State& layerState(mLayer->getDrawingState());
4386 return Rect(layerState.active.w, layerState.active.h);
4387 }
4388 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4389 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4390 bool isSecure() const override { return false; }
4391 bool needsFiltering() const override { return false; }
4392
chaviw7206d492017-11-10 16:16:12 -08004393 Rect getSourceCrop() const override {
4394 if (mCrop.isEmpty()) {
4395 return getBounds();
4396 } else {
4397 return mCrop;
4398 }
4399 }
chaviwa76b2712017-09-20 12:02:26 -07004400 bool getWideColorSupport() const override { return false; }
4401 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4402
4403 private:
chaviw7206d492017-11-10 16:16:12 -08004404 const sp<Layer> mLayer;
4405 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004406 };
4407
4408 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4409 auto parent = layerHandle->owner.promote();
4410
chaviw7206d492017-11-10 16:16:12 -08004411 if (parent == nullptr || parent->isPendingRemoval()) {
4412 ALOGE("captureLayers called with a removed parent");
4413 return NAME_NOT_FOUND;
4414 }
4415
4416 Rect crop(sourceCrop);
4417 if (sourceCrop.width() <= 0) {
4418 crop.left = 0;
4419 crop.right = parent->getCurrentState().active.w;
4420 }
4421
4422 if (sourceCrop.height() <= 0) {
4423 crop.top = 0;
4424 crop.bottom = parent->getCurrentState().active.h;
4425 }
4426
4427 int32_t reqWidth = crop.width() * frameScale;
4428 int32_t reqHeight = crop.height() * frameScale;
4429
4430 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4431
chaviwa76b2712017-09-20 12:02:26 -07004432 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4433 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4434 if (!layer->isVisible()) {
4435 return;
4436 }
4437 visitor(layer);
4438 });
4439 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004440 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004441}
4442
4443status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4444 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004445 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004446 bool useIdentityTransform) {
4447 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004448
chaviwa76b2712017-09-20 12:02:26 -07004449 renderArea.updateDimensions();
4450
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004451 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4452 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4453 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4454 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004455
4456 // This mutex protects syncFd and captureResult for communication of the return values from the
4457 // main thread back to this Binder thread
4458 std::mutex captureMutex;
4459 std::condition_variable captureCondition;
4460 std::unique_lock<std::mutex> captureLock(captureMutex);
4461 int syncFd = -1;
4462 std::optional<status_t> captureResult;
4463
Robert Carr03480e22018-01-04 16:02:06 -08004464 const int uid = IPCThreadState::self()->getCallingUid();
4465 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4466
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004467 sp<LambdaMessage> message = new LambdaMessage([&]() {
4468 // If there is a refresh pending, bug out early and tell the binder thread to try again
4469 // after the refresh.
4470 if (mRefreshPending) {
4471 ATRACE_NAME("Skipping screenshot for now");
4472 std::unique_lock<std::mutex> captureLock(captureMutex);
4473 captureResult = std::make_optional<status_t>(EAGAIN);
4474 captureCondition.notify_one();
4475 return;
4476 }
4477
4478 status_t result = NO_ERROR;
4479 int fd = -1;
4480 {
4481 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004482 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004483 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004484 }
4485
4486 {
4487 std::unique_lock<std::mutex> captureLock(captureMutex);
4488 syncFd = fd;
4489 captureResult = std::make_optional<status_t>(result);
4490 captureCondition.notify_one();
4491 }
4492 });
4493
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004494 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004495 if (result == NO_ERROR) {
4496 captureCondition.wait(captureLock, [&]() { return captureResult; });
4497 while (*captureResult == EAGAIN) {
4498 captureResult.reset();
4499 result = postMessageAsync(message);
4500 if (result != NO_ERROR) {
4501 return result;
4502 }
4503 captureCondition.wait(captureLock, [&]() { return captureResult; });
4504 }
4505 result = *captureResult;
4506 }
4507
4508 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004509 sync_wait(syncFd, -1);
4510 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004511 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004512
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004513 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004514}
4515
chaviwa76b2712017-09-20 12:02:26 -07004516void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4517 TraverseLayersFunction traverseLayers, bool yswap,
4518 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004519 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004520
Mathias Agopian3f844832013-08-07 21:24:32 -07004521 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004522
4523 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004524 const auto raWidth = renderArea.getWidth();
4525 const auto raHeight = renderArea.getHeight();
4526
4527 const auto reqWidth = renderArea.getReqWidth();
4528 const auto reqHeight = renderArea.getReqHeight();
4529 Rect sourceCrop = renderArea.getSourceCrop();
4530
4531 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4532 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004533
Dan Stozac1879002014-05-22 15:59:05 -07004534 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004535 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004536 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004537 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004538 }
4539
4540 // ensure that sourceCrop is inside screen
4541 if (sourceCrop.left < 0) {
4542 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4543 }
chaviwa76b2712017-09-20 12:02:26 -07004544 if (sourceCrop.right > raWidth) {
4545 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004546 }
4547 if (sourceCrop.top < 0) {
4548 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4549 }
chaviwa76b2712017-09-20 12:02:26 -07004550 if (sourceCrop.bottom > raHeight) {
4551 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004552 }
4553
chaviwa76b2712017-09-20 12:02:26 -07004554 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004555 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4556 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004557
Mathias Agopian180f10d2013-04-10 22:55:41 -07004558 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004559 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004560
4561 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004562 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4563 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004564 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004565
4566 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004567 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004568
chaviwa76b2712017-09-20 12:02:26 -07004569 traverseLayers([&](Layer* layer) {
4570 if (filtering) layer->setFiltering(true);
4571 layer->draw(renderArea, useIdentityTransform);
4572 if (filtering) layer->setFiltering(false);
4573 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004574}
4575
chaviwa76b2712017-09-20 12:02:26 -07004576status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4577 TraverseLayersFunction traverseLayers,
4578 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004579 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004580 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004581 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004582 ATRACE_CALL();
4583
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004584 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004585
4586 traverseLayers([&](Layer* layer) {
4587 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4588 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004589
Robert Carr03480e22018-01-04 16:02:06 -08004590 // We allow the system server to take screenshots of secure layers for
4591 // use in situations like the Screen-rotation animation and place
4592 // the impetus on WindowManager to not persist them.
4593 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004594 ALOGW("FB is protected: PERMISSION_DENIED");
4595 return PERMISSION_DENIED;
4596 }
4597
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004598 // this binds the given EGLImage as a framebuffer for the
4599 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004600 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4601 if (bufferBond.getStatus() != NO_ERROR) {
4602 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004603 return INVALID_OPERATION;
4604 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004605
Dan Stozaabcda352017-06-01 14:37:39 -07004606 // this will in fact render into our dequeued buffer
4607 // via an FBO, which means we didn't have to create
4608 // an EGLSurface and therefore we're not
4609 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004610 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004611
Dan Stozaabcda352017-06-01 14:37:39 -07004612 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004613 getRenderEngine().finish();
4614 *outSyncFd = -1;
4615
chaviwa76b2712017-09-20 12:02:26 -07004616 const auto reqWidth = renderArea.getReqWidth();
4617 const auto reqHeight = renderArea.getReqHeight();
4618
Dan Stozaabcda352017-06-01 14:37:39 -07004619 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4620 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004621 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004622 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004623 } else {
4624 base::unique_fd syncFd = getRenderEngine().flush();
4625 if (syncFd < 0) {
4626 getRenderEngine().finish();
4627 }
4628 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004629 }
4630
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004631 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004632}
4633
Mathias Agopiand5556842013-09-19 17:08:37 -07004634void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004635 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004636 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004637 for (size_t y = 0; y < h; y++) {
4638 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4639 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004640 if (p[x] != 0xFF000000) return;
4641 }
4642 }
chaviwa76b2712017-09-20 12:02:26 -07004643 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004644
Robert Carr2047fae2016-11-28 14:09:09 -08004645 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004646 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004647 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004648 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4649 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4650 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4651 static_cast<float>(state.color.a));
4652 i++;
4653 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004654 }
4655}
4656
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004657// ---------------------------------------------------------------------------
4658
Dan Stoza412903f2017-04-27 13:42:17 -07004659void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4660 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004661}
4662
Dan Stoza412903f2017-04-27 13:42:17 -07004663void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4664 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004665}
4666
chaviwa76b2712017-09-20 12:02:26 -07004667void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4668 int32_t maxLayerZ,
4669 const LayerVector::Visitor& visitor) {
4670 // We loop through the first level of layers without traversing,
4671 // as we need to interpret min/max layer Z in the top level Z space.
4672 for (const auto& layer : mDrawingState.layersSortedByZ) {
4673 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4674 continue;
4675 }
4676 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004677 // relative layers are traversed in Layer::traverseInZOrder
4678 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004679 continue;
4680 }
4681 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004682 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4683 return;
4684 }
chaviwa76b2712017-09-20 12:02:26 -07004685 if (!layer->isVisible()) {
4686 return;
4687 }
4688 visitor(layer);
4689 });
4690 }
4691}
4692
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004694
4695
4696#if defined(__gl_h_)
4697#error "don't include gl/gl.h in this file"
4698#endif
4699
4700#if defined(__gl2_h_)
4701#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004702#endif