blob: 1054c3204321c04b5c7eb018125b49b6139b8d3e [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.");
David Sodmanbc815282017-11-05 18:57:52 -0800596 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700597 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800598 // Process any initial hotplug and resulting display changes.
599 processDisplayHotplugEventsLocked();
600 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
601 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800602
Lloyd Piquefcd86612017-12-14 17:15:36 -0800603 // make the default display GLContext current so that we can create textures
604 // when creating Layers (which may happens before we render something)
605 getDefaultDisplayDeviceLocked()->makeCurrent();
606
Steven Thomas050b2c82017-03-06 11:45:16 -0800607 if (useVrFlinger) {
608 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700609 // This callback is called from the vr flinger dispatch thread. We
610 // need to call signalTransaction(), which requires holding
611 // mStateLock when we're not on the main thread. Acquiring
612 // mStateLock from the vr flinger dispatch thread might trigger a
613 // deadlock in surface flinger (see b/66916578), so post a message
614 // to be handled on the main thread instead.
615 sp<LambdaMessage> message = new LambdaMessage([=]() {
616 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
617 mVrFlingerRequestsDisplay = requestDisplay;
618 signalTransaction();
619 });
620 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800621 };
David Sodman105b7dc2017-11-04 20:28:14 -0700622 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
623 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800624 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 if (!mVrFlinger) {
626 ALOGE("Failed to start vrflinger");
627 }
628 }
629
Lloyd Pique755e3192018-01-31 16:46:15 -0800630 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
631 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
632 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700633
Mathias Agopian92a979a2012-08-02 18:32:23 -0700634 // initialize our drawing state
635 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700636
Andy McFadden13a082e2012-08-24 10:16:42 -0700637 // set initial conditions (e.g. unblank default device)
638 initializeDisplays();
639
David Sodmanbc815282017-11-05 18:57:52 -0800640 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700641
Wei Wangf9b05ee2017-07-19 20:59:39 -0700642 // Inform native graphics APIs whether the present timestamp is supported:
643 if (getHwComposer().hasCapability(
644 HWC2::Capability::PresentFenceIsNotReliable)) {
645 mStartPropertySetThread = new StartPropertySetThread(false);
646 } else {
647 mStartPropertySetThread = new StartPropertySetThread(true);
648 }
649
650 if (mStartPropertySetThread->Start() != NO_ERROR) {
651 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800653
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700655}
656
Romain Guy11d63f42017-07-20 12:47:14 -0700657void SurfaceFlinger::readPersistentProperties() {
658 char value[PROPERTY_VALUE_MAX];
659
660 property_get("persist.sys.sf.color_saturation", value, "1.0");
661 mSaturation = atof(value);
662 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100663
664 property_get("persist.sys.sf.native_mode", value, "0");
665 mForceNativeColorMode = atoi(value) == 1;
666 if (mForceNativeColorMode) {
667 ALOGV("Forcing native color mode");
668 }
Romain Guy11d63f42017-07-20 12:47:14 -0700669}
670
Mathias Agopiana67e4182012-06-19 17:26:12 -0700671void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800672 // Start boot animation service by setting a property mailbox
673 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700674 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800675 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700676 if (mStartPropertySetThread->join() != NO_ERROR) {
677 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800678 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700679}
680
Mathias Agopian875d8e12013-06-07 15:35:48 -0700681size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800682 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700683}
684
Mathias Agopian875d8e12013-06-07 15:35:48 -0700685size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800686 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700687}
688
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800689// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800690
Jamie Gennis582270d2011-08-17 18:19:00 -0700691bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800692 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800693 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800694 return authenticateSurfaceTextureLocked(bufferProducer);
695}
696
697bool SurfaceFlinger::authenticateSurfaceTextureLocked(
698 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800699 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700700 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800701}
702
Brian Anderson6b376712017-04-04 10:51:39 -0700703status_t SurfaceFlinger::getSupportedFrameTimestamps(
704 std::vector<FrameEvent>* outSupported) const {
705 *outSupported = {
706 FrameEvent::REQUESTED_PRESENT,
707 FrameEvent::ACQUIRE,
708 FrameEvent::LATCH,
709 FrameEvent::FIRST_REFRESH_START,
710 FrameEvent::LAST_REFRESH_START,
711 FrameEvent::GPU_COMPOSITION_DONE,
712 FrameEvent::DEQUEUE_READY,
713 FrameEvent::RELEASE,
714 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700715 ConditionalLock _l(mStateLock,
716 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700717 if (!getHwComposer().hasCapability(
718 HWC2::Capability::PresentFenceIsNotReliable)) {
719 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
720 }
721 return NO_ERROR;
722}
723
Dan Stoza7f7da322014-05-02 15:26:25 -0700724status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
725 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800726 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700727 return BAD_VALUE;
728 }
729
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500730 if (!display.get())
731 return NAME_NOT_FOUND;
732
Jesse Hall692c7232012-11-08 15:41:56 -0800733 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700734 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800735 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700736 type = i;
737 break;
738 }
739 }
740
741 if (type < 0) {
742 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700743 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700744
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745 // TODO: Not sure if display density should handled by SF any longer
746 class Density {
747 static int getDensityFromProperty(char const* propName) {
748 char property[PROPERTY_VALUE_MAX];
749 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800750 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751 density = atoi(property);
752 }
753 return density;
754 }
755 public:
756 static int getEmuDensity() {
757 return getDensityFromProperty("qemu.sf.lcd_density"); }
758 static int getBuildDensity() {
759 return getDensityFromProperty("ro.sf.lcd_density"); }
760 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700763
Steven Thomas6d8110b2017-08-31 18:24:21 -0700764 ConditionalLock _l(mStateLock,
765 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800766 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700767 DisplayInfo info = DisplayInfo();
768
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 float xdpi = hwConfig->getDpiX();
770 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700771
772 if (type == DisplayDevice::DISPLAY_PRIMARY) {
773 // The density of the device is provided by a build property
774 float density = Density::getBuildDensity() / 160.0f;
775 if (density == 0) {
776 // the build doesn't provide a density -- this is wrong!
777 // use xdpi instead
778 ALOGE("ro.sf.lcd_density must be defined as a build property");
779 density = xdpi / 160.0f;
780 }
781 if (Density::getEmuDensity()) {
782 // if "qemu.sf.lcd_density" is specified, it overrides everything
783 xdpi = ydpi = density = Density::getEmuDensity();
784 density /= 160.0f;
785 }
786 info.density = density;
787
788 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700789 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800790 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 } else {
792 // TODO: where should this value come from?
793 static const int TV_DENSITY = 213;
794 info.density = TV_DENSITY / 160.0f;
795 info.orientation = 0;
796 }
797
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798 info.w = hwConfig->getWidth();
799 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 info.xdpi = xdpi;
801 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900803 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804
Andy McFadden91b2ca82014-06-13 14:04:23 -0700805 // This is how far in advance a buffer must be queued for
806 // presentation at a given time. If you want a buffer to appear
807 // on the screen at time N, you must submit the buffer before
808 // (N - presentationDeadline).
809 //
810 // Normally it's one full refresh period (to give SF a chance to
811 // latch the buffer), but this can be reduced by configuring a
812 // DispSync offset. Any additional delays introduced by the hardware
813 // composer or panel must be accounted for here.
814 //
815 // We add an additional 1ms to allow for processing time and
816 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800818 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700819
820 // All non-virtual displays are currently considered secure.
821 info.secure = true;
822
Michael Wright28f24d02016-07-12 13:30:53 -0700823 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 }
825
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 return NO_ERROR;
827}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700828
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800829status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700830 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800831 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700832 return BAD_VALUE;
833 }
834
835 // FIXME for now we always return stats for the primary display
836 memset(stats, 0, sizeof(*stats));
837 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
838 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
839 return NO_ERROR;
840}
841
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700842int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800843 if (display == nullptr) {
844 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800845 return BAD_VALUE;
846 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700847
848 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800849 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700850 return device->getActiveConfig();
851 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700852
Dan Stoza24a42e92015-03-09 10:04:11 -0700853 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700854}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700855
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700856void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
857 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
858 this);
859 int32_t type = hw->getDisplayType();
860 int currentMode = hw->getActiveConfig();
861
862 if (mode == currentMode) {
863 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
864 return;
865 }
866
867 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
868 ALOGW("Trying to set config for virtual display");
869 return;
870 }
871
872 hw->setActiveConfig(mode);
873 getHwComposer().setActiveConfig(type, mode);
874}
875
876status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
877 class MessageSetActiveConfig: public MessageBase {
878 SurfaceFlinger& mFlinger;
879 sp<IBinder> mDisplay;
880 int mMode;
881 public:
882 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
883 int mode) :
884 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
885 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700886 Vector<DisplayInfo> configs;
887 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700888 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700889 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700890 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700891 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700892 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700893 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800894 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700896 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700897 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
898 ALOGW("Attempt to set active config = %d for virtual display",
899 mMode);
900 } else {
901 mFlinger.setActiveConfigInternal(hw, mMode);
902 }
903 return true;
904 }
905 };
906 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
907 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700908 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700909}
Michael Wright28f24d02016-07-12 13:30:53 -0700910status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
911 Vector<android_color_mode_t>* outColorModes) {
912 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
913 return BAD_VALUE;
914 }
915
916 if (!display.get()) {
917 return NAME_NOT_FOUND;
918 }
919
920 int32_t type = NAME_NOT_FOUND;
921 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
922 if (display == mBuiltinDisplays[i]) {
923 type = i;
924 break;
925 }
926 }
927
928 if (type < 0) {
929 return type;
930 }
931
Steven Thomas6d8110b2017-08-31 18:24:21 -0700932 std::vector<android_color_mode_t> modes;
933 {
934 ConditionalLock _l(mStateLock,
935 std::this_thread::get_id() != mMainThreadId);
936 modes = getHwComposer().getColorModes(type);
937 }
Michael Wright28f24d02016-07-12 13:30:53 -0700938 outColorModes->clear();
939 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
940
941 return NO_ERROR;
942}
943
944android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700945 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700946 if (device != nullptr) {
947 return device->getActiveColorMode();
948 }
949 return static_cast<android_color_mode_t>(BAD_VALUE);
950}
951
952void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
953 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700954 int32_t type = hw->getDisplayType();
955 android_color_mode_t currentMode = hw->getActiveColorMode();
956
957 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700958 return;
959 }
960
961 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
962 ALOGW("Trying to set config for virtual display");
963 return;
964 }
965
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600966 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
967 hw->getDisplayType());
968
Michael Wright28f24d02016-07-12 13:30:53 -0700969 hw->setActiveColorMode(mode);
970 getHwComposer().setActiveColorMode(type, mode);
971}
972
973
974status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
975 android_color_mode_t colorMode) {
976 class MessageSetActiveColorMode: public MessageBase {
977 SurfaceFlinger& mFlinger;
978 sp<IBinder> mDisplay;
979 android_color_mode_t mMode;
980 public:
981 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
982 android_color_mode_t mode) :
983 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
984 virtual bool handler() {
985 Vector<android_color_mode_t> modes;
986 mFlinger.getDisplayColorModes(mDisplay, &modes);
987 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
988 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600989 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
990 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700991 return true;
992 }
993 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
994 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600995 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
996 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700997 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600998 ALOGW("Attempt to set active color mode %s %d for virtual display",
999 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001000 } else {
1001 mFlinger.setActiveColorModeInternal(hw, mMode);
1002 }
1003 return true;
1004 }
1005 };
1006 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1007 postMessageSync(msg);
1008 return NO_ERROR;
1009}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001010
Svetoslavd85084b2014-03-20 10:28:31 -07001011status_t SurfaceFlinger::clearAnimationFrameStats() {
1012 Mutex::Autolock _l(mStateLock);
1013 mAnimFrameTracker.clearStats();
1014 return NO_ERROR;
1015}
1016
1017status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1018 Mutex::Autolock _l(mStateLock);
1019 mAnimFrameTracker.getStats(outStats);
1020 return NO_ERROR;
1021}
1022
Dan Stozac4f471e2016-03-24 09:31:08 -07001023status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1024 HdrCapabilities* outCapabilities) const {
1025 Mutex::Autolock _l(mStateLock);
1026
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001027 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001028 if (displayDevice == nullptr) {
1029 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1030 return BAD_VALUE;
1031 }
1032
1033 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001034 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001035 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001036 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1037 // insert HDR10 as we will force client composition for HDR10
1038 // layers
1039 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1040 types.push_back(HAL_HDR_HDR10);
1041
1042 *outCapabilities = HdrCapabilities(types,
1043 capabilities->getDesiredMaxLuminance(),
1044 capabilities->getDesiredMaxAverageLuminance(),
1045 capabilities->getDesiredMinLuminance());
1046 } else {
1047 *outCapabilities = std::move(*capabilities);
1048 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001049 } else {
1050 return BAD_VALUE;
1051 }
1052
1053 return NO_ERROR;
1054}
1055
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001056status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001057 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1058 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001059
Chia-I Wu90f669f2017-10-05 14:24:41 -07001060 if (mInjectVSyncs == enable) {
1061 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001062 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001063
1064 if (enable) {
1065 ALOGV("VSync Injections enabled");
1066 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001067 mVSyncInjector = std::make_unique<InjectVSyncSource>();
1068 mInjectorEventThread = std::make_unique<EventThread>(
1069 mVSyncInjector.get(), *this, false, "injEvThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001071 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001072 } else {
1073 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001074 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001075 }
1076
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001077 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078 });
1079 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001080 return NO_ERROR;
1081}
1082
1083status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 Mutex::Autolock _l(mStateLock);
1085
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001086 if (!mInjectVSyncs) {
1087 ALOGE("VSync Injections not enabled");
1088 return BAD_VALUE;
1089 }
1090 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1091 ALOGV("Injecting VSync inside SurfaceFlinger");
1092 mVSyncInjector->onInjectSyncEvent(when);
1093 }
1094 return NO_ERROR;
1095}
1096
Lloyd Pique755e3192018-01-31 16:46:15 -08001097status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1098 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001099 IPCThreadState* ipc = IPCThreadState::self();
1100 const int pid = ipc->getCallingPid();
1101 const int uid = ipc->getCallingUid();
1102 if ((uid != AID_SHELL) &&
1103 !PermissionCache::checkPermission(sDump, pid, uid)) {
1104 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1105 return PERMISSION_DENIED;
1106 }
1107
1108 // Try to acquire a lock for 1s, fail gracefully
1109 const status_t err = mStateLock.timedLock(s2ns(1));
1110 const bool locked = (err == NO_ERROR);
1111 if (!locked) {
1112 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1113 return TIMED_OUT;
1114 }
1115
1116 outLayers->clear();
1117 mCurrentState.traverseInZOrder([&](Layer* layer) {
1118 outLayers->push_back(layer->getLayerDebugInfo());
1119 });
1120
1121 mStateLock.unlock();
1122 return NO_ERROR;
1123}
1124
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001125// ----------------------------------------------------------------------------
1126
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001127sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1128 ISurfaceComposer::VsyncSource vsyncSource) {
1129 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1130 return mSFEventThread->createEventConnection();
1131 } else {
1132 return mEventThread->createEventConnection();
1133 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001134}
1135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001137
1138void SurfaceFlinger::waitForEvent() {
1139 mEventQueue.waitMessage();
1140}
1141
1142void SurfaceFlinger::signalTransaction() {
1143 mEventQueue.invalidate();
1144}
1145
1146void SurfaceFlinger::signalLayerUpdate() {
1147 mEventQueue.invalidate();
1148}
1149
1150void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001151 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152 mEventQueue.refresh();
1153}
1154
1155status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001156 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001157 return mEventQueue.postMessage(msg, reltime);
1158}
1159
1160status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001161 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162 status_t res = mEventQueue.postMessage(msg, reltime);
1163 if (res == NO_ERROR) {
1164 msg->wait();
1165 }
1166 return res;
1167}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001168
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001169void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001170 do {
1171 waitForEvent();
1172 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001173}
1174
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175void SurfaceFlinger::enableHardwareVsync() {
1176 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001177 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001179 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1180 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001182 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183}
1184
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 Mutex::Autolock _l(mHWVsyncLock);
1187
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188 if (makeAvailable) {
1189 mHWVsyncAvailable = true;
1190 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001191 // Hardware vsync is not currently available, so abort the resync
1192 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193 return;
1194 }
1195
David Sodman105b7dc2017-11-04 20:28:14 -07001196 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001197 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198
1199 mPrimaryDispSync.reset();
1200 mPrimaryDispSync.setPeriod(period);
1201
1202 if (!mPrimaryHWVsyncEnabled) {
1203 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001204 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1205 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206 mPrimaryHWVsyncEnabled = true;
1207 }
1208}
1209
Jesse Hall948fe0c2013-10-14 12:56:09 -07001210void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 Mutex::Autolock _l(mHWVsyncLock);
1212 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001213 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1214 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215 mPrimaryDispSync.endResync();
1216 mPrimaryHWVsyncEnabled = false;
1217 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001218 if (makeUnavailable) {
1219 mHWVsyncAvailable = false;
1220 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221}
1222
Tim Murray4a4e4a22016-04-19 16:29:23 +00001223void SurfaceFlinger::resyncWithRateLimit() {
1224 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001225
1226 // No explicit locking is needed here since EventThread holds a lock while calling this method
1227 static nsecs_t sLastResyncAttempted = 0;
1228 const nsecs_t now = systemTime();
1229 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001230 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001231 }
Dan Stoza57164302017-05-08 14:03:54 -07001232 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001233}
1234
Steven Thomasb02664d2017-07-26 18:48:28 -07001235void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1236 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001237 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001238 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001239 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001240 return;
1241 }
1242
1243 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001244 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001245 return;
1246 }
1247
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 { // Scope for the lock
1251 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001252 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001255 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001256
1257 if (needsHwVsync) {
1258 enableHardwareVsync();
1259 } else {
1260 disableHardwareVsync(false);
1261 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001262}
1263
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001264void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001265 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1266 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001267}
1268
Lloyd Pique715a2c12017-12-14 17:18:08 -08001269void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1270 HWC2::Connection connection) {
1271 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1272 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001273
Lloyd Piqueba04e622017-12-14 17:11:26 -08001274 // Ignore events that do not have the right sequenceId.
1275 if (sequenceId != getBE().mComposerSequenceId) {
1276 return;
1277 }
1278
Steven Thomasb02664d2017-07-26 18:48:28 -07001279 // Only lock if we're not on the main thread. This function is normally
1280 // called on a hwbinder thread, but for the primary display it's called on
1281 // the main thread with the state lock already held, so don't attempt to
1282 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001283 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001284
Lloyd Pique715a2c12017-12-14 17:18:08 -08001285 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001286
Lloyd Piqueba04e622017-12-14 17:11:26 -08001287 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001288}
1289
Steven Thomasb02664d2017-07-26 18:48:28 -07001290void SurfaceFlinger::onRefreshReceived(int sequenceId,
1291 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001293 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001296 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001297}
1298
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001301 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 getHwComposer().setVsyncEnabled(disp,
1303 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001307void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 // Clear the drawing state so that the logic inside of
1310 // handleTransactionLocked will fire. It will determine the delta between
1311 // mCurrentState and mDrawingState and re-apply all changes when we make the
1312 // transition.
1313 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001314 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315 mDisplays.clear();
1316}
1317
Steven Thomas050b2c82017-03-06 11:45:16 -08001318void SurfaceFlinger::updateVrFlinger() {
1319 if (!mVrFlinger)
1320 return;
1321 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001322 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001323 return;
1324 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325
David Sodman105b7dc2017-11-04 20:28:14 -07001326 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 ALOGE("Vr flinger is only supported for remote hardware composer"
1328 " service connections. Ignoring request to transition to vr"
1329 " flinger.");
1330 mVrFlingerRequestsDisplay = false;
1331 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001332 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001335
Steven Thomasb02664d2017-07-26 18:48:28 -07001336 int currentDisplayPowerMode = getDisplayDeviceLocked(
1337 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001338
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001344 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001345 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001346 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347
David Sodman105b7dc2017-11-04 20:28:14 -07001348 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1349 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001350
1351 if (vrFlingerRequestsDisplay) {
1352 mVrFlinger->GrantDisplayOwnership();
1353 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356
1357 mVisibleRegionsDirty = true;
1358 invalidateHwcGeometry();
1359
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001360 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1362 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1363 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001364
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001366 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 const nsecs_t period = activeConfig->getVsyncPeriod();
1368 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001369
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 // Use phase of 0 since phase is not known.
1371 // Use latency of 0, which will snap to the ideal latency.
1372 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374 android_atomic_or(1, &mRepaintEverything);
1375 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001376}
1377
Mathias Agopian4fec8732012-06-29 14:12:52 -07001378void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001379 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001380 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001381 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001382 bool frameMissed = !mHadClientComposition &&
1383 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001384 (mPreviousPresentFence->getSignalTime() ==
1385 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001386 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001387 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001388 signalLayerUpdate();
1389 break;
1390 }
1391
Steven Thomas050b2c82017-03-06 11:45:16 -08001392 // Now that we're going to make it to the handleMessageTransaction()
1393 // call below it's safe to call updateVrFlinger(), which will
1394 // potentially trigger a display handoff.
1395 updateVrFlinger();
1396
Dan Stoza6b9454d2014-11-07 16:00:59 -08001397 bool refreshNeeded = handleMessageTransaction();
1398 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001399 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001400 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001401 // Signal a refresh if a transaction modified the window state,
1402 // a new buffer was latched, or if HWC has requested a full
1403 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001404 signalRefresh();
1405 }
1406 break;
1407 }
1408 case MessageQueue::REFRESH: {
1409 handleMessageRefresh();
1410 break;
1411 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001412 }
1413}
1414
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001416 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001417 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001418 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001420 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001422}
1423
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001425 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001427}
1428
1429void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001430 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001431
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001432 mRefreshPending = false;
1433
Pablo Ceballos40845df2016-01-25 17:41:15 -08001434 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001435
Brian Andersond6927fb2016-07-23 23:37:30 -07001436 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001437 rebuildLayerStacks();
1438 setUpHWComposer();
1439 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001440 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001441 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001442 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001443
David Sodman105b7dc2017-11-04 20:28:14 -07001444 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001445
1446 mHadClientComposition = false;
1447 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1448 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1449 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001450 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001451 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001452
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001454}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456void SurfaceFlinger::doDebugFlashRegions()
1457{
1458 // is debugging enabled
1459 if (CC_LIKELY(!mDebugRegion))
1460 return;
1461
1462 const bool repaintEverything = mRepaintEverything;
1463 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1464 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001465 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466 // transform the dirty region into this screen's coordinate space
1467 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1468 if (!dirtyRegion.isEmpty()) {
1469 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001470 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471
1472 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001474 RenderEngine& engine(getRenderEngine());
1475 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1476
Mathias Agopianda27af92012-09-13 18:17:13 -07001477 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001478 }
1479 }
1480 }
1481
1482 postFramebuffer();
1483
1484 if (mDebugRegion > 1) {
1485 usleep(mDebugRegion * 1000);
1486 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001487
Dan Stoza9e56aa02015-11-02 13:00:03 -08001488 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001489 auto& displayDevice = mDisplays[displayId];
1490 if (!displayDevice->isDisplayOn()) {
1491 continue;
1492 }
1493
David Sodman105b7dc2017-11-04 20:28:14 -07001494 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1495 ALOGE_IF(result != NO_ERROR,
1496 "prepareFrame for display %zd failed:"
1497 " %d (%s)",
1498 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001499 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500}
1501
Adrian Roos1e1a1282017-11-01 19:05:31 +01001502void SurfaceFlinger::doTracing(const char* where) {
1503 ATRACE_CALL();
1504 ATRACE_NAME(where);
1505 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001506 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001507 }
1508}
1509
Brian Andersond6927fb2016-07-23 23:37:30 -07001510void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001512 ATRACE_CALL();
1513 ALOGV("preComposition");
1514
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001516 mDrawingState.traverseInZOrder([&](Layer* layer) {
1517 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518 needExtraInvalidate = true;
1519 }
Robert Carr2047fae2016-11-28 14:09:09 -08001520 });
1521
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522 if (needExtraInvalidate) {
1523 signalLayerUpdate();
1524 }
1525}
1526
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527void SurfaceFlinger::updateCompositorTiming(
1528 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1529 std::shared_ptr<FenceTime>& presentFenceTime) {
1530 // Update queue of past composite+present times and determine the
1531 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001532 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001534 while (!getBE().mCompositePresentTimes.empty()) {
1535 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536 // Cached values should have been updated before calling this method,
1537 // which helps avoid duplicate syscalls.
1538 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1539 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1540 break;
1541 }
1542 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001543 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001544 }
1545
1546 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001547 while (getBE().mCompositePresentTimes.size() > 16) {
1548 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001549 }
1550
Brian Andersond0010582017-03-07 13:20:31 -08001551 setCompositorTimingSnapped(
1552 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1553}
1554
1555void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1556 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557 // Integer division and modulo round toward 0 not -inf, so we need to
1558 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001559 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001560 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1561 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1562
Brian Andersond0010582017-03-07 13:20:31 -08001563 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1564 if (idealLatency <= 0) {
1565 idealLatency = vsyncInterval;
1566 }
1567
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568 // Snap the latency to a value that removes scheduling jitter from the
1569 // composition and present times, which often have >1ms of jitter.
1570 // Reducing jitter is important if an app attempts to extrapolate
1571 // something (such as user input) to an accurate diasplay time.
1572 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1573 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001574 nsecs_t bias = vsyncInterval / 2;
1575 int64_t extraVsyncs =
1576 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1577 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1578 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001579
David Sodman99974d22017-11-28 12:04:33 -08001580 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1581 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1582 getBE().mCompositorTiming.interval = vsyncInterval;
1583 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001584}
1585
1586void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001588 ATRACE_CALL();
1589 ALOGV("postComposition");
1590
Brian Anderson3546a3f2016-07-14 11:51:14 -07001591 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001592 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001593 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001594 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001595 }
1596
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001597 // |mStateLock| not needed as we are on the main thread
1598 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001599
David Sodman73beded2017-11-15 11:56:06 -08001600 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001601 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001602 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603 glCompositionDoneFenceTime =
1604 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001605 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001606 } else {
1607 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1608 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001609
David Sodman73beded2017-11-15 11:56:06 -08001610 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001611 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001612 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001613 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001614
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1616 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1617
1618 // We use the refreshStartTime which might be sampled a little later than
1619 // when we started doing work for this frame, but that should be okay
1620 // since updateCompositorTiming has snapping logic.
1621 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001622 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001623 CompositorTiming compositorTiming;
1624 {
David Sodman99974d22017-11-28 12:04:33 -08001625 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1626 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001627 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001628
Robert Carr2047fae2016-11-28 14:09:09 -08001629 mDrawingState.traverseInZOrder([&](Layer* layer) {
1630 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001631 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001632 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001633 recordBufferingStats(layer->getName().string(),
1634 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001635 }
Robert Carr2047fae2016-11-28 14:09:09 -08001636 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001637
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001638 if (presentFenceTime->isValid()) {
1639 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001640 enableHardwareVsync();
1641 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001642 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001643 }
1644 }
1645
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001646 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001647 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001648 enableHardwareVsync();
1649 }
1650 }
1651
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001652 if (mAnimCompositionPending) {
1653 mAnimCompositionPending = false;
1654
Brian Anderson4e606e32017-03-16 15:34:57 -07001655 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001656 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001657 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001658 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001659 // The HWC doesn't support present fences, so use the refresh
1660 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001661 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001662 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001663 mAnimFrameTracker.setActualPresentTime(presentTime);
1664 }
1665 mAnimFrameTracker.advanceFrame();
1666 }
Dan Stozab90cf072015-03-05 11:05:59 -08001667
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001668 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1669 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001670 return;
1671 }
1672
1673 nsecs_t currentTime = systemTime();
1674 if (mHasPoweredOff) {
1675 mHasPoweredOff = false;
1676 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001677 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001679 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1680 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001681 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001682 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001683 }
David Sodman4a36e932017-11-07 14:29:47 -08001684 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001685 }
David Sodman4a36e932017-11-07 14:29:47 -08001686 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687}
1688
1689void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690 ATRACE_CALL();
1691 ALOGV("rebuildLayerStacks");
1692
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001694 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001695 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001696 mVisibleRegionsDirty = false;
1697 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001698
Jeff Sharkey76488112017-02-27 14:15:18 -07001699 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1700 Region opaqueRegion;
1701 Region dirtyRegion;
1702 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001703 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001704 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1705 const Transform& tr(displayDevice->getTransform());
1706 const Rect bounds(displayDevice->getBounds());
1707 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001708 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001709
Jeff Sharkey76488112017-02-27 14:15:18 -07001710 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001711 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001712 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1713 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001714 Region drawRegion(tr.transform(
1715 layer->visibleNonTransparentRegion));
1716 drawRegion.andSelf(bounds);
1717 if (!drawRegion.isEmpty()) {
1718 layersSortedByZ.add(layer);
1719 } else {
1720 // Clear out the HWC layer if this layer was
1721 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001722 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001723 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001724 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001725 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001726 // WM changes displayDevice->layerStack upon sleep/awake.
1727 // Here we make sure we delete the HWC layers even if
1728 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001729 hwcLayerDestroyed = layer->destroyHwcLayer(
1730 displayDevice->getHwcDisplayId());
1731 }
1732
1733 // If a layer is not going to get a release fence because
1734 // it is invisible, but it is also going to release its
1735 // old buffer, add it to the list of layers needing
1736 // fences.
1737 if (hwcLayerDestroyed) {
1738 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1739 mLayersWithQueuedFrames.cend(), layer);
1740 if (found != mLayersWithQueuedFrames.cend()) {
1741 layersNeedingFences.add(layer);
1742 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001743 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001744 });
1745 }
1746 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001747 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 displayDevice->undefinedRegion.set(bounds);
1749 displayDevice->undefinedRegion.subtractSelf(
1750 tr.transform(opaqueRegion));
1751 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001752 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001753 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001755
Romain Guy0147a172017-06-01 13:53:56 -07001756mat4 SurfaceFlinger::computeSaturationMatrix() const {
1757 if (mSaturation == 1.0f) {
1758 return mat4();
1759 }
1760
1761 // Rec.709 luma coefficients
1762 float3 luminance{0.213f, 0.715f, 0.072f};
1763 luminance *= 1.0f - mSaturation;
1764 return mat4(
1765 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1766 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1767 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1768 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1769 );
1770}
1771
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001772// pickColorMode translates a given dataspace into the best available color mode.
1773// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001774android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001775 if (mForceNativeColorMode) {
1776 return HAL_COLOR_MODE_NATIVE;
1777 }
1778
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001779 switch (dataSpace) {
1780 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1781 // system expects.
1782 case HAL_DATASPACE_UNKNOWN:
1783 case HAL_DATASPACE_SRGB:
1784 case HAL_DATASPACE_V0_SRGB:
1785 return HAL_COLOR_MODE_SRGB;
1786 break;
1787
1788 case HAL_DATASPACE_DISPLAY_P3:
1789 return HAL_COLOR_MODE_DISPLAY_P3;
1790 break;
1791
1792 default:
1793 // TODO (courtneygo): Do we want to assert an error here?
1794 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1795 dataSpace);
1796 return HAL_COLOR_MODE_SRGB;
1797 break;
1798 }
1799}
1800
Romain Guy0147a172017-06-01 13:53:56 -07001801android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001802 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001803 // Only support sRGB and Display-P3 right now.
1804 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1805 return HAL_DATASPACE_DISPLAY_P3;
1806 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001807 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1808 return HAL_DATASPACE_DISPLAY_P3;
1809 }
1810 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1811 return HAL_DATASPACE_DISPLAY_P3;
1812 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001813 if (!hasHdr) {
1814 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1815 return HAL_DATASPACE_DISPLAY_P3;
1816 }
1817 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1818 return HAL_DATASPACE_DISPLAY_P3;
1819 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001820 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001821
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001822 return HAL_DATASPACE_V0_SRGB;
1823}
1824
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 ATRACE_CALL();
1827 ALOGV("setUpHWComposer");
1828
Jesse Hall028dc8f2013-08-20 16:35:32 -07001829 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001830 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1831 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1832 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1833
1834 // If nothing has changed (!dirty), don't recompose.
1835 // If something changed, but we don't currently have any visible layers,
1836 // and didn't when we last did a composition, then skip it this time.
1837 // The second rule does two things:
1838 // - When all layers are removed from a display, we'll emit one black
1839 // frame, then nothing more until we get new layers.
1840 // - When a display is created with a private layer stack, we won't
1841 // emit any black frames until a layer is added to the layer stack.
1842 bool mustRecompose = dirty && !(empty && wasEmpty);
1843
1844 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1845 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1846 mustRecompose ? "doing" : "skipping",
1847 dirty ? "+" : "-",
1848 empty ? "+" : "-",
1849 wasEmpty ? "+" : "-");
1850
Dan Stoza71433162014-02-04 16:22:36 -08001851 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001852
1853 if (mustRecompose) {
1854 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1855 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001856 }
1857
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 // build the h/w work list
1859 if (CC_UNLIKELY(mGeometryInvalid)) {
1860 mGeometryInvalid = false;
1861 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1862 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1863 const auto hwcId = displayDevice->getHwcDisplayId();
1864 if (hwcId >= 0) {
1865 const Vector<sp<Layer>>& currentLayers(
1866 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001867 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001868 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001869 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001870 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001873 }
1874 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001875
Robert Carrae060832016-11-28 10:51:00 -08001876 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001877 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001878 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001879 }
1880 }
1881 }
1882 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 }
Riley Andrews03414a12014-07-01 14:22:59 -07001884
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001885
Romain Guy0147a172017-06-01 13:53:56 -07001886 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001887
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 // Set the per-frame data
1889 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1890 auto& displayDevice = mDisplays[displayId];
1891 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001892
Dan Stoza9e56aa02015-11-02 13:00:03 -08001893 if (hwcId < 0) {
1894 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001895 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001896 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001897 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001898 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1899 "display %zd: %d", displayId, result);
1900 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001902 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1903 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001904 !displayDevice->getHdrSupport()) {
1905 layer->forceClientComposition(hwcId);
1906 }
1907
chaviwc9232ed2017-11-14 15:31:15 -08001908 if (layer->getForceClientComposition(hwcId)) {
1909 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1910 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1911 continue;
1912 }
1913
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 layer->setPerFrameData(displayDevice);
1915 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001916
1917 if (hasWideColorDisplay) {
1918 android_color_mode newColorMode;
1919 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1920
1921 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001922 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1923 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001924 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1925 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1926 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1927 }
1928 newColorMode = pickColorMode(newDataSpace);
1929
Thierry Strudel2924d012017-08-14 15:19:37 -07001930 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 }
1933
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001934 mPreviousColorMatrix = colorMatrix;
1935
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001937 auto& displayDevice = mDisplays[displayId];
1938 if (!displayDevice->isDisplayOn()) {
1939 continue;
1940 }
1941
David Sodman105b7dc2017-11-04 20:28:14 -07001942 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1944 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001945 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001946}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001947
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948void SurfaceFlinger::doComposition() {
1949 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950 ALOGV("doComposition");
1951
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001952 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001953 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001954 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001955 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001956 // transform the dirty region into this screen's coordinate space
1957 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001958
1959 // repaint the framebuffer (if needed)
1960 doDisplayComposition(hw, dirtyRegion);
1961
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001963 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001964 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001965 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001966 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001967}
1968
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001969void SurfaceFlinger::postFramebuffer()
1970{
Mathias Agopian841cde52012-03-01 15:44:37 -08001971 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001973
Mathias Agopiana44b0412011-10-16 18:46:35 -07001974 const nsecs_t now = systemTime();
1975 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001976
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1978 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001979 if (!displayDevice->isDisplayOn()) {
1980 continue;
1981 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 const auto hwcId = displayDevice->getHwcDisplayId();
1983 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001984 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001985 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001986 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001987 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001989 // The layer buffer from the previous frame (if any) is released
1990 // by HWC only when the release fence from this frame (if any) is
1991 // signaled. Always get the release fence from HWC first.
1992 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001993 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08001994
1995 // If the layer was client composited in the previous frame, we
1996 // need to merge with the previous client target acquire fence.
1997 // Since we do not track that, always merge with the current
1998 // client target acquire fence when it is available, even though
1999 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002001 releaseFence = Fence::merge("LayerRelease", releaseFence,
2002 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002003 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002004
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 layer->onLayerDisplayed(releaseFence);
2006 }
Chia-I Wu83806892017-11-16 10:50:20 -08002007
2008 // We've got a list of layers needing fences, that are disjoint with
2009 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2010 // supply them with the present fence.
2011 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002012 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002013 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2014 layer->onLayerDisplayed(presentFence);
2015 }
2016 }
2017
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002019 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002020 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002021 }
2022
Mathias Agopiana44b0412011-10-16 18:46:35 -07002023 mLastSwapBufferTime = systemTime() - now;
2024 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002025
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002026 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002027 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2028 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2029 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2030 logFrameStats();
2031 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033}
2034
Mathias Agopian87baae12012-07-31 12:38:26 -07002035void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036{
Mathias Agopian841cde52012-03-01 15:44:37 -08002037 ATRACE_CALL();
2038
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002039 // here we keep a copy of the drawing state (that is the state that's
2040 // going to be overwritten by handleTransactionLocked()) outside of
2041 // mStateLock so that the side-effects of the State assignment
2042 // don't happen with mStateLock held (which can cause deadlocks).
2043 State drawingState(mDrawingState);
2044
Mathias Agopianca4d3602011-05-19 15:38:14 -07002045 Mutex::Autolock _l(mStateLock);
2046 const nsecs_t now = systemTime();
2047 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002048
Mathias Agopianca4d3602011-05-19 15:38:14 -07002049 // Here we're guaranteed that some transaction flags are set
2050 // so we can call handleTransactionLocked() unconditionally.
2051 // We call getTransactionFlags(), which will also clear the flags,
2052 // with mStateLock held to guarantee that mCurrentState won't change
2053 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002054
Mathias Agopiane57f2922012-08-09 16:29:12 -07002055 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002056 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002057
Mathias Agopianca4d3602011-05-19 15:38:14 -07002058 mLastTransactionTime = systemTime() - now;
2059 mDebugInTransaction = 0;
2060 invalidateHwcGeometry();
2061 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002062}
2063
Lloyd Pique715a2c12017-12-14 17:18:08 -08002064DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2065 HWC2::Connection connection) const {
2066 // Figure out whether the event is for the primary display or an
2067 // external display by matching the Hwc display id against one for a
2068 // connected display. If we did not find a match, we then check what
2069 // displays are not already connected to determine the type. If we don't
2070 // have a connected primary display, we assume the new display is meant to
2071 // be the primary display, and then if we don't have an external display,
2072 // we assume it is that.
2073 const auto primaryDisplayId =
2074 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2075 const auto externalDisplayId =
2076 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2077 if (primaryDisplayId && primaryDisplayId == display) {
2078 return DisplayDevice::DISPLAY_PRIMARY;
2079 } else if (externalDisplayId && externalDisplayId == display) {
2080 return DisplayDevice::DISPLAY_EXTERNAL;
2081 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2082 return DisplayDevice::DISPLAY_PRIMARY;
2083 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2084 return DisplayDevice::DISPLAY_EXTERNAL;
2085 }
2086
2087 return DisplayDevice::DISPLAY_ID_INVALID;
2088}
2089
Lloyd Piqueba04e622017-12-14 17:11:26 -08002090void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2091 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002092 auto displayType = determineDisplayType(event.display, event.connection);
2093 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2094 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2095 continue;
2096 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002097
2098 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2099 ALOGE("External displays are not supported by the vr hardware composer.");
2100 continue;
2101 }
2102
Lloyd Pique715a2c12017-12-14 17:18:08 -08002103 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002104
2105 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002106 ALOGV("Creating built in display %d", displayType);
2107 ALOGW_IF(mBuiltinDisplays[displayType],
2108 "Overwriting display token for display type %d", displayType);
2109 mBuiltinDisplays[displayType] = new BBinder();
2110 // All non-virtual displays are currently considered secure.
2111 DisplayDeviceState info(displayType, true);
2112 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2113 "Built-in Screen" : "External Screen";
2114 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2115 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002116 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002117 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002118
Lloyd Piquefcd86612017-12-14 17:15:36 -08002119 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2120 if (idx >= 0) {
2121 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2122 mInterceptor.saveDisplayDeletion(info.displayId);
2123 mCurrentState.displays.removeItemsAt(idx);
2124 }
2125 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002126 }
2127
2128 processDisplayChangesLocked();
2129 }
2130
2131 mPendingHotplugEvents.clear();
2132}
2133
Lloyd Pique347200f2017-12-14 17:00:15 -08002134void SurfaceFlinger::processDisplayChangesLocked() {
2135 // here we take advantage of Vector's copy-on-write semantics to
2136 // improve performance by skipping the transaction entirely when
2137 // know that the lists are identical
2138 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2139 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2140 if (!curr.isIdenticalTo(draw)) {
2141 mVisibleRegionsDirty = true;
2142 const size_t cc = curr.size();
2143 size_t dc = draw.size();
2144
2145 // find the displays that were removed
2146 // (ie: in drawing state but not in current state)
2147 // also handle displays that changed
2148 // (ie: displays that are in both lists)
2149 for (size_t i = 0; i < dc;) {
2150 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2151 if (j < 0) {
2152 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002153 // Call makeCurrent() on the primary display so we can
2154 // be sure that nothing associated with this display
2155 // is current.
2156 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2157 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2158 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2159 if (hw != nullptr) hw->disconnect(getHwComposer());
2160 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2161 mEventThread->onHotplugReceived(draw[i].type, false);
2162 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002163 } else {
2164 // this display is in both lists. see if something changed.
2165 const DisplayDeviceState& state(curr[j]);
2166 const wp<IBinder>& display(curr.keyAt(j));
2167 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2168 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2169 if (state_binder != draw_binder) {
2170 // changing the surface is like destroying and
2171 // recreating the DisplayDevice, so we just remove it
2172 // from the drawing state, so that it get re-added
2173 // below.
2174 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2175 if (hw != nullptr) hw->disconnect(getHwComposer());
2176 mDisplays.removeItem(display);
2177 mDrawingState.displays.removeItemsAt(i);
2178 dc--;
2179 // at this point we must loop to the next item
2180 continue;
2181 }
2182
2183 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2184 if (disp != nullptr) {
2185 if (state.layerStack != draw[i].layerStack) {
2186 disp->setLayerStack(state.layerStack);
2187 }
2188 if ((state.orientation != draw[i].orientation) ||
2189 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2190 disp->setProjection(state.orientation, state.viewport, state.frame);
2191 }
2192 if (state.width != draw[i].width || state.height != draw[i].height) {
2193 disp->setDisplaySize(state.width, state.height);
2194 }
2195 }
2196 }
2197 ++i;
2198 }
2199
2200 // find displays that were added
2201 // (ie: in current state but not in drawing state)
2202 for (size_t i = 0; i < cc; i++) {
2203 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2204 const DisplayDeviceState& state(curr[i]);
2205
2206 sp<DisplaySurface> dispSurface;
2207 sp<IGraphicBufferProducer> producer;
2208 sp<IGraphicBufferProducer> bqProducer;
2209 sp<IGraphicBufferConsumer> bqConsumer;
2210 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2211
2212 int32_t hwcId = -1;
2213 if (state.isVirtualDisplay()) {
2214 // Virtual displays without a surface are dormant:
2215 // they have external state (layer stack, projection,
2216 // etc.) but no internal state (i.e. a DisplayDevice).
2217 if (state.surface != nullptr) {
2218 // Allow VR composer to use virtual displays.
2219 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2220 int width = 0;
2221 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2222 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2223 int height = 0;
2224 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2225 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2226 int intFormat = 0;
2227 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2228 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2229 auto format = static_cast<android_pixel_format_t>(intFormat);
2230
2231 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2232 }
2233
2234 // TODO: Plumb requested format back up to consumer
2235
2236 sp<VirtualDisplaySurface> vds =
2237 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2238 bqProducer, bqConsumer,
2239 state.displayName);
2240
2241 dispSurface = vds;
2242 producer = vds;
2243 }
2244 } else {
2245 ALOGE_IF(state.surface != nullptr,
2246 "adding a supported display, but rendering "
2247 "surface is provided (%p), ignoring it",
2248 state.surface.get());
2249
2250 hwcId = state.type;
2251 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2252 producer = bqProducer;
2253 }
2254
2255 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002256
Lloyd Pique347200f2017-12-14 17:00:15 -08002257 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002258 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002259 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002260 bool hasWideColorModes = false;
2261 std::vector<android_color_mode_t> modes =
2262 getHwComposer().getColorModes(state.type);
2263 for (android_color_mode_t colorMode : modes) {
2264 switch (colorMode) {
2265 case HAL_COLOR_MODE_DISPLAY_P3:
2266 case HAL_COLOR_MODE_ADOBE_RGB:
2267 case HAL_COLOR_MODE_DCI_P3:
2268 hasWideColorModes = true;
2269 break;
2270 default:
2271 break;
2272 }
2273 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002274 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002275 }
2276
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002277 bool hasHdrSupport = false;
2278 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2279 getHwComposer().getHdrCapabilities(state.type);
2280 if (hdrCapabilities) {
2281 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2282 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2283 hasHdrSupport = iter != types.cend();
2284 }
2285
Lloyd Pique347200f2017-12-14 17:00:15 -08002286 sp<DisplayDevice> hw =
2287 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002288 dispSurface, producer, useWideColorMode,
2289 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002290
Lloyd Piquec5208312018-01-08 17:59:02 -08002291 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2292 if (useWideColorMode) {
2293 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002294 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002295 setActiveColorModeInternal(hw, defaultColorMode);
2296 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002297 hw->setLayerStack(state.layerStack);
2298 hw->setProjection(state.orientation, state.viewport, state.frame);
2299 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002300
Lloyd Pique347200f2017-12-14 17:00:15 -08002301 mDisplays.add(display, hw);
2302 if (!state.isVirtualDisplay()) {
2303 mEventThread->onHotplugReceived(state.type, true);
2304 }
2305 }
2306 }
2307 }
2308 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309
2310 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002311}
2312
Mathias Agopian87baae12012-07-31 12:38:26 -07002313void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002314{
Dan Stoza7dde5992015-05-22 09:51:44 -07002315 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002316 mCurrentState.traverseInZOrder([](Layer* layer) {
2317 layer->notifyAvailableFrames();
2318 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320 /*
2321 * Traversal of the children
2322 * (perform the transaction for each of them if needed)
2323 */
2324
Mathias Agopian3559b072012-08-15 13:46:03 -07002325 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002326 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002328 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002329
2330 const uint32_t flags = layer->doTransaction(0);
2331 if (flags & Layer::eVisibleRegion)
2332 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002333 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002334 }
2335
2336 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002337 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 */
2339
Mathias Agopiane57f2922012-08-09 16:29:12 -07002340 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002341 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002342 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344
Mathias Agopian84300952012-11-21 16:02:13 -08002345 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2346 // The transform hint might have changed for some layers
2347 // (either because a display has changed, or because a layer
2348 // as changed).
2349 //
2350 // Walk through all the layers in currentLayers,
2351 // and update their transform hint.
2352 //
2353 // If a layer is visible only on a single display, then that
2354 // display is used to calculate the hint, otherwise we use the
2355 // default display.
2356 //
2357 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2358 // the hint is set before we acquire a buffer from the surface texture.
2359 //
2360 // NOTE: layer transactions have taken place already, so we use their
2361 // drawing state. However, SurfaceFlinger's own transaction has not
2362 // happened yet, so we must use the current state layer list
2363 // (soon to become the drawing state list).
2364 //
2365 sp<const DisplayDevice> disp;
2366 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002367 bool first = true;
2368 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002369 // NOTE: we rely on the fact that layers are sorted by
2370 // layerStack first (so we don't have to traverse the list
2371 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002372 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002373 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002374 currentlayerStack = layerStack;
2375 // figure out if this layerstack is mirrored
2376 // (more than one display) if so, pick the default display,
2377 // if not, pick the only display it's on.
2378 disp.clear();
2379 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2380 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002381 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002382 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002383 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002384 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002385 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002386 break;
2387 }
2388 }
2389 }
2390 }
Chet Haase91d25932013-04-11 15:24:55 -07002391
Robert Carr56a0b9a2017-12-04 16:06:13 -08002392 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002393 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002394 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2395 // redraw after transform hint changes. See bug 8508397.
2396
2397 // could be null when this layer is using a layerStack
2398 // that is not visible on any display. Also can occur at
2399 // screen off/on times.
2400 disp = getDefaultDisplayDeviceLocked();
2401 }
2402 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002403 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002404 if (disp != nullptr) {
2405 layer->updateTransformHint(disp);
2406 }
Robert Carr2047fae2016-11-28 14:09:09 -08002407
2408 first = false;
2409 });
Mathias Agopian84300952012-11-21 16:02:13 -08002410 }
2411
2412
Mathias Agopian3559b072012-08-15 13:46:03 -07002413 /*
2414 * Perform our own transaction if needed
2415 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002416
2417 if (mLayersAdded) {
2418 mLayersAdded = false;
2419 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002420 mVisibleRegionsDirty = true;
2421 }
2422
2423 // some layers might have been removed, so
2424 // we need to update the regions they're exposing.
2425 if (mLayersRemoved) {
2426 mLayersRemoved = false;
2427 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002428 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002429 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002430 // this layer is not visible anymore
2431 // TODO: we could traverse the tree from front to back and
2432 // compute the actual visible region
2433 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002434 Region visibleReg;
2435 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002436 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002437 }
Robert Carr2047fae2016-11-28 14:09:09 -08002438 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 }
2440
2441 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002442
2443 updateCursorAsync();
2444}
2445
2446void SurfaceFlinger::updateCursorAsync()
2447{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2449 auto& displayDevice = mDisplays[displayId];
2450 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002451 continue;
2452 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453
2454 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2455 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002456 }
2457 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002458}
2459
2460void SurfaceFlinger::commitTransaction()
2461{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002462 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002463 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002464 for (const auto& l : mLayersPendingRemoval) {
2465 recordBufferingStats(l->getName().string(),
2466 l->getOccupancyHistory(true));
2467 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002468 }
2469 mLayersPendingRemoval.clear();
2470 }
2471
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002472 // If this transaction is part of a window animation then the next frame
2473 // we composite should be considered an animation as well.
2474 mAnimCompositionPending = mAnimTransactionPending;
2475
Mathias Agopian4fec8732012-06-29 14:12:52 -07002476 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002477 mDrawingState.traverseInZOrder([](Layer* layer) {
2478 layer->commitChildList();
2479 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002480 mTransactionPending = false;
2481 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002482 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483}
2484
Chia-I Wuab0c3192017-08-01 11:29:00 -07002485void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487{
Mathias Agopian841cde52012-03-01 15:44:37 -08002488 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002490
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 Region aboveOpaqueLayers;
2492 Region aboveCoveredLayers;
2493 Region dirty;
2494
Mathias Agopian87baae12012-07-31 12:38:26 -07002495 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496
Robert Carr2047fae2016-11-28 14:09:09 -08002497 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002499 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500
Jesse Hall01e29052013-02-19 16:13:35 -08002501 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002502 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002503 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002504
Mathias Agopianab028732010-03-16 16:41:46 -07002505 /*
2506 * opaqueRegion: area of a surface that is fully opaque.
2507 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002509
2510 /*
2511 * visibleRegion: area of a surface that is visible on screen
2512 * and not fully transparent. This is essentially the layer's
2513 * footprint minus the opaque regions above it.
2514 * Areas covered by a translucent surface are considered visible.
2515 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002517
2518 /*
2519 * coveredRegion: area of a surface that is covered by all
2520 * visible regions above it (which includes the translucent areas).
2521 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002522 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002523
Jesse Halla8026d22012-09-25 13:25:04 -07002524 /*
2525 * transparentRegion: area of a surface that is hinted to be completely
2526 * transparent. This is only used to tell when the layer has no visible
2527 * non-transparent regions and can be removed from the layer list. It
2528 * does not affect the visibleRegion of this layer or any layers
2529 * beneath it. The hint may not be correct if apps don't respect the
2530 * SurfaceView restrictions (which, sadly, some don't).
2531 */
2532 Region transparentRegion;
2533
Mathias Agopianab028732010-03-16 16:41:46 -07002534
2535 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002536 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002537 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002541 if (!visibleRegion.isEmpty()) {
2542 // Remove the transparent area from the visible region
2543 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002544 if (tr.preserveRects()) {
2545 // transform the transparent region
2546 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002547 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002548 // transformation too complex, can't do the
2549 // transparent region optimization.
2550 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002551 }
Mathias Agopianab028732010-03-16 16:41:46 -07002552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553
Mathias Agopianab028732010-03-16 16:41:46 -07002554 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002555 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002556 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002557 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2558 // the opaque region is the layer's footprint
2559 opaqueRegion = visibleRegion;
2560 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 }
2562 }
2563
Robert Carre5f4f692018-01-12 13:12:28 -08002564 if (visibleRegion.isEmpty()) {
2565 layer->clearVisibilityRegions();
2566 return;
2567 }
2568
Mathias Agopianab028732010-03-16 16:41:46 -07002569 // Clip the covered region to the visible region
2570 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2571
2572 // Update aboveCoveredLayers for next (lower) layer
2573 aboveCoveredLayers.orSelf(visibleRegion);
2574
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 // subtract the opaque region covered by the layers above us
2576 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577
2578 // compute this layer's dirty region
2579 if (layer->contentDirty) {
2580 // we need to invalidate the whole region
2581 dirty = visibleRegion;
2582 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002583 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 layer->contentDirty = false;
2585 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002586 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002587 * the exposed region consists of two components:
2588 * 1) what's VISIBLE now and was COVERED before
2589 * 2) what's EXPOSED now less what was EXPOSED before
2590 *
2591 * note that (1) is conservative, we start with the whole
2592 * visible region but only keep what used to be covered by
2593 * something -- which mean it may have been exposed.
2594 *
2595 * (2) handles areas that were not covered by anything but got
2596 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002597 */
Mathias Agopianab028732010-03-16 16:41:46 -07002598 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002599 const Region oldVisibleRegion = layer->visibleRegion;
2600 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002601 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2602 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 }
2604 dirty.subtractSelf(aboveOpaqueLayers);
2605
2606 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002607 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608
Mathias Agopianab028732010-03-16 16:41:46 -07002609 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002611
Jesse Halla8026d22012-09-25 13:25:04 -07002612 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 layer->setVisibleRegion(visibleRegion);
2614 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002615 layer->setVisibleNonTransparentRegion(
2616 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002617 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618
Mathias Agopian87baae12012-07-31 12:38:26 -07002619 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620}
2621
Chia-I Wuab0c3192017-08-01 11:29:00 -07002622void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002623 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002624 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002625 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002626 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002627 }
2628 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002629}
2630
Dan Stoza6b9454d2014-11-07 16:00:59 -08002631bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 ALOGV("handlePageFlip");
2634
Brian Andersond6927fb2016-07-23 23:37:30 -07002635 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002638 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002639 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002640
2641 // Store the set of layers that need updates. This set must not change as
2642 // buffers are being latched, as this could result in a deadlock.
2643 // Example: Two producers share the same command stream and:
2644 // 1.) Layer 0 is latched
2645 // 2.) Layer 0 gets a new frame
2646 // 2.) Layer 1 gets a new frame
2647 // 3.) Layer 1 is latched.
2648 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2649 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002650 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002651 if (layer->hasQueuedFrame()) {
2652 frameQueued = true;
2653 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002654 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002655 } else {
2656 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002657 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002658 } else {
2659 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002660 }
Robert Carr2047fae2016-11-28 14:09:09 -08002661 });
2662
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002664 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002665 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002666 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002667 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002668 newDataLatched = true;
2669 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002670 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002671
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002672 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002673
2674 // If we will need to wake up at some time in the future to deal with a
2675 // queued frame that shouldn't be displayed during this vsync period, wake
2676 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002677 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002678 signalLayerUpdate();
2679 }
2680
2681 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002682 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683}
2684
Mathias Agopianad456f92011-01-13 17:53:01 -08002685void SurfaceFlinger::invalidateHwcGeometry()
2686{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002688}
2689
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002690
Fabien Sanglard830b8472016-11-30 16:35:58 -08002691void SurfaceFlinger::doDisplayComposition(
2692 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002693 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694{
Dan Stoza71433162014-02-04 16:22:36 -08002695 // We only need to actually compose the display if:
2696 // 1) It is being handled by hardware composer, which may need this to
2697 // keep its virtual display state machine in sync, or
2698 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002699 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002700 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002701 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002702 return;
2703 }
2704
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002706 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002707
2708 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002709 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710}
2711
Chia-I Wub02087d2017-11-09 10:19:54 -08002712bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002713{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002715
Chia-I Wub02087d2017-11-09 10:19:54 -08002716 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002717 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002719
2720 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002721 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2722 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002723 if (applyColorMatrix) {
2724 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2725 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2726 }
2727
David Sodman105b7dc2017-11-04 20:28:14 -07002728 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 if (hasClientComposition) {
2730 ALOGV("hasClientComposition");
2731
David Sodmanbc815282017-11-05 18:57:52 -08002732 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002733 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002734 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002735 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002736 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002737 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002738 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002739 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002740
2741 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002742 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002743 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2744 }
2745 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002746 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002747
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002748 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002749 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002751 // when using overlays, we assume a fully transparent framebuffer
2752 // NOTE: we could reduce how much we need to clear, for instance
2753 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002754 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002755 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002756 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002757 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002758 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002759 // we're left with the letterbox region
2760 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002761 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002762
2763 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002765
Mathias Agopianb9494d52012-04-18 02:28:45 -07002766 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002767 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002768 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002770 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002771 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002772
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002774 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002775 // scissor on the main display. It should never be needed
2776 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 const Rect& bounds(displayDevice->getBounds());
2778 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002779 if (scissor != bounds) {
2780 // scissor doesn't match the screen's dimensions, so we
2781 // need to clear everything outside of it and enable
2782 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002783
Mathias Agopianf45c5102012-10-24 16:29:17 -07002784 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002786 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002787 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002788 }
2789 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002790 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002791
Mathias Agopian85d751c2012-08-29 16:59:24 -07002792 /*
2793 * and then, render the layers targeted at the framebuffer
2794 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002795
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 ALOGV("Rendering client layers");
2797 const Transform& displayTransform = displayDevice->getTransform();
2798 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002799 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 bool firstLayer = true;
2801 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002802 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 displayTransform.transform(layer->visibleRegion)));
2804 ALOGV("Layer: %s", layer->getName().string());
2805 ALOGV(" Composition type: %s",
2806 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002807 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 switch (layer->getCompositionType(hwcId)) {
2809 case HWC2::Composition::Cursor:
2810 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002811 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002813 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002815 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002817 // never clear the very first layer since we're
2818 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002819 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002820 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002821 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002822 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002824 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002825 break;
2826 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002828 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002829 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 } else {
2831 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002832 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002834 }
2835 } else {
2836 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002838 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002840 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002841 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002842 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002843 }
2844 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002845
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002846 if (applyColorMatrix) {
2847 getRenderEngine().setupColorTransform(oldColorMatrix);
2848 }
2849
Mathias Agopianf45c5102012-10-24 16:29:17 -07002850 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002851 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002852 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853}
2854
Fabien Sanglard830b8472016-11-30 16:35:58 -08002855void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2856 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002857 RenderEngine& engine(getRenderEngine());
2858 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Dan Stoza7d89d062015-04-30 13:29:25 -07002861status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002862 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002863 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 const sp<Layer>& lbc,
2865 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002866{
Dan Stoza7d89d062015-04-30 13:29:25 -07002867 // add this layer to the current state list
2868 {
2869 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002871 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2872 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002873 return NO_MEMORY;
2874 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 if (parent == nullptr) {
2876 mCurrentState.layersSortedByZ.add(lbc);
2877 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002878 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002879 ALOGE("addClientLayer called with a removed parent");
2880 return NAME_NOT_FOUND;
2881 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 parent->addChild(lbc);
2883 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002884
Dan Stoza7d89d062015-04-30 13:29:25 -07002885 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 mLayersAdded = true;
2887 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002888 }
2889
Mathias Agopian96f08192010-06-02 23:28:45 -07002890 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002891 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002892
Dan Stoza7d89d062015-04-30 13:29:25 -07002893 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002894}
2895
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002896status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002897 Mutex::Autolock _l(mStateLock);
2898
chaviw8b3871a2017-11-01 17:41:01 -07002899 if (layer->isPendingRemoval()) {
2900 return NO_ERROR;
2901 }
2902
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002904 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002905 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002906 if (topLevelOnly) {
2907 return NO_ERROR;
2908 }
2909
Chia-I Wu98f1c102017-05-30 14:54:08 -07002910 sp<Layer> ancestor = p;
2911 while (ancestor->getParent() != nullptr) {
2912 ancestor = ancestor->getParent();
2913 }
2914 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2915 ALOGE("removeLayer called with a layer whose parent has been removed");
2916 return NAME_NOT_FOUND;
2917 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002918
2919 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002920 } else {
2921 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002922 }
2923
Robert Carr136e2f62017-02-08 17:54:29 -08002924 // As a matter of normal operation, the LayerCleaner will produce a second
2925 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2926 // so we will succeed in promoting it, but it's already been removed
2927 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2928 // otherwise something has gone wrong and we are leaking the layer.
2929 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2931 layer->getName().string(),
2932 (p != nullptr) ? p->getName().string() : "no-parent");
2933 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002934 } else if (index < 0) {
2935 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002936 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002937
Chia-I Wuc6657022017-08-15 11:18:17 -07002938 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002939 mLayersPendingRemoval.add(layer);
2940 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002941 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002942 setTransactionFlags(eTransactionNeeded);
2943 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944}
2945
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002946uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002947 return android_atomic_release_load(&mTransactionFlags);
2948}
2949
Mathias Agopian3f844832013-08-07 21:24:32 -07002950uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2952}
2953
Mathias Agopian3f844832013-08-07 21:24:32 -07002954uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2956 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002957 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 }
2959 return old;
2960}
2961
Mathias Agopian8b33f032012-07-24 20:43:54 -07002962void SurfaceFlinger::setTransactionState(
2963 const Vector<ComposerState>& state,
2964 const Vector<DisplayState>& displays,
2965 uint32_t flags)
2966{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002967 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002968 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002969 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002970
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002971 if (flags & eAnimation) {
2972 // For window updates that are part of an animation we must wait for
2973 // previous animation "frames" to be handled.
2974 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002975 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002976 if (CC_UNLIKELY(err != NO_ERROR)) {
2977 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002978 // caller after a few seconds.
2979 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2980 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002981 mAnimTransactionPending = false;
2982 break;
2983 }
2984 }
2985 }
2986
Mathias Agopiane57f2922012-08-09 16:29:12 -07002987 size_t count = displays.size();
2988 for (size_t i=0 ; i<count ; i++) {
2989 const DisplayState& s(displays[i]);
2990 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002991 }
2992
Mathias Agopiane57f2922012-08-09 16:29:12 -07002993 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002994 for (size_t i=0 ; i<count ; i++) {
2995 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002996 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08002997 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002998 // IInterface, or one of its own or even one of our own but a
2999 // different type. All these situations would cause us to crash.
3000 //
3001 // NOTE: it would be better to use RTTI as we could directly check
3002 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08003003 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003004 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08003005 if (binder != nullptr) {
3006 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003007 sp<Client> client( static_cast<Client *>(s.client.get()) );
3008 transactionFlags |= setClientStateLocked(client, s.state);
3009 }
3010 }
3011 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003012 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003013
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003014 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3015 // anyway. This can be used as a flush mechanism for previous async transactions.
3016 // Empty animation transaction can be used to simulate back-pressure, so also force a
3017 // transaction for empty animation transactions.
3018 if (transactionFlags == 0 &&
3019 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003020 transactionFlags = eTransactionNeeded;
3021 }
3022
Mathias Agopian386aa982011-11-07 21:58:03 -08003023 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003024 if (mInterceptor.isEnabled()) {
3025 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3026 }
Irvel468051e2016-06-13 16:44:44 -07003027
Mathias Agopian386aa982011-11-07 21:58:03 -08003028 // this triggers the transaction
3029 setTransactionFlags(transactionFlags);
3030
3031 // if this is a synchronous transaction, wait for it to take effect
3032 // before returning.
3033 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003034 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003035 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003036 if (flags & eAnimation) {
3037 mAnimTransactionPending = true;
3038 }
3039 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003040 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3041 if (CC_UNLIKELY(err != NO_ERROR)) {
3042 // just in case something goes wrong in SF, return to the
3043 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003044 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3045 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003046 break;
3047 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003048 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 }
3050}
3051
Mathias Agopiane57f2922012-08-09 16:29:12 -07003052uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3053{
Jesse Hall9a143922012-10-04 16:29:19 -07003054 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3055 if (dpyIdx < 0)
3056 return 0;
3057
Mathias Agopiane57f2922012-08-09 16:29:12 -07003058 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003059 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003060 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 const uint32_t what = s.what;
3062 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003063 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 disp.surface = s.surface;
3065 flags |= eDisplayTransactionNeeded;
3066 }
3067 }
3068 if (what & DisplayState::eLayerStackChanged) {
3069 if (disp.layerStack != s.layerStack) {
3070 disp.layerStack = s.layerStack;
3071 flags |= eDisplayTransactionNeeded;
3072 }
3073 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003074 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003075 if (disp.orientation != s.orientation) {
3076 disp.orientation = s.orientation;
3077 flags |= eDisplayTransactionNeeded;
3078 }
3079 if (disp.frame != s.frame) {
3080 disp.frame = s.frame;
3081 flags |= eDisplayTransactionNeeded;
3082 }
3083 if (disp.viewport != s.viewport) {
3084 disp.viewport = s.viewport;
3085 flags |= eDisplayTransactionNeeded;
3086 }
3087 }
Michael Lentine47e45402014-07-18 15:34:25 -07003088 if (what & DisplayState::eDisplaySizeChanged) {
3089 if (disp.width != s.width) {
3090 disp.width = s.width;
3091 flags |= eDisplayTransactionNeeded;
3092 }
3093 if (disp.height != s.height) {
3094 disp.height = s.height;
3095 flags |= eDisplayTransactionNeeded;
3096 }
3097 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098 }
3099 return flags;
3100}
3101
3102uint32_t SurfaceFlinger::setClientStateLocked(
3103 const sp<Client>& client,
3104 const layer_state_t& s)
3105{
Mathias Agopian13127d82013-03-05 17:47:11 -08003106 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003107 if (layer == nullptr) {
3108 return 0;
3109 }
3110
3111 if (layer->isPendingRemoval()) {
3112 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3113 return 0;
3114 }
3115
3116 uint32_t flags = 0;
3117
3118 const uint32_t what = s.what;
3119 bool geometryAppliesWithResize =
3120 what & layer_state_t::eGeometryAppliesWithResize;
3121 if (what & layer_state_t::ePositionChanged) {
3122 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3123 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003124 }
chaviw8b3871a2017-11-01 17:41:01 -07003125 }
3126 if (what & layer_state_t::eLayerChanged) {
3127 // NOTE: index needs to be calculated before we update the state
3128 const auto& p = layer->getParent();
3129 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003130 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003131 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132 mCurrentState.layersSortedByZ.removeAt(idx);
3133 mCurrentState.layersSortedByZ.add(layer);
3134 // we need traversal (state changed)
3135 // AND transaction (list changed)
3136 flags |= eTransactionNeeded|eTraversalNeeded;
3137 }
chaviw8b3871a2017-11-01 17:41:01 -07003138 } else {
3139 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003140 flags |= eTransactionNeeded|eTraversalNeeded;
3141 }
3142 }
chaviw8b3871a2017-11-01 17:41:01 -07003143 }
3144 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003145 // NOTE: index needs to be calculated before we update the state
3146 const auto& p = layer->getParent();
3147 if (p == nullptr) {
3148 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3149 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3150 mCurrentState.layersSortedByZ.removeAt(idx);
3151 mCurrentState.layersSortedByZ.add(layer);
3152 // we need traversal (state changed)
3153 // AND transaction (list changed)
3154 flags |= eTransactionNeeded|eTraversalNeeded;
3155 }
3156 } else {
3157 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3158 flags |= eTransactionNeeded|eTraversalNeeded;
3159 }
chaviw8b3871a2017-11-01 17:41:01 -07003160 }
3161 }
3162 if (what & layer_state_t::eSizeChanged) {
3163 if (layer->setSize(s.w, s.h)) {
3164 flags |= eTraversalNeeded;
3165 }
3166 }
3167 if (what & layer_state_t::eAlphaChanged) {
3168 if (layer->setAlpha(s.alpha))
3169 flags |= eTraversalNeeded;
3170 }
3171 if (what & layer_state_t::eColorChanged) {
3172 if (layer->setColor(s.color))
3173 flags |= eTraversalNeeded;
3174 }
3175 if (what & layer_state_t::eMatrixChanged) {
3176 if (layer->setMatrix(s.matrix))
3177 flags |= eTraversalNeeded;
3178 }
3179 if (what & layer_state_t::eTransparentRegionChanged) {
3180 if (layer->setTransparentRegionHint(s.transparentRegion))
3181 flags |= eTraversalNeeded;
3182 }
3183 if (what & layer_state_t::eFlagsChanged) {
3184 if (layer->setFlags(s.flags, s.mask))
3185 flags |= eTraversalNeeded;
3186 }
3187 if (what & layer_state_t::eCropChanged) {
3188 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3189 flags |= eTraversalNeeded;
3190 }
3191 if (what & layer_state_t::eFinalCropChanged) {
3192 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3193 flags |= eTraversalNeeded;
3194 }
3195 if (what & layer_state_t::eLayerStackChanged) {
3196 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3197 // We only allow setting layer stacks for top level layers,
3198 // everything else inherits layer stack from its parent.
3199 if (layer->hasParent()) {
3200 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3201 layer->getName().string());
3202 } else if (idx < 0) {
3203 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3204 "that also does not appear in the top level layer list. Something"
3205 " has gone wrong.", layer->getName().string());
3206 } else if (layer->setLayerStack(s.layerStack)) {
3207 mCurrentState.layersSortedByZ.removeAt(idx);
3208 mCurrentState.layersSortedByZ.add(layer);
3209 // we need traversal (state changed)
3210 // AND transaction (list changed)
3211 flags |= eTransactionNeeded|eTraversalNeeded;
3212 }
3213 }
3214 if (what & layer_state_t::eDeferTransaction) {
3215 if (s.barrierHandle != nullptr) {
3216 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3217 } else if (s.barrierGbp != nullptr) {
3218 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3219 if (authenticateSurfaceTextureLocked(gbp)) {
3220 const auto& otherLayer =
3221 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3222 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3223 } else {
3224 ALOGE("Attempt to defer transaction to to an"
3225 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003226 }
3227 }
chaviw8b3871a2017-11-01 17:41:01 -07003228 // We don't trigger a traversal here because if no other state is
3229 // changed, we don't want this to cause any more work
3230 }
3231 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003232 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003233 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003234 if (!hadParent) {
3235 mCurrentState.layersSortedByZ.remove(layer);
3236 }
chaviw8b3871a2017-11-01 17:41:01 -07003237 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003238 }
chaviw8b3871a2017-11-01 17:41:01 -07003239 }
3240 if (what & layer_state_t::eReparentChildren) {
3241 if (layer->reparentChildren(s.reparentHandle)) {
3242 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003243 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003244 }
chaviw8b3871a2017-11-01 17:41:01 -07003245 if (what & layer_state_t::eDetachChildren) {
3246 layer->detachChildren();
3247 }
3248 if (what & layer_state_t::eOverrideScalingModeChanged) {
3249 layer->setOverrideScalingMode(s.overrideScalingMode);
3250 // We don't trigger a traversal here because if no other state is
3251 // changed, we don't want this to cause any more work
3252 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003253 return flags;
3254}
3255
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003256status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003257 const String8& name,
3258 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003259 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003260 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3261 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003263 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003264 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003265 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003266 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003267 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003268
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003269 status_t result = NO_ERROR;
3270
3271 sp<Layer> layer;
3272
Cody Northropbc755282017-03-31 12:00:08 -06003273 String8 uniqueName = getUniqueLayerName(name);
3274
Mathias Agopian3165cc22012-08-08 19:42:09 -07003275 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3276 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003277 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003278 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003279 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281 break;
chaviw13fdc492017-06-27 12:40:18 -07003282 case ISurfaceComposerClient::eFXSurfaceColor:
3283 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003284 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003285 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003286 break;
3287 default:
3288 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 break;
3290 }
3291
Dan Stoza7d89d062015-04-30 13:29:25 -07003292 if (result != NO_ERROR) {
3293 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003295
Chia-I Wuab0c3192017-08-01 11:29:00 -07003296 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3297 // TODO b/64227542
3298 if (windowType == 441731) {
3299 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3300 layer->setPrimaryDisplayOnly();
3301 }
3302
Albert Chaulk479c60c2017-01-27 14:21:34 -05003303 layer->setInfo(windowType, ownerUid);
3304
Robert Carr1f0a16a2016-10-24 16:27:39 -07003305 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003306 if (result != NO_ERROR) {
3307 return result;
3308 }
Irvelffc9efc2016-07-27 15:16:37 -07003309 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003310
3311 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003312 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313}
3314
Cody Northropbc755282017-03-31 12:00:08 -06003315String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3316{
3317 bool matchFound = true;
3318 uint32_t dupeCounter = 0;
3319
3320 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3321 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3322
3323 // Loop over layers until we're sure there is no matching name
3324 while (matchFound) {
3325 matchFound = false;
3326 mDrawingState.traverseInZOrder([&](Layer* layer) {
3327 if (layer->getName() == uniqueName) {
3328 matchFound = true;
3329 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3330 }
3331 });
3332 }
3333
3334 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3335
3336 return uniqueName;
3337}
3338
David Sodman0c69cad2017-08-21 12:12:51 -07003339status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003340 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3341 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342{
3343 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003344 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003345 case PIXEL_FORMAT_TRANSPARENT:
3346 case PIXEL_FORMAT_TRANSLUCENT:
3347 format = PIXEL_FORMAT_RGBA_8888;
3348 break;
3349 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003350 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 break;
3352 }
3353
David Sodman0c69cad2017-08-21 12:12:51 -07003354 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3355 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003356 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003357 *handle = layer->getHandle();
3358 *gbp = layer->getProducer();
3359 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003360 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003361
David Sodman0c69cad2017-08-21 12:12:51 -07003362 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003363 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364}
3365
chaviw13fdc492017-06-27 12:40:18 -07003366status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003367 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003368 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369{
chaviw13fdc492017-06-27 12:40:18 -07003370 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003371 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003372 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003373}
3374
Mathias Agopianac9fa422013-02-11 16:40:36 -08003375status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003376{
Robert Carr9524cb32017-02-13 11:32:32 -08003377 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003378 status_t err = NO_ERROR;
3379 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003380 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003381 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003382 err = removeLayer(l);
3383 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3384 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003385 }
3386 return err;
3387}
3388
Mathias Agopian13127d82013-03-05 17:47:11 -08003389status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003390{
Mathias Agopian67106042013-03-14 19:18:13 -07003391 // called by ~LayerCleaner() when all references to the IBinder (handle)
3392 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003393 sp<Layer> l = layer.promote();
3394 if (l == nullptr) {
3395 // The layer has already been removed, carry on
3396 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003397 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003398 // If we have a parent, then we can continue to live as long as it does.
3399 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003400}
3401
Mathias Agopianb60314a2012-04-10 22:09:54 -07003402// ---------------------------------------------------------------------------
3403
Andy McFadden13a082e2012-08-24 10:16:42 -07003404void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003405 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003406 Vector<ComposerState> state;
3407 Vector<DisplayState> displays;
3408 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003409 d.what = DisplayState::eDisplayProjectionChanged |
3410 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003411 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003412 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003413 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003414 d.frame.makeInvalid();
3415 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003416 d.width = 0;
3417 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003418 displays.add(d);
3419 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003420 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3421 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003422
David Sodman105b7dc2017-11-04 20:28:14 -07003423 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003424 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003425 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003426
Brian Andersond0010582017-03-07 13:20:31 -08003427 // Use phase of 0 since phase is not known.
3428 // Use latency of 0, which will snap to the ideal latency.
3429 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003430}
3431
3432void SurfaceFlinger::initializeDisplays() {
3433 class MessageScreenInitialized : public MessageBase {
3434 SurfaceFlinger* flinger;
3435 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003436 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003437 virtual bool handler() {
3438 flinger->onInitializeDisplays();
3439 return true;
3440 }
3441 };
3442 sp<MessageBase> msg = new MessageScreenInitialized(this);
3443 postMessageAsync(msg); // we may be called from main thread, use async message
3444}
3445
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003446void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003447 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003448 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3449 this);
3450 int32_t type = hw->getDisplayType();
3451 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003452
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003453 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003454 return;
3455 }
3456
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003457 hw->setPowerMode(mode);
3458 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3459 ALOGW("Trying to set power mode for virtual display");
3460 return;
3461 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003462
Irvelffc9efc2016-07-27 15:16:37 -07003463 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003464 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003465 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3466 if (idx < 0) {
3467 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3468 return;
3469 }
3470 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3471 }
3472
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003473 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003474 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003475 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003476 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3477 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003478 // FIXME: eventthread only knows about the main display right now
3479 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003480 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003483 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003484 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003485 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003486
3487 struct sched_param param = {0};
3488 param.sched_priority = 1;
3489 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3490 ALOGW("Couldn't set SCHED_FIFO on display on");
3491 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003492 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003493 // Turn off the display
3494 struct sched_param param = {0};
3495 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3496 ALOGW("Couldn't set SCHED_OTHER on display off");
3497 }
3498
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003499 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3500 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003501 disableHardwareVsync(true); // also cancels any in-progress resync
3502
Mathias Agopiancde87a32012-09-13 14:09:01 -07003503 // FIXME: eventthread only knows about the main display right now
3504 mEventThread->onScreenReleased();
3505 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003506
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003507 getHwComposer().setPowerMode(type, mode);
3508 mVisibleRegionsDirty = true;
3509 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003510 } else if (mode == HWC_POWER_MODE_DOZE ||
3511 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003512 // Update display while dozing
3513 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003514 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3515 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003516 // FIXME: eventthread only knows about the main display right now
3517 mEventThread->onScreenAcquired();
3518 resyncToHardwareVsync(true);
3519 }
3520 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3521 // Leave display going to doze
3522 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3523 disableHardwareVsync(true); // also cancels any in-progress resync
3524 // FIXME: eventthread only knows about the main display right now
3525 mEventThread->onScreenReleased();
3526 }
3527 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003528 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003529 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003531 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003532}
3533
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003534void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3535 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003536 SurfaceFlinger& mFlinger;
3537 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003538 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003539 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003540 MessageSetPowerMode(SurfaceFlinger& flinger,
3541 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3542 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003543 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003544 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003545 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003547 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003548 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003549 ALOGW("Attempt to set power mode = %d for virtual display",
3550 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003551 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003552 mFlinger.setPowerModeInternal(
3553 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003554 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003555 return true;
3556 }
3557 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003558 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003559 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003560}
3561
3562// ---------------------------------------------------------------------------
3563
Lloyd Pique755e3192018-01-31 16:46:15 -08003564status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3565 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003567
Mathias Agopianbd115332013-04-18 16:41:04 -07003568 IPCThreadState* ipc = IPCThreadState::self();
3569 const int pid = ipc->getCallingPid();
3570 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003571
Mathias Agopianbd115332013-04-18 16:41:04 -07003572 if ((uid != AID_SHELL) &&
3573 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003574 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003575 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003577 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003578 // (this would indicate SF is stuck, but we want to be able to
3579 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003580 status_t err = mStateLock.timedLock(s2ns(1));
3581 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003582 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003583 result.appendFormat(
3584 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3585 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003586 }
3587
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003588 bool dumpAll = true;
3589 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003590 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003591
3592 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003593 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003594 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3595 dumpAll = false;
3596 }
3597
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003598 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003599 if ((index < numArgs) &&
3600 (args[index] == String16("--list"))) {
3601 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003602 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003603 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003604 }
3605
3606 if ((index < numArgs) &&
3607 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003608 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003609 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003610 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003612
3613 if ((index < numArgs) &&
3614 (args[index] == String16("--latency-clear"))) {
3615 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003616 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003617 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003618 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003619
3620 if ((index < numArgs) &&
3621 (args[index] == String16("--dispsync"))) {
3622 index++;
3623 mPrimaryDispSync.dump(result);
3624 dumpAll = false;
3625 }
Dan Stozab90cf072015-03-05 11:05:59 -08003626
3627 if ((index < numArgs) &&
3628 (args[index] == String16("--static-screen"))) {
3629 index++;
3630 dumpStaticScreenStats(result);
3631 dumpAll = false;
3632 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003633
3634 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003635 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003636 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003637 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003638 dumpAll = false;
3639 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003640
3641 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3642 index++;
3643 dumpWideColorInfo(result);
3644 dumpAll = false;
3645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003647
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003648 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003649 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003650 }
3651
Mathias Agopian9795c422009-08-26 16:36:26 -07003652 if (locked) {
3653 mStateLock.unlock();
3654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003655 }
3656 write(fd, result.string(), result.size());
3657 return NO_ERROR;
3658}
3659
Dan Stozac7014012014-02-14 15:03:43 -08003660void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3661 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003662{
Robert Carr2047fae2016-11-28 14:09:09 -08003663 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003664 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003665 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003666}
3667
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003668void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003669 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003670{
3671 String8 name;
3672 if (index < args.size()) {
3673 name = String8(args[index]);
3674 index++;
3675 }
3676
David Sodman105b7dc2017-11-04 20:28:14 -07003677 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003678 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003679 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003680
3681 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003682 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003683 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003684 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003685 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003686 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003687 }
Robert Carr2047fae2016-11-28 14:09:09 -08003688 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003689 }
3690}
3691
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003692void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003693 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003694{
3695 String8 name;
3696 if (index < args.size()) {
3697 name = String8(args[index]);
3698 index++;
3699 }
3700
Robert Carr2047fae2016-11-28 14:09:09 -08003701 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003702 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003703 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003704 }
Robert Carr2047fae2016-11-28 14:09:09 -08003705 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003706
Svetoslavd85084b2014-03-20 10:28:31 -07003707 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003708}
3709
Jamie Gennis6547ff42013-07-16 20:12:42 -07003710// This should only be called from the main thread. Otherwise it would need
3711// the lock and should use mCurrentState rather than mDrawingState.
3712void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003713 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003714 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003715 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003716
3717 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3718}
3719
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003720void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003721{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003722 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003723
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003724 if (isLayerTripleBufferingDisabled())
3725 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003726
3727 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003728 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003729 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003730 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003731 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3732 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003733 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003734}
3735
Dan Stozab90cf072015-03-05 11:05:59 -08003736void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3737{
3738 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003739 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3740 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003741 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003742 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003743 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3744 b + 1, bucketTimeSec, percent);
3745 }
David Sodman4a36e932017-11-07 14:29:47 -08003746 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003747 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003748 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003749 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003750 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003751}
3752
Dan Stozae77c7662016-05-13 11:37:28 -07003753void SurfaceFlinger::recordBufferingStats(const char* layerName,
3754 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003755 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3756 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003757 for (const auto& segment : history) {
3758 if (!segment.usedThirdBuffer) {
3759 stats.twoBufferTime += segment.totalTime;
3760 }
3761 if (segment.occupancyAverage < 1.0f) {
3762 stats.doubleBufferedTime += segment.totalTime;
3763 } else if (segment.occupancyAverage < 2.0f) {
3764 stats.tripleBufferedTime += segment.totalTime;
3765 }
3766 ++stats.numSegments;
3767 stats.totalTime += segment.totalTime;
3768 }
3769}
3770
Brian Andersond6927fb2016-07-23 23:37:30 -07003771void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3772 result.appendFormat("Layer frame timestamps:\n");
3773
3774 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3775 const size_t count = currentLayers.size();
3776 for (size_t i=0 ; i<count ; i++) {
3777 currentLayers[i]->dumpFrameEvents(result);
3778 }
3779}
3780
Dan Stozae77c7662016-05-13 11:37:28 -07003781void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3782 result.append("Buffering stats:\n");
3783 result.append(" [Layer name] <Active time> <Two buffer> "
3784 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003785 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003786 typedef std::tuple<std::string, float, float, float> BufferTuple;
3787 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003788 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003789 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003790 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003791 if (stats.numSegments == 0) {
3792 continue;
3793 }
3794 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3795 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3796 stats.totalTime;
3797 float doubleBufferRatio = static_cast<float>(
3798 stats.doubleBufferedTime) / stats.totalTime;
3799 float tripleBufferRatio = static_cast<float>(
3800 stats.tripleBufferedTime) / stats.totalTime;
3801 sorted.insert({activeTime, {name, twoBufferRatio,
3802 doubleBufferRatio, tripleBufferRatio}});
3803 }
3804 for (const auto& sortedPair : sorted) {
3805 float activeTime = sortedPair.first;
3806 const BufferTuple& values = sortedPair.second;
3807 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3808 std::get<0>(values).c_str(), activeTime,
3809 std::get<1>(values), std::get<2>(values),
3810 std::get<3>(values));
3811 }
3812 result.append("\n");
3813}
3814
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003815void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3816 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003817 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003818
3819 // TODO: print out if wide-color mode is active or not
3820
3821 for (size_t d = 0; d < mDisplays.size(); d++) {
3822 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3823 int32_t hwcId = displayDevice->getHwcDisplayId();
3824 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3825 continue;
3826 }
3827
3828 result.appendFormat("Display %d color modes:\n", hwcId);
3829 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3830 for (auto&& mode : modes) {
3831 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3832 }
3833
3834 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3835 result.appendFormat(" Current color mode: %s (%d)\n",
3836 decodeColorMode(currentMode).c_str(), currentMode);
3837 }
3838 result.append("\n");
3839}
3840
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003841LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003842 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003843 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3844 const State& state = useDrawing ? mDrawingState : mCurrentState;
3845 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003846 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003847 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003848 });
3849
3850 return layersProto;
3851}
3852
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3854 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003855{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003856 bool colorize = false;
3857 if (index < args.size()
3858 && (args[index] == String16("--color"))) {
3859 colorize = true;
3860 index++;
3861 }
3862
3863 Colorizer colorizer(colorize);
3864
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865 // figure out if we're stuck somewhere
3866 const nsecs_t now = systemTime();
3867 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3868 const nsecs_t inTransaction(mDebugInTransaction);
3869 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3870 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3871
3872 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003873 * Dump library configuration.
3874 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003875
3876 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003877 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003878 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003879 appendSfConfigString(result);
3880 appendUiConfigString(result);
3881 appendGuiConfigString(result);
3882 result.append("\n");
3883
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003884 result.append("\nWide-Color information:\n");
3885 dumpWideColorInfo(result);
3886
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003887 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003888 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003889 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003890 result.append(SyncFeatures::getInstance().toString());
3891 result.append("\n");
3892
David Sodman105b7dc2017-11-04 20:28:14 -07003893 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003894
Andy McFadden41d67d72014-04-25 16:58:34 -07003895 colorizer.bold(result);
3896 result.append("DispSync configuration: ");
3897 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003898 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003899 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003900 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003901 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003902 result.append("\n");
3903
Dan Stozab90cf072015-03-05 11:05:59 -08003904 // Dump static screen stats
3905 result.append("\n");
3906 dumpStaticScreenStats(result);
3907 result.append("\n");
3908
Dan Stozae77c7662016-05-13 11:37:28 -07003909 dumpBufferingStats(result);
3910
Andy McFadden4803b742012-09-24 19:07:20 -07003911 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 * Dump the visible layer list
3913 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003914 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003915 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003916 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003917
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003918 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003919 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3920 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921
3922 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003923 * Dump Display state
3924 */
3925
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003926 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003927 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003928 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003929 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3930 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003931 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003932 }
3933
3934 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 * Dump SurfaceFlinger global state
3936 */
3937
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003938 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003939 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003940 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003941
Mathias Agopian888c8222012-08-04 21:10:38 -07003942 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003943 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003944
David Sodmanbc815282017-11-05 18:57:52 -08003945 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003947 if (hw) {
3948 hw->undefinedRegion.dump(result, "undefinedRegion");
3949 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3950 hw->getOrientation(), hw->isDisplayOn());
3951 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003952 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003953 " last eglSwapBuffers() time: %f us\n"
3954 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003955 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003956 " refresh-rate : %f fps\n"
3957 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003958 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003959 " gpu_to_cpu_unsupported : %d\n"
3960 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 mLastSwapBufferTime/1000.0,
3962 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003963 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003964 1e9 / activeConfig->getVsyncPeriod(),
3965 activeConfig->getDpiX(),
3966 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003967 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003968
Mathias Agopian74d211a2013-04-22 16:55:35 +02003969 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003970 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003971
Mathias Agopian74d211a2013-04-22 16:55:35 +02003972 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974
3975 /*
3976 * VSYNC state
3977 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003978 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003979 result.append("\n");
3980
3981 /*
3982 * HWC layer minidump
3983 */
3984 for (size_t d = 0; d < mDisplays.size(); d++) {
3985 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3986 int32_t hwcId = displayDevice->getHwcDisplayId();
3987 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3988 continue;
3989 }
3990
3991 result.appendFormat("Display %d HWC layers:\n", hwcId);
3992 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003993 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003994 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003995 });
Dan Stozae22aec72016-08-01 13:20:59 -07003996 result.append("\n");
3997 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003998
3999 /*
4000 * Dump HWComposer state
4001 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004002 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004003 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004004 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004005 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004006 result.appendFormat(" h/w composer %s\n",
4007 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004008 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004009
4010 /*
4011 * Dump gralloc state
4012 */
4013 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4014 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004015
4016 /*
4017 * Dump VrFlinger state if in use.
4018 */
4019 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4020 result.append("VrFlinger state:\n");
4021 result.append(mVrFlinger->Dump().c_str());
4022 result.append("\n");
4023 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004024}
4025
Mathias Agopian13127d82013-03-05 17:47:11 -08004026const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004027SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004028 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004029 wp<IBinder> dpy;
4030 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4031 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4032 dpy = mDisplays.keyAt(i);
4033 break;
4034 }
4035 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004036 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004037 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4038 // Just use the primary display so we have something to return
4039 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4040 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004041 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004042}
4043
Keun young Park63f165f2012-08-31 10:53:36 -07004044bool SurfaceFlinger::startDdmConnection()
4045{
4046 void* libddmconnection_dso =
4047 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4048 if (!libddmconnection_dso) {
4049 return false;
4050 }
4051 void (*DdmConnection_start)(const char* name);
4052 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004053 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004054 if (!DdmConnection_start) {
4055 dlclose(libddmconnection_dso);
4056 return false;
4057 }
4058 (*DdmConnection_start)(getServiceName());
4059 return true;
4060}
4061
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004062status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004063 switch (code) {
4064 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004065 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004067 case CLEAR_ANIMATION_FRAME_STATS:
4068 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004069 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004070 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004071 case ENABLE_VSYNC_INJECTIONS:
4072 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 {
4074 // codes that require permission check
4075 IPCThreadState* ipc = IPCThreadState::self();
4076 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004077 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004078 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004079 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004080 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004081 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004082 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004083 break;
4084 }
Robert Carr1db73f62016-12-21 12:58:51 -08004085 /*
4086 * Calling setTransactionState is safe, because you need to have been
4087 * granted a reference to Client* and Handle* to do anything with it.
4088 *
4089 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4090 */
4091 case SET_TRANSACTION_STATE:
4092 case CREATE_SCOPED_CONNECTION:
4093 {
4094 return OK;
4095 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004096 case CAPTURE_SCREEN:
4097 {
4098 // codes that require permission check
4099 IPCThreadState* ipc = IPCThreadState::self();
4100 const int pid = ipc->getCallingPid();
4101 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004102 if ((uid != AID_GRAPHICS) &&
4103 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004104 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004105 return PERMISSION_DENIED;
4106 }
4107 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004108 }
chaviwa76b2712017-09-20 12:02:26 -07004109 case CAPTURE_LAYERS: {
4110 IPCThreadState* ipc = IPCThreadState::self();
4111 const int pid = ipc->getCallingPid();
4112 const int uid = ipc->getCallingUid();
4113 if ((uid != AID_GRAPHICS) &&
4114 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4115 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4116 return PERMISSION_DENIED;
4117 }
4118 break;
4119 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004121 return OK;
4122}
4123
4124status_t SurfaceFlinger::onTransact(
4125 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4126{
4127 status_t credentialCheck = CheckTransactCodeCredentials(code);
4128 if (credentialCheck != OK) {
4129 return credentialCheck;
4130 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4133 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004134 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004135 IPCThreadState* ipc = IPCThreadState::self();
4136 const int uid = ipc->getCallingUid();
4137 if (CC_UNLIKELY(uid != AID_SYSTEM
4138 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004139 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004140 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004141 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 return PERMISSION_DENIED;
4143 }
4144 int n;
4145 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004146 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004147 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 return NO_ERROR;
4149 case 1002: // SHOW_UPDATES
4150 n = data.readInt32();
4151 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004152 invalidateHwcGeometry();
4153 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004154 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004156 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004157 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004158 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004159 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004160 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004161 setTransactionFlags(
4162 eTransactionNeeded|
4163 eDisplayTransactionNeeded|
4164 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004165 return NO_ERROR;
4166 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004167 case 1006:{ // send empty update
4168 signalRefresh();
4169 return NO_ERROR;
4170 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004171 case 1008: // toggle use of hw composer
4172 n = data.readInt32();
4173 mDebugDisableHWC = n ? 1 : 0;
4174 invalidateHwcGeometry();
4175 repaintEverything();
4176 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004177 case 1009: // toggle use of transform hint
4178 n = data.readInt32();
4179 mDebugDisableTransformHint = n ? 1 : 0;
4180 invalidateHwcGeometry();
4181 repaintEverything();
4182 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004184 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 reply->writeInt32(0);
4186 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004187 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004188 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189 return NO_ERROR;
4190 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004191 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004192 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004193 return NO_ERROR;
4194 }
4195 case 1014: {
4196 // daltonize
4197 n = data.readInt32();
4198 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004199 case 1:
4200 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4201 break;
4202 case 2:
4203 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4204 break;
4205 case 3:
4206 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4207 break;
4208 default:
4209 mDaltonizer.setType(ColorBlindnessType::None);
4210 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004211 }
4212 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004213 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004214 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004215 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004216 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004217 invalidateHwcGeometry();
4218 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004219 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004220 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004221 case 1015: {
4222 // apply a color matrix
4223 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004224 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004225 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004226 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004227 for (size_t j = 0; j < 4; j++) {
4228 mColorMatrix[i][j] = data.readFloat();
4229 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004230 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004231 } else {
4232 mColorMatrix = mat4();
4233 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004234
4235 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4236 // the division by w in the fragment shader
4237 float4 lastRow(transpose(mColorMatrix)[3]);
4238 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4239 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4240 }
4241
Alan Viverette9c5a3332013-09-12 20:04:35 -07004242 invalidateHwcGeometry();
4243 repaintEverything();
4244 return NO_ERROR;
4245 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004246 // This is an experimental interface
4247 // Needs to be shifted to proper binder interface when we productize
4248 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004249 n = data.readInt32();
4250 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004251 return NO_ERROR;
4252 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004253 case 1017: {
4254 n = data.readInt32();
4255 mForceFullDamage = static_cast<bool>(n);
4256 return NO_ERROR;
4257 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004258 case 1018: { // Modify Choreographer's phase offset
4259 n = data.readInt32();
4260 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4261 return NO_ERROR;
4262 }
4263 case 1019: { // Modify SurfaceFlinger's phase offset
4264 n = data.readInt32();
4265 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4266 return NO_ERROR;
4267 }
Irvel468051e2016-06-13 16:44:44 -07004268 case 1020: { // Layer updates interceptor
4269 n = data.readInt32();
4270 if (n) {
4271 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004272 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004273 }
4274 else{
4275 ALOGV("Interceptor disabled");
4276 mInterceptor.disable();
4277 }
4278 return NO_ERROR;
4279 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004280 case 1021: { // Disable HWC virtual displays
4281 n = data.readInt32();
4282 mUseHwcVirtualDisplays = !n;
4283 return NO_ERROR;
4284 }
Romain Guy0147a172017-06-01 13:53:56 -07004285 case 1022: { // Set saturation boost
4286 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4287
4288 invalidateHwcGeometry();
4289 repaintEverything();
4290 return NO_ERROR;
4291 }
Romain Guy54f154a2017-10-24 21:40:32 +01004292 case 1023: { // Set native mode
4293 mForceNativeColorMode = data.readInt32() == 1;
4294
4295 invalidateHwcGeometry();
4296 repaintEverything();
4297 return NO_ERROR;
4298 }
4299 case 1024: { // Is wide color gamut rendering/color management supported?
4300 reply->writeBool(hasWideColorDisplay);
4301 return NO_ERROR;
4302 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004303 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004304 n = data.readInt32();
4305 if (n) {
4306 ALOGV("LayerTracing enabled");
4307 mTracing.enable();
4308 doTracing("tracing.enable");
4309 reply->writeInt32(NO_ERROR);
4310 } else {
4311 ALOGV("LayerTracing disabled");
4312 status_t err = mTracing.disable();
4313 reply->writeInt32(err);
4314 }
4315 return NO_ERROR;
4316 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004317 case 1026: { // Get layer tracing status
4318 reply->writeBool(mTracing.isEnabled());
4319 return NO_ERROR;
4320 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004321 }
4322 }
4323 return err;
4324}
4325
Steven Thomas6d8110b2017-08-31 18:24:21 -07004326void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004327 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004328 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004329}
4330
Steven Thomas6d8110b2017-08-31 18:24:21 -07004331void SurfaceFlinger::repaintEverything() {
4332 ConditionalLock _l(mStateLock,
4333 std::this_thread::get_id() != mMainThreadId);
4334 repaintEverythingLocked();
4335}
4336
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004337// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4338class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004339public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004340 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4341 ~WindowDisconnector() {
4342 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004343 }
4344
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004345private:
4346 ANativeWindow* mWindow;
4347 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004348};
4349
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004350status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4351 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4352 int32_t minLayerZ, int32_t maxLayerZ,
4353 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004354 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004355 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004356
chaviwa76b2712017-09-20 12:02:26 -07004357 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4358
4359 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4360 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4361
4362 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4363 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004364 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004365}
4366
4367status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004368 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004369 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004370 ATRACE_CALL();
4371
4372 class LayerRenderArea : public RenderArea {
4373 public:
chaviw7206d492017-11-10 16:16:12 -08004374 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004375 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004376 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004377 const Transform& getTransform() const override {
4378 // Make the top level transform the inverse the transform and it's parent so it sets
4379 // the whole capture back to 0,0
4380 return *new Transform(mLayer->getTransform().inverse());
4381 }
4382 Rect getBounds() const override {
4383 const Layer::State& layerState(mLayer->getDrawingState());
4384 return Rect(layerState.active.w, layerState.active.h);
4385 }
4386 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4387 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4388 bool isSecure() const override { return false; }
4389 bool needsFiltering() const override { return false; }
4390
chaviw7206d492017-11-10 16:16:12 -08004391 Rect getSourceCrop() const override {
4392 if (mCrop.isEmpty()) {
4393 return getBounds();
4394 } else {
4395 return mCrop;
4396 }
4397 }
chaviwa76b2712017-09-20 12:02:26 -07004398 bool getWideColorSupport() const override { return false; }
4399 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4400
4401 private:
chaviw7206d492017-11-10 16:16:12 -08004402 const sp<Layer> mLayer;
4403 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004404 };
4405
4406 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4407 auto parent = layerHandle->owner.promote();
4408
chaviw7206d492017-11-10 16:16:12 -08004409 if (parent == nullptr || parent->isPendingRemoval()) {
4410 ALOGE("captureLayers called with a removed parent");
4411 return NAME_NOT_FOUND;
4412 }
4413
4414 Rect crop(sourceCrop);
4415 if (sourceCrop.width() <= 0) {
4416 crop.left = 0;
4417 crop.right = parent->getCurrentState().active.w;
4418 }
4419
4420 if (sourceCrop.height() <= 0) {
4421 crop.top = 0;
4422 crop.bottom = parent->getCurrentState().active.h;
4423 }
4424
4425 int32_t reqWidth = crop.width() * frameScale;
4426 int32_t reqHeight = crop.height() * frameScale;
4427
4428 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4429
chaviwa76b2712017-09-20 12:02:26 -07004430 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4431 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4432 if (!layer->isVisible()) {
4433 return;
4434 }
4435 visitor(layer);
4436 });
4437 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004438 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004439}
4440
4441status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4442 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004443 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004444 bool useIdentityTransform) {
4445 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004446
chaviwa76b2712017-09-20 12:02:26 -07004447 renderArea.updateDimensions();
4448
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004449 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4450 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4451 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4452 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004453
4454 // This mutex protects syncFd and captureResult for communication of the return values from the
4455 // main thread back to this Binder thread
4456 std::mutex captureMutex;
4457 std::condition_variable captureCondition;
4458 std::unique_lock<std::mutex> captureLock(captureMutex);
4459 int syncFd = -1;
4460 std::optional<status_t> captureResult;
4461
Robert Carr03480e22018-01-04 16:02:06 -08004462 const int uid = IPCThreadState::self()->getCallingUid();
4463 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4464
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004465 sp<LambdaMessage> message = new LambdaMessage([&]() {
4466 // If there is a refresh pending, bug out early and tell the binder thread to try again
4467 // after the refresh.
4468 if (mRefreshPending) {
4469 ATRACE_NAME("Skipping screenshot for now");
4470 std::unique_lock<std::mutex> captureLock(captureMutex);
4471 captureResult = std::make_optional<status_t>(EAGAIN);
4472 captureCondition.notify_one();
4473 return;
4474 }
4475
4476 status_t result = NO_ERROR;
4477 int fd = -1;
4478 {
4479 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004480 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004481 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004482 }
4483
4484 {
4485 std::unique_lock<std::mutex> captureLock(captureMutex);
4486 syncFd = fd;
4487 captureResult = std::make_optional<status_t>(result);
4488 captureCondition.notify_one();
4489 }
4490 });
4491
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004492 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004493 if (result == NO_ERROR) {
4494 captureCondition.wait(captureLock, [&]() { return captureResult; });
4495 while (*captureResult == EAGAIN) {
4496 captureResult.reset();
4497 result = postMessageAsync(message);
4498 if (result != NO_ERROR) {
4499 return result;
4500 }
4501 captureCondition.wait(captureLock, [&]() { return captureResult; });
4502 }
4503 result = *captureResult;
4504 }
4505
4506 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004507 sync_wait(syncFd, -1);
4508 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004509 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004510
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004511 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004512}
4513
chaviwa76b2712017-09-20 12:02:26 -07004514void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4515 TraverseLayersFunction traverseLayers, bool yswap,
4516 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004517 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004518
Mathias Agopian3f844832013-08-07 21:24:32 -07004519 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004520
4521 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004522 const auto raWidth = renderArea.getWidth();
4523 const auto raHeight = renderArea.getHeight();
4524
4525 const auto reqWidth = renderArea.getReqWidth();
4526 const auto reqHeight = renderArea.getReqHeight();
4527 Rect sourceCrop = renderArea.getSourceCrop();
4528
4529 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4530 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004531
Dan Stozac1879002014-05-22 15:59:05 -07004532 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004533 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004534 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004535 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004536 }
4537
4538 // ensure that sourceCrop is inside screen
4539 if (sourceCrop.left < 0) {
4540 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4541 }
chaviwa76b2712017-09-20 12:02:26 -07004542 if (sourceCrop.right > raWidth) {
4543 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004544 }
4545 if (sourceCrop.top < 0) {
4546 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4547 }
chaviwa76b2712017-09-20 12:02:26 -07004548 if (sourceCrop.bottom > raHeight) {
4549 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004550 }
4551
chaviwa76b2712017-09-20 12:02:26 -07004552 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004553 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4554 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004555
Mathias Agopian180f10d2013-04-10 22:55:41 -07004556 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004557 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004558
4559 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004560 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4561 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004562 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004563
4564 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004565 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004566
chaviwa76b2712017-09-20 12:02:26 -07004567 traverseLayers([&](Layer* layer) {
4568 if (filtering) layer->setFiltering(true);
4569 layer->draw(renderArea, useIdentityTransform);
4570 if (filtering) layer->setFiltering(false);
4571 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004572}
4573
chaviwa76b2712017-09-20 12:02:26 -07004574status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4575 TraverseLayersFunction traverseLayers,
4576 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004577 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004578 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004579 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004580 ATRACE_CALL();
4581
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004582 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004583
4584 traverseLayers([&](Layer* layer) {
4585 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4586 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004587
Robert Carr03480e22018-01-04 16:02:06 -08004588 // We allow the system server to take screenshots of secure layers for
4589 // use in situations like the Screen-rotation animation and place
4590 // the impetus on WindowManager to not persist them.
4591 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004592 ALOGW("FB is protected: PERMISSION_DENIED");
4593 return PERMISSION_DENIED;
4594 }
4595
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004596 // this binds the given EGLImage as a framebuffer for the
4597 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004598 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4599 if (bufferBond.getStatus() != NO_ERROR) {
4600 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004601 return INVALID_OPERATION;
4602 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004603
Dan Stozaabcda352017-06-01 14:37:39 -07004604 // this will in fact render into our dequeued buffer
4605 // via an FBO, which means we didn't have to create
4606 // an EGLSurface and therefore we're not
4607 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004608 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004609
Dan Stozaabcda352017-06-01 14:37:39 -07004610 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004611 getRenderEngine().finish();
4612 *outSyncFd = -1;
4613
chaviwa76b2712017-09-20 12:02:26 -07004614 const auto reqWidth = renderArea.getReqWidth();
4615 const auto reqHeight = renderArea.getReqHeight();
4616
Dan Stozaabcda352017-06-01 14:37:39 -07004617 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4618 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004619 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004620 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004621 } else {
4622 base::unique_fd syncFd = getRenderEngine().flush();
4623 if (syncFd < 0) {
4624 getRenderEngine().finish();
4625 }
4626 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004627 }
4628
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004629 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004630}
4631
Mathias Agopiand5556842013-09-19 17:08:37 -07004632void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004633 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004634 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004635 for (size_t y = 0; y < h; y++) {
4636 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4637 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004638 if (p[x] != 0xFF000000) return;
4639 }
4640 }
chaviwa76b2712017-09-20 12:02:26 -07004641 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004642
Robert Carr2047fae2016-11-28 14:09:09 -08004643 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004644 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004645 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004646 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4647 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4648 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4649 static_cast<float>(state.color.a));
4650 i++;
4651 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004652 }
4653}
4654
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004655// ---------------------------------------------------------------------------
4656
Dan Stoza412903f2017-04-27 13:42:17 -07004657void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4658 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004659}
4660
Dan Stoza412903f2017-04-27 13:42:17 -07004661void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4662 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004663}
4664
chaviwa76b2712017-09-20 12:02:26 -07004665void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4666 int32_t maxLayerZ,
4667 const LayerVector::Visitor& visitor) {
4668 // We loop through the first level of layers without traversing,
4669 // as we need to interpret min/max layer Z in the top level Z space.
4670 for (const auto& layer : mDrawingState.layersSortedByZ) {
4671 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4672 continue;
4673 }
4674 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004675 // relative layers are traversed in Layer::traverseInZOrder
4676 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004677 continue;
4678 }
4679 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004680 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4681 return;
4682 }
chaviwa76b2712017-09-20 12:02:26 -07004683 if (!layer->isVisible()) {
4684 return;
4685 }
4686 visitor(layer);
4687 });
4688 }
4689}
4690
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004692
4693
4694#if defined(__gl_h_)
4695#error "don't include gl/gl.h in this file"
4696#endif
4697
4698#if defined(__gl2_h_)
4699#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004700#endif