blob: 7ad13e3ef2c9a918e0607ea602bf35e60f66a2cb [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 {
Lloyd Pique144e1162017-12-20 16:44:52 -0800413 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700414 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700415 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800416 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
417 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700419 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700420 return true;
421 }
422 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700423 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424}
425
Lloyd Piquee83f9312018-02-01 12:53:17 -0800426class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000429 const char* name) :
430 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700431 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
434 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 mDispSync(dispSync),
436 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 mVsyncMutex(),
438 mPhaseOffset(phaseOffset),
439 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700440
Lloyd Piquee83f9312018-02-01 12:53:17 -0800441 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442
Lloyd Piquee83f9312018-02-01 12:53:17 -0800443 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700444 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000446 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 static_cast<DispSync::Callback*>(this));
448 if (err != NO_ERROR) {
449 ALOGE("error registering vsync callback: %s (%d)",
450 strerror(-err), err);
451 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700452 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 } else {
454 status_t err = mDispSync->removeEventListener(
455 static_cast<DispSync::Callback*>(this));
456 if (err != NO_ERROR) {
457 ALOGE("error unregistering vsync callback: %s (%d)",
458 strerror(-err), err);
459 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700460 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
464
Lloyd Piquee83f9312018-02-01 12:53:17 -0800465 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700466 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 mCallback = callback;
468 }
469
Lloyd Piquee83f9312018-02-01 12:53:17 -0800470 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 Mutex::Autolock lock(mVsyncMutex);
472
473 // Normalize phaseOffset to [0, period)
474 auto period = mDispSync->getPeriod();
475 phaseOffset %= period;
476 if (phaseOffset < 0) {
477 // If we're here, then phaseOffset is in (-period, 0). After this
478 // operation, it will be in (0, period)
479 phaseOffset += period;
480 }
481 mPhaseOffset = phaseOffset;
482
483 // If we're not enabled, we don't need to mess with the listeners
484 if (!mEnabled) {
485 return;
486 }
487
488 // Remove the listener with the old offset
489 status_t err = mDispSync->removeEventListener(
490 static_cast<DispSync::Callback*>(this));
491 if (err != NO_ERROR) {
492 ALOGE("error unregistering vsync callback: %s (%d)",
493 strerror(-err), err);
494 }
495
496 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000497 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700498 static_cast<DispSync::Callback*>(this));
499 if (err != NO_ERROR) {
500 ALOGE("error registering vsync callback: %s (%d)",
501 strerror(-err), err);
502 }
503 }
504
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505private:
506 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800507 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700509 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 callback = mCallback;
511
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700512 if (mTraceVsync) {
513 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700514 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700515 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 }
517
Peiyong Lin566a3b42018-01-09 18:22:43 -0800518 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519 callback->onVSyncEvent(when);
520 }
521 }
522
Tim Murray4a4e4a22016-04-19 16:29:23 +0000523 const char* const mName;
524
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 int mValue;
526
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700527 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700528 const String8 mVsyncOnLabel;
529 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700530
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700532
533 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800534 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700535
536 Mutex mVsyncMutex; // Protects the following
537 nsecs_t mPhaseOffset;
538 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539};
540
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700542public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800543 InjectVSyncSource() = default;
544 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700545
Lloyd Piquee83f9312018-02-01 12:53:17 -0800546 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700547 std::lock_guard<std::mutex> lock(mCallbackMutex);
548 mCallback = callback;
549 }
550
Lloyd Piquee83f9312018-02-01 12:53:17 -0800551 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700552 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700553 if (mCallback) {
554 mCallback->onVSyncEvent(when);
555 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700556 }
557
Lloyd Piquee83f9312018-02-01 12:53:17 -0800558 void setVSyncEnabled(bool) override {}
559 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700560
561private:
562 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800563 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700564};
565
Wei Wangf9b05ee2017-07-19 20:59:39 -0700566// Do not call property_set on main thread which will be blocked by init
567// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700569 ALOGI( "SurfaceFlinger's main thread ready to run. "
570 "Initializing graphics H/W...");
571
Thierry Strudel2924d012017-08-14 15:19:37 -0700572 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900573
Steven Thomasb02664d2017-07-26 18:48:28 -0700574 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575
Steven Thomasb02664d2017-07-26 18:48:28 -0700576 // start the EventThread
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577
578 mEventThreadSource = std::make_unique<DispSyncSource>(
579 &mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
580 mEventThread = std::make_unique<EventThread>(
581 mEventThreadSource.get(), *this, false, "sfEventThread");
582 mSfEventThreadSource = std::make_unique<DispSyncSource>(
583 &mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
584 mSFEventThread = std::make_unique<EventThread>(
585 mSfEventThreadSource.get(), *this, true, "appEventThread");
586 mEventQueue.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800589 getBE().mRenderEngine =
590 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
591 hasWideColorDisplay
592 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
593 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800594 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700595
596 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
597 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800598 getBE().mHwc.reset(
599 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700600 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800601 // Process any initial hotplug and resulting display changes.
602 processDisplayHotplugEventsLocked();
603 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
604 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800605
Lloyd Piquefcd86612017-12-14 17:15:36 -0800606 // make the default display GLContext current so that we can create textures
607 // when creating Layers (which may happens before we render something)
608 getDefaultDisplayDeviceLocked()->makeCurrent();
609
Steven Thomas050b2c82017-03-06 11:45:16 -0800610 if (useVrFlinger) {
611 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700612 // This callback is called from the vr flinger dispatch thread. We
613 // need to call signalTransaction(), which requires holding
614 // mStateLock when we're not on the main thread. Acquiring
615 // mStateLock from the vr flinger dispatch thread might trigger a
616 // deadlock in surface flinger (see b/66916578), so post a message
617 // to be handled on the main thread instead.
618 sp<LambdaMessage> message = new LambdaMessage([=]() {
619 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
620 mVrFlingerRequestsDisplay = requestDisplay;
621 signalTransaction();
622 });
623 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800624 };
David Sodman105b7dc2017-11-04 20:28:14 -0700625 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
626 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800627 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 if (!mVrFlinger) {
629 ALOGE("Failed to start vrflinger");
630 }
631 }
632
Lloyd Pique755e3192018-01-31 16:46:15 -0800633 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
634 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
635 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700636
Mathias Agopian92a979a2012-08-02 18:32:23 -0700637 // initialize our drawing state
638 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700639
Andy McFadden13a082e2012-08-24 10:16:42 -0700640 // set initial conditions (e.g. unblank default device)
641 initializeDisplays();
642
David Sodmanbc815282017-11-05 18:57:52 -0800643 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700644
Wei Wangf9b05ee2017-07-19 20:59:39 -0700645 // Inform native graphics APIs whether the present timestamp is supported:
646 if (getHwComposer().hasCapability(
647 HWC2::Capability::PresentFenceIsNotReliable)) {
648 mStartPropertySetThread = new StartPropertySetThread(false);
649 } else {
650 mStartPropertySetThread = new StartPropertySetThread(true);
651 }
652
653 if (mStartPropertySetThread->Start() != NO_ERROR) {
654 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800656
Dan Stoza9e56aa02015-11-02 13:00:03 -0800657 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700658}
659
Romain Guy11d63f42017-07-20 12:47:14 -0700660void SurfaceFlinger::readPersistentProperties() {
661 char value[PROPERTY_VALUE_MAX];
662
663 property_get("persist.sys.sf.color_saturation", value, "1.0");
664 mSaturation = atof(value);
665 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100666
667 property_get("persist.sys.sf.native_mode", value, "0");
668 mForceNativeColorMode = atoi(value) == 1;
669 if (mForceNativeColorMode) {
670 ALOGV("Forcing native color mode");
671 }
Romain Guy11d63f42017-07-20 12:47:14 -0700672}
673
Mathias Agopiana67e4182012-06-19 17:26:12 -0700674void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800675 // Start boot animation service by setting a property mailbox
676 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700677 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800678 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679 if (mStartPropertySetThread->join() != NO_ERROR) {
680 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800681 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700682}
683
Mathias Agopian875d8e12013-06-07 15:35:48 -0700684size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800685 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700686}
687
Mathias Agopian875d8e12013-06-07 15:35:48 -0700688size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800689 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700690}
691
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800693
Jamie Gennis582270d2011-08-17 18:19:00 -0700694bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800695 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800696 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800697 return authenticateSurfaceTextureLocked(bufferProducer);
698}
699
700bool SurfaceFlinger::authenticateSurfaceTextureLocked(
701 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800702 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700703 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800704}
705
Brian Anderson6b376712017-04-04 10:51:39 -0700706status_t SurfaceFlinger::getSupportedFrameTimestamps(
707 std::vector<FrameEvent>* outSupported) const {
708 *outSupported = {
709 FrameEvent::REQUESTED_PRESENT,
710 FrameEvent::ACQUIRE,
711 FrameEvent::LATCH,
712 FrameEvent::FIRST_REFRESH_START,
713 FrameEvent::LAST_REFRESH_START,
714 FrameEvent::GPU_COMPOSITION_DONE,
715 FrameEvent::DEQUEUE_READY,
716 FrameEvent::RELEASE,
717 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700718 ConditionalLock _l(mStateLock,
719 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700720 if (!getHwComposer().hasCapability(
721 HWC2::Capability::PresentFenceIsNotReliable)) {
722 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
723 }
724 return NO_ERROR;
725}
726
Dan Stoza7f7da322014-05-02 15:26:25 -0700727status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
728 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800729 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700730 return BAD_VALUE;
731 }
732
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500733 if (!display.get())
734 return NAME_NOT_FOUND;
735
Jesse Hall692c7232012-11-08 15:41:56 -0800736 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700737 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800738 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700739 type = i;
740 break;
741 }
742 }
743
744 if (type < 0) {
745 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700746 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700747
Mathias Agopian8b736f12012-08-13 17:54:26 -0700748 // TODO: Not sure if display density should handled by SF any longer
749 class Density {
750 static int getDensityFromProperty(char const* propName) {
751 char property[PROPERTY_VALUE_MAX];
752 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800753 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754 density = atoi(property);
755 }
756 return density;
757 }
758 public:
759 static int getEmuDensity() {
760 return getDensityFromProperty("qemu.sf.lcd_density"); }
761 static int getBuildDensity() {
762 return getDensityFromProperty("ro.sf.lcd_density"); }
763 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700764
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700766
Steven Thomas6d8110b2017-08-31 18:24:21 -0700767 ConditionalLock _l(mStateLock,
768 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 DisplayInfo info = DisplayInfo();
771
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 float xdpi = hwConfig->getDpiX();
773 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700774
775 if (type == DisplayDevice::DISPLAY_PRIMARY) {
776 // The density of the device is provided by a build property
777 float density = Density::getBuildDensity() / 160.0f;
778 if (density == 0) {
779 // the build doesn't provide a density -- this is wrong!
780 // use xdpi instead
781 ALOGE("ro.sf.lcd_density must be defined as a build property");
782 density = xdpi / 160.0f;
783 }
784 if (Density::getEmuDensity()) {
785 // if "qemu.sf.lcd_density" is specified, it overrides everything
786 xdpi = ydpi = density = Density::getEmuDensity();
787 density /= 160.0f;
788 }
789 info.density = density;
790
791 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700792 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800793 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 } else {
795 // TODO: where should this value come from?
796 static const int TV_DENSITY = 213;
797 info.density = TV_DENSITY / 160.0f;
798 info.orientation = 0;
799 }
800
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801 info.w = hwConfig->getWidth();
802 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 info.xdpi = xdpi;
804 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900806 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807
Andy McFadden91b2ca82014-06-13 14:04:23 -0700808 // This is how far in advance a buffer must be queued for
809 // presentation at a given time. If you want a buffer to appear
810 // on the screen at time N, you must submit the buffer before
811 // (N - presentationDeadline).
812 //
813 // Normally it's one full refresh period (to give SF a chance to
814 // latch the buffer), but this can be reduced by configuring a
815 // DispSync offset. Any additional delays introduced by the hardware
816 // composer or panel must be accounted for here.
817 //
818 // We add an additional 1ms to allow for processing time and
819 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800821 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700822
823 // All non-virtual displays are currently considered secure.
824 info.secure = true;
825
Michael Wright28f24d02016-07-12 13:30:53 -0700826 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 }
828
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 return NO_ERROR;
830}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700831
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800832status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700833 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800834 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700835 return BAD_VALUE;
836 }
837
838 // FIXME for now we always return stats for the primary display
839 memset(stats, 0, sizeof(*stats));
840 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
841 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
842 return NO_ERROR;
843}
844
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700845int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800846 if (display == nullptr) {
847 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800848 return BAD_VALUE;
849 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700850
851 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800852 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700853 return device->getActiveConfig();
854 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700855
Dan Stoza24a42e92015-03-09 10:04:11 -0700856 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700858
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700859void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
860 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
861 this);
862 int32_t type = hw->getDisplayType();
863 int currentMode = hw->getActiveConfig();
864
865 if (mode == currentMode) {
866 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
867 return;
868 }
869
870 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
871 ALOGW("Trying to set config for virtual display");
872 return;
873 }
874
875 hw->setActiveConfig(mode);
876 getHwComposer().setActiveConfig(type, mode);
877}
878
879status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
880 class MessageSetActiveConfig: public MessageBase {
881 SurfaceFlinger& mFlinger;
882 sp<IBinder> mDisplay;
883 int mMode;
884 public:
885 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
886 int mode) :
887 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
888 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700889 Vector<DisplayInfo> configs;
890 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700891 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700892 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700893 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700894 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700895 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700896 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800897 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700898 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700899 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700900 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
901 ALOGW("Attempt to set active config = %d for virtual display",
902 mMode);
903 } else {
904 mFlinger.setActiveConfigInternal(hw, mMode);
905 }
906 return true;
907 }
908 };
909 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
910 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700911 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700912}
Michael Wright28f24d02016-07-12 13:30:53 -0700913status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
914 Vector<android_color_mode_t>* outColorModes) {
915 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
916 return BAD_VALUE;
917 }
918
919 if (!display.get()) {
920 return NAME_NOT_FOUND;
921 }
922
923 int32_t type = NAME_NOT_FOUND;
924 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
925 if (display == mBuiltinDisplays[i]) {
926 type = i;
927 break;
928 }
929 }
930
931 if (type < 0) {
932 return type;
933 }
934
Steven Thomas6d8110b2017-08-31 18:24:21 -0700935 std::vector<android_color_mode_t> modes;
936 {
937 ConditionalLock _l(mStateLock,
938 std::this_thread::get_id() != mMainThreadId);
939 modes = getHwComposer().getColorModes(type);
940 }
Michael Wright28f24d02016-07-12 13:30:53 -0700941 outColorModes->clear();
942 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
943
944 return NO_ERROR;
945}
946
947android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700948 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700949 if (device != nullptr) {
950 return device->getActiveColorMode();
951 }
952 return static_cast<android_color_mode_t>(BAD_VALUE);
953}
954
955void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
956 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700957 int32_t type = hw->getDisplayType();
958 android_color_mode_t currentMode = hw->getActiveColorMode();
959
960 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700961 return;
962 }
963
964 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
965 ALOGW("Trying to set config for virtual display");
966 return;
967 }
968
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600969 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
970 hw->getDisplayType());
971
Michael Wright28f24d02016-07-12 13:30:53 -0700972 hw->setActiveColorMode(mode);
973 getHwComposer().setActiveColorMode(type, mode);
974}
975
976
977status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
978 android_color_mode_t colorMode) {
979 class MessageSetActiveColorMode: public MessageBase {
980 SurfaceFlinger& mFlinger;
981 sp<IBinder> mDisplay;
982 android_color_mode_t mMode;
983 public:
984 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
985 android_color_mode_t mode) :
986 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
987 virtual bool handler() {
988 Vector<android_color_mode_t> modes;
989 mFlinger.getDisplayColorModes(mDisplay, &modes);
990 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
991 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600992 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
993 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700994 return true;
995 }
996 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
997 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600998 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
999 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001000 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001001 ALOGW("Attempt to set active color mode %s %d for virtual display",
1002 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001003 } else {
1004 mFlinger.setActiveColorModeInternal(hw, mMode);
1005 }
1006 return true;
1007 }
1008 };
1009 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1010 postMessageSync(msg);
1011 return NO_ERROR;
1012}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001013
Svetoslavd85084b2014-03-20 10:28:31 -07001014status_t SurfaceFlinger::clearAnimationFrameStats() {
1015 Mutex::Autolock _l(mStateLock);
1016 mAnimFrameTracker.clearStats();
1017 return NO_ERROR;
1018}
1019
1020status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1021 Mutex::Autolock _l(mStateLock);
1022 mAnimFrameTracker.getStats(outStats);
1023 return NO_ERROR;
1024}
1025
Dan Stozac4f471e2016-03-24 09:31:08 -07001026status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1027 HdrCapabilities* outCapabilities) const {
1028 Mutex::Autolock _l(mStateLock);
1029
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001030 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001031 if (displayDevice == nullptr) {
1032 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1033 return BAD_VALUE;
1034 }
1035
1036 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001037 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001038 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001039 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1040 // insert HDR10 as we will force client composition for HDR10
1041 // layers
1042 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1043 types.push_back(HAL_HDR_HDR10);
1044
1045 *outCapabilities = HdrCapabilities(types,
1046 capabilities->getDesiredMaxLuminance(),
1047 capabilities->getDesiredMaxAverageLuminance(),
1048 capabilities->getDesiredMinLuminance());
1049 } else {
1050 *outCapabilities = std::move(*capabilities);
1051 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001052 } else {
1053 return BAD_VALUE;
1054 }
1055
1056 return NO_ERROR;
1057}
1058
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001059status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001060 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1061 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001062
Chia-I Wu90f669f2017-10-05 14:24:41 -07001063 if (mInjectVSyncs == enable) {
1064 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001066
1067 if (enable) {
1068 ALOGV("VSync Injections enabled");
1069 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001070 mVSyncInjector = std::make_unique<InjectVSyncSource>();
1071 mInjectorEventThread = std::make_unique<EventThread>(
1072 mVSyncInjector.get(), *this, false, "injEvThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073 }
Lloyd Piquee83f9312018-02-01 12:53:17 -08001074 mEventQueue.setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001075 } else {
1076 ALOGV("VSync Injections disabled");
Lloyd Piquee83f9312018-02-01 12:53:17 -08001077 mEventQueue.setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001078 }
1079
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001080 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 });
1082 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001083 return NO_ERROR;
1084}
1085
1086status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 Mutex::Autolock _l(mStateLock);
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 if (!mInjectVSyncs) {
1090 ALOGE("VSync Injections not enabled");
1091 return BAD_VALUE;
1092 }
1093 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1094 ALOGV("Injecting VSync inside SurfaceFlinger");
1095 mVSyncInjector->onInjectSyncEvent(when);
1096 }
1097 return NO_ERROR;
1098}
1099
Lloyd Pique755e3192018-01-31 16:46:15 -08001100status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1101 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001102 IPCThreadState* ipc = IPCThreadState::self();
1103 const int pid = ipc->getCallingPid();
1104 const int uid = ipc->getCallingUid();
1105 if ((uid != AID_SHELL) &&
1106 !PermissionCache::checkPermission(sDump, pid, uid)) {
1107 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1108 return PERMISSION_DENIED;
1109 }
1110
1111 // Try to acquire a lock for 1s, fail gracefully
1112 const status_t err = mStateLock.timedLock(s2ns(1));
1113 const bool locked = (err == NO_ERROR);
1114 if (!locked) {
1115 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1116 return TIMED_OUT;
1117 }
1118
1119 outLayers->clear();
1120 mCurrentState.traverseInZOrder([&](Layer* layer) {
1121 outLayers->push_back(layer->getLayerDebugInfo());
1122 });
1123
1124 mStateLock.unlock();
1125 return NO_ERROR;
1126}
1127
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001128// ----------------------------------------------------------------------------
1129
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001130sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1131 ISurfaceComposer::VsyncSource vsyncSource) {
1132 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1133 return mSFEventThread->createEventConnection();
1134 } else {
1135 return mEventThread->createEventConnection();
1136 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001137}
1138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001139// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140
1141void SurfaceFlinger::waitForEvent() {
1142 mEventQueue.waitMessage();
1143}
1144
1145void SurfaceFlinger::signalTransaction() {
1146 mEventQueue.invalidate();
1147}
1148
1149void SurfaceFlinger::signalLayerUpdate() {
1150 mEventQueue.invalidate();
1151}
1152
1153void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001154 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155 mEventQueue.refresh();
1156}
1157
1158status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001159 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160 return mEventQueue.postMessage(msg, reltime);
1161}
1162
1163status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001164 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165 status_t res = mEventQueue.postMessage(msg, reltime);
1166 if (res == NO_ERROR) {
1167 msg->wait();
1168 }
1169 return res;
1170}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173 do {
1174 waitForEvent();
1175 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176}
1177
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178void SurfaceFlinger::enableHardwareVsync() {
1179 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001180 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001182 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1183 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001185 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186}
1187
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 Mutex::Autolock _l(mHWVsyncLock);
1190
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191 if (makeAvailable) {
1192 mHWVsyncAvailable = true;
1193 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001194 // Hardware vsync is not currently available, so abort the resync
1195 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 return;
1197 }
1198
David Sodman105b7dc2017-11-04 20:28:14 -07001199 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001200 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201
1202 mPrimaryDispSync.reset();
1203 mPrimaryDispSync.setPeriod(period);
1204
1205 if (!mPrimaryHWVsyncEnabled) {
1206 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001207 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1208 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 mPrimaryHWVsyncEnabled = true;
1210 }
1211}
1212
Jesse Hall948fe0c2013-10-14 12:56:09 -07001213void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214 Mutex::Autolock _l(mHWVsyncLock);
1215 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1217 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.endResync();
1219 mPrimaryHWVsyncEnabled = false;
1220 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001221 if (makeUnavailable) {
1222 mHWVsyncAvailable = false;
1223 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224}
1225
Tim Murray4a4e4a22016-04-19 16:29:23 +00001226void SurfaceFlinger::resyncWithRateLimit() {
1227 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001228
1229 // No explicit locking is needed here since EventThread holds a lock while calling this method
1230 static nsecs_t sLastResyncAttempted = 0;
1231 const nsecs_t now = systemTime();
1232 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001233 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001234 }
Dan Stoza57164302017-05-08 14:03:54 -07001235 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236}
1237
Steven Thomasb02664d2017-07-26 18:48:28 -07001238void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1239 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001240 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001241 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001242 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001243 return;
1244 }
1245
1246 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001247 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001248 return;
1249 }
1250
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 { // Scope for the lock
1254 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001255 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001258 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001259
1260 if (needsHwVsync) {
1261 enableHardwareVsync();
1262 } else {
1263 disableHardwareVsync(false);
1264 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001265}
1266
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001267void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001268 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1269 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001270}
1271
Lloyd Pique715a2c12017-12-14 17:18:08 -08001272void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1273 HWC2::Connection connection) {
1274 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1275 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001276
Lloyd Piqueba04e622017-12-14 17:11:26 -08001277 // Ignore events that do not have the right sequenceId.
1278 if (sequenceId != getBE().mComposerSequenceId) {
1279 return;
1280 }
1281
Steven Thomasb02664d2017-07-26 18:48:28 -07001282 // Only lock if we're not on the main thread. This function is normally
1283 // called on a hwbinder thread, but for the primary display it's called on
1284 // the main thread with the state lock already held, so don't attempt to
1285 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001286 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001287
Lloyd Pique715a2c12017-12-14 17:18:08 -08001288 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001289
Lloyd Piqueba04e622017-12-14 17:11:26 -08001290 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001291}
1292
Steven Thomasb02664d2017-07-26 18:48:28 -07001293void SurfaceFlinger::onRefreshReceived(int sequenceId,
1294 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001296 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001297 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001298 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001299 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001300}
1301
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001304 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001305 getHwComposer().setVsyncEnabled(disp,
1306 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001307}
1308
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001309// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001310void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001311 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001312 // Clear the drawing state so that the logic inside of
1313 // handleTransactionLocked will fire. It will determine the delta between
1314 // mCurrentState and mDrawingState and re-apply all changes when we make the
1315 // transition.
1316 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001317 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001318 mDisplays.clear();
1319}
1320
Steven Thomas050b2c82017-03-06 11:45:16 -08001321void SurfaceFlinger::updateVrFlinger() {
1322 if (!mVrFlinger)
1323 return;
1324 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001326 return;
1327 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328
David Sodman105b7dc2017-11-04 20:28:14 -07001329 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 ALOGE("Vr flinger is only supported for remote hardware composer"
1331 " service connections. Ignoring request to transition to vr"
1332 " flinger.");
1333 mVrFlingerRequestsDisplay = false;
1334 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001335 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001338
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 int currentDisplayPowerMode = getDisplayDeviceLocked(
1340 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001343 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001345
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001347 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001348 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1349 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001350 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351
David Sodman105b7dc2017-11-04 20:28:14 -07001352 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1353 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001354
1355 if (vrFlingerRequestsDisplay) {
1356 mVrFlinger->GrantDisplayOwnership();
1357 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360
1361 mVisibleRegionsDirty = true;
1362 invalidateHwcGeometry();
1363
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001364 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1366 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1367 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001368
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001370 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 const nsecs_t period = activeConfig->getVsyncPeriod();
1372 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001373
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 // Use phase of 0 since phase is not known.
1375 // Use latency of 0, which will snap to the ideal latency.
1376 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001377
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378 android_atomic_or(1, &mRepaintEverything);
1379 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380}
1381
Mathias Agopian4fec8732012-06-29 14:12:52 -07001382void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001383 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001384 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001385 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001386 bool frameMissed = !mHadClientComposition &&
1387 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388 (mPreviousPresentFence->getSignalTime() ==
1389 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001390 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001391 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001392 signalLayerUpdate();
1393 break;
1394 }
1395
Steven Thomas050b2c82017-03-06 11:45:16 -08001396 // Now that we're going to make it to the handleMessageTransaction()
1397 // call below it's safe to call updateVrFlinger(), which will
1398 // potentially trigger a display handoff.
1399 updateVrFlinger();
1400
Dan Stoza6b9454d2014-11-07 16:00:59 -08001401 bool refreshNeeded = handleMessageTransaction();
1402 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001403 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001404 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001405 // Signal a refresh if a transaction modified the window state,
1406 // a new buffer was latched, or if HWC has requested a full
1407 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408 signalRefresh();
1409 }
1410 break;
1411 }
1412 case MessageQueue::REFRESH: {
1413 handleMessageRefresh();
1414 break;
1415 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001416 }
1417}
1418
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001420 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001421 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001422 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001425 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001426}
1427
Dan Stoza6b9454d2014-11-07 16:00:59 -08001428bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001429 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001430 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001431}
1432
1433void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001434 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001435
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001436 mRefreshPending = false;
1437
Pablo Ceballos40845df2016-01-25 17:41:15 -08001438 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001439
Brian Andersond6927fb2016-07-23 23:37:30 -07001440 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001441 rebuildLayerStacks();
1442 setUpHWComposer();
1443 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001444 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001445 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001447
David Sodman105b7dc2017-11-04 20:28:14 -07001448 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001449
1450 mHadClientComposition = false;
1451 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1452 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1453 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001454 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001455 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001456
Dan Stoza9e56aa02015-11-02 13:00:03 -08001457 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001458}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001459
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460void SurfaceFlinger::doDebugFlashRegions()
1461{
1462 // is debugging enabled
1463 if (CC_LIKELY(!mDebugRegion))
1464 return;
1465
1466 const bool repaintEverything = mRepaintEverything;
1467 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1468 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001469 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 // transform the dirty region into this screen's coordinate space
1471 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1472 if (!dirtyRegion.isEmpty()) {
1473 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001474 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475
1476 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001478 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001479 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1480
Mathias Agopianda27af92012-09-13 18:17:13 -07001481 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001482 }
1483 }
1484 }
1485
1486 postFramebuffer();
1487
1488 if (mDebugRegion > 1) {
1489 usleep(mDebugRegion * 1000);
1490 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001491
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001493 auto& displayDevice = mDisplays[displayId];
1494 if (!displayDevice->isDisplayOn()) {
1495 continue;
1496 }
1497
David Sodman105b7dc2017-11-04 20:28:14 -07001498 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1499 ALOGE_IF(result != NO_ERROR,
1500 "prepareFrame for display %zd failed:"
1501 " %d (%s)",
1502 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001503 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504}
1505
Adrian Roos1e1a1282017-11-01 19:05:31 +01001506void SurfaceFlinger::doTracing(const char* where) {
1507 ATRACE_CALL();
1508 ATRACE_NAME(where);
1509 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001510 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001511 }
1512}
1513
Brian Andersond6927fb2016-07-23 23:37:30 -07001514void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001516 ATRACE_CALL();
1517 ALOGV("preComposition");
1518
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001520 mDrawingState.traverseInZOrder([&](Layer* layer) {
1521 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522 needExtraInvalidate = true;
1523 }
Robert Carr2047fae2016-11-28 14:09:09 -08001524 });
1525
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 if (needExtraInvalidate) {
1527 signalLayerUpdate();
1528 }
1529}
1530
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001531void SurfaceFlinger::updateCompositorTiming(
1532 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1533 std::shared_ptr<FenceTime>& presentFenceTime) {
1534 // Update queue of past composite+present times and determine the
1535 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001536 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001538 while (!getBE().mCompositePresentTimes.empty()) {
1539 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001540 // Cached values should have been updated before calling this method,
1541 // which helps avoid duplicate syscalls.
1542 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1543 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1544 break;
1545 }
1546 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001547 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001548 }
1549
1550 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001551 while (getBE().mCompositePresentTimes.size() > 16) {
1552 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001553 }
1554
Brian Andersond0010582017-03-07 13:20:31 -08001555 setCompositorTimingSnapped(
1556 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1557}
1558
1559void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1560 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561 // Integer division and modulo round toward 0 not -inf, so we need to
1562 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001563 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1565 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1566
Brian Andersond0010582017-03-07 13:20:31 -08001567 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1568 if (idealLatency <= 0) {
1569 idealLatency = vsyncInterval;
1570 }
1571
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001572 // Snap the latency to a value that removes scheduling jitter from the
1573 // composition and present times, which often have >1ms of jitter.
1574 // Reducing jitter is important if an app attempts to extrapolate
1575 // something (such as user input) to an accurate diasplay time.
1576 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1577 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001578 nsecs_t bias = vsyncInterval / 2;
1579 int64_t extraVsyncs =
1580 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1581 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1582 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001583
David Sodman99974d22017-11-28 12:04:33 -08001584 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1585 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1586 getBE().mCompositorTiming.interval = vsyncInterval;
1587 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588}
1589
1590void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001592 ATRACE_CALL();
1593 ALOGV("postComposition");
1594
Brian Anderson3546a3f2016-07-14 11:51:14 -07001595 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001596 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001597 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001598 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001599 }
1600
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001601 // |mStateLock| not needed as we are on the main thread
1602 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603
David Sodman73beded2017-11-15 11:56:06 -08001604 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001605 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001606 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001607 glCompositionDoneFenceTime =
1608 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001609 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001610 } else {
1611 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1612 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001613
David Sodman73beded2017-11-15 11:56:06 -08001614 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001615 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001616 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001617 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001618
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001619 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1620 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1621
1622 // We use the refreshStartTime which might be sampled a little later than
1623 // when we started doing work for this frame, but that should be okay
1624 // since updateCompositorTiming has snapping logic.
1625 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001626 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001627 CompositorTiming compositorTiming;
1628 {
David Sodman99974d22017-11-28 12:04:33 -08001629 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1630 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001631 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632
Robert Carr2047fae2016-11-28 14:09:09 -08001633 mDrawingState.traverseInZOrder([&](Layer* layer) {
1634 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001635 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001636 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001637 recordBufferingStats(layer->getName().string(),
1638 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001639 }
Robert Carr2047fae2016-11-28 14:09:09 -08001640 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001641
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001642 if (presentFenceTime->isValid()) {
1643 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001644 enableHardwareVsync();
1645 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001646 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001647 }
1648 }
1649
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001650 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001651 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001652 enableHardwareVsync();
1653 }
1654 }
1655
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001656 if (mAnimCompositionPending) {
1657 mAnimCompositionPending = false;
1658
Brian Anderson4e606e32017-03-16 15:34:57 -07001659 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001660 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001661 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001662 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001663 // The HWC doesn't support present fences, so use the refresh
1664 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001665 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001666 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001667 mAnimFrameTracker.setActualPresentTime(presentTime);
1668 }
1669 mAnimFrameTracker.advanceFrame();
1670 }
Dan Stozab90cf072015-03-05 11:05:59 -08001671
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001672 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1673 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001674 return;
1675 }
1676
1677 nsecs_t currentTime = systemTime();
1678 if (mHasPoweredOff) {
1679 mHasPoweredOff = false;
1680 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001681 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001683 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1684 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001685 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001686 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001687 }
David Sodman4a36e932017-11-07 14:29:47 -08001688 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001689 }
David Sodman4a36e932017-11-07 14:29:47 -08001690 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691}
1692
1693void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 ATRACE_CALL();
1695 ALOGV("rebuildLayerStacks");
1696
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001698 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001699 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001700 mVisibleRegionsDirty = false;
1701 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001702
Jeff Sharkey76488112017-02-27 14:15:18 -07001703 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1704 Region opaqueRegion;
1705 Region dirtyRegion;
1706 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001707 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001708 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1709 const Transform& tr(displayDevice->getTransform());
1710 const Rect bounds(displayDevice->getBounds());
1711 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001712 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001713
Jeff Sharkey76488112017-02-27 14:15:18 -07001714 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001715 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001716 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1717 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001718 Region drawRegion(tr.transform(
1719 layer->visibleNonTransparentRegion));
1720 drawRegion.andSelf(bounds);
1721 if (!drawRegion.isEmpty()) {
1722 layersSortedByZ.add(layer);
1723 } else {
1724 // Clear out the HWC layer if this layer was
1725 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001726 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001727 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001728 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001729 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001730 // WM changes displayDevice->layerStack upon sleep/awake.
1731 // Here we make sure we delete the HWC layers even if
1732 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001733 hwcLayerDestroyed = layer->destroyHwcLayer(
1734 displayDevice->getHwcDisplayId());
1735 }
1736
1737 // If a layer is not going to get a release fence because
1738 // it is invisible, but it is also going to release its
1739 // old buffer, add it to the list of layers needing
1740 // fences.
1741 if (hwcLayerDestroyed) {
1742 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1743 mLayersWithQueuedFrames.cend(), layer);
1744 if (found != mLayersWithQueuedFrames.cend()) {
1745 layersNeedingFences.add(layer);
1746 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001747 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001748 });
1749 }
1750 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001751 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001752 displayDevice->undefinedRegion.set(bounds);
1753 displayDevice->undefinedRegion.subtractSelf(
1754 tr.transform(opaqueRegion));
1755 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001756 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001757 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001759
Romain Guy0147a172017-06-01 13:53:56 -07001760mat4 SurfaceFlinger::computeSaturationMatrix() const {
1761 if (mSaturation == 1.0f) {
1762 return mat4();
1763 }
1764
1765 // Rec.709 luma coefficients
1766 float3 luminance{0.213f, 0.715f, 0.072f};
1767 luminance *= 1.0f - mSaturation;
1768 return mat4(
1769 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1770 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1771 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1772 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1773 );
1774}
1775
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001776// pickColorMode translates a given dataspace into the best available color mode.
1777// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001778android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001779 if (mForceNativeColorMode) {
1780 return HAL_COLOR_MODE_NATIVE;
1781 }
1782
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001783 switch (dataSpace) {
1784 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1785 // system expects.
1786 case HAL_DATASPACE_UNKNOWN:
1787 case HAL_DATASPACE_SRGB:
1788 case HAL_DATASPACE_V0_SRGB:
1789 return HAL_COLOR_MODE_SRGB;
1790 break;
1791
1792 case HAL_DATASPACE_DISPLAY_P3:
1793 return HAL_COLOR_MODE_DISPLAY_P3;
1794 break;
1795
1796 default:
1797 // TODO (courtneygo): Do we want to assert an error here?
1798 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1799 dataSpace);
1800 return HAL_COLOR_MODE_SRGB;
1801 break;
1802 }
1803}
1804
Romain Guy0147a172017-06-01 13:53:56 -07001805android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001806 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001807 // Only support sRGB and Display-P3 right now.
1808 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1809 return HAL_DATASPACE_DISPLAY_P3;
1810 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001811 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1812 return HAL_DATASPACE_DISPLAY_P3;
1813 }
1814 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1815 return HAL_DATASPACE_DISPLAY_P3;
1816 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001817 if (!hasHdr) {
1818 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1819 return HAL_DATASPACE_DISPLAY_P3;
1820 }
1821 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1822 return HAL_DATASPACE_DISPLAY_P3;
1823 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001824 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001825
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001826 return HAL_DATASPACE_V0_SRGB;
1827}
1828
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 ATRACE_CALL();
1831 ALOGV("setUpHWComposer");
1832
Jesse Hall028dc8f2013-08-20 16:35:32 -07001833 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001834 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1835 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1836 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1837
1838 // If nothing has changed (!dirty), don't recompose.
1839 // If something changed, but we don't currently have any visible layers,
1840 // and didn't when we last did a composition, then skip it this time.
1841 // The second rule does two things:
1842 // - When all layers are removed from a display, we'll emit one black
1843 // frame, then nothing more until we get new layers.
1844 // - When a display is created with a private layer stack, we won't
1845 // emit any black frames until a layer is added to the layer stack.
1846 bool mustRecompose = dirty && !(empty && wasEmpty);
1847
1848 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1849 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1850 mustRecompose ? "doing" : "skipping",
1851 dirty ? "+" : "-",
1852 empty ? "+" : "-",
1853 wasEmpty ? "+" : "-");
1854
Dan Stoza71433162014-02-04 16:22:36 -08001855 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001856
1857 if (mustRecompose) {
1858 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1859 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001860 }
1861
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 // build the h/w work list
1863 if (CC_UNLIKELY(mGeometryInvalid)) {
1864 mGeometryInvalid = false;
1865 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1866 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1867 const auto hwcId = displayDevice->getHwcDisplayId();
1868 if (hwcId >= 0) {
1869 const Vector<sp<Layer>>& currentLayers(
1870 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001871 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001872 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001874 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001877 }
1878 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001879
Robert Carrae060832016-11-28 10:51:00 -08001880 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001881 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001883 }
1884 }
1885 }
1886 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 }
Riley Andrews03414a12014-07-01 14:22:59 -07001888
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001889
Romain Guy0147a172017-06-01 13:53:56 -07001890 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001891
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 // Set the per-frame data
1893 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1894 auto& displayDevice = mDisplays[displayId];
1895 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 if (hwcId < 0) {
1898 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001899 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001900 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001901 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001902 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1903 "display %zd: %d", displayId, result);
1904 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001906 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1907 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001908 !displayDevice->getHdrSupport()) {
1909 layer->forceClientComposition(hwcId);
1910 }
1911
chaviwc9232ed2017-11-14 15:31:15 -08001912 if (layer->getForceClientComposition(hwcId)) {
1913 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1914 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1915 continue;
1916 }
1917
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 layer->setPerFrameData(displayDevice);
1919 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001920
1921 if (hasWideColorDisplay) {
1922 android_color_mode newColorMode;
1923 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1924
1925 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001926 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1927 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001928 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1929 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1930 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1931 }
1932 newColorMode = pickColorMode(newDataSpace);
1933
Thierry Strudel2924d012017-08-14 15:19:37 -07001934 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001935 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001936 }
1937
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001938 mPreviousColorMatrix = colorMatrix;
1939
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001941 auto& displayDevice = mDisplays[displayId];
1942 if (!displayDevice->isDisplayOn()) {
1943 continue;
1944 }
1945
David Sodman105b7dc2017-11-04 20:28:14 -07001946 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1948 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001949 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001950}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001951
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952void SurfaceFlinger::doComposition() {
1953 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 ALOGV("doComposition");
1955
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001956 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001957 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001958 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001959 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001960 // transform the dirty region into this screen's coordinate space
1961 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001962
1963 // repaint the framebuffer (if needed)
1964 doDisplayComposition(hw, dirtyRegion);
1965
Mathias Agopiancd60f992012-08-16 16:28:27 -07001966 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001967 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001968 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001969 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001970 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001971}
1972
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001973void SurfaceFlinger::postFramebuffer()
1974{
Mathias Agopian841cde52012-03-01 15:44:37 -08001975 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001977
Mathias Agopiana44b0412011-10-16 18:46:35 -07001978 const nsecs_t now = systemTime();
1979 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001980
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1982 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001983 if (!displayDevice->isDisplayOn()) {
1984 continue;
1985 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001986 const auto hwcId = displayDevice->getHwcDisplayId();
1987 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001988 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001989 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001990 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001991 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001993 // The layer buffer from the previous frame (if any) is released
1994 // by HWC only when the release fence from this frame (if any) is
1995 // signaled. Always get the release fence from HWC first.
1996 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001997 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08001998
1999 // If the layer was client composited in the previous frame, we
2000 // need to merge with the previous client target acquire fence.
2001 // Since we do not track that, always merge with the current
2002 // client target acquire fence when it is available, even though
2003 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002005 releaseFence = Fence::merge("LayerRelease", releaseFence,
2006 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002007 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002008
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 layer->onLayerDisplayed(releaseFence);
2010 }
Chia-I Wu83806892017-11-16 10:50:20 -08002011
2012 // We've got a list of layers needing fences, that are disjoint with
2013 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2014 // supply them with the present fence.
2015 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002016 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002017 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2018 layer->onLayerDisplayed(presentFence);
2019 }
2020 }
2021
Dan Stoza9e56aa02015-11-02 13:00:03 -08002022 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002023 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002024 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002025 }
2026
Mathias Agopiana44b0412011-10-16 18:46:35 -07002027 mLastSwapBufferTime = systemTime() - now;
2028 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002029
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002030 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002031 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2032 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2033 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2034 logFrameStats();
2035 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002036 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002037}
2038
Mathias Agopian87baae12012-07-31 12:38:26 -07002039void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040{
Mathias Agopian841cde52012-03-01 15:44:37 -08002041 ATRACE_CALL();
2042
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002043 // here we keep a copy of the drawing state (that is the state that's
2044 // going to be overwritten by handleTransactionLocked()) outside of
2045 // mStateLock so that the side-effects of the State assignment
2046 // don't happen with mStateLock held (which can cause deadlocks).
2047 State drawingState(mDrawingState);
2048
Mathias Agopianca4d3602011-05-19 15:38:14 -07002049 Mutex::Autolock _l(mStateLock);
2050 const nsecs_t now = systemTime();
2051 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052
Mathias Agopianca4d3602011-05-19 15:38:14 -07002053 // Here we're guaranteed that some transaction flags are set
2054 // so we can call handleTransactionLocked() unconditionally.
2055 // We call getTransactionFlags(), which will also clear the flags,
2056 // with mStateLock held to guarantee that mCurrentState won't change
2057 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002058
Mathias Agopiane57f2922012-08-09 16:29:12 -07002059 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002060 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002061
Mathias Agopianca4d3602011-05-19 15:38:14 -07002062 mLastTransactionTime = systemTime() - now;
2063 mDebugInTransaction = 0;
2064 invalidateHwcGeometry();
2065 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002066}
2067
Lloyd Pique715a2c12017-12-14 17:18:08 -08002068DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2069 HWC2::Connection connection) const {
2070 // Figure out whether the event is for the primary display or an
2071 // external display by matching the Hwc display id against one for a
2072 // connected display. If we did not find a match, we then check what
2073 // displays are not already connected to determine the type. If we don't
2074 // have a connected primary display, we assume the new display is meant to
2075 // be the primary display, and then if we don't have an external display,
2076 // we assume it is that.
2077 const auto primaryDisplayId =
2078 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2079 const auto externalDisplayId =
2080 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2081 if (primaryDisplayId && primaryDisplayId == display) {
2082 return DisplayDevice::DISPLAY_PRIMARY;
2083 } else if (externalDisplayId && externalDisplayId == display) {
2084 return DisplayDevice::DISPLAY_EXTERNAL;
2085 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2086 return DisplayDevice::DISPLAY_PRIMARY;
2087 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2088 return DisplayDevice::DISPLAY_EXTERNAL;
2089 }
2090
2091 return DisplayDevice::DISPLAY_ID_INVALID;
2092}
2093
Lloyd Piqueba04e622017-12-14 17:11:26 -08002094void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2095 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002096 auto displayType = determineDisplayType(event.display, event.connection);
2097 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2098 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2099 continue;
2100 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002101
2102 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2103 ALOGE("External displays are not supported by the vr hardware composer.");
2104 continue;
2105 }
2106
Lloyd Pique715a2c12017-12-14 17:18:08 -08002107 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002108
2109 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002110 ALOGV("Creating built in display %d", displayType);
2111 ALOGW_IF(mBuiltinDisplays[displayType],
2112 "Overwriting display token for display type %d", displayType);
2113 mBuiltinDisplays[displayType] = new BBinder();
2114 // All non-virtual displays are currently considered secure.
2115 DisplayDeviceState info(displayType, true);
2116 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2117 "Built-in Screen" : "External Screen";
2118 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2119 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002120 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002121 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002122
Lloyd Piquefcd86612017-12-14 17:15:36 -08002123 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2124 if (idx >= 0) {
2125 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2126 mInterceptor.saveDisplayDeletion(info.displayId);
2127 mCurrentState.displays.removeItemsAt(idx);
2128 }
2129 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002130 }
2131
2132 processDisplayChangesLocked();
2133 }
2134
2135 mPendingHotplugEvents.clear();
2136}
2137
Lloyd Pique347200f2017-12-14 17:00:15 -08002138void SurfaceFlinger::processDisplayChangesLocked() {
2139 // here we take advantage of Vector's copy-on-write semantics to
2140 // improve performance by skipping the transaction entirely when
2141 // know that the lists are identical
2142 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2143 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2144 if (!curr.isIdenticalTo(draw)) {
2145 mVisibleRegionsDirty = true;
2146 const size_t cc = curr.size();
2147 size_t dc = draw.size();
2148
2149 // find the displays that were removed
2150 // (ie: in drawing state but not in current state)
2151 // also handle displays that changed
2152 // (ie: displays that are in both lists)
2153 for (size_t i = 0; i < dc;) {
2154 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2155 if (j < 0) {
2156 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002157 // Call makeCurrent() on the primary display so we can
2158 // be sure that nothing associated with this display
2159 // is current.
2160 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2161 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2162 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2163 if (hw != nullptr) hw->disconnect(getHwComposer());
2164 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2165 mEventThread->onHotplugReceived(draw[i].type, false);
2166 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002167 } else {
2168 // this display is in both lists. see if something changed.
2169 const DisplayDeviceState& state(curr[j]);
2170 const wp<IBinder>& display(curr.keyAt(j));
2171 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2172 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2173 if (state_binder != draw_binder) {
2174 // changing the surface is like destroying and
2175 // recreating the DisplayDevice, so we just remove it
2176 // from the drawing state, so that it get re-added
2177 // below.
2178 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2179 if (hw != nullptr) hw->disconnect(getHwComposer());
2180 mDisplays.removeItem(display);
2181 mDrawingState.displays.removeItemsAt(i);
2182 dc--;
2183 // at this point we must loop to the next item
2184 continue;
2185 }
2186
2187 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2188 if (disp != nullptr) {
2189 if (state.layerStack != draw[i].layerStack) {
2190 disp->setLayerStack(state.layerStack);
2191 }
2192 if ((state.orientation != draw[i].orientation) ||
2193 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2194 disp->setProjection(state.orientation, state.viewport, state.frame);
2195 }
2196 if (state.width != draw[i].width || state.height != draw[i].height) {
2197 disp->setDisplaySize(state.width, state.height);
2198 }
2199 }
2200 }
2201 ++i;
2202 }
2203
2204 // find displays that were added
2205 // (ie: in current state but not in drawing state)
2206 for (size_t i = 0; i < cc; i++) {
2207 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2208 const DisplayDeviceState& state(curr[i]);
2209
2210 sp<DisplaySurface> dispSurface;
2211 sp<IGraphicBufferProducer> producer;
2212 sp<IGraphicBufferProducer> bqProducer;
2213 sp<IGraphicBufferConsumer> bqConsumer;
2214 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2215
2216 int32_t hwcId = -1;
2217 if (state.isVirtualDisplay()) {
2218 // Virtual displays without a surface are dormant:
2219 // they have external state (layer stack, projection,
2220 // etc.) but no internal state (i.e. a DisplayDevice).
2221 if (state.surface != nullptr) {
2222 // Allow VR composer to use virtual displays.
2223 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2224 int width = 0;
2225 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2226 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2227 int height = 0;
2228 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2229 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2230 int intFormat = 0;
2231 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2232 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2233 auto format = static_cast<android_pixel_format_t>(intFormat);
2234
2235 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2236 }
2237
2238 // TODO: Plumb requested format back up to consumer
2239
2240 sp<VirtualDisplaySurface> vds =
2241 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2242 bqProducer, bqConsumer,
2243 state.displayName);
2244
2245 dispSurface = vds;
2246 producer = vds;
2247 }
2248 } else {
2249 ALOGE_IF(state.surface != nullptr,
2250 "adding a supported display, but rendering "
2251 "surface is provided (%p), ignoring it",
2252 state.surface.get());
2253
2254 hwcId = state.type;
2255 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2256 producer = bqProducer;
2257 }
2258
2259 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002260
Lloyd Pique347200f2017-12-14 17:00:15 -08002261 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002262 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002263 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002264 bool hasWideColorModes = false;
2265 std::vector<android_color_mode_t> modes =
2266 getHwComposer().getColorModes(state.type);
2267 for (android_color_mode_t colorMode : modes) {
2268 switch (colorMode) {
2269 case HAL_COLOR_MODE_DISPLAY_P3:
2270 case HAL_COLOR_MODE_ADOBE_RGB:
2271 case HAL_COLOR_MODE_DCI_P3:
2272 hasWideColorModes = true;
2273 break;
2274 default:
2275 break;
2276 }
2277 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002278 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002279 }
2280
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002281 bool hasHdrSupport = false;
2282 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2283 getHwComposer().getHdrCapabilities(state.type);
2284 if (hdrCapabilities) {
2285 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2286 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2287 hasHdrSupport = iter != types.cend();
2288 }
2289
Lloyd Pique347200f2017-12-14 17:00:15 -08002290 sp<DisplayDevice> hw =
2291 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002292 dispSurface, producer, useWideColorMode,
2293 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002294
Lloyd Piquec5208312018-01-08 17:59:02 -08002295 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2296 if (useWideColorMode) {
2297 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002298 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002299 setActiveColorModeInternal(hw, defaultColorMode);
2300 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002301 hw->setLayerStack(state.layerStack);
2302 hw->setProjection(state.orientation, state.viewport, state.frame);
2303 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002304
Lloyd Pique347200f2017-12-14 17:00:15 -08002305 mDisplays.add(display, hw);
2306 if (!state.isVirtualDisplay()) {
2307 mEventThread->onHotplugReceived(state.type, true);
2308 }
2309 }
2310 }
2311 }
2312 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002313
2314 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002315}
2316
Mathias Agopian87baae12012-07-31 12:38:26 -07002317void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002318{
Dan Stoza7dde5992015-05-22 09:51:44 -07002319 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002320 mCurrentState.traverseInZOrder([](Layer* layer) {
2321 layer->notifyAvailableFrames();
2322 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324 /*
2325 * Traversal of the children
2326 * (perform the transaction for each of them if needed)
2327 */
2328
Mathias Agopian3559b072012-08-15 13:46:03 -07002329 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002330 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002332 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333
2334 const uint32_t flags = layer->doTransaction(0);
2335 if (flags & Layer::eVisibleRegion)
2336 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002337 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 }
2339
2340 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002341 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 */
2343
Mathias Agopiane57f2922012-08-09 16:29:12 -07002344 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002345 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002346 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348
Mathias Agopian84300952012-11-21 16:02:13 -08002349 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2350 // The transform hint might have changed for some layers
2351 // (either because a display has changed, or because a layer
2352 // as changed).
2353 //
2354 // Walk through all the layers in currentLayers,
2355 // and update their transform hint.
2356 //
2357 // If a layer is visible only on a single display, then that
2358 // display is used to calculate the hint, otherwise we use the
2359 // default display.
2360 //
2361 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2362 // the hint is set before we acquire a buffer from the surface texture.
2363 //
2364 // NOTE: layer transactions have taken place already, so we use their
2365 // drawing state. However, SurfaceFlinger's own transaction has not
2366 // happened yet, so we must use the current state layer list
2367 // (soon to become the drawing state list).
2368 //
2369 sp<const DisplayDevice> disp;
2370 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002371 bool first = true;
2372 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002373 // NOTE: we rely on the fact that layers are sorted by
2374 // layerStack first (so we don't have to traverse the list
2375 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002376 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002377 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002378 currentlayerStack = layerStack;
2379 // figure out if this layerstack is mirrored
2380 // (more than one display) if so, pick the default display,
2381 // if not, pick the only display it's on.
2382 disp.clear();
2383 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2384 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002385 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002386 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002387 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002388 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002389 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002390 break;
2391 }
2392 }
2393 }
2394 }
Chet Haase91d25932013-04-11 15:24:55 -07002395
Robert Carr56a0b9a2017-12-04 16:06:13 -08002396 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002397 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002398 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2399 // redraw after transform hint changes. See bug 8508397.
2400
2401 // could be null when this layer is using a layerStack
2402 // that is not visible on any display. Also can occur at
2403 // screen off/on times.
2404 disp = getDefaultDisplayDeviceLocked();
2405 }
2406 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002407 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002408 if (disp != nullptr) {
2409 layer->updateTransformHint(disp);
2410 }
Robert Carr2047fae2016-11-28 14:09:09 -08002411
2412 first = false;
2413 });
Mathias Agopian84300952012-11-21 16:02:13 -08002414 }
2415
2416
Mathias Agopian3559b072012-08-15 13:46:03 -07002417 /*
2418 * Perform our own transaction if needed
2419 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002420
2421 if (mLayersAdded) {
2422 mLayersAdded = false;
2423 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002424 mVisibleRegionsDirty = true;
2425 }
2426
2427 // some layers might have been removed, so
2428 // we need to update the regions they're exposing.
2429 if (mLayersRemoved) {
2430 mLayersRemoved = false;
2431 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002432 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002433 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002434 // this layer is not visible anymore
2435 // TODO: we could traverse the tree from front to back and
2436 // compute the actual visible region
2437 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002438 Region visibleReg;
2439 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002440 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002441 }
Robert Carr2047fae2016-11-28 14:09:09 -08002442 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 }
2444
2445 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002446
2447 updateCursorAsync();
2448}
2449
2450void SurfaceFlinger::updateCursorAsync()
2451{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002452 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2453 auto& displayDevice = mDisplays[displayId];
2454 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002455 continue;
2456 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457
2458 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2459 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002460 }
2461 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462}
2463
2464void SurfaceFlinger::commitTransaction()
2465{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002466 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002467 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002468 for (const auto& l : mLayersPendingRemoval) {
2469 recordBufferingStats(l->getName().string(),
2470 l->getOccupancyHistory(true));
2471 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002472 }
2473 mLayersPendingRemoval.clear();
2474 }
2475
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002476 // If this transaction is part of a window animation then the next frame
2477 // we composite should be considered an animation as well.
2478 mAnimCompositionPending = mAnimTransactionPending;
2479
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002481 mDrawingState.traverseInZOrder([](Layer* layer) {
2482 layer->commitChildList();
2483 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002484 mTransactionPending = false;
2485 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002486 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487}
2488
Chia-I Wuab0c3192017-08-01 11:29:00 -07002489void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002490 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491{
Mathias Agopian841cde52012-03-01 15:44:37 -08002492 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002493 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002494
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 Region aboveOpaqueLayers;
2496 Region aboveCoveredLayers;
2497 Region dirty;
2498
Mathias Agopian87baae12012-07-31 12:38:26 -07002499 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500
Robert Carr2047fae2016-11-28 14:09:09 -08002501 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002503 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
Jesse Hall01e29052013-02-19 16:13:35 -08002505 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002506 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002507 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002508
Mathias Agopianab028732010-03-16 16:41:46 -07002509 /*
2510 * opaqueRegion: area of a surface that is fully opaque.
2511 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002513
2514 /*
2515 * visibleRegion: area of a surface that is visible on screen
2516 * and not fully transparent. This is essentially the layer's
2517 * footprint minus the opaque regions above it.
2518 * Areas covered by a translucent surface are considered visible.
2519 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002521
2522 /*
2523 * coveredRegion: area of a surface that is covered by all
2524 * visible regions above it (which includes the translucent areas).
2525 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002527
Jesse Halla8026d22012-09-25 13:25:04 -07002528 /*
2529 * transparentRegion: area of a surface that is hinted to be completely
2530 * transparent. This is only used to tell when the layer has no visible
2531 * non-transparent regions and can be removed from the layer list. It
2532 * does not affect the visibleRegion of this layer or any layers
2533 * beneath it. The hint may not be correct if apps don't respect the
2534 * SurfaceView restrictions (which, sadly, some don't).
2535 */
2536 Region transparentRegion;
2537
Mathias Agopianab028732010-03-16 16:41:46 -07002538
2539 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002540 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002541 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002542 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002545 if (!visibleRegion.isEmpty()) {
2546 // Remove the transparent area from the visible region
2547 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002548 if (tr.preserveRects()) {
2549 // transform the transparent region
2550 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002551 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002552 // transformation too complex, can't do the
2553 // transparent region optimization.
2554 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002555 }
Mathias Agopianab028732010-03-16 16:41:46 -07002556 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557
Mathias Agopianab028732010-03-16 16:41:46 -07002558 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002559 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002560 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002561 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2562 // the opaque region is the layer's footprint
2563 opaqueRegion = visibleRegion;
2564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 }
2566 }
2567
Robert Carre5f4f692018-01-12 13:12:28 -08002568 if (visibleRegion.isEmpty()) {
2569 layer->clearVisibilityRegions();
2570 return;
2571 }
2572
Mathias Agopianab028732010-03-16 16:41:46 -07002573 // Clip the covered region to the visible region
2574 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2575
2576 // Update aboveCoveredLayers for next (lower) layer
2577 aboveCoveredLayers.orSelf(visibleRegion);
2578
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 // subtract the opaque region covered by the layers above us
2580 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581
2582 // compute this layer's dirty region
2583 if (layer->contentDirty) {
2584 // we need to invalidate the whole region
2585 dirty = visibleRegion;
2586 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002587 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 layer->contentDirty = false;
2589 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002590 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002591 * the exposed region consists of two components:
2592 * 1) what's VISIBLE now and was COVERED before
2593 * 2) what's EXPOSED now less what was EXPOSED before
2594 *
2595 * note that (1) is conservative, we start with the whole
2596 * visible region but only keep what used to be covered by
2597 * something -- which mean it may have been exposed.
2598 *
2599 * (2) handles areas that were not covered by anything but got
2600 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002601 */
Mathias Agopianab028732010-03-16 16:41:46 -07002602 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603 const Region oldVisibleRegion = layer->visibleRegion;
2604 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002605 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2606 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607 }
2608 dirty.subtractSelf(aboveOpaqueLayers);
2609
2610 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002611 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612
Mathias Agopianab028732010-03-16 16:41:46 -07002613 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002615
Jesse Halla8026d22012-09-25 13:25:04 -07002616 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617 layer->setVisibleRegion(visibleRegion);
2618 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002619 layer->setVisibleNonTransparentRegion(
2620 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002621 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622
Mathias Agopian87baae12012-07-31 12:38:26 -07002623 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624}
2625
Chia-I Wuab0c3192017-08-01 11:29:00 -07002626void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002627 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002628 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002629 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002630 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002631 }
2632 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002633}
2634
Dan Stoza6b9454d2014-11-07 16:00:59 -08002635bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002637 ALOGV("handlePageFlip");
2638
Brian Andersond6927fb2016-07-23 23:37:30 -07002639 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640
Mathias Agopian4fec8732012-06-29 14:12:52 -07002641 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002642 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002643 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002644
2645 // Store the set of layers that need updates. This set must not change as
2646 // buffers are being latched, as this could result in a deadlock.
2647 // Example: Two producers share the same command stream and:
2648 // 1.) Layer 0 is latched
2649 // 2.) Layer 0 gets a new frame
2650 // 2.) Layer 1 gets a new frame
2651 // 3.) Layer 1 is latched.
2652 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2653 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002654 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002655 if (layer->hasQueuedFrame()) {
2656 frameQueued = true;
2657 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002658 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002659 } else {
2660 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002661 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002662 } else {
2663 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002664 }
Robert Carr2047fae2016-11-28 14:09:09 -08002665 });
2666
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002668 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002669 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002670 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002671 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002672 newDataLatched = true;
2673 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002674 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002675
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002676 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002677
2678 // If we will need to wake up at some time in the future to deal with a
2679 // queued frame that shouldn't be displayed during this vsync period, wake
2680 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002681 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002682 signalLayerUpdate();
2683 }
2684
2685 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002686 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687}
2688
Mathias Agopianad456f92011-01-13 17:53:01 -08002689void SurfaceFlinger::invalidateHwcGeometry()
2690{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002691 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002692}
2693
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002694
Fabien Sanglard830b8472016-11-30 16:35:58 -08002695void SurfaceFlinger::doDisplayComposition(
2696 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002697 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698{
Dan Stoza71433162014-02-04 16:22:36 -08002699 // We only need to actually compose the display if:
2700 // 1) It is being handled by hardware composer, which may need this to
2701 // keep its virtual display state machine in sync, or
2702 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002703 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002704 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002706 return;
2707 }
2708
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002710 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002711
2712 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002713 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714}
2715
Chia-I Wub02087d2017-11-09 10:19:54 -08002716bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002717{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002719
Chia-I Wub02087d2017-11-09 10:19:54 -08002720 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002721 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002722 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002723
2724 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002725 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2726 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002727 if (applyColorMatrix) {
2728 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2729 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2730 }
2731
David Sodman105b7dc2017-11-04 20:28:14 -07002732 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 if (hasClientComposition) {
2734 ALOGV("hasClientComposition");
2735
David Sodmanbc815282017-11-05 18:57:52 -08002736 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002737 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002738 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002739 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002740 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002741 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002743 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002744
2745 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002746 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002747 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2748 }
2749 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002750 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002751
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002752 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002753 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002755 // when using overlays, we assume a fully transparent framebuffer
2756 // NOTE: we could reduce how much we need to clear, for instance
2757 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002758 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002759 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002760 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002761 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002762 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002763 // we're left with the letterbox region
2764 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002766
2767 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002769
Mathias Agopianb9494d52012-04-18 02:28:45 -07002770 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002771 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002772 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002774 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002775 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002776
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002778 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002779 // scissor on the main display. It should never be needed
2780 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 const Rect& bounds(displayDevice->getBounds());
2782 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002783 if (scissor != bounds) {
2784 // scissor doesn't match the screen's dimensions, so we
2785 // need to clear everything outside of it and enable
2786 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002787
Mathias Agopianf45c5102012-10-24 16:29:17 -07002788 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002790 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002791 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002792 }
2793 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002794 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002795
Mathias Agopian85d751c2012-08-29 16:59:24 -07002796 /*
2797 * and then, render the layers targeted at the framebuffer
2798 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002799
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 ALOGV("Rendering client layers");
2801 const Transform& displayTransform = displayDevice->getTransform();
2802 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002803 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 bool firstLayer = true;
2805 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002806 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 displayTransform.transform(layer->visibleRegion)));
2808 ALOGV("Layer: %s", layer->getName().string());
2809 ALOGV(" Composition type: %s",
2810 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002811 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 switch (layer->getCompositionType(hwcId)) {
2813 case HWC2::Composition::Cursor:
2814 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002815 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002817 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002819 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002821 // never clear the very first layer since we're
2822 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002823 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002824 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002825 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002826 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002828 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002829 break;
2830 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002832 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002833 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 } else {
2835 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002836 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002837 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002838 }
2839 } else {
2840 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002842 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002843 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002844 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002845 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002846 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002847 }
2848 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002849
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002850 if (applyColorMatrix) {
2851 getRenderEngine().setupColorTransform(oldColorMatrix);
2852 }
2853
Mathias Agopianf45c5102012-10-24 16:29:17 -07002854 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002855 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002856 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857}
2858
Fabien Sanglard830b8472016-11-30 16:35:58 -08002859void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2860 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002861 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002862 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863}
2864
Dan Stoza7d89d062015-04-30 13:29:25 -07002865status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002866 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002867 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 const sp<Layer>& lbc,
2869 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002870{
Dan Stoza7d89d062015-04-30 13:29:25 -07002871 // add this layer to the current state list
2872 {
2873 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002874 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002875 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2876 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002877 return NO_MEMORY;
2878 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002879 if (parent == nullptr) {
2880 mCurrentState.layersSortedByZ.add(lbc);
2881 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002882 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002883 ALOGE("addClientLayer called with a removed parent");
2884 return NAME_NOT_FOUND;
2885 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 parent->addChild(lbc);
2887 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002888
Dan Stoza7d89d062015-04-30 13:29:25 -07002889 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890 mLayersAdded = true;
2891 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002892 }
2893
Mathias Agopian96f08192010-06-02 23:28:45 -07002894 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002895 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002896
Dan Stoza7d89d062015-04-30 13:29:25 -07002897 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002898}
2899
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002900status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002901 Mutex::Autolock _l(mStateLock);
2902
chaviw8b3871a2017-11-01 17:41:01 -07002903 if (layer->isPendingRemoval()) {
2904 return NO_ERROR;
2905 }
2906
Robert Carr1f0a16a2016-10-24 16:27:39 -07002907 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002908 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002909 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002910 if (topLevelOnly) {
2911 return NO_ERROR;
2912 }
2913
Chia-I Wu98f1c102017-05-30 14:54:08 -07002914 sp<Layer> ancestor = p;
2915 while (ancestor->getParent() != nullptr) {
2916 ancestor = ancestor->getParent();
2917 }
2918 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2919 ALOGE("removeLayer called with a layer whose parent has been removed");
2920 return NAME_NOT_FOUND;
2921 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002922
2923 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002924 } else {
2925 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002926 }
2927
Robert Carr136e2f62017-02-08 17:54:29 -08002928 // As a matter of normal operation, the LayerCleaner will produce a second
2929 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2930 // so we will succeed in promoting it, but it's already been removed
2931 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2932 // otherwise something has gone wrong and we are leaking the layer.
2933 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002934 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2935 layer->getName().string(),
2936 (p != nullptr) ? p->getName().string() : "no-parent");
2937 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002938 } else if (index < 0) {
2939 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002940 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941
Chia-I Wuc6657022017-08-15 11:18:17 -07002942 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002943 mLayersPendingRemoval.add(layer);
2944 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002945 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002946 setTransactionFlags(eTransactionNeeded);
2947 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948}
2949
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002950uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002951 return android_atomic_release_load(&mTransactionFlags);
2952}
2953
Mathias Agopian3f844832013-08-07 21:24:32 -07002954uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2956}
2957
Mathias Agopian3f844832013-08-07 21:24:32 -07002958uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2960 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002961 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962 }
2963 return old;
2964}
2965
Mathias Agopian8b33f032012-07-24 20:43:54 -07002966void SurfaceFlinger::setTransactionState(
2967 const Vector<ComposerState>& state,
2968 const Vector<DisplayState>& displays,
2969 uint32_t flags)
2970{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002971 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002972 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002973 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002974
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002975 if (flags & eAnimation) {
2976 // For window updates that are part of an animation we must wait for
2977 // previous animation "frames" to be handled.
2978 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002979 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002980 if (CC_UNLIKELY(err != NO_ERROR)) {
2981 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002982 // caller after a few seconds.
2983 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2984 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002985 mAnimTransactionPending = false;
2986 break;
2987 }
2988 }
2989 }
2990
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 size_t count = displays.size();
2992 for (size_t i=0 ; i<count ; i++) {
2993 const DisplayState& s(displays[i]);
2994 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002995 }
2996
Mathias Agopiane57f2922012-08-09 16:29:12 -07002997 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002998 for (size_t i=0 ; i<count ; i++) {
2999 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003000 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08003001 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003002 // IInterface, or one of its own or even one of our own but a
3003 // different type. All these situations would cause us to crash.
3004 //
3005 // NOTE: it would be better to use RTTI as we could directly check
3006 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08003007 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003008 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08003009 if (binder != nullptr) {
3010 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003011 sp<Client> client( static_cast<Client *>(s.client.get()) );
3012 transactionFlags |= setClientStateLocked(client, s.state);
3013 }
3014 }
3015 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003016 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003017
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003018 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3019 // anyway. This can be used as a flush mechanism for previous async transactions.
3020 // Empty animation transaction can be used to simulate back-pressure, so also force a
3021 // transaction for empty animation transactions.
3022 if (transactionFlags == 0 &&
3023 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003024 transactionFlags = eTransactionNeeded;
3025 }
3026
Mathias Agopian386aa982011-11-07 21:58:03 -08003027 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003028 if (mInterceptor.isEnabled()) {
3029 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3030 }
Irvel468051e2016-06-13 16:44:44 -07003031
Mathias Agopian386aa982011-11-07 21:58:03 -08003032 // this triggers the transaction
3033 setTransactionFlags(transactionFlags);
3034
3035 // if this is a synchronous transaction, wait for it to take effect
3036 // before returning.
3037 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003038 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003039 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003040 if (flags & eAnimation) {
3041 mAnimTransactionPending = true;
3042 }
3043 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003044 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3045 if (CC_UNLIKELY(err != NO_ERROR)) {
3046 // just in case something goes wrong in SF, return to the
3047 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003048 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3049 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003050 break;
3051 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053 }
3054}
3055
Mathias Agopiane57f2922012-08-09 16:29:12 -07003056uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3057{
Jesse Hall9a143922012-10-04 16:29:19 -07003058 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3059 if (dpyIdx < 0)
3060 return 0;
3061
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003063 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003064 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003065 const uint32_t what = s.what;
3066 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003067 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003068 disp.surface = s.surface;
3069 flags |= eDisplayTransactionNeeded;
3070 }
3071 }
3072 if (what & DisplayState::eLayerStackChanged) {
3073 if (disp.layerStack != s.layerStack) {
3074 disp.layerStack = s.layerStack;
3075 flags |= eDisplayTransactionNeeded;
3076 }
3077 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003078 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003079 if (disp.orientation != s.orientation) {
3080 disp.orientation = s.orientation;
3081 flags |= eDisplayTransactionNeeded;
3082 }
3083 if (disp.frame != s.frame) {
3084 disp.frame = s.frame;
3085 flags |= eDisplayTransactionNeeded;
3086 }
3087 if (disp.viewport != s.viewport) {
3088 disp.viewport = s.viewport;
3089 flags |= eDisplayTransactionNeeded;
3090 }
3091 }
Michael Lentine47e45402014-07-18 15:34:25 -07003092 if (what & DisplayState::eDisplaySizeChanged) {
3093 if (disp.width != s.width) {
3094 disp.width = s.width;
3095 flags |= eDisplayTransactionNeeded;
3096 }
3097 if (disp.height != s.height) {
3098 disp.height = s.height;
3099 flags |= eDisplayTransactionNeeded;
3100 }
3101 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 }
3103 return flags;
3104}
3105
3106uint32_t SurfaceFlinger::setClientStateLocked(
3107 const sp<Client>& client,
3108 const layer_state_t& s)
3109{
Mathias Agopian13127d82013-03-05 17:47:11 -08003110 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003111 if (layer == nullptr) {
3112 return 0;
3113 }
3114
3115 if (layer->isPendingRemoval()) {
3116 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3117 return 0;
3118 }
3119
3120 uint32_t flags = 0;
3121
3122 const uint32_t what = s.what;
3123 bool geometryAppliesWithResize =
3124 what & layer_state_t::eGeometryAppliesWithResize;
3125 if (what & layer_state_t::ePositionChanged) {
3126 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3127 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003128 }
chaviw8b3871a2017-11-01 17:41:01 -07003129 }
3130 if (what & layer_state_t::eLayerChanged) {
3131 // NOTE: index needs to be calculated before we update the state
3132 const auto& p = layer->getParent();
3133 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003134 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003135 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003136 mCurrentState.layersSortedByZ.removeAt(idx);
3137 mCurrentState.layersSortedByZ.add(layer);
3138 // we need traversal (state changed)
3139 // AND transaction (list changed)
3140 flags |= eTransactionNeeded|eTraversalNeeded;
3141 }
chaviw8b3871a2017-11-01 17:41:01 -07003142 } else {
3143 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003144 flags |= eTransactionNeeded|eTraversalNeeded;
3145 }
3146 }
chaviw8b3871a2017-11-01 17:41:01 -07003147 }
3148 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003149 // NOTE: index needs to be calculated before we update the state
3150 const auto& p = layer->getParent();
3151 if (p == nullptr) {
3152 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3153 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3154 mCurrentState.layersSortedByZ.removeAt(idx);
3155 mCurrentState.layersSortedByZ.add(layer);
3156 // we need traversal (state changed)
3157 // AND transaction (list changed)
3158 flags |= eTransactionNeeded|eTraversalNeeded;
3159 }
3160 } else {
3161 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3162 flags |= eTransactionNeeded|eTraversalNeeded;
3163 }
chaviw8b3871a2017-11-01 17:41:01 -07003164 }
3165 }
3166 if (what & layer_state_t::eSizeChanged) {
3167 if (layer->setSize(s.w, s.h)) {
3168 flags |= eTraversalNeeded;
3169 }
3170 }
3171 if (what & layer_state_t::eAlphaChanged) {
3172 if (layer->setAlpha(s.alpha))
3173 flags |= eTraversalNeeded;
3174 }
3175 if (what & layer_state_t::eColorChanged) {
3176 if (layer->setColor(s.color))
3177 flags |= eTraversalNeeded;
3178 }
3179 if (what & layer_state_t::eMatrixChanged) {
3180 if (layer->setMatrix(s.matrix))
3181 flags |= eTraversalNeeded;
3182 }
3183 if (what & layer_state_t::eTransparentRegionChanged) {
3184 if (layer->setTransparentRegionHint(s.transparentRegion))
3185 flags |= eTraversalNeeded;
3186 }
3187 if (what & layer_state_t::eFlagsChanged) {
3188 if (layer->setFlags(s.flags, s.mask))
3189 flags |= eTraversalNeeded;
3190 }
3191 if (what & layer_state_t::eCropChanged) {
3192 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3193 flags |= eTraversalNeeded;
3194 }
3195 if (what & layer_state_t::eFinalCropChanged) {
3196 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3197 flags |= eTraversalNeeded;
3198 }
3199 if (what & layer_state_t::eLayerStackChanged) {
3200 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3201 // We only allow setting layer stacks for top level layers,
3202 // everything else inherits layer stack from its parent.
3203 if (layer->hasParent()) {
3204 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3205 layer->getName().string());
3206 } else if (idx < 0) {
3207 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3208 "that also does not appear in the top level layer list. Something"
3209 " has gone wrong.", layer->getName().string());
3210 } else if (layer->setLayerStack(s.layerStack)) {
3211 mCurrentState.layersSortedByZ.removeAt(idx);
3212 mCurrentState.layersSortedByZ.add(layer);
3213 // we need traversal (state changed)
3214 // AND transaction (list changed)
3215 flags |= eTransactionNeeded|eTraversalNeeded;
3216 }
3217 }
3218 if (what & layer_state_t::eDeferTransaction) {
3219 if (s.barrierHandle != nullptr) {
3220 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3221 } else if (s.barrierGbp != nullptr) {
3222 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3223 if (authenticateSurfaceTextureLocked(gbp)) {
3224 const auto& otherLayer =
3225 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3226 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3227 } else {
3228 ALOGE("Attempt to defer transaction to to an"
3229 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003230 }
3231 }
chaviw8b3871a2017-11-01 17:41:01 -07003232 // We don't trigger a traversal here because if no other state is
3233 // changed, we don't want this to cause any more work
3234 }
3235 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003236 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003237 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003238 if (!hadParent) {
3239 mCurrentState.layersSortedByZ.remove(layer);
3240 }
chaviw8b3871a2017-11-01 17:41:01 -07003241 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003242 }
chaviw8b3871a2017-11-01 17:41:01 -07003243 }
3244 if (what & layer_state_t::eReparentChildren) {
3245 if (layer->reparentChildren(s.reparentHandle)) {
3246 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003247 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003248 }
chaviw8b3871a2017-11-01 17:41:01 -07003249 if (what & layer_state_t::eDetachChildren) {
3250 layer->detachChildren();
3251 }
3252 if (what & layer_state_t::eOverrideScalingModeChanged) {
3253 layer->setOverrideScalingMode(s.overrideScalingMode);
3254 // We don't trigger a traversal here because if no other state is
3255 // changed, we don't want this to cause any more work
3256 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003257 return flags;
3258}
3259
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003260status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003261 const String8& name,
3262 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003263 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003264 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3265 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003267 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003268 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003269 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003270 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003271 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003272
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003273 status_t result = NO_ERROR;
3274
3275 sp<Layer> layer;
3276
Cody Northropbc755282017-03-31 12:00:08 -06003277 String8 uniqueName = getUniqueLayerName(name);
3278
Mathias Agopian3165cc22012-08-08 19:42:09 -07003279 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3280 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003281 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003282 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003283 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003285 break;
chaviw13fdc492017-06-27 12:40:18 -07003286 case ISurfaceComposerClient::eFXSurfaceColor:
3287 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003288 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003289 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003290 break;
3291 default:
3292 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293 break;
3294 }
3295
Dan Stoza7d89d062015-04-30 13:29:25 -07003296 if (result != NO_ERROR) {
3297 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003299
Chia-I Wuab0c3192017-08-01 11:29:00 -07003300 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3301 // TODO b/64227542
3302 if (windowType == 441731) {
3303 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3304 layer->setPrimaryDisplayOnly();
3305 }
3306
Albert Chaulk479c60c2017-01-27 14:21:34 -05003307 layer->setInfo(windowType, ownerUid);
3308
Robert Carr1f0a16a2016-10-24 16:27:39 -07003309 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003310 if (result != NO_ERROR) {
3311 return result;
3312 }
Irvelffc9efc2016-07-27 15:16:37 -07003313 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003314
3315 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003316 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003317}
3318
Cody Northropbc755282017-03-31 12:00:08 -06003319String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3320{
3321 bool matchFound = true;
3322 uint32_t dupeCounter = 0;
3323
3324 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3325 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3326
3327 // Loop over layers until we're sure there is no matching name
3328 while (matchFound) {
3329 matchFound = false;
3330 mDrawingState.traverseInZOrder([&](Layer* layer) {
3331 if (layer->getName() == uniqueName) {
3332 matchFound = true;
3333 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3334 }
3335 });
3336 }
3337
3338 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3339
3340 return uniqueName;
3341}
3342
David Sodman0c69cad2017-08-21 12:12:51 -07003343status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003344 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3345 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346{
3347 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003348 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349 case PIXEL_FORMAT_TRANSPARENT:
3350 case PIXEL_FORMAT_TRANSLUCENT:
3351 format = PIXEL_FORMAT_RGBA_8888;
3352 break;
3353 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003354 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 break;
3356 }
3357
David Sodman0c69cad2017-08-21 12:12:51 -07003358 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3359 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003360 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003361 *handle = layer->getHandle();
3362 *gbp = layer->getProducer();
3363 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003365
David Sodman0c69cad2017-08-21 12:12:51 -07003366 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003367 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003368}
3369
chaviw13fdc492017-06-27 12:40:18 -07003370status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003371 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003372 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373{
chaviw13fdc492017-06-27 12:40:18 -07003374 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003375 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003376 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003377}
3378
Mathias Agopianac9fa422013-02-11 16:40:36 -08003379status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003380{
Robert Carr9524cb32017-02-13 11:32:32 -08003381 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003382 status_t err = NO_ERROR;
3383 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003384 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003385 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003386 err = removeLayer(l);
3387 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3388 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003389 }
3390 return err;
3391}
3392
Mathias Agopian13127d82013-03-05 17:47:11 -08003393status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003394{
Mathias Agopian67106042013-03-14 19:18:13 -07003395 // called by ~LayerCleaner() when all references to the IBinder (handle)
3396 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003397 sp<Layer> l = layer.promote();
3398 if (l == nullptr) {
3399 // The layer has already been removed, carry on
3400 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003401 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003402 // If we have a parent, then we can continue to live as long as it does.
3403 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003404}
3405
Mathias Agopianb60314a2012-04-10 22:09:54 -07003406// ---------------------------------------------------------------------------
3407
Andy McFadden13a082e2012-08-24 10:16:42 -07003408void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003409 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003410 Vector<ComposerState> state;
3411 Vector<DisplayState> displays;
3412 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003413 d.what = DisplayState::eDisplayProjectionChanged |
3414 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003415 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003416 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003417 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003418 d.frame.makeInvalid();
3419 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003420 d.width = 0;
3421 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003422 displays.add(d);
3423 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003424 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3425 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003426
David Sodman105b7dc2017-11-04 20:28:14 -07003427 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003428 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003429 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003430
Brian Andersond0010582017-03-07 13:20:31 -08003431 // Use phase of 0 since phase is not known.
3432 // Use latency of 0, which will snap to the ideal latency.
3433 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003434}
3435
3436void SurfaceFlinger::initializeDisplays() {
3437 class MessageScreenInitialized : public MessageBase {
3438 SurfaceFlinger* flinger;
3439 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003440 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003441 virtual bool handler() {
3442 flinger->onInitializeDisplays();
3443 return true;
3444 }
3445 };
3446 sp<MessageBase> msg = new MessageScreenInitialized(this);
3447 postMessageAsync(msg); // we may be called from main thread, use async message
3448}
3449
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003450void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003451 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003452 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3453 this);
3454 int32_t type = hw->getDisplayType();
3455 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003456
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003457 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003458 return;
3459 }
3460
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003461 hw->setPowerMode(mode);
3462 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3463 ALOGW("Trying to set power mode for virtual display");
3464 return;
3465 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003466
Irvelffc9efc2016-07-27 15:16:37 -07003467 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003468 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003469 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3470 if (idx < 0) {
3471 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3472 return;
3473 }
3474 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3475 }
3476
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003477 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003478 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003479 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003480 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3481 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003482 // FIXME: eventthread only knows about the main display right now
3483 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003484 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003485 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003486
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003487 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003488 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003489 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003490
3491 struct sched_param param = {0};
3492 param.sched_priority = 1;
3493 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3494 ALOGW("Couldn't set SCHED_FIFO on display on");
3495 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003496 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003497 // Turn off the display
3498 struct sched_param param = {0};
3499 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3500 ALOGW("Couldn't set SCHED_OTHER on display off");
3501 }
3502
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003503 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3504 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003505 disableHardwareVsync(true); // also cancels any in-progress resync
3506
Mathias Agopiancde87a32012-09-13 14:09:01 -07003507 // FIXME: eventthread only knows about the main display right now
3508 mEventThread->onScreenReleased();
3509 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003510
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003511 getHwComposer().setPowerMode(type, mode);
3512 mVisibleRegionsDirty = true;
3513 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003514 } else if (mode == HWC_POWER_MODE_DOZE ||
3515 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003516 // Update display while dozing
3517 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003518 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3519 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003520 // FIXME: eventthread only knows about the main display right now
3521 mEventThread->onScreenAcquired();
3522 resyncToHardwareVsync(true);
3523 }
3524 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3525 // Leave display going to doze
3526 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3527 disableHardwareVsync(true); // also cancels any in-progress resync
3528 // FIXME: eventthread only knows about the main display right now
3529 mEventThread->onScreenReleased();
3530 }
3531 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003532 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003533 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003534 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003535 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003536}
3537
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003538void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3539 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003540 SurfaceFlinger& mFlinger;
3541 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003542 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003543 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003544 MessageSetPowerMode(SurfaceFlinger& flinger,
3545 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3546 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003547 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003548 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003549 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003550 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003551 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003552 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003553 ALOGW("Attempt to set power mode = %d for virtual display",
3554 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003555 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003556 mFlinger.setPowerModeInternal(
3557 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003558 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003559 return true;
3560 }
3561 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003562 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003563 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003564}
3565
3566// ---------------------------------------------------------------------------
3567
Lloyd Pique755e3192018-01-31 16:46:15 -08003568status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3569 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003571
Mathias Agopianbd115332013-04-18 16:41:04 -07003572 IPCThreadState* ipc = IPCThreadState::self();
3573 const int pid = ipc->getCallingPid();
3574 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003575
Mathias Agopianbd115332013-04-18 16:41:04 -07003576 if ((uid != AID_SHELL) &&
3577 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003578 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003579 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003581 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003582 // (this would indicate SF is stuck, but we want to be able to
3583 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003584 status_t err = mStateLock.timedLock(s2ns(1));
3585 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003586 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003587 result.appendFormat(
3588 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3589 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003590 }
3591
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003592 bool dumpAll = true;
3593 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003594 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003595
3596 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003597 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003598 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3599 dumpAll = false;
3600 }
3601
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003602 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003603 if ((index < numArgs) &&
3604 (args[index] == String16("--list"))) {
3605 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003606 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003607 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003608 }
3609
3610 if ((index < numArgs) &&
3611 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003612 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003613 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003614 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003615 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003616
3617 if ((index < numArgs) &&
3618 (args[index] == String16("--latency-clear"))) {
3619 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003620 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003621 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003622 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003623
3624 if ((index < numArgs) &&
3625 (args[index] == String16("--dispsync"))) {
3626 index++;
3627 mPrimaryDispSync.dump(result);
3628 dumpAll = false;
3629 }
Dan Stozab90cf072015-03-05 11:05:59 -08003630
3631 if ((index < numArgs) &&
3632 (args[index] == String16("--static-screen"))) {
3633 index++;
3634 dumpStaticScreenStats(result);
3635 dumpAll = false;
3636 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003637
3638 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003639 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003640 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003641 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003642 dumpAll = false;
3643 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003644
3645 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3646 index++;
3647 dumpWideColorInfo(result);
3648 dumpAll = false;
3649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003651
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003652 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003653 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003654 }
3655
Mathias Agopian9795c422009-08-26 16:36:26 -07003656 if (locked) {
3657 mStateLock.unlock();
3658 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003659 }
3660 write(fd, result.string(), result.size());
3661 return NO_ERROR;
3662}
3663
Dan Stozac7014012014-02-14 15:03:43 -08003664void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3665 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003666{
Robert Carr2047fae2016-11-28 14:09:09 -08003667 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003668 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003669 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003670}
3671
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003673 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003674{
3675 String8 name;
3676 if (index < args.size()) {
3677 name = String8(args[index]);
3678 index++;
3679 }
3680
David Sodman105b7dc2017-11-04 20:28:14 -07003681 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003682 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003683 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003684
3685 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003686 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003687 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003688 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003689 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003690 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003691 }
Robert Carr2047fae2016-11-28 14:09:09 -08003692 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003693 }
3694}
3695
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003696void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003697 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003698{
3699 String8 name;
3700 if (index < args.size()) {
3701 name = String8(args[index]);
3702 index++;
3703 }
3704
Robert Carr2047fae2016-11-28 14:09:09 -08003705 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003706 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003707 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003708 }
Robert Carr2047fae2016-11-28 14:09:09 -08003709 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003710
Svetoslavd85084b2014-03-20 10:28:31 -07003711 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003712}
3713
Jamie Gennis6547ff42013-07-16 20:12:42 -07003714// This should only be called from the main thread. Otherwise it would need
3715// the lock and should use mCurrentState rather than mDrawingState.
3716void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003717 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003718 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003719 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003720
3721 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3722}
3723
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003724void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003725{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003726 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003727
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003728 if (isLayerTripleBufferingDisabled())
3729 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003730
3731 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003732 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003733 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003734 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003735 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3736 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003737 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003738}
3739
Dan Stozab90cf072015-03-05 11:05:59 -08003740void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3741{
3742 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003743 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3744 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003745 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003746 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003747 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3748 b + 1, bucketTimeSec, percent);
3749 }
David Sodman4a36e932017-11-07 14:29:47 -08003750 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003751 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003752 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003753 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003754 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003755}
3756
Dan Stozae77c7662016-05-13 11:37:28 -07003757void SurfaceFlinger::recordBufferingStats(const char* layerName,
3758 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003759 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3760 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003761 for (const auto& segment : history) {
3762 if (!segment.usedThirdBuffer) {
3763 stats.twoBufferTime += segment.totalTime;
3764 }
3765 if (segment.occupancyAverage < 1.0f) {
3766 stats.doubleBufferedTime += segment.totalTime;
3767 } else if (segment.occupancyAverage < 2.0f) {
3768 stats.tripleBufferedTime += segment.totalTime;
3769 }
3770 ++stats.numSegments;
3771 stats.totalTime += segment.totalTime;
3772 }
3773}
3774
Brian Andersond6927fb2016-07-23 23:37:30 -07003775void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3776 result.appendFormat("Layer frame timestamps:\n");
3777
3778 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3779 const size_t count = currentLayers.size();
3780 for (size_t i=0 ; i<count ; i++) {
3781 currentLayers[i]->dumpFrameEvents(result);
3782 }
3783}
3784
Dan Stozae77c7662016-05-13 11:37:28 -07003785void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3786 result.append("Buffering stats:\n");
3787 result.append(" [Layer name] <Active time> <Two buffer> "
3788 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003789 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003790 typedef std::tuple<std::string, float, float, float> BufferTuple;
3791 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003792 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003793 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003794 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003795 if (stats.numSegments == 0) {
3796 continue;
3797 }
3798 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3799 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3800 stats.totalTime;
3801 float doubleBufferRatio = static_cast<float>(
3802 stats.doubleBufferedTime) / stats.totalTime;
3803 float tripleBufferRatio = static_cast<float>(
3804 stats.tripleBufferedTime) / stats.totalTime;
3805 sorted.insert({activeTime, {name, twoBufferRatio,
3806 doubleBufferRatio, tripleBufferRatio}});
3807 }
3808 for (const auto& sortedPair : sorted) {
3809 float activeTime = sortedPair.first;
3810 const BufferTuple& values = sortedPair.second;
3811 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3812 std::get<0>(values).c_str(), activeTime,
3813 std::get<1>(values), std::get<2>(values),
3814 std::get<3>(values));
3815 }
3816 result.append("\n");
3817}
3818
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003819void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3820 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003821 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003822
3823 // TODO: print out if wide-color mode is active or not
3824
3825 for (size_t d = 0; d < mDisplays.size(); d++) {
3826 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3827 int32_t hwcId = displayDevice->getHwcDisplayId();
3828 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3829 continue;
3830 }
3831
3832 result.appendFormat("Display %d color modes:\n", hwcId);
3833 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3834 for (auto&& mode : modes) {
3835 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3836 }
3837
3838 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3839 result.appendFormat(" Current color mode: %s (%d)\n",
3840 decodeColorMode(currentMode).c_str(), currentMode);
3841 }
3842 result.append("\n");
3843}
3844
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003845LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003846 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003847 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3848 const State& state = useDrawing ? mDrawingState : mCurrentState;
3849 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003850 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003851 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003852 });
3853
3854 return layersProto;
3855}
3856
Mathias Agopian74d211a2013-04-22 16:55:35 +02003857void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3858 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 bool colorize = false;
3861 if (index < args.size()
3862 && (args[index] == String16("--color"))) {
3863 colorize = true;
3864 index++;
3865 }
3866
3867 Colorizer colorizer(colorize);
3868
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003869 // figure out if we're stuck somewhere
3870 const nsecs_t now = systemTime();
3871 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3872 const nsecs_t inTransaction(mDebugInTransaction);
3873 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3874 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3875
3876 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003877 * Dump library configuration.
3878 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003879
3880 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003881 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003882 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003883 appendSfConfigString(result);
3884 appendUiConfigString(result);
3885 appendGuiConfigString(result);
3886 result.append("\n");
3887
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003888 result.append("\nWide-Color information:\n");
3889 dumpWideColorInfo(result);
3890
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003891 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003892 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003893 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003894 result.append(SyncFeatures::getInstance().toString());
3895 result.append("\n");
3896
David Sodman105b7dc2017-11-04 20:28:14 -07003897 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003898
Andy McFadden41d67d72014-04-25 16:58:34 -07003899 colorizer.bold(result);
3900 result.append("DispSync configuration: ");
3901 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003902 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003903 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003904 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003905 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003906 result.append("\n");
3907
Dan Stozab90cf072015-03-05 11:05:59 -08003908 // Dump static screen stats
3909 result.append("\n");
3910 dumpStaticScreenStats(result);
3911 result.append("\n");
3912
Dan Stozae77c7662016-05-13 11:37:28 -07003913 dumpBufferingStats(result);
3914
Andy McFadden4803b742012-09-24 19:07:20 -07003915 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003916 * Dump the visible layer list
3917 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003918 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003919 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003920 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003921
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003922 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003923 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3924 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003925
3926 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003927 * Dump Display state
3928 */
3929
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003930 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003931 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003932 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003933 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3934 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003935 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003936 }
3937
3938 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939 * Dump SurfaceFlinger global state
3940 */
3941
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003942 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003943 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003944 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003945
Mathias Agopian888c8222012-08-04 21:10:38 -07003946 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003947 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003948
David Sodmanbc815282017-11-05 18:57:52 -08003949 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003951 if (hw) {
3952 hw->undefinedRegion.dump(result, "undefinedRegion");
3953 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3954 hw->getOrientation(), hw->isDisplayOn());
3955 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957 " last eglSwapBuffers() time: %f us\n"
3958 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003959 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960 " refresh-rate : %f fps\n"
3961 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003962 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003963 " gpu_to_cpu_unsupported : %d\n"
3964 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965 mLastSwapBufferTime/1000.0,
3966 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003967 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003968 1e9 / activeConfig->getVsyncPeriod(),
3969 activeConfig->getDpiX(),
3970 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003971 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003972
Mathias Agopian74d211a2013-04-22 16:55:35 +02003973 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975
Mathias Agopian74d211a2013-04-22 16:55:35 +02003976 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003977 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003978
3979 /*
3980 * VSYNC state
3981 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003982 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003983 result.append("\n");
3984
3985 /*
3986 * HWC layer minidump
3987 */
3988 for (size_t d = 0; d < mDisplays.size(); d++) {
3989 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3990 int32_t hwcId = displayDevice->getHwcDisplayId();
3991 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3992 continue;
3993 }
3994
3995 result.appendFormat("Display %d HWC layers:\n", hwcId);
3996 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003997 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003998 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003999 });
Dan Stozae22aec72016-08-01 13:20:59 -07004000 result.append("\n");
4001 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004002
4003 /*
4004 * Dump HWComposer state
4005 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004006 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004007 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004008 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004009 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004010 result.appendFormat(" h/w composer %s\n",
4011 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004012 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004013
4014 /*
4015 * Dump gralloc state
4016 */
4017 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4018 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004019
4020 /*
4021 * Dump VrFlinger state if in use.
4022 */
4023 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4024 result.append("VrFlinger state:\n");
4025 result.append(mVrFlinger->Dump().c_str());
4026 result.append("\n");
4027 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004028}
4029
Mathias Agopian13127d82013-03-05 17:47:11 -08004030const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004031SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004032 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004033 wp<IBinder> dpy;
4034 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4035 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4036 dpy = mDisplays.keyAt(i);
4037 break;
4038 }
4039 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004040 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004041 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4042 // Just use the primary display so we have something to return
4043 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4044 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004045 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004046}
4047
Keun young Park63f165f2012-08-31 10:53:36 -07004048bool SurfaceFlinger::startDdmConnection()
4049{
4050 void* libddmconnection_dso =
4051 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4052 if (!libddmconnection_dso) {
4053 return false;
4054 }
4055 void (*DdmConnection_start)(const char* name);
4056 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004057 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004058 if (!DdmConnection_start) {
4059 dlclose(libddmconnection_dso);
4060 return false;
4061 }
4062 (*DdmConnection_start)(getServiceName());
4063 return true;
4064}
4065
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004066status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 switch (code) {
4068 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004069 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004070 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004071 case CLEAR_ANIMATION_FRAME_STATS:
4072 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004073 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004074 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004075 case ENABLE_VSYNC_INJECTIONS:
4076 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077 {
4078 // codes that require permission check
4079 IPCThreadState* ipc = IPCThreadState::self();
4080 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004081 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004082 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004083 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004084 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004085 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004087 break;
4088 }
Robert Carr1db73f62016-12-21 12:58:51 -08004089 /*
4090 * Calling setTransactionState is safe, because you need to have been
4091 * granted a reference to Client* and Handle* to do anything with it.
4092 *
4093 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4094 */
4095 case SET_TRANSACTION_STATE:
4096 case CREATE_SCOPED_CONNECTION:
4097 {
4098 return OK;
4099 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004100 case CAPTURE_SCREEN:
4101 {
4102 // codes that require permission check
4103 IPCThreadState* ipc = IPCThreadState::self();
4104 const int pid = ipc->getCallingPid();
4105 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004106 if ((uid != AID_GRAPHICS) &&
4107 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004108 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004109 return PERMISSION_DENIED;
4110 }
4111 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 }
chaviwa76b2712017-09-20 12:02:26 -07004113 case CAPTURE_LAYERS: {
4114 IPCThreadState* ipc = IPCThreadState::self();
4115 const int pid = ipc->getCallingPid();
4116 const int uid = ipc->getCallingUid();
4117 if ((uid != AID_GRAPHICS) &&
4118 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4119 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4120 return PERMISSION_DENIED;
4121 }
4122 break;
4123 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004125 return OK;
4126}
4127
4128status_t SurfaceFlinger::onTransact(
4129 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4130{
4131 status_t credentialCheck = CheckTransactCodeCredentials(code);
4132 if (credentialCheck != OK) {
4133 return credentialCheck;
4134 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4137 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004138 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004139 IPCThreadState* ipc = IPCThreadState::self();
4140 const int uid = ipc->getCallingUid();
4141 if (CC_UNLIKELY(uid != AID_SYSTEM
4142 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004143 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004144 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004145 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146 return PERMISSION_DENIED;
4147 }
4148 int n;
4149 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004150 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004151 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152 return NO_ERROR;
4153 case 1002: // SHOW_UPDATES
4154 n = data.readInt32();
4155 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004156 invalidateHwcGeometry();
4157 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004158 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004159 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004160 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004161 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004162 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004163 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004164 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004165 setTransactionFlags(
4166 eTransactionNeeded|
4167 eDisplayTransactionNeeded|
4168 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004169 return NO_ERROR;
4170 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004171 case 1006:{ // send empty update
4172 signalRefresh();
4173 return NO_ERROR;
4174 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004175 case 1008: // toggle use of hw composer
4176 n = data.readInt32();
4177 mDebugDisableHWC = n ? 1 : 0;
4178 invalidateHwcGeometry();
4179 repaintEverything();
4180 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004181 case 1009: // toggle use of transform hint
4182 n = data.readInt32();
4183 mDebugDisableTransformHint = n ? 1 : 0;
4184 invalidateHwcGeometry();
4185 repaintEverything();
4186 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004188 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189 reply->writeInt32(0);
4190 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004191 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004192 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 return NO_ERROR;
4194 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004195 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004196 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004197 return NO_ERROR;
4198 }
4199 case 1014: {
4200 // daltonize
4201 n = data.readInt32();
4202 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004203 case 1:
4204 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4205 break;
4206 case 2:
4207 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4208 break;
4209 case 3:
4210 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4211 break;
4212 default:
4213 mDaltonizer.setType(ColorBlindnessType::None);
4214 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004215 }
4216 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004217 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004218 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004219 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004220 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004221 invalidateHwcGeometry();
4222 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004223 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004224 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004225 case 1015: {
4226 // apply a color matrix
4227 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004228 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004229 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004230 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004231 for (size_t j = 0; j < 4; j++) {
4232 mColorMatrix[i][j] = data.readFloat();
4233 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004234 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004235 } else {
4236 mColorMatrix = mat4();
4237 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004238
4239 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4240 // the division by w in the fragment shader
4241 float4 lastRow(transpose(mColorMatrix)[3]);
4242 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4243 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4244 }
4245
Alan Viverette9c5a3332013-09-12 20:04:35 -07004246 invalidateHwcGeometry();
4247 repaintEverything();
4248 return NO_ERROR;
4249 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004250 // This is an experimental interface
4251 // Needs to be shifted to proper binder interface when we productize
4252 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004253 n = data.readInt32();
4254 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004255 return NO_ERROR;
4256 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004257 case 1017: {
4258 n = data.readInt32();
4259 mForceFullDamage = static_cast<bool>(n);
4260 return NO_ERROR;
4261 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004262 case 1018: { // Modify Choreographer's phase offset
4263 n = data.readInt32();
4264 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4265 return NO_ERROR;
4266 }
4267 case 1019: { // Modify SurfaceFlinger's phase offset
4268 n = data.readInt32();
4269 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4270 return NO_ERROR;
4271 }
Irvel468051e2016-06-13 16:44:44 -07004272 case 1020: { // Layer updates interceptor
4273 n = data.readInt32();
4274 if (n) {
4275 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004276 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004277 }
4278 else{
4279 ALOGV("Interceptor disabled");
4280 mInterceptor.disable();
4281 }
4282 return NO_ERROR;
4283 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004284 case 1021: { // Disable HWC virtual displays
4285 n = data.readInt32();
4286 mUseHwcVirtualDisplays = !n;
4287 return NO_ERROR;
4288 }
Romain Guy0147a172017-06-01 13:53:56 -07004289 case 1022: { // Set saturation boost
4290 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4291
4292 invalidateHwcGeometry();
4293 repaintEverything();
4294 return NO_ERROR;
4295 }
Romain Guy54f154a2017-10-24 21:40:32 +01004296 case 1023: { // Set native mode
4297 mForceNativeColorMode = data.readInt32() == 1;
4298
4299 invalidateHwcGeometry();
4300 repaintEverything();
4301 return NO_ERROR;
4302 }
4303 case 1024: { // Is wide color gamut rendering/color management supported?
4304 reply->writeBool(hasWideColorDisplay);
4305 return NO_ERROR;
4306 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004307 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004308 n = data.readInt32();
4309 if (n) {
4310 ALOGV("LayerTracing enabled");
4311 mTracing.enable();
4312 doTracing("tracing.enable");
4313 reply->writeInt32(NO_ERROR);
4314 } else {
4315 ALOGV("LayerTracing disabled");
4316 status_t err = mTracing.disable();
4317 reply->writeInt32(err);
4318 }
4319 return NO_ERROR;
4320 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004321 case 1026: { // Get layer tracing status
4322 reply->writeBool(mTracing.isEnabled());
4323 return NO_ERROR;
4324 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004325 }
4326 }
4327 return err;
4328}
4329
Steven Thomas6d8110b2017-08-31 18:24:21 -07004330void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004331 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004332 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004333}
4334
Steven Thomas6d8110b2017-08-31 18:24:21 -07004335void SurfaceFlinger::repaintEverything() {
4336 ConditionalLock _l(mStateLock,
4337 std::this_thread::get_id() != mMainThreadId);
4338 repaintEverythingLocked();
4339}
4340
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004341// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4342class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004343public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004344 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4345 ~WindowDisconnector() {
4346 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004347 }
4348
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004349private:
4350 ANativeWindow* mWindow;
4351 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004352};
4353
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004354status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4355 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4356 int32_t minLayerZ, int32_t maxLayerZ,
4357 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004358 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004359 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004360
chaviwa76b2712017-09-20 12:02:26 -07004361 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4362
4363 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4364 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4365
4366 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4367 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004368 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004369}
4370
4371status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004372 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004373 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004374 ATRACE_CALL();
4375
4376 class LayerRenderArea : public RenderArea {
4377 public:
chaviw7206d492017-11-10 16:16:12 -08004378 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004379 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004380 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004381 const Transform& getTransform() const override {
4382 // Make the top level transform the inverse the transform and it's parent so it sets
4383 // the whole capture back to 0,0
4384 return *new Transform(mLayer->getTransform().inverse());
4385 }
4386 Rect getBounds() const override {
4387 const Layer::State& layerState(mLayer->getDrawingState());
4388 return Rect(layerState.active.w, layerState.active.h);
4389 }
4390 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4391 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4392 bool isSecure() const override { return false; }
4393 bool needsFiltering() const override { return false; }
4394
chaviw7206d492017-11-10 16:16:12 -08004395 Rect getSourceCrop() const override {
4396 if (mCrop.isEmpty()) {
4397 return getBounds();
4398 } else {
4399 return mCrop;
4400 }
4401 }
chaviwa76b2712017-09-20 12:02:26 -07004402 bool getWideColorSupport() const override { return false; }
4403 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4404
4405 private:
chaviw7206d492017-11-10 16:16:12 -08004406 const sp<Layer> mLayer;
4407 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004408 };
4409
4410 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4411 auto parent = layerHandle->owner.promote();
4412
chaviw7206d492017-11-10 16:16:12 -08004413 if (parent == nullptr || parent->isPendingRemoval()) {
4414 ALOGE("captureLayers called with a removed parent");
4415 return NAME_NOT_FOUND;
4416 }
4417
4418 Rect crop(sourceCrop);
4419 if (sourceCrop.width() <= 0) {
4420 crop.left = 0;
4421 crop.right = parent->getCurrentState().active.w;
4422 }
4423
4424 if (sourceCrop.height() <= 0) {
4425 crop.top = 0;
4426 crop.bottom = parent->getCurrentState().active.h;
4427 }
4428
4429 int32_t reqWidth = crop.width() * frameScale;
4430 int32_t reqHeight = crop.height() * frameScale;
4431
4432 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4433
chaviwa76b2712017-09-20 12:02:26 -07004434 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4435 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4436 if (!layer->isVisible()) {
4437 return;
4438 }
4439 visitor(layer);
4440 });
4441 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004442 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004443}
4444
4445status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4446 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004447 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004448 bool useIdentityTransform) {
4449 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004450
chaviwa76b2712017-09-20 12:02:26 -07004451 renderArea.updateDimensions();
4452
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004453 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4454 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4455 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4456 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004457
4458 // This mutex protects syncFd and captureResult for communication of the return values from the
4459 // main thread back to this Binder thread
4460 std::mutex captureMutex;
4461 std::condition_variable captureCondition;
4462 std::unique_lock<std::mutex> captureLock(captureMutex);
4463 int syncFd = -1;
4464 std::optional<status_t> captureResult;
4465
Robert Carr03480e22018-01-04 16:02:06 -08004466 const int uid = IPCThreadState::self()->getCallingUid();
4467 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4468
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004469 sp<LambdaMessage> message = new LambdaMessage([&]() {
4470 // If there is a refresh pending, bug out early and tell the binder thread to try again
4471 // after the refresh.
4472 if (mRefreshPending) {
4473 ATRACE_NAME("Skipping screenshot for now");
4474 std::unique_lock<std::mutex> captureLock(captureMutex);
4475 captureResult = std::make_optional<status_t>(EAGAIN);
4476 captureCondition.notify_one();
4477 return;
4478 }
4479
4480 status_t result = NO_ERROR;
4481 int fd = -1;
4482 {
4483 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004484 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004485 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004486 }
4487
4488 {
4489 std::unique_lock<std::mutex> captureLock(captureMutex);
4490 syncFd = fd;
4491 captureResult = std::make_optional<status_t>(result);
4492 captureCondition.notify_one();
4493 }
4494 });
4495
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004496 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004497 if (result == NO_ERROR) {
4498 captureCondition.wait(captureLock, [&]() { return captureResult; });
4499 while (*captureResult == EAGAIN) {
4500 captureResult.reset();
4501 result = postMessageAsync(message);
4502 if (result != NO_ERROR) {
4503 return result;
4504 }
4505 captureCondition.wait(captureLock, [&]() { return captureResult; });
4506 }
4507 result = *captureResult;
4508 }
4509
4510 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004511 sync_wait(syncFd, -1);
4512 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004513 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004514
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004515 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004516}
4517
chaviwa76b2712017-09-20 12:02:26 -07004518void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4519 TraverseLayersFunction traverseLayers, bool yswap,
4520 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004521 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004522
Lloyd Pique144e1162017-12-20 16:44:52 -08004523 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004524
4525 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004526 const auto raWidth = renderArea.getWidth();
4527 const auto raHeight = renderArea.getHeight();
4528
4529 const auto reqWidth = renderArea.getReqWidth();
4530 const auto reqHeight = renderArea.getReqHeight();
4531 Rect sourceCrop = renderArea.getSourceCrop();
4532
4533 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4534 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004535
Dan Stozac1879002014-05-22 15:59:05 -07004536 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004537 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004538 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004539 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004540 }
4541
4542 // ensure that sourceCrop is inside screen
4543 if (sourceCrop.left < 0) {
4544 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4545 }
chaviwa76b2712017-09-20 12:02:26 -07004546 if (sourceCrop.right > raWidth) {
4547 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004548 }
4549 if (sourceCrop.top < 0) {
4550 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4551 }
chaviwa76b2712017-09-20 12:02:26 -07004552 if (sourceCrop.bottom > raHeight) {
4553 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004554 }
4555
chaviwa76b2712017-09-20 12:02:26 -07004556 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004557 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4558 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004559
Mathias Agopian180f10d2013-04-10 22:55:41 -07004560 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004561 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004562
4563 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004564 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4565 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004566 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004567
4568 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004569 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004570
chaviwa76b2712017-09-20 12:02:26 -07004571 traverseLayers([&](Layer* layer) {
4572 if (filtering) layer->setFiltering(true);
4573 layer->draw(renderArea, useIdentityTransform);
4574 if (filtering) layer->setFiltering(false);
4575 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004576}
4577
chaviwa76b2712017-09-20 12:02:26 -07004578status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4579 TraverseLayersFunction traverseLayers,
4580 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004581 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004582 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004583 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004584 ATRACE_CALL();
4585
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004586 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004587
4588 traverseLayers([&](Layer* layer) {
4589 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4590 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004591
Robert Carr03480e22018-01-04 16:02:06 -08004592 // We allow the system server to take screenshots of secure layers for
4593 // use in situations like the Screen-rotation animation and place
4594 // the impetus on WindowManager to not persist them.
4595 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004596 ALOGW("FB is protected: PERMISSION_DENIED");
4597 return PERMISSION_DENIED;
4598 }
4599
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004600 // this binds the given EGLImage as a framebuffer for the
4601 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004602 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004603 if (bufferBond.getStatus() != NO_ERROR) {
4604 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004605 return INVALID_OPERATION;
4606 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004607
Dan Stozaabcda352017-06-01 14:37:39 -07004608 // this will in fact render into our dequeued buffer
4609 // via an FBO, which means we didn't have to create
4610 // an EGLSurface and therefore we're not
4611 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004612 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004613
Dan Stozaabcda352017-06-01 14:37:39 -07004614 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004615 getRenderEngine().finish();
4616 *outSyncFd = -1;
4617
chaviwa76b2712017-09-20 12:02:26 -07004618 const auto reqWidth = renderArea.getReqWidth();
4619 const auto reqHeight = renderArea.getReqHeight();
4620
Dan Stozaabcda352017-06-01 14:37:39 -07004621 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4622 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004623 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004624 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004625 } else {
4626 base::unique_fd syncFd = getRenderEngine().flush();
4627 if (syncFd < 0) {
4628 getRenderEngine().finish();
4629 }
4630 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004631 }
4632
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004633 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004634}
4635
Mathias Agopiand5556842013-09-19 17:08:37 -07004636void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004637 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004638 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004639 for (size_t y = 0; y < h; y++) {
4640 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4641 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004642 if (p[x] != 0xFF000000) return;
4643 }
4644 }
chaviwa76b2712017-09-20 12:02:26 -07004645 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004646
Robert Carr2047fae2016-11-28 14:09:09 -08004647 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004648 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004649 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004650 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4651 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4652 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4653 static_cast<float>(state.color.a));
4654 i++;
4655 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004656 }
4657}
4658
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004659// ---------------------------------------------------------------------------
4660
Dan Stoza412903f2017-04-27 13:42:17 -07004661void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4662 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004663}
4664
Dan Stoza412903f2017-04-27 13:42:17 -07004665void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4666 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004667}
4668
chaviwa76b2712017-09-20 12:02:26 -07004669void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4670 int32_t maxLayerZ,
4671 const LayerVector::Visitor& visitor) {
4672 // We loop through the first level of layers without traversing,
4673 // as we need to interpret min/max layer Z in the top level Z space.
4674 for (const auto& layer : mDrawingState.layersSortedByZ) {
4675 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4676 continue;
4677 }
4678 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004679 // relative layers are traversed in Layer::traverseInZOrder
4680 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004681 continue;
4682 }
4683 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004684 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4685 return;
4686 }
chaviwa76b2712017-09-20 12:02:26 -07004687 if (!layer->isVisible()) {
4688 return;
4689 }
4690 visitor(layer);
4691 });
4692 }
4693}
4694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004695}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004696
4697
4698#if defined(__gl_h_)
4699#error "don't include gl/gl.h in this file"
4700#endif
4701
4702#if defined(__gl2_h_)
4703#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004704#endif