blob: 70a282db17ca9083e0ba6a14e1a8654d5054f744 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
David Sodman0c69cad2017-08-21 12:12:51 -070073#include "BufferLayer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070075#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
chaviw1d044282017-09-27 12:19:28 -070092#include <layerproto/LayerProtoParser.h>
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094#define DISPLAY_COUNT 1
95
Mathias Agopianfee2b462013-07-03 12:34:01 -070096/*
97 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
98 * black pixels.
99 */
100#define DEBUG_SCREENSHOTS false
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Steven Thomasb02664d2017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700132int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700133bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800134uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800135bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800136bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800137int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800138// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
Kalle Raitaa099a242017-01-11 11:17:29 -0800141
142std::string getHwcServiceName() {
143 char value[PROPERTY_VALUE_MAX] = {};
144 property_get("debug.sf.hwc_service_name", value, "default");
145 ALOGI("Using HWComposer service: '%s'", value);
146 return std::string(value);
147}
148
149bool useTrebleTestingOverride() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.treble_testing_override", value, "false");
152 ALOGI("Treble testing override: '%s'", value);
153 return std::string(value) == "true";
154}
155
David Sodmanbc815282017-11-05 18:57:52 -0800156SurfaceFlingerBE::SurfaceFlingerBE()
157 : mHwcServiceName(getHwcServiceName()),
158 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800162 mComposerSequenceId(0) {
163}
164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700166 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700168 mTransactionPending(false),
169 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700170 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700171 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700172 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800174 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800176 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800177 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700180 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700181 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700182 mDebugInSwapBuffers(0),
183 mLastSwapBufferTime(0),
184 mDebugInTransaction(0),
185 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700186 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700187 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800188 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
David Sodman105b7dc2017-11-04 20:28:14 -0700196 mMainThreadId(std::this_thread::get_id())
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
211
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
214
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800215 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
217
Steven Thomas050b2c82017-03-06 11:45:16 -0800218 // Vr flinger is only enabled on Daydream ready devices.
219 useVrFlinger = getBool< ISurfaceFlingerConfigs,
220 &ISurfaceFlingerConfigs::useVrFlinger>(false);
221
Fabien Sanglard1971b632017-03-10 14:50:03 -0800222 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
224
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600225 hasWideColorDisplay =
226 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
227
David Sodman99974d22017-11-28 12:04:33 -0800228 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 // debugging stuff...
231 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700232
Mathias Agopianb4b17302013-03-20 18:36:41 -0700233 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700234 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 property_get("debug.sf.showupdates", value, "0");
237 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700238
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239 property_get("debug.sf.ddms", value, "0");
240 mDebugDDMS = atoi(value);
241 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700242 if (!startDdmConnection()) {
243 // start failed, and DDMS debugging not enabled
244 mDebugDDMS = 0;
245 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700246 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700247 ALOGI_IF(mDebugRegion, "showupdates enabled");
248 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700249
250 property_get("debug.sf.disable_backpressure", value, "0");
251 mPropagateBackpressure = !atoi(value);
252 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700253
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800254 property_get("debug.sf.enable_hwc_vds", value, "0");
255 mUseHwcVirtualDisplays = atoi(value);
256 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800257
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800258 property_get("ro.sf.disable_triple_buffer", value, "1");
259 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700261
Romain Guy11d63f42017-07-20 12:47:14 -0700262 // We should be reading 'persist.sys.sf.color_saturation' here
263 // but since /data may be encrypted, we need to wait until after vold
264 // comes online to attempt to read the property. The property is
265 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800266
267 if (useTrebleTestingOverride()) {
268 // Without the override SurfaceFlinger cannot connect to HIDL
269 // services that are not listed in the manifests. Considered
270 // deriving the setting from the set service name, but it
271 // would be brittle if the name that's not 'default' is used
272 // for production purposes later on.
273 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800277void SurfaceFlinger::onFirstRef()
278{
279 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280}
281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282SurfaceFlinger::~SurfaceFlinger()
283{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Dan Stozac7014012014-02-14 15:03:43 -0800286void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800287{
288 // the window manager died on us. prepare its eulogy.
289
Andy McFadden13a082e2012-08-24 10:16:42 -0700290 // restore initial conditions (default device unblank, etc)
291 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800292
293 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700294 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295}
296
Robert Carr1db73f62016-12-21 12:58:51 -0800297static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700298 status_t err = client->initCheck();
299 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800300 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 }
Robert Carr1db73f62016-12-21 12:58:51 -0800302 return nullptr;
303}
304
305sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
306 return initClient(new Client(this));
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
310 const sp<IGraphicBufferProducer>& gbp) {
311 if (authenticateSurfaceTexture(gbp) == false) {
312 return nullptr;
313 }
314 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
315 if (layer == nullptr) {
316 return nullptr;
317 }
318
319 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700322sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
323 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324{
325 class DisplayToken : public BBinder {
326 sp<SurfaceFlinger> flinger;
327 virtual ~DisplayToken() {
328 // no more references, this display must be terminated
329 Mutex::Autolock _l(flinger->mStateLock);
330 flinger->mCurrentState.displays.removeItem(this);
331 flinger->setTransactionFlags(eDisplayTransactionNeeded);
332 }
333 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700334 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335 : flinger(flinger) {
336 }
337 };
338
339 sp<BBinder> token = new DisplayToken(this);
340
341 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700342 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700343 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700344 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700345 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346 return token;
347}
348
Jesse Hall6c913be2013-08-08 12:15:49 -0700349void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
350 Mutex::Autolock _l(mStateLock);
351
352 ssize_t idx = mCurrentState.displays.indexOfKey(display);
353 if (idx < 0) {
354 ALOGW("destroyDisplay: invalid display token");
355 return;
356 }
357
358 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
359 if (!info.isVirtualDisplay()) {
360 ALOGE("destroyDisplay called for non-virtual display");
361 return;
362 }
Irvelffc9efc2016-07-27 15:16:37 -0700363 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700364 mCurrentState.displays.removeItemsAt(idx);
365 setTransactionFlags(eDisplayTransactionNeeded);
366}
367
Mathias Agopiane57f2922012-08-09 16:29:12 -0700368sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700369 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700370 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800371 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700372 }
Jesse Hall692c7232012-11-08 15:41:56 -0800373 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376void SurfaceFlinger::bootFinished()
377{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700378 if (mStartPropertySetThread->join() != NO_ERROR) {
379 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 const nsecs_t now = systemTime();
382 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000383 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700384
385 // wait patiently for the window manager death
386 const String16 name("window");
387 sp<IBinder> window(defaultServiceManager()->getService(name));
388 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700390 }
391
Steven Thomas050b2c82017-03-06 11:45:16 -0800392 if (mVrFlinger) {
393 mVrFlinger->OnBootFinished();
394 }
395
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700396 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700397 // formerly we would just kill the process, but we now ask it to exit so it
398 // can choose where to stop the animation.
399 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700400
401 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
402 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
403 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700404
Thierry Strudel2924d012017-08-14 15:19:37 -0700405 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700406 readPersistentProperties();
407 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700408 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Mathias Agopian3f844832013-08-07 21:24:32 -0700411void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700412 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700413 RenderEngine& engine;
414 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700415 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700416 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
417 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 }
419 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 return true;
422 }
423 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425}
426
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427class DispSyncSource : public VSyncSource, private DispSync::Callback {
428public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* name) :
431 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
435 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 mDispSync(dispSync),
437 mCallbackMutex(),
438 mCallback(),
439 mVsyncMutex(),
440 mPhaseOffset(phaseOffset),
441 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700442
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 virtual ~DispSyncSource() {}
444
445 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 static_cast<DispSync::Callback*>(this));
450 if (err != NO_ERROR) {
451 ALOGE("error registering vsync callback: %s (%d)",
452 strerror(-err), err);
453 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 } else {
456 status_t err = mDispSync->removeEventListener(
457 static_cast<DispSync::Callback*>(this));
458 if (err != NO_ERROR) {
459 ALOGE("error unregistering vsync callback: %s (%d)",
460 strerror(-err), err);
461 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700462 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700464 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 }
466
467 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 mCallback = callback;
470 }
471
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 virtual void setPhaseOffset(nsecs_t phaseOffset) {
473 Mutex::Autolock lock(mVsyncMutex);
474
475 // Normalize phaseOffset to [0, period)
476 auto period = mDispSync->getPeriod();
477 phaseOffset %= period;
478 if (phaseOffset < 0) {
479 // If we're here, then phaseOffset is in (-period, 0). After this
480 // operation, it will be in (0, period)
481 phaseOffset += period;
482 }
483 mPhaseOffset = phaseOffset;
484
485 // If we're not enabled, we don't need to mess with the listeners
486 if (!mEnabled) {
487 return;
488 }
489
490 // Remove the listener with the old offset
491 status_t err = mDispSync->removeEventListener(
492 static_cast<DispSync::Callback*>(this));
493 if (err != NO_ERROR) {
494 ALOGE("error unregistering vsync callback: %s (%d)",
495 strerror(-err), err);
496 }
497
498 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 static_cast<DispSync::Callback*>(this));
501 if (err != NO_ERROR) {
502 ALOGE("error registering vsync callback: %s (%d)",
503 strerror(-err), err);
504 }
505 }
506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507private:
508 virtual void onDispSyncEvent(nsecs_t when) {
509 sp<VSyncSource::Callback> callback;
510 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 callback = mCallback;
513
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514 if (mTraceVsync) {
515 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700516 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700517 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 }
519
Peiyong Lin566a3b42018-01-09 18:22:43 -0800520 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 callback->onVSyncEvent(when);
522 }
523 }
524
Tim Murray4a4e4a22016-04-19 16:29:23 +0000525 const char* const mName;
526
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 int mValue;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 const String8 mVsyncOnLabel;
531 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534
535 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537
538 Mutex mVsyncMutex; // Protects the following
539 nsecs_t mPhaseOffset;
540 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541};
542
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700543class InjectVSyncSource : public VSyncSource {
544public:
545 InjectVSyncSource() {}
546
547 virtual ~InjectVSyncSource() {}
548
549 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
550 std::lock_guard<std::mutex> lock(mCallbackMutex);
551 mCallback = callback;
552 }
553
554 virtual void onInjectSyncEvent(nsecs_t when) {
555 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700556 if (mCallback) {
557 mCallback->onVSyncEvent(when);
558 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700559 }
560
561 virtual void setVSyncEnabled(bool) {}
562 virtual void setPhaseOffset(nsecs_t) {}
563
564private:
565 std::mutex mCallbackMutex; // Protects the following
566 sp<VSyncSource::Callback> mCallback;
567};
568
Wei Wangf9b05ee2017-07-19 20:59:39 -0700569// Do not call property_set on main thread which will be blocked by init
570// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700572 ALOGI( "SurfaceFlinger's main thread ready to run. "
573 "Initializing graphics H/W...");
574
Thierry Strudel2924d012017-08-14 15:19:37 -0700575 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 // start the EventThread
David Sodman99974d22017-11-28 12:04:33 -0800580 sp<VSyncSource> vsyncSrc =
581 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 mEventThread = new EventThread(vsyncSrc, *this, false);
David Sodman99974d22017-11-28 12:04:33 -0800583 sp<VSyncSource> sfVsyncSrc =
584 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
586 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
589 struct sched_param param = {0};
590 param.sched_priority = 2;
591 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
592 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
593 }
594 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
595 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596 }
597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800599 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800601 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700602
603 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
604 "Starting with vr flinger active is not currently supported.");
David Sodmanbc815282017-11-05 18:57:52 -0800605 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700606 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800607 // Process any initial hotplug and resulting display changes.
608 processDisplayHotplugEventsLocked();
609 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
610 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800611
Lloyd Piquefcd86612017-12-14 17:15:36 -0800612 // make the default display GLContext current so that we can create textures
613 // when creating Layers (which may happens before we render something)
614 getDefaultDisplayDeviceLocked()->makeCurrent();
615
Steven Thomas050b2c82017-03-06 11:45:16 -0800616 if (useVrFlinger) {
617 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700618 // This callback is called from the vr flinger dispatch thread. We
619 // need to call signalTransaction(), which requires holding
620 // mStateLock when we're not on the main thread. Acquiring
621 // mStateLock from the vr flinger dispatch thread might trigger a
622 // deadlock in surface flinger (see b/66916578), so post a message
623 // to be handled on the main thread instead.
624 sp<LambdaMessage> message = new LambdaMessage([=]() {
625 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
626 mVrFlingerRequestsDisplay = requestDisplay;
627 signalTransaction();
628 });
629 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 };
David Sodman105b7dc2017-11-04 20:28:14 -0700631 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
632 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800633 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 if (!mVrFlinger) {
635 ALOGE("Failed to start vrflinger");
636 }
637 }
638
Lloyd Pique755e3192018-01-31 16:46:15 -0800639 mEventControlThread = std::make_unique<EventControlThread>([this](bool enabled) {
640 setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled);
641 });
Jamie Gennisd1700752013-10-14 12:22:52 -0700642
Mathias Agopian92a979a2012-08-02 18:32:23 -0700643 // initialize our drawing state
644 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700645
Andy McFadden13a082e2012-08-24 10:16:42 -0700646 // set initial conditions (e.g. unblank default device)
647 initializeDisplays();
648
David Sodmanbc815282017-11-05 18:57:52 -0800649 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700650
Wei Wangf9b05ee2017-07-19 20:59:39 -0700651 // Inform native graphics APIs whether the present timestamp is supported:
652 if (getHwComposer().hasCapability(
653 HWC2::Capability::PresentFenceIsNotReliable)) {
654 mStartPropertySetThread = new StartPropertySetThread(false);
655 } else {
656 mStartPropertySetThread = new StartPropertySetThread(true);
657 }
658
659 if (mStartPropertySetThread->Start() != NO_ERROR) {
660 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800662
Dan Stoza9e56aa02015-11-02 13:00:03 -0800663 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700664}
665
Romain Guy11d63f42017-07-20 12:47:14 -0700666void SurfaceFlinger::readPersistentProperties() {
667 char value[PROPERTY_VALUE_MAX];
668
669 property_get("persist.sys.sf.color_saturation", value, "1.0");
670 mSaturation = atof(value);
671 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100672
673 property_get("persist.sys.sf.native_mode", value, "0");
674 mForceNativeColorMode = atoi(value) == 1;
675 if (mForceNativeColorMode) {
676 ALOGV("Forcing native color mode");
677 }
Romain Guy11d63f42017-07-20 12:47:14 -0700678}
679
Mathias Agopiana67e4182012-06-19 17:26:12 -0700680void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800681 // Start boot animation service by setting a property mailbox
682 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800684 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 if (mStartPropertySetThread->join() != NO_ERROR) {
686 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800687 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700688}
689
Mathias Agopian875d8e12013-06-07 15:35:48 -0700690size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800691 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700692}
693
Mathias Agopian875d8e12013-06-07 15:35:48 -0700694size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800695 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700696}
697
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800698// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800699
Jamie Gennis582270d2011-08-17 18:19:00 -0700700bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800701 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800702 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800703 return authenticateSurfaceTextureLocked(bufferProducer);
704}
705
706bool SurfaceFlinger::authenticateSurfaceTextureLocked(
707 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800708 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700709 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800710}
711
Brian Anderson6b376712017-04-04 10:51:39 -0700712status_t SurfaceFlinger::getSupportedFrameTimestamps(
713 std::vector<FrameEvent>* outSupported) const {
714 *outSupported = {
715 FrameEvent::REQUESTED_PRESENT,
716 FrameEvent::ACQUIRE,
717 FrameEvent::LATCH,
718 FrameEvent::FIRST_REFRESH_START,
719 FrameEvent::LAST_REFRESH_START,
720 FrameEvent::GPU_COMPOSITION_DONE,
721 FrameEvent::DEQUEUE_READY,
722 FrameEvent::RELEASE,
723 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700724 ConditionalLock _l(mStateLock,
725 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700726 if (!getHwComposer().hasCapability(
727 HWC2::Capability::PresentFenceIsNotReliable)) {
728 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
729 }
730 return NO_ERROR;
731}
732
Dan Stoza7f7da322014-05-02 15:26:25 -0700733status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
734 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800735 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700736 return BAD_VALUE;
737 }
738
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500739 if (!display.get())
740 return NAME_NOT_FOUND;
741
Jesse Hall692c7232012-11-08 15:41:56 -0800742 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700743 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800744 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700745 type = i;
746 break;
747 }
748 }
749
750 if (type < 0) {
751 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700752 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754 // TODO: Not sure if display density should handled by SF any longer
755 class Density {
756 static int getDensityFromProperty(char const* propName) {
757 char property[PROPERTY_VALUE_MAX];
758 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800759 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 density = atoi(property);
761 }
762 return density;
763 }
764 public:
765 static int getEmuDensity() {
766 return getDensityFromProperty("qemu.sf.lcd_density"); }
767 static int getBuildDensity() {
768 return getDensityFromProperty("ro.sf.lcd_density"); }
769 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700770
Dan Stoza7f7da322014-05-02 15:26:25 -0700771 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Steven Thomas6d8110b2017-08-31 18:24:21 -0700773 ConditionalLock _l(mStateLock,
774 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 DisplayInfo info = DisplayInfo();
777
Dan Stoza9e56aa02015-11-02 13:00:03 -0800778 float xdpi = hwConfig->getDpiX();
779 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700780
781 if (type == DisplayDevice::DISPLAY_PRIMARY) {
782 // The density of the device is provided by a build property
783 float density = Density::getBuildDensity() / 160.0f;
784 if (density == 0) {
785 // the build doesn't provide a density -- this is wrong!
786 // use xdpi instead
787 ALOGE("ro.sf.lcd_density must be defined as a build property");
788 density = xdpi / 160.0f;
789 }
790 if (Density::getEmuDensity()) {
791 // if "qemu.sf.lcd_density" is specified, it overrides everything
792 xdpi = ydpi = density = Density::getEmuDensity();
793 density /= 160.0f;
794 }
795 info.density = density;
796
797 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800799 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 } else {
801 // TODO: where should this value come from?
802 static const int TV_DENSITY = 213;
803 info.density = TV_DENSITY / 160.0f;
804 info.orientation = 0;
805 }
806
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 info.w = hwConfig->getWidth();
808 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 info.xdpi = xdpi;
810 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900812 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813
Andy McFadden91b2ca82014-06-13 14:04:23 -0700814 // This is how far in advance a buffer must be queued for
815 // presentation at a given time. If you want a buffer to appear
816 // on the screen at time N, you must submit the buffer before
817 // (N - presentationDeadline).
818 //
819 // Normally it's one full refresh period (to give SF a chance to
820 // latch the buffer), but this can be reduced by configuring a
821 // DispSync offset. Any additional delays introduced by the hardware
822 // composer or panel must be accounted for here.
823 //
824 // We add an additional 1ms to allow for processing time and
825 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800827 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700828
829 // All non-virtual displays are currently considered secure.
830 info.secure = true;
831
Michael Wright28f24d02016-07-12 13:30:53 -0700832 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 }
834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 return NO_ERROR;
836}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700837
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800838status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700839 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 return BAD_VALUE;
842 }
843
844 // FIXME for now we always return stats for the primary display
845 memset(stats, 0, sizeof(*stats));
846 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
847 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
848 return NO_ERROR;
849}
850
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700851int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800852 if (display == nullptr) {
853 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800854 return BAD_VALUE;
855 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700856
857 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800858 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700859 return device->getActiveConfig();
860 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700861
Dan Stoza24a42e92015-03-09 10:04:11 -0700862 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700864
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700865void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
866 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
867 this);
868 int32_t type = hw->getDisplayType();
869 int currentMode = hw->getActiveConfig();
870
871 if (mode == currentMode) {
872 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
873 return;
874 }
875
876 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
877 ALOGW("Trying to set config for virtual display");
878 return;
879 }
880
881 hw->setActiveConfig(mode);
882 getHwComposer().setActiveConfig(type, mode);
883}
884
885status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
886 class MessageSetActiveConfig: public MessageBase {
887 SurfaceFlinger& mFlinger;
888 sp<IBinder> mDisplay;
889 int mMode;
890 public:
891 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
892 int mode) :
893 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
894 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700895 Vector<DisplayInfo> configs;
896 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700897 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700898 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700899 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700900 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700901 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700902 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800903 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700905 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
907 ALOGW("Attempt to set active config = %d for virtual display",
908 mMode);
909 } else {
910 mFlinger.setActiveConfigInternal(hw, mMode);
911 }
912 return true;
913 }
914 };
915 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
916 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700917 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700918}
Michael Wright28f24d02016-07-12 13:30:53 -0700919status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
920 Vector<android_color_mode_t>* outColorModes) {
921 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
922 return BAD_VALUE;
923 }
924
925 if (!display.get()) {
926 return NAME_NOT_FOUND;
927 }
928
929 int32_t type = NAME_NOT_FOUND;
930 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
931 if (display == mBuiltinDisplays[i]) {
932 type = i;
933 break;
934 }
935 }
936
937 if (type < 0) {
938 return type;
939 }
940
Steven Thomas6d8110b2017-08-31 18:24:21 -0700941 std::vector<android_color_mode_t> modes;
942 {
943 ConditionalLock _l(mStateLock,
944 std::this_thread::get_id() != mMainThreadId);
945 modes = getHwComposer().getColorModes(type);
946 }
Michael Wright28f24d02016-07-12 13:30:53 -0700947 outColorModes->clear();
948 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
949
950 return NO_ERROR;
951}
952
953android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700954 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700955 if (device != nullptr) {
956 return device->getActiveColorMode();
957 }
958 return static_cast<android_color_mode_t>(BAD_VALUE);
959}
960
961void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
962 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700963 int32_t type = hw->getDisplayType();
964 android_color_mode_t currentMode = hw->getActiveColorMode();
965
966 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700967 return;
968 }
969
970 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
971 ALOGW("Trying to set config for virtual display");
972 return;
973 }
974
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600975 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
976 hw->getDisplayType());
977
Michael Wright28f24d02016-07-12 13:30:53 -0700978 hw->setActiveColorMode(mode);
979 getHwComposer().setActiveColorMode(type, mode);
980}
981
982
983status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
984 android_color_mode_t colorMode) {
985 class MessageSetActiveColorMode: public MessageBase {
986 SurfaceFlinger& mFlinger;
987 sp<IBinder> mDisplay;
988 android_color_mode_t mMode;
989 public:
990 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
991 android_color_mode_t mode) :
992 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
993 virtual bool handler() {
994 Vector<android_color_mode_t> modes;
995 mFlinger.getDisplayColorModes(mDisplay, &modes);
996 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
997 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600998 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
999 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001000 return true;
1001 }
1002 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1003 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001004 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1005 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001006 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001007 ALOGW("Attempt to set active color mode %s %d for virtual display",
1008 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001009 } else {
1010 mFlinger.setActiveColorModeInternal(hw, mMode);
1011 }
1012 return true;
1013 }
1014 };
1015 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1016 postMessageSync(msg);
1017 return NO_ERROR;
1018}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001019
Svetoslavd85084b2014-03-20 10:28:31 -07001020status_t SurfaceFlinger::clearAnimationFrameStats() {
1021 Mutex::Autolock _l(mStateLock);
1022 mAnimFrameTracker.clearStats();
1023 return NO_ERROR;
1024}
1025
1026status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1027 Mutex::Autolock _l(mStateLock);
1028 mAnimFrameTracker.getStats(outStats);
1029 return NO_ERROR;
1030}
1031
Dan Stozac4f471e2016-03-24 09:31:08 -07001032status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1033 HdrCapabilities* outCapabilities) const {
1034 Mutex::Autolock _l(mStateLock);
1035
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001036 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001037 if (displayDevice == nullptr) {
1038 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1039 return BAD_VALUE;
1040 }
1041
1042 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001043 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001044 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001045 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1046 // insert HDR10 as we will force client composition for HDR10
1047 // layers
1048 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1049 types.push_back(HAL_HDR_HDR10);
1050
1051 *outCapabilities = HdrCapabilities(types,
1052 capabilities->getDesiredMaxLuminance(),
1053 capabilities->getDesiredMaxAverageLuminance(),
1054 capabilities->getDesiredMinLuminance());
1055 } else {
1056 *outCapabilities = std::move(*capabilities);
1057 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001058 } else {
1059 return BAD_VALUE;
1060 }
1061
1062 return NO_ERROR;
1063}
1064
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001066 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1067 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069 if (mInjectVSyncs == enable) {
1070 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001071 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001072
1073 if (enable) {
1074 ALOGV("VSync Injections enabled");
1075 if (mVSyncInjector.get() == nullptr) {
1076 mVSyncInjector = new InjectVSyncSource();
1077 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1078 }
1079 mEventQueue.setEventThread(mInjectorEventThread);
1080 } else {
1081 ALOGV("VSync Injections disabled");
1082 mEventQueue.setEventThread(mSFEventThread);
1083 }
1084
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001086 });
1087 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001088 return NO_ERROR;
1089}
1090
1091status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001092 Mutex::Autolock _l(mStateLock);
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094 if (!mInjectVSyncs) {
1095 ALOGE("VSync Injections not enabled");
1096 return BAD_VALUE;
1097 }
1098 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1099 ALOGV("Injecting VSync inside SurfaceFlinger");
1100 mVSyncInjector->onInjectSyncEvent(when);
1101 }
1102 return NO_ERROR;
1103}
1104
Lloyd Pique755e3192018-01-31 16:46:15 -08001105status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1106 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001107 IPCThreadState* ipc = IPCThreadState::self();
1108 const int pid = ipc->getCallingPid();
1109 const int uid = ipc->getCallingUid();
1110 if ((uid != AID_SHELL) &&
1111 !PermissionCache::checkPermission(sDump, pid, uid)) {
1112 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1113 return PERMISSION_DENIED;
1114 }
1115
1116 // Try to acquire a lock for 1s, fail gracefully
1117 const status_t err = mStateLock.timedLock(s2ns(1));
1118 const bool locked = (err == NO_ERROR);
1119 if (!locked) {
1120 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1121 return TIMED_OUT;
1122 }
1123
1124 outLayers->clear();
1125 mCurrentState.traverseInZOrder([&](Layer* layer) {
1126 outLayers->push_back(layer->getLayerDebugInfo());
1127 });
1128
1129 mStateLock.unlock();
1130 return NO_ERROR;
1131}
1132
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001133// ----------------------------------------------------------------------------
1134
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001135sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1136 ISurfaceComposer::VsyncSource vsyncSource) {
1137 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1138 return mSFEventThread->createEventConnection();
1139 } else {
1140 return mEventThread->createEventConnection();
1141 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001142}
1143
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001144// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145
1146void SurfaceFlinger::waitForEvent() {
1147 mEventQueue.waitMessage();
1148}
1149
1150void SurfaceFlinger::signalTransaction() {
1151 mEventQueue.invalidate();
1152}
1153
1154void SurfaceFlinger::signalLayerUpdate() {
1155 mEventQueue.invalidate();
1156}
1157
1158void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001159 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160 mEventQueue.refresh();
1161}
1162
1163status_t SurfaceFlinger::postMessageAsync(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 return mEventQueue.postMessage(msg, reltime);
1166}
1167
1168status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001169 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001170 status_t res = mEventQueue.postMessage(msg, reltime);
1171 if (res == NO_ERROR) {
1172 msg->wait();
1173 }
1174 return res;
1175}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001177void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001178 do {
1179 waitForEvent();
1180 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181}
1182
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183void SurfaceFlinger::enableHardwareVsync() {
1184 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001187 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1188 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001190 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191}
1192
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 Mutex::Autolock _l(mHWVsyncLock);
1195
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 if (makeAvailable) {
1197 mHWVsyncAvailable = true;
1198 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001199 // Hardware vsync is not currently available, so abort the resync
1200 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001201 return;
1202 }
1203
David Sodman105b7dc2017-11-04 20:28:14 -07001204 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001205 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206
1207 mPrimaryDispSync.reset();
1208 mPrimaryDispSync.setPeriod(period);
1209
1210 if (!mPrimaryHWVsyncEnabled) {
1211 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001212 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1213 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214 mPrimaryHWVsyncEnabled = true;
1215 }
1216}
1217
Jesse Hall948fe0c2013-10-14 12:56:09 -07001218void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 Mutex::Autolock _l(mHWVsyncLock);
1220 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001221 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1222 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223 mPrimaryDispSync.endResync();
1224 mPrimaryHWVsyncEnabled = false;
1225 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001226 if (makeUnavailable) {
1227 mHWVsyncAvailable = false;
1228 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229}
1230
Tim Murray4a4e4a22016-04-19 16:29:23 +00001231void SurfaceFlinger::resyncWithRateLimit() {
1232 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001233
1234 // No explicit locking is needed here since EventThread holds a lock while calling this method
1235 static nsecs_t sLastResyncAttempted = 0;
1236 const nsecs_t now = systemTime();
1237 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001238 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239 }
Dan Stoza57164302017-05-08 14:03:54 -07001240 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001241}
1242
Steven Thomasb02664d2017-07-26 18:48:28 -07001243void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1244 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001245 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001247 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001248 return;
1249 }
1250
1251 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001252 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001253 return;
1254 }
1255
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 { // Scope for the lock
1259 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001260 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001263 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001264
1265 if (needsHwVsync) {
1266 enableHardwareVsync();
1267 } else {
1268 disableHardwareVsync(false);
1269 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001270}
1271
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001272void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001273 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1274 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001275}
1276
Lloyd Pique715a2c12017-12-14 17:18:08 -08001277void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1278 HWC2::Connection connection) {
1279 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1280 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001281
Lloyd Piqueba04e622017-12-14 17:11:26 -08001282 // Ignore events that do not have the right sequenceId.
1283 if (sequenceId != getBE().mComposerSequenceId) {
1284 return;
1285 }
1286
Steven Thomasb02664d2017-07-26 18:48:28 -07001287 // Only lock if we're not on the main thread. This function is normally
1288 // called on a hwbinder thread, but for the primary display it's called on
1289 // the main thread with the state lock already held, so don't attempt to
1290 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001291 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292
Lloyd Pique715a2c12017-12-14 17:18:08 -08001293 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001294
Lloyd Piqueba04e622017-12-14 17:11:26 -08001295 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001296}
1297
Steven Thomasb02664d2017-07-26 18:48:28 -07001298void SurfaceFlinger::onRefreshReceived(int sequenceId,
1299 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001300 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001301 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001302 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001303 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001304 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001305}
1306
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001308 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001310 getHwComposer().setVsyncEnabled(disp,
1311 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001312}
1313
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001314// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001315void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001316 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001317 // Clear the drawing state so that the logic inside of
1318 // handleTransactionLocked will fire. It will determine the delta between
1319 // mCurrentState and mDrawingState and re-apply all changes when we make the
1320 // transition.
1321 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001322 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001323 mDisplays.clear();
1324}
1325
Steven Thomas050b2c82017-03-06 11:45:16 -08001326void SurfaceFlinger::updateVrFlinger() {
1327 if (!mVrFlinger)
1328 return;
1329 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001330 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001331 return;
1332 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001333
David Sodman105b7dc2017-11-04 20:28:14 -07001334 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001335 ALOGE("Vr flinger is only supported for remote hardware composer"
1336 " service connections. Ignoring request to transition to vr"
1337 " flinger.");
1338 mVrFlingerRequestsDisplay = false;
1339 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001340 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 int currentDisplayPowerMode = getDisplayDeviceLocked(
1345 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001348 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001352 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001353 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001354 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001355
David Sodman105b7dc2017-11-04 20:28:14 -07001356 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1357 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001358
1359 if (vrFlingerRequestsDisplay) {
1360 mVrFlinger->GrantDisplayOwnership();
1361 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001363 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001364
1365 mVisibleRegionsDirty = true;
1366 invalidateHwcGeometry();
1367
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001368 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1370 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1371 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001372
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001374 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 const nsecs_t period = activeConfig->getVsyncPeriod();
1376 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001377
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 // Use phase of 0 since phase is not known.
1379 // Use latency of 0, which will snap to the ideal latency.
1380 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001381
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001382 android_atomic_or(1, &mRepaintEverything);
1383 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384}
1385
Mathias Agopian4fec8732012-06-29 14:12:52 -07001386void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001387 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001388 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001389 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001390 bool frameMissed = !mHadClientComposition &&
1391 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392 (mPreviousPresentFence->getSignalTime() ==
1393 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001394 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001395 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001396 signalLayerUpdate();
1397 break;
1398 }
1399
Steven Thomas050b2c82017-03-06 11:45:16 -08001400 // Now that we're going to make it to the handleMessageTransaction()
1401 // call below it's safe to call updateVrFlinger(), which will
1402 // potentially trigger a display handoff.
1403 updateVrFlinger();
1404
Dan Stoza6b9454d2014-11-07 16:00:59 -08001405 bool refreshNeeded = handleMessageTransaction();
1406 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001407 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001409 // Signal a refresh if a transaction modified the window state,
1410 // a new buffer was latched, or if HWC has requested a full
1411 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 signalRefresh();
1413 }
1414 break;
1415 }
1416 case MessageQueue::REFRESH: {
1417 handleMessageRefresh();
1418 break;
1419 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001420 }
1421}
1422
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001424 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001425 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001426 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001428 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001430}
1431
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001433 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435}
1436
1437void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001438 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001439
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001440 mRefreshPending = false;
1441
Pablo Ceballos40845df2016-01-25 17:41:15 -08001442 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001443
Brian Andersond6927fb2016-07-23 23:37:30 -07001444 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001445 rebuildLayerStacks();
1446 setUpHWComposer();
1447 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001448 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001449 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001450 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001451
David Sodman105b7dc2017-11-04 20:28:14 -07001452 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001453
1454 mHadClientComposition = false;
1455 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1456 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1457 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001458 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001459 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001460
Dan Stoza9e56aa02015-11-02 13:00:03 -08001461 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001462}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463
Mathias Agopiancd60f992012-08-16 16:28:27 -07001464void SurfaceFlinger::doDebugFlashRegions()
1465{
1466 // is debugging enabled
1467 if (CC_LIKELY(!mDebugRegion))
1468 return;
1469
1470 const bool repaintEverything = mRepaintEverything;
1471 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1472 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001473 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001474 // transform the dirty region into this screen's coordinate space
1475 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1476 if (!dirtyRegion.isEmpty()) {
1477 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001478 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479
1480 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001481 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001482 RenderEngine& engine(getRenderEngine());
1483 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1484
Mathias Agopianda27af92012-09-13 18:17:13 -07001485 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001486 }
1487 }
1488 }
1489
1490 postFramebuffer();
1491
1492 if (mDebugRegion > 1) {
1493 usleep(mDebugRegion * 1000);
1494 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001495
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001497 auto& displayDevice = mDisplays[displayId];
1498 if (!displayDevice->isDisplayOn()) {
1499 continue;
1500 }
1501
David Sodman105b7dc2017-11-04 20:28:14 -07001502 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1503 ALOGE_IF(result != NO_ERROR,
1504 "prepareFrame for display %zd failed:"
1505 " %d (%s)",
1506 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001507 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508}
1509
Adrian Roos1e1a1282017-11-01 19:05:31 +01001510void SurfaceFlinger::doTracing(const char* where) {
1511 ATRACE_CALL();
1512 ATRACE_NAME(where);
1513 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001514 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001515 }
1516}
1517
Brian Andersond6927fb2016-07-23 23:37:30 -07001518void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001520 ATRACE_CALL();
1521 ALOGV("preComposition");
1522
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001524 mDrawingState.traverseInZOrder([&](Layer* layer) {
1525 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 needExtraInvalidate = true;
1527 }
Robert Carr2047fae2016-11-28 14:09:09 -08001528 });
1529
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530 if (needExtraInvalidate) {
1531 signalLayerUpdate();
1532 }
1533}
1534
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535void SurfaceFlinger::updateCompositorTiming(
1536 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1537 std::shared_ptr<FenceTime>& presentFenceTime) {
1538 // Update queue of past composite+present times and determine the
1539 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001540 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001542 while (!getBE().mCompositePresentTimes.empty()) {
1543 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001544 // Cached values should have been updated before calling this method,
1545 // which helps avoid duplicate syscalls.
1546 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1547 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1548 break;
1549 }
1550 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001551 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001552 }
1553
1554 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001555 while (getBE().mCompositePresentTimes.size() > 16) {
1556 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557 }
1558
Brian Andersond0010582017-03-07 13:20:31 -08001559 setCompositorTimingSnapped(
1560 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1561}
1562
1563void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1564 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565 // Integer division and modulo round toward 0 not -inf, so we need to
1566 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001567 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1569 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1570
Brian Andersond0010582017-03-07 13:20:31 -08001571 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1572 if (idealLatency <= 0) {
1573 idealLatency = vsyncInterval;
1574 }
1575
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001576 // Snap the latency to a value that removes scheduling jitter from the
1577 // composition and present times, which often have >1ms of jitter.
1578 // Reducing jitter is important if an app attempts to extrapolate
1579 // something (such as user input) to an accurate diasplay time.
1580 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1581 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001582 nsecs_t bias = vsyncInterval / 2;
1583 int64_t extraVsyncs =
1584 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1585 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1586 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587
David Sodman99974d22017-11-28 12:04:33 -08001588 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1589 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1590 getBE().mCompositorTiming.interval = vsyncInterval;
1591 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592}
1593
1594void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001596 ATRACE_CALL();
1597 ALOGV("postComposition");
1598
Brian Anderson3546a3f2016-07-14 11:51:14 -07001599 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001600 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001601 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001602 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001603 }
1604
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001605 // |mStateLock| not needed as we are on the main thread
1606 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001607
David Sodman73beded2017-11-15 11:56:06 -08001608 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001609 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001610 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001611 glCompositionDoneFenceTime =
1612 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001613 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001614 } else {
1615 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1616 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001617
David Sodman73beded2017-11-15 11:56:06 -08001618 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001619 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001620 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001621 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001622
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1624 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1625
1626 // We use the refreshStartTime which might be sampled a little later than
1627 // when we started doing work for this frame, but that should be okay
1628 // since updateCompositorTiming has snapping logic.
1629 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001630 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001631 CompositorTiming compositorTiming;
1632 {
David Sodman99974d22017-11-28 12:04:33 -08001633 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1634 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001635 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636
Robert Carr2047fae2016-11-28 14:09:09 -08001637 mDrawingState.traverseInZOrder([&](Layer* layer) {
1638 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001639 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001640 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001641 recordBufferingStats(layer->getName().string(),
1642 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001643 }
Robert Carr2047fae2016-11-28 14:09:09 -08001644 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001645
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001646 if (presentFenceTime->isValid()) {
1647 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001648 enableHardwareVsync();
1649 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001650 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001651 }
1652 }
1653
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001654 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001655 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001656 enableHardwareVsync();
1657 }
1658 }
1659
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001660 if (mAnimCompositionPending) {
1661 mAnimCompositionPending = false;
1662
Brian Anderson4e606e32017-03-16 15:34:57 -07001663 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001664 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001665 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001666 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001667 // The HWC doesn't support present fences, so use the refresh
1668 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001670 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001671 mAnimFrameTracker.setActualPresentTime(presentTime);
1672 }
1673 mAnimFrameTracker.advanceFrame();
1674 }
Dan Stozab90cf072015-03-05 11:05:59 -08001675
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001676 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1677 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001678 return;
1679 }
1680
1681 nsecs_t currentTime = systemTime();
1682 if (mHasPoweredOff) {
1683 mHasPoweredOff = false;
1684 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001685 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001687 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1688 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001689 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001690 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001691 }
David Sodman4a36e932017-11-07 14:29:47 -08001692 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001693 }
David Sodman4a36e932017-11-07 14:29:47 -08001694 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695}
1696
1697void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 ATRACE_CALL();
1699 ALOGV("rebuildLayerStacks");
1700
Mathias Agopiancd60f992012-08-16 16:28:27 -07001701 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001702 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001703 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001704 mVisibleRegionsDirty = false;
1705 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001706
Jeff Sharkey76488112017-02-27 14:15:18 -07001707 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1708 Region opaqueRegion;
1709 Region dirtyRegion;
1710 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001711 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001712 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1713 const Transform& tr(displayDevice->getTransform());
1714 const Rect bounds(displayDevice->getBounds());
1715 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001716 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001717
Jeff Sharkey76488112017-02-27 14:15:18 -07001718 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001719 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001720 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1721 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 Region drawRegion(tr.transform(
1723 layer->visibleNonTransparentRegion));
1724 drawRegion.andSelf(bounds);
1725 if (!drawRegion.isEmpty()) {
1726 layersSortedByZ.add(layer);
1727 } else {
1728 // Clear out the HWC layer if this layer was
1729 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001730 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001731 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001732 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001733 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001734 // WM changes displayDevice->layerStack upon sleep/awake.
1735 // Here we make sure we delete the HWC layers even if
1736 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001737 hwcLayerDestroyed = layer->destroyHwcLayer(
1738 displayDevice->getHwcDisplayId());
1739 }
1740
1741 // If a layer is not going to get a release fence because
1742 // it is invisible, but it is also going to release its
1743 // old buffer, add it to the list of layers needing
1744 // fences.
1745 if (hwcLayerDestroyed) {
1746 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1747 mLayersWithQueuedFrames.cend(), layer);
1748 if (found != mLayersWithQueuedFrames.cend()) {
1749 layersNeedingFences.add(layer);
1750 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001751 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001752 });
1753 }
1754 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001755 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001756 displayDevice->undefinedRegion.set(bounds);
1757 displayDevice->undefinedRegion.subtractSelf(
1758 tr.transform(opaqueRegion));
1759 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001760 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001761 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001762}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001763
Romain Guy0147a172017-06-01 13:53:56 -07001764mat4 SurfaceFlinger::computeSaturationMatrix() const {
1765 if (mSaturation == 1.0f) {
1766 return mat4();
1767 }
1768
1769 // Rec.709 luma coefficients
1770 float3 luminance{0.213f, 0.715f, 0.072f};
1771 luminance *= 1.0f - mSaturation;
1772 return mat4(
1773 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1774 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1775 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1776 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1777 );
1778}
1779
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001780// pickColorMode translates a given dataspace into the best available color mode.
1781// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001782android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001783 if (mForceNativeColorMode) {
1784 return HAL_COLOR_MODE_NATIVE;
1785 }
1786
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001787 switch (dataSpace) {
1788 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1789 // system expects.
1790 case HAL_DATASPACE_UNKNOWN:
1791 case HAL_DATASPACE_SRGB:
1792 case HAL_DATASPACE_V0_SRGB:
1793 return HAL_COLOR_MODE_SRGB;
1794 break;
1795
1796 case HAL_DATASPACE_DISPLAY_P3:
1797 return HAL_COLOR_MODE_DISPLAY_P3;
1798 break;
1799
1800 default:
1801 // TODO (courtneygo): Do we want to assert an error here?
1802 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1803 dataSpace);
1804 return HAL_COLOR_MODE_SRGB;
1805 break;
1806 }
1807}
1808
Romain Guy0147a172017-06-01 13:53:56 -07001809android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001810 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001811 // Only support sRGB and Display-P3 right now.
1812 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1813 return HAL_DATASPACE_DISPLAY_P3;
1814 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001815 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1816 return HAL_DATASPACE_DISPLAY_P3;
1817 }
1818 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1819 return HAL_DATASPACE_DISPLAY_P3;
1820 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001821 if (!hasHdr) {
1822 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1823 return HAL_DATASPACE_DISPLAY_P3;
1824 }
1825 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1826 return HAL_DATASPACE_DISPLAY_P3;
1827 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001828 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001829
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001830 return HAL_DATASPACE_V0_SRGB;
1831}
1832
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 ATRACE_CALL();
1835 ALOGV("setUpHWComposer");
1836
Jesse Hall028dc8f2013-08-20 16:35:32 -07001837 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001838 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1839 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1840 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1841
1842 // If nothing has changed (!dirty), don't recompose.
1843 // If something changed, but we don't currently have any visible layers,
1844 // and didn't when we last did a composition, then skip it this time.
1845 // The second rule does two things:
1846 // - When all layers are removed from a display, we'll emit one black
1847 // frame, then nothing more until we get new layers.
1848 // - When a display is created with a private layer stack, we won't
1849 // emit any black frames until a layer is added to the layer stack.
1850 bool mustRecompose = dirty && !(empty && wasEmpty);
1851
1852 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1853 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1854 mustRecompose ? "doing" : "skipping",
1855 dirty ? "+" : "-",
1856 empty ? "+" : "-",
1857 wasEmpty ? "+" : "-");
1858
Dan Stoza71433162014-02-04 16:22:36 -08001859 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001860
1861 if (mustRecompose) {
1862 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1863 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001864 }
1865
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 // build the h/w work list
1867 if (CC_UNLIKELY(mGeometryInvalid)) {
1868 mGeometryInvalid = false;
1869 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1870 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1871 const auto hwcId = displayDevice->getHwcDisplayId();
1872 if (hwcId >= 0) {
1873 const Vector<sp<Layer>>& currentLayers(
1874 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001875 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001876 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001878 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001881 }
1882 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001883
Robert Carrae060832016-11-28 10:51:00 -08001884 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001885 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001887 }
1888 }
1889 }
1890 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 }
Riley Andrews03414a12014-07-01 14:22:59 -07001892
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001893
Romain Guy0147a172017-06-01 13:53:56 -07001894 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001895
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 // Set the per-frame data
1897 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1898 auto& displayDevice = mDisplays[displayId];
1899 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001900
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 if (hwcId < 0) {
1902 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001903 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001905 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001906 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1907 "display %zd: %d", displayId, result);
1908 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001910 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1911 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001912 !displayDevice->getHdrSupport()) {
1913 layer->forceClientComposition(hwcId);
1914 }
1915
chaviwc9232ed2017-11-14 15:31:15 -08001916 if (layer->getForceClientComposition(hwcId)) {
1917 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1918 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1919 continue;
1920 }
1921
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 layer->setPerFrameData(displayDevice);
1923 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001924
1925 if (hasWideColorDisplay) {
1926 android_color_mode newColorMode;
1927 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1928
1929 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001930 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1931 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001932 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1933 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1934 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1935 }
1936 newColorMode = pickColorMode(newDataSpace);
1937
Thierry Strudel2924d012017-08-14 15:19:37 -07001938 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001939 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 }
1941
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001942 mPreviousColorMatrix = colorMatrix;
1943
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001945 auto& displayDevice = mDisplays[displayId];
1946 if (!displayDevice->isDisplayOn()) {
1947 continue;
1948 }
1949
David Sodman105b7dc2017-11-04 20:28:14 -07001950 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1952 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001953 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001955
Mathias Agopiancd60f992012-08-16 16:28:27 -07001956void SurfaceFlinger::doComposition() {
1957 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001958 ALOGV("doComposition");
1959
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001960 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001961 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001962 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001963 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001964 // transform the dirty region into this screen's coordinate space
1965 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001966
1967 // repaint the framebuffer (if needed)
1968 doDisplayComposition(hw, dirtyRegion);
1969
Mathias Agopiancd60f992012-08-16 16:28:27 -07001970 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001971 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001972 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001973 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001974 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001975}
1976
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977void SurfaceFlinger::postFramebuffer()
1978{
Mathias Agopian841cde52012-03-01 15:44:37 -08001979 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001981
Mathias Agopiana44b0412011-10-16 18:46:35 -07001982 const nsecs_t now = systemTime();
1983 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001984
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1986 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001987 if (!displayDevice->isDisplayOn()) {
1988 continue;
1989 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 const auto hwcId = displayDevice->getHwcDisplayId();
1991 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001992 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001993 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001994 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001995 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001997 // The layer buffer from the previous frame (if any) is released
1998 // by HWC only when the release fence from this frame (if any) is
1999 // signaled. Always get the release fence from HWC first.
2000 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002001 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002002
2003 // If the layer was client composited in the previous frame, we
2004 // need to merge with the previous client target acquire fence.
2005 // Since we do not track that, always merge with the current
2006 // client target acquire fence when it is available, even though
2007 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002009 releaseFence = Fence::merge("LayerRelease", releaseFence,
2010 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002011 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002012
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 layer->onLayerDisplayed(releaseFence);
2014 }
Chia-I Wu83806892017-11-16 10:50:20 -08002015
2016 // We've got a list of layers needing fences, that are disjoint with
2017 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2018 // supply them with the present fence.
2019 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002020 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002021 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2022 layer->onLayerDisplayed(presentFence);
2023 }
2024 }
2025
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002027 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002028 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002029 }
2030
Mathias Agopiana44b0412011-10-16 18:46:35 -07002031 mLastSwapBufferTime = systemTime() - now;
2032 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002033
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002034 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002035 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2036 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2037 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2038 logFrameStats();
2039 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041}
2042
Mathias Agopian87baae12012-07-31 12:38:26 -07002043void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002044{
Mathias Agopian841cde52012-03-01 15:44:37 -08002045 ATRACE_CALL();
2046
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002047 // here we keep a copy of the drawing state (that is the state that's
2048 // going to be overwritten by handleTransactionLocked()) outside of
2049 // mStateLock so that the side-effects of the State assignment
2050 // don't happen with mStateLock held (which can cause deadlocks).
2051 State drawingState(mDrawingState);
2052
Mathias Agopianca4d3602011-05-19 15:38:14 -07002053 Mutex::Autolock _l(mStateLock);
2054 const nsecs_t now = systemTime();
2055 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056
Mathias Agopianca4d3602011-05-19 15:38:14 -07002057 // Here we're guaranteed that some transaction flags are set
2058 // so we can call handleTransactionLocked() unconditionally.
2059 // We call getTransactionFlags(), which will also clear the flags,
2060 // with mStateLock held to guarantee that mCurrentState won't change
2061 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002062
Mathias Agopiane57f2922012-08-09 16:29:12 -07002063 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002064 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002065
Mathias Agopianca4d3602011-05-19 15:38:14 -07002066 mLastTransactionTime = systemTime() - now;
2067 mDebugInTransaction = 0;
2068 invalidateHwcGeometry();
2069 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002070}
2071
Lloyd Pique715a2c12017-12-14 17:18:08 -08002072DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2073 HWC2::Connection connection) const {
2074 // Figure out whether the event is for the primary display or an
2075 // external display by matching the Hwc display id against one for a
2076 // connected display. If we did not find a match, we then check what
2077 // displays are not already connected to determine the type. If we don't
2078 // have a connected primary display, we assume the new display is meant to
2079 // be the primary display, and then if we don't have an external display,
2080 // we assume it is that.
2081 const auto primaryDisplayId =
2082 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2083 const auto externalDisplayId =
2084 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2085 if (primaryDisplayId && primaryDisplayId == display) {
2086 return DisplayDevice::DISPLAY_PRIMARY;
2087 } else if (externalDisplayId && externalDisplayId == display) {
2088 return DisplayDevice::DISPLAY_EXTERNAL;
2089 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2090 return DisplayDevice::DISPLAY_PRIMARY;
2091 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2092 return DisplayDevice::DISPLAY_EXTERNAL;
2093 }
2094
2095 return DisplayDevice::DISPLAY_ID_INVALID;
2096}
2097
Lloyd Piqueba04e622017-12-14 17:11:26 -08002098void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2099 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002100 auto displayType = determineDisplayType(event.display, event.connection);
2101 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2102 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2103 continue;
2104 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002105
2106 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2107 ALOGE("External displays are not supported by the vr hardware composer.");
2108 continue;
2109 }
2110
Lloyd Pique715a2c12017-12-14 17:18:08 -08002111 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002112
2113 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002114 ALOGV("Creating built in display %d", displayType);
2115 ALOGW_IF(mBuiltinDisplays[displayType],
2116 "Overwriting display token for display type %d", displayType);
2117 mBuiltinDisplays[displayType] = new BBinder();
2118 // All non-virtual displays are currently considered secure.
2119 DisplayDeviceState info(displayType, true);
2120 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2121 "Built-in Screen" : "External Screen";
2122 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2123 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002124 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002125 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002126
Lloyd Piquefcd86612017-12-14 17:15:36 -08002127 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2128 if (idx >= 0) {
2129 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2130 mInterceptor.saveDisplayDeletion(info.displayId);
2131 mCurrentState.displays.removeItemsAt(idx);
2132 }
2133 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002134 }
2135
2136 processDisplayChangesLocked();
2137 }
2138
2139 mPendingHotplugEvents.clear();
2140}
2141
Lloyd Pique347200f2017-12-14 17:00:15 -08002142void SurfaceFlinger::processDisplayChangesLocked() {
2143 // here we take advantage of Vector's copy-on-write semantics to
2144 // improve performance by skipping the transaction entirely when
2145 // know that the lists are identical
2146 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2147 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2148 if (!curr.isIdenticalTo(draw)) {
2149 mVisibleRegionsDirty = true;
2150 const size_t cc = curr.size();
2151 size_t dc = draw.size();
2152
2153 // find the displays that were removed
2154 // (ie: in drawing state but not in current state)
2155 // also handle displays that changed
2156 // (ie: displays that are in both lists)
2157 for (size_t i = 0; i < dc;) {
2158 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2159 if (j < 0) {
2160 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002161 // Call makeCurrent() on the primary display so we can
2162 // be sure that nothing associated with this display
2163 // is current.
2164 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2165 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2166 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2167 if (hw != nullptr) hw->disconnect(getHwComposer());
2168 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2169 mEventThread->onHotplugReceived(draw[i].type, false);
2170 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002171 } else {
2172 // this display is in both lists. see if something changed.
2173 const DisplayDeviceState& state(curr[j]);
2174 const wp<IBinder>& display(curr.keyAt(j));
2175 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2176 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2177 if (state_binder != draw_binder) {
2178 // changing the surface is like destroying and
2179 // recreating the DisplayDevice, so we just remove it
2180 // from the drawing state, so that it get re-added
2181 // below.
2182 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2183 if (hw != nullptr) hw->disconnect(getHwComposer());
2184 mDisplays.removeItem(display);
2185 mDrawingState.displays.removeItemsAt(i);
2186 dc--;
2187 // at this point we must loop to the next item
2188 continue;
2189 }
2190
2191 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2192 if (disp != nullptr) {
2193 if (state.layerStack != draw[i].layerStack) {
2194 disp->setLayerStack(state.layerStack);
2195 }
2196 if ((state.orientation != draw[i].orientation) ||
2197 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2198 disp->setProjection(state.orientation, state.viewport, state.frame);
2199 }
2200 if (state.width != draw[i].width || state.height != draw[i].height) {
2201 disp->setDisplaySize(state.width, state.height);
2202 }
2203 }
2204 }
2205 ++i;
2206 }
2207
2208 // find displays that were added
2209 // (ie: in current state but not in drawing state)
2210 for (size_t i = 0; i < cc; i++) {
2211 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2212 const DisplayDeviceState& state(curr[i]);
2213
2214 sp<DisplaySurface> dispSurface;
2215 sp<IGraphicBufferProducer> producer;
2216 sp<IGraphicBufferProducer> bqProducer;
2217 sp<IGraphicBufferConsumer> bqConsumer;
2218 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2219
2220 int32_t hwcId = -1;
2221 if (state.isVirtualDisplay()) {
2222 // Virtual displays without a surface are dormant:
2223 // they have external state (layer stack, projection,
2224 // etc.) but no internal state (i.e. a DisplayDevice).
2225 if (state.surface != nullptr) {
2226 // Allow VR composer to use virtual displays.
2227 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2228 int width = 0;
2229 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2230 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2231 int height = 0;
2232 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2233 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2234 int intFormat = 0;
2235 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2236 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2237 auto format = static_cast<android_pixel_format_t>(intFormat);
2238
2239 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2240 }
2241
2242 // TODO: Plumb requested format back up to consumer
2243
2244 sp<VirtualDisplaySurface> vds =
2245 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2246 bqProducer, bqConsumer,
2247 state.displayName);
2248
2249 dispSurface = vds;
2250 producer = vds;
2251 }
2252 } else {
2253 ALOGE_IF(state.surface != nullptr,
2254 "adding a supported display, but rendering "
2255 "surface is provided (%p), ignoring it",
2256 state.surface.get());
2257
2258 hwcId = state.type;
2259 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2260 producer = bqProducer;
2261 }
2262
2263 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002264
Lloyd Pique347200f2017-12-14 17:00:15 -08002265 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002266 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002267 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002268 bool hasWideColorModes = false;
2269 std::vector<android_color_mode_t> modes =
2270 getHwComposer().getColorModes(state.type);
2271 for (android_color_mode_t colorMode : modes) {
2272 switch (colorMode) {
2273 case HAL_COLOR_MODE_DISPLAY_P3:
2274 case HAL_COLOR_MODE_ADOBE_RGB:
2275 case HAL_COLOR_MODE_DCI_P3:
2276 hasWideColorModes = true;
2277 break;
2278 default:
2279 break;
2280 }
2281 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002282 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002283 }
2284
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002285 bool hasHdrSupport = false;
2286 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2287 getHwComposer().getHdrCapabilities(state.type);
2288 if (hdrCapabilities) {
2289 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2290 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2291 hasHdrSupport = iter != types.cend();
2292 }
2293
Lloyd Pique347200f2017-12-14 17:00:15 -08002294 sp<DisplayDevice> hw =
2295 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002296 dispSurface, producer, useWideColorMode,
2297 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002298
Lloyd Piquec5208312018-01-08 17:59:02 -08002299 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2300 if (useWideColorMode) {
2301 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002302 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002303 setActiveColorModeInternal(hw, defaultColorMode);
2304 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002305 hw->setLayerStack(state.layerStack);
2306 hw->setProjection(state.orientation, state.viewport, state.frame);
2307 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002308
Lloyd Pique347200f2017-12-14 17:00:15 -08002309 mDisplays.add(display, hw);
2310 if (!state.isVirtualDisplay()) {
2311 mEventThread->onHotplugReceived(state.type, true);
2312 }
2313 }
2314 }
2315 }
2316 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002317
2318 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002319}
2320
Mathias Agopian87baae12012-07-31 12:38:26 -07002321void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002322{
Dan Stoza7dde5992015-05-22 09:51:44 -07002323 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002324 mCurrentState.traverseInZOrder([](Layer* layer) {
2325 layer->notifyAvailableFrames();
2326 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328 /*
2329 * Traversal of the children
2330 * (perform the transaction for each of them if needed)
2331 */
2332
Mathias Agopian3559b072012-08-15 13:46:03 -07002333 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002334 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002336 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337
2338 const uint32_t flags = layer->doTransaction(0);
2339 if (flags & Layer::eVisibleRegion)
2340 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002341 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 }
2343
2344 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002345 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346 */
2347
Mathias Agopiane57f2922012-08-09 16:29:12 -07002348 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002349 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002351 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352
Mathias Agopian84300952012-11-21 16:02:13 -08002353 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2354 // The transform hint might have changed for some layers
2355 // (either because a display has changed, or because a layer
2356 // as changed).
2357 //
2358 // Walk through all the layers in currentLayers,
2359 // and update their transform hint.
2360 //
2361 // If a layer is visible only on a single display, then that
2362 // display is used to calculate the hint, otherwise we use the
2363 // default display.
2364 //
2365 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2366 // the hint is set before we acquire a buffer from the surface texture.
2367 //
2368 // NOTE: layer transactions have taken place already, so we use their
2369 // drawing state. However, SurfaceFlinger's own transaction has not
2370 // happened yet, so we must use the current state layer list
2371 // (soon to become the drawing state list).
2372 //
2373 sp<const DisplayDevice> disp;
2374 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002375 bool first = true;
2376 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002377 // NOTE: we rely on the fact that layers are sorted by
2378 // layerStack first (so we don't have to traverse the list
2379 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002380 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002381 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002382 currentlayerStack = layerStack;
2383 // figure out if this layerstack is mirrored
2384 // (more than one display) if so, pick the default display,
2385 // if not, pick the only display it's on.
2386 disp.clear();
2387 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2388 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002389 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002390 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002391 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002392 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002393 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002394 break;
2395 }
2396 }
2397 }
2398 }
Chet Haase91d25932013-04-11 15:24:55 -07002399
Robert Carr56a0b9a2017-12-04 16:06:13 -08002400 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002401 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002402 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2403 // redraw after transform hint changes. See bug 8508397.
2404
2405 // could be null when this layer is using a layerStack
2406 // that is not visible on any display. Also can occur at
2407 // screen off/on times.
2408 disp = getDefaultDisplayDeviceLocked();
2409 }
2410 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002411 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002412 if (disp != nullptr) {
2413 layer->updateTransformHint(disp);
2414 }
Robert Carr2047fae2016-11-28 14:09:09 -08002415
2416 first = false;
2417 });
Mathias Agopian84300952012-11-21 16:02:13 -08002418 }
2419
2420
Mathias Agopian3559b072012-08-15 13:46:03 -07002421 /*
2422 * Perform our own transaction if needed
2423 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002424
2425 if (mLayersAdded) {
2426 mLayersAdded = false;
2427 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002428 mVisibleRegionsDirty = true;
2429 }
2430
2431 // some layers might have been removed, so
2432 // we need to update the regions they're exposing.
2433 if (mLayersRemoved) {
2434 mLayersRemoved = false;
2435 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002436 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002437 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002438 // this layer is not visible anymore
2439 // TODO: we could traverse the tree from front to back and
2440 // compute the actual visible region
2441 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442 Region visibleReg;
2443 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002444 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002445 }
Robert Carr2047fae2016-11-28 14:09:09 -08002446 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447 }
2448
2449 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002450
2451 updateCursorAsync();
2452}
2453
2454void SurfaceFlinger::updateCursorAsync()
2455{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002456 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2457 auto& displayDevice = mDisplays[displayId];
2458 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002459 continue;
2460 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461
2462 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2463 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002464 }
2465 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002466}
2467
2468void SurfaceFlinger::commitTransaction()
2469{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002470 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002471 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002472 for (const auto& l : mLayersPendingRemoval) {
2473 recordBufferingStats(l->getName().string(),
2474 l->getOccupancyHistory(true));
2475 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002476 }
2477 mLayersPendingRemoval.clear();
2478 }
2479
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002480 // If this transaction is part of a window animation then the next frame
2481 // we composite should be considered an animation as well.
2482 mAnimCompositionPending = mAnimTransactionPending;
2483
Mathias Agopian4fec8732012-06-29 14:12:52 -07002484 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002485 mDrawingState.traverseInZOrder([](Layer* layer) {
2486 layer->commitChildList();
2487 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002488 mTransactionPending = false;
2489 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002490 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491}
2492
Chia-I Wuab0c3192017-08-01 11:29:00 -07002493void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002494 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
Mathias Agopian841cde52012-03-01 15:44:37 -08002496 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499 Region aboveOpaqueLayers;
2500 Region aboveCoveredLayers;
2501 Region dirty;
2502
Mathias Agopian87baae12012-07-31 12:38:26 -07002503 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
Robert Carr2047fae2016-11-28 14:09:09 -08002505 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002507 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508
Jesse Hall01e29052013-02-19 16:13:35 -08002509 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002510 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002511 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002512
Mathias Agopianab028732010-03-16 16:41:46 -07002513 /*
2514 * opaqueRegion: area of a surface that is fully opaque.
2515 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002517
2518 /*
2519 * visibleRegion: area of a surface that is visible on screen
2520 * and not fully transparent. This is essentially the layer's
2521 * footprint minus the opaque regions above it.
2522 * Areas covered by a translucent surface are considered visible.
2523 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002525
2526 /*
2527 * coveredRegion: area of a surface that is covered by all
2528 * visible regions above it (which includes the translucent areas).
2529 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002531
Jesse Halla8026d22012-09-25 13:25:04 -07002532 /*
2533 * transparentRegion: area of a surface that is hinted to be completely
2534 * transparent. This is only used to tell when the layer has no visible
2535 * non-transparent regions and can be removed from the layer list. It
2536 * does not affect the visibleRegion of this layer or any layers
2537 * beneath it. The hint may not be correct if apps don't respect the
2538 * SurfaceView restrictions (which, sadly, some don't).
2539 */
2540 Region transparentRegion;
2541
Mathias Agopianab028732010-03-16 16:41:46 -07002542
2543 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002544 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002545 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002546 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002549 if (!visibleRegion.isEmpty()) {
2550 // Remove the transparent area from the visible region
2551 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002552 if (tr.preserveRects()) {
2553 // transform the transparent region
2554 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002555 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002556 // transformation too complex, can't do the
2557 // transparent region optimization.
2558 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002559 }
Mathias Agopianab028732010-03-16 16:41:46 -07002560 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561
Mathias Agopianab028732010-03-16 16:41:46 -07002562 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002563 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002564 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002565 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2566 // the opaque region is the layer's footprint
2567 opaqueRegion = visibleRegion;
2568 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 }
2570 }
2571
Robert Carre5f4f692018-01-12 13:12:28 -08002572 if (visibleRegion.isEmpty()) {
2573 layer->clearVisibilityRegions();
2574 return;
2575 }
2576
Mathias Agopianab028732010-03-16 16:41:46 -07002577 // Clip the covered region to the visible region
2578 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2579
2580 // Update aboveCoveredLayers for next (lower) layer
2581 aboveCoveredLayers.orSelf(visibleRegion);
2582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 // subtract the opaque region covered by the layers above us
2584 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585
2586 // compute this layer's dirty region
2587 if (layer->contentDirty) {
2588 // we need to invalidate the whole region
2589 dirty = visibleRegion;
2590 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002591 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 layer->contentDirty = false;
2593 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002594 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002595 * the exposed region consists of two components:
2596 * 1) what's VISIBLE now and was COVERED before
2597 * 2) what's EXPOSED now less what was EXPOSED before
2598 *
2599 * note that (1) is conservative, we start with the whole
2600 * visible region but only keep what used to be covered by
2601 * something -- which mean it may have been exposed.
2602 *
2603 * (2) handles areas that were not covered by anything but got
2604 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002605 */
Mathias Agopianab028732010-03-16 16:41:46 -07002606 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002607 const Region oldVisibleRegion = layer->visibleRegion;
2608 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002609 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2610 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 }
2612 dirty.subtractSelf(aboveOpaqueLayers);
2613
2614 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002615 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616
Mathias Agopianab028732010-03-16 16:41:46 -07002617 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002619
Jesse Halla8026d22012-09-25 13:25:04 -07002620 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 layer->setVisibleRegion(visibleRegion);
2622 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002623 layer->setVisibleNonTransparentRegion(
2624 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002625 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626
Mathias Agopian87baae12012-07-31 12:38:26 -07002627 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628}
2629
Chia-I Wuab0c3192017-08-01 11:29:00 -07002630void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002631 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002632 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002633 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002634 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002635 }
2636 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002637}
2638
Dan Stoza6b9454d2014-11-07 16:00:59 -08002639bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002641 ALOGV("handlePageFlip");
2642
Brian Andersond6927fb2016-07-23 23:37:30 -07002643 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644
Mathias Agopian4fec8732012-06-29 14:12:52 -07002645 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002646 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002647 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002648
2649 // Store the set of layers that need updates. This set must not change as
2650 // buffers are being latched, as this could result in a deadlock.
2651 // Example: Two producers share the same command stream and:
2652 // 1.) Layer 0 is latched
2653 // 2.) Layer 0 gets a new frame
2654 // 2.) Layer 1 gets a new frame
2655 // 3.) Layer 1 is latched.
2656 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2657 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002658 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002659 if (layer->hasQueuedFrame()) {
2660 frameQueued = true;
2661 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002662 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002663 } else {
2664 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002665 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002666 } else {
2667 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002668 }
Robert Carr2047fae2016-11-28 14:09:09 -08002669 });
2670
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002672 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002673 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002674 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002675 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002676 newDataLatched = true;
2677 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002678 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002679
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002680 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002681
2682 // If we will need to wake up at some time in the future to deal with a
2683 // queued frame that shouldn't be displayed during this vsync period, wake
2684 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002685 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002686 signalLayerUpdate();
2687 }
2688
2689 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002690 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691}
2692
Mathias Agopianad456f92011-01-13 17:53:01 -08002693void SurfaceFlinger::invalidateHwcGeometry()
2694{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002695 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002696}
2697
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002698
Fabien Sanglard830b8472016-11-30 16:35:58 -08002699void SurfaceFlinger::doDisplayComposition(
2700 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002701 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702{
Dan Stoza71433162014-02-04 16:22:36 -08002703 // We only need to actually compose the display if:
2704 // 1) It is being handled by hardware composer, which may need this to
2705 // keep its virtual display state machine in sync, or
2706 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002707 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002708 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002710 return;
2711 }
2712
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002714 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002715
2716 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002717 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718}
2719
Chia-I Wub02087d2017-11-09 10:19:54 -08002720bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002721{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002722 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002723
Chia-I Wub02087d2017-11-09 10:19:54 -08002724 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002725 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002727
2728 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002729 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2730 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002731 if (applyColorMatrix) {
2732 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2733 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2734 }
2735
David Sodman105b7dc2017-11-04 20:28:14 -07002736 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 if (hasClientComposition) {
2738 ALOGV("hasClientComposition");
2739
David Sodmanbc815282017-11-05 18:57:52 -08002740 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002741 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002742 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002743 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002744 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002745 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002747 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002748
2749 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002750 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002751 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2752 }
2753 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002754 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002755
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002756 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002757 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002759 // when using overlays, we assume a fully transparent framebuffer
2760 // NOTE: we could reduce how much we need to clear, for instance
2761 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002762 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002763 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002764 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002765 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002766 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002767 // we're left with the letterbox region
2768 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002770
2771 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002772 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002773
Mathias Agopianb9494d52012-04-18 02:28:45 -07002774 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002775 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002776 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002778 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002779 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002780
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002782 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002783 // scissor on the main display. It should never be needed
2784 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002785 const Rect& bounds(displayDevice->getBounds());
2786 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002787 if (scissor != bounds) {
2788 // scissor doesn't match the screen's dimensions, so we
2789 // need to clear everything outside of it and enable
2790 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002791
Mathias Agopianf45c5102012-10-24 16:29:17 -07002792 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002794 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002795 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002796 }
2797 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002798 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002799
Mathias Agopian85d751c2012-08-29 16:59:24 -07002800 /*
2801 * and then, render the layers targeted at the framebuffer
2802 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002803
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 ALOGV("Rendering client layers");
2805 const Transform& displayTransform = displayDevice->getTransform();
2806 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002807 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 bool firstLayer = true;
2809 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002810 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 displayTransform.transform(layer->visibleRegion)));
2812 ALOGV("Layer: %s", layer->getName().string());
2813 ALOGV(" Composition type: %s",
2814 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002815 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 switch (layer->getCompositionType(hwcId)) {
2817 case HWC2::Composition::Cursor:
2818 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002819 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002821 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002823 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002824 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002825 // never clear the very first layer since we're
2826 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002827 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002828 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002829 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002830 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002832 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002833 break;
2834 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002836 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002837 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002838 } else {
2839 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002840 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002842 }
2843 } else {
2844 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002846 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002848 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002849 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002850 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002851 }
2852 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002853
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002854 if (applyColorMatrix) {
2855 getRenderEngine().setupColorTransform(oldColorMatrix);
2856 }
2857
Mathias Agopianf45c5102012-10-24 16:29:17 -07002858 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002859 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002860 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861}
2862
Fabien Sanglard830b8472016-11-30 16:35:58 -08002863void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2864 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002865 RenderEngine& engine(getRenderEngine());
2866 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867}
2868
Dan Stoza7d89d062015-04-30 13:29:25 -07002869status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002870 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002871 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002872 const sp<Layer>& lbc,
2873 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002874{
Dan Stoza7d89d062015-04-30 13:29:25 -07002875 // add this layer to the current state list
2876 {
2877 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002879 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2880 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002881 return NO_MEMORY;
2882 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 if (parent == nullptr) {
2884 mCurrentState.layersSortedByZ.add(lbc);
2885 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002886 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002887 ALOGE("addClientLayer called with a removed parent");
2888 return NAME_NOT_FOUND;
2889 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890 parent->addChild(lbc);
2891 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002892
Dan Stoza7d89d062015-04-30 13:29:25 -07002893 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 mLayersAdded = true;
2895 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002896 }
2897
Mathias Agopian96f08192010-06-02 23:28:45 -07002898 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002899 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002900
Dan Stoza7d89d062015-04-30 13:29:25 -07002901 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002902}
2903
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002904status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002905 Mutex::Autolock _l(mStateLock);
2906
chaviw8b3871a2017-11-01 17:41:01 -07002907 if (layer->isPendingRemoval()) {
2908 return NO_ERROR;
2909 }
2910
Robert Carr1f0a16a2016-10-24 16:27:39 -07002911 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002912 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002913 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002914 if (topLevelOnly) {
2915 return NO_ERROR;
2916 }
2917
Chia-I Wu98f1c102017-05-30 14:54:08 -07002918 sp<Layer> ancestor = p;
2919 while (ancestor->getParent() != nullptr) {
2920 ancestor = ancestor->getParent();
2921 }
2922 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2923 ALOGE("removeLayer called with a layer whose parent has been removed");
2924 return NAME_NOT_FOUND;
2925 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002926
2927 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002928 } else {
2929 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002930 }
2931
Robert Carr136e2f62017-02-08 17:54:29 -08002932 // As a matter of normal operation, the LayerCleaner will produce a second
2933 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2934 // so we will succeed in promoting it, but it's already been removed
2935 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2936 // otherwise something has gone wrong and we are leaking the layer.
2937 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002938 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2939 layer->getName().string(),
2940 (p != nullptr) ? p->getName().string() : "no-parent");
2941 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002942 } else if (index < 0) {
2943 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002944 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002945
Chia-I Wuc6657022017-08-15 11:18:17 -07002946 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002947 mLayersPendingRemoval.add(layer);
2948 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002949 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002950 setTransactionFlags(eTransactionNeeded);
2951 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952}
2953
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002954uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002955 return android_atomic_release_load(&mTransactionFlags);
2956}
2957
Mathias Agopian3f844832013-08-07 21:24:32 -07002958uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2960}
2961
Mathias Agopian3f844832013-08-07 21:24:32 -07002962uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2964 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002965 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 }
2967 return old;
2968}
2969
Mathias Agopian8b33f032012-07-24 20:43:54 -07002970void SurfaceFlinger::setTransactionState(
2971 const Vector<ComposerState>& state,
2972 const Vector<DisplayState>& displays,
2973 uint32_t flags)
2974{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002975 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002976 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002977 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002978
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002979 if (flags & eAnimation) {
2980 // For window updates that are part of an animation we must wait for
2981 // previous animation "frames" to be handled.
2982 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002983 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002984 if (CC_UNLIKELY(err != NO_ERROR)) {
2985 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002986 // caller after a few seconds.
2987 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2988 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002989 mAnimTransactionPending = false;
2990 break;
2991 }
2992 }
2993 }
2994
Mathias Agopiane57f2922012-08-09 16:29:12 -07002995 size_t count = displays.size();
2996 for (size_t i=0 ; i<count ; i++) {
2997 const DisplayState& s(displays[i]);
2998 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002999 }
3000
Mathias Agopiane57f2922012-08-09 16:29:12 -07003001 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07003002 for (size_t i=0 ; i<count ; i++) {
3003 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003004 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08003005 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003006 // IInterface, or one of its own or even one of our own but a
3007 // different type. All these situations would cause us to crash.
3008 //
3009 // NOTE: it would be better to use RTTI as we could directly check
3010 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08003011 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003012 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08003013 if (binder != nullptr) {
3014 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003015 sp<Client> client( static_cast<Client *>(s.client.get()) );
3016 transactionFlags |= setClientStateLocked(client, s.state);
3017 }
3018 }
3019 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003020 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003021
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003022 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3023 // anyway. This can be used as a flush mechanism for previous async transactions.
3024 // Empty animation transaction can be used to simulate back-pressure, so also force a
3025 // transaction for empty animation transactions.
3026 if (transactionFlags == 0 &&
3027 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003028 transactionFlags = eTransactionNeeded;
3029 }
3030
Mathias Agopian386aa982011-11-07 21:58:03 -08003031 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003032 if (mInterceptor.isEnabled()) {
3033 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3034 }
Irvel468051e2016-06-13 16:44:44 -07003035
Mathias Agopian386aa982011-11-07 21:58:03 -08003036 // this triggers the transaction
3037 setTransactionFlags(transactionFlags);
3038
3039 // if this is a synchronous transaction, wait for it to take effect
3040 // before returning.
3041 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003042 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003043 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003044 if (flags & eAnimation) {
3045 mAnimTransactionPending = true;
3046 }
3047 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003048 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3049 if (CC_UNLIKELY(err != NO_ERROR)) {
3050 // just in case something goes wrong in SF, return to the
3051 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003052 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3053 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003054 break;
3055 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003056 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 }
3058}
3059
Mathias Agopiane57f2922012-08-09 16:29:12 -07003060uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3061{
Jesse Hall9a143922012-10-04 16:29:19 -07003062 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3063 if (dpyIdx < 0)
3064 return 0;
3065
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003067 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003068 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003069 const uint32_t what = s.what;
3070 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003071 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 disp.surface = s.surface;
3073 flags |= eDisplayTransactionNeeded;
3074 }
3075 }
3076 if (what & DisplayState::eLayerStackChanged) {
3077 if (disp.layerStack != s.layerStack) {
3078 disp.layerStack = s.layerStack;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003082 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003083 if (disp.orientation != s.orientation) {
3084 disp.orientation = s.orientation;
3085 flags |= eDisplayTransactionNeeded;
3086 }
3087 if (disp.frame != s.frame) {
3088 disp.frame = s.frame;
3089 flags |= eDisplayTransactionNeeded;
3090 }
3091 if (disp.viewport != s.viewport) {
3092 disp.viewport = s.viewport;
3093 flags |= eDisplayTransactionNeeded;
3094 }
3095 }
Michael Lentine47e45402014-07-18 15:34:25 -07003096 if (what & DisplayState::eDisplaySizeChanged) {
3097 if (disp.width != s.width) {
3098 disp.width = s.width;
3099 flags |= eDisplayTransactionNeeded;
3100 }
3101 if (disp.height != s.height) {
3102 disp.height = s.height;
3103 flags |= eDisplayTransactionNeeded;
3104 }
3105 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003106 }
3107 return flags;
3108}
3109
3110uint32_t SurfaceFlinger::setClientStateLocked(
3111 const sp<Client>& client,
3112 const layer_state_t& s)
3113{
Mathias Agopian13127d82013-03-05 17:47:11 -08003114 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003115 if (layer == nullptr) {
3116 return 0;
3117 }
3118
3119 if (layer->isPendingRemoval()) {
3120 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3121 return 0;
3122 }
3123
3124 uint32_t flags = 0;
3125
3126 const uint32_t what = s.what;
3127 bool geometryAppliesWithResize =
3128 what & layer_state_t::eGeometryAppliesWithResize;
3129 if (what & layer_state_t::ePositionChanged) {
3130 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3131 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132 }
chaviw8b3871a2017-11-01 17:41:01 -07003133 }
3134 if (what & layer_state_t::eLayerChanged) {
3135 // NOTE: index needs to be calculated before we update the state
3136 const auto& p = layer->getParent();
3137 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003138 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003139 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003140 mCurrentState.layersSortedByZ.removeAt(idx);
3141 mCurrentState.layersSortedByZ.add(layer);
3142 // we need traversal (state changed)
3143 // AND transaction (list changed)
3144 flags |= eTransactionNeeded|eTraversalNeeded;
3145 }
chaviw8b3871a2017-11-01 17:41:01 -07003146 } else {
3147 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003148 flags |= eTransactionNeeded|eTraversalNeeded;
3149 }
3150 }
chaviw8b3871a2017-11-01 17:41:01 -07003151 }
3152 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003153 // NOTE: index needs to be calculated before we update the state
3154 const auto& p = layer->getParent();
3155 if (p == nullptr) {
3156 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3157 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3158 mCurrentState.layersSortedByZ.removeAt(idx);
3159 mCurrentState.layersSortedByZ.add(layer);
3160 // we need traversal (state changed)
3161 // AND transaction (list changed)
3162 flags |= eTransactionNeeded|eTraversalNeeded;
3163 }
3164 } else {
3165 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3166 flags |= eTransactionNeeded|eTraversalNeeded;
3167 }
chaviw8b3871a2017-11-01 17:41:01 -07003168 }
3169 }
3170 if (what & layer_state_t::eSizeChanged) {
3171 if (layer->setSize(s.w, s.h)) {
3172 flags |= eTraversalNeeded;
3173 }
3174 }
3175 if (what & layer_state_t::eAlphaChanged) {
3176 if (layer->setAlpha(s.alpha))
3177 flags |= eTraversalNeeded;
3178 }
3179 if (what & layer_state_t::eColorChanged) {
3180 if (layer->setColor(s.color))
3181 flags |= eTraversalNeeded;
3182 }
3183 if (what & layer_state_t::eMatrixChanged) {
3184 if (layer->setMatrix(s.matrix))
3185 flags |= eTraversalNeeded;
3186 }
3187 if (what & layer_state_t::eTransparentRegionChanged) {
3188 if (layer->setTransparentRegionHint(s.transparentRegion))
3189 flags |= eTraversalNeeded;
3190 }
3191 if (what & layer_state_t::eFlagsChanged) {
3192 if (layer->setFlags(s.flags, s.mask))
3193 flags |= eTraversalNeeded;
3194 }
3195 if (what & layer_state_t::eCropChanged) {
3196 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3197 flags |= eTraversalNeeded;
3198 }
3199 if (what & layer_state_t::eFinalCropChanged) {
3200 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3201 flags |= eTraversalNeeded;
3202 }
3203 if (what & layer_state_t::eLayerStackChanged) {
3204 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3205 // We only allow setting layer stacks for top level layers,
3206 // everything else inherits layer stack from its parent.
3207 if (layer->hasParent()) {
3208 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3209 layer->getName().string());
3210 } else if (idx < 0) {
3211 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3212 "that also does not appear in the top level layer list. Something"
3213 " has gone wrong.", layer->getName().string());
3214 } else if (layer->setLayerStack(s.layerStack)) {
3215 mCurrentState.layersSortedByZ.removeAt(idx);
3216 mCurrentState.layersSortedByZ.add(layer);
3217 // we need traversal (state changed)
3218 // AND transaction (list changed)
3219 flags |= eTransactionNeeded|eTraversalNeeded;
3220 }
3221 }
3222 if (what & layer_state_t::eDeferTransaction) {
3223 if (s.barrierHandle != nullptr) {
3224 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3225 } else if (s.barrierGbp != nullptr) {
3226 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3227 if (authenticateSurfaceTextureLocked(gbp)) {
3228 const auto& otherLayer =
3229 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3230 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3231 } else {
3232 ALOGE("Attempt to defer transaction to to an"
3233 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003234 }
3235 }
chaviw8b3871a2017-11-01 17:41:01 -07003236 // We don't trigger a traversal here because if no other state is
3237 // changed, we don't want this to cause any more work
3238 }
3239 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003240 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003241 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003242 if (!hadParent) {
3243 mCurrentState.layersSortedByZ.remove(layer);
3244 }
chaviw8b3871a2017-11-01 17:41:01 -07003245 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003246 }
chaviw8b3871a2017-11-01 17:41:01 -07003247 }
3248 if (what & layer_state_t::eReparentChildren) {
3249 if (layer->reparentChildren(s.reparentHandle)) {
3250 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003251 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003252 }
chaviw8b3871a2017-11-01 17:41:01 -07003253 if (what & layer_state_t::eDetachChildren) {
3254 layer->detachChildren();
3255 }
3256 if (what & layer_state_t::eOverrideScalingModeChanged) {
3257 layer->setOverrideScalingMode(s.overrideScalingMode);
3258 // We don't trigger a traversal here because if no other state is
3259 // changed, we don't want this to cause any more work
3260 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003261 return flags;
3262}
3263
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003264status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003265 const String8& name,
3266 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003267 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003268 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3269 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003271 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003272 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003273 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003274 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003275 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003276
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003277 status_t result = NO_ERROR;
3278
3279 sp<Layer> layer;
3280
Cody Northropbc755282017-03-31 12:00:08 -06003281 String8 uniqueName = getUniqueLayerName(name);
3282
Mathias Agopian3165cc22012-08-08 19:42:09 -07003283 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3284 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003285 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003286 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003287 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 break;
chaviw13fdc492017-06-27 12:40:18 -07003290 case ISurfaceComposerClient::eFXSurfaceColor:
3291 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003292 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003293 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003294 break;
3295 default:
3296 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297 break;
3298 }
3299
Dan Stoza7d89d062015-04-30 13:29:25 -07003300 if (result != NO_ERROR) {
3301 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003302 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003303
Chia-I Wuab0c3192017-08-01 11:29:00 -07003304 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3305 // TODO b/64227542
3306 if (windowType == 441731) {
3307 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3308 layer->setPrimaryDisplayOnly();
3309 }
3310
Albert Chaulk479c60c2017-01-27 14:21:34 -05003311 layer->setInfo(windowType, ownerUid);
3312
Robert Carr1f0a16a2016-10-24 16:27:39 -07003313 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003314 if (result != NO_ERROR) {
3315 return result;
3316 }
Irvelffc9efc2016-07-27 15:16:37 -07003317 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003318
3319 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003320 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321}
3322
Cody Northropbc755282017-03-31 12:00:08 -06003323String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3324{
3325 bool matchFound = true;
3326 uint32_t dupeCounter = 0;
3327
3328 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3329 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3330
3331 // Loop over layers until we're sure there is no matching name
3332 while (matchFound) {
3333 matchFound = false;
3334 mDrawingState.traverseInZOrder([&](Layer* layer) {
3335 if (layer->getName() == uniqueName) {
3336 matchFound = true;
3337 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3338 }
3339 });
3340 }
3341
3342 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3343
3344 return uniqueName;
3345}
3346
David Sodman0c69cad2017-08-21 12:12:51 -07003347status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003348 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3349 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350{
3351 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003352 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 case PIXEL_FORMAT_TRANSPARENT:
3354 case PIXEL_FORMAT_TRANSLUCENT:
3355 format = PIXEL_FORMAT_RGBA_8888;
3356 break;
3357 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003358 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359 break;
3360 }
3361
David Sodman0c69cad2017-08-21 12:12:51 -07003362 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3363 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003364 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003365 *handle = layer->getHandle();
3366 *gbp = layer->getProducer();
3367 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003368 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003369
David Sodman0c69cad2017-08-21 12:12:51 -07003370 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003371 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003372}
3373
chaviw13fdc492017-06-27 12:40:18 -07003374status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003375 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003376 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003377{
chaviw13fdc492017-06-27 12:40:18 -07003378 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003379 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003380 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003381}
3382
Mathias Agopianac9fa422013-02-11 16:40:36 -08003383status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384{
Robert Carr9524cb32017-02-13 11:32:32 -08003385 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003386 status_t err = NO_ERROR;
3387 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003388 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003389 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003390 err = removeLayer(l);
3391 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3392 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003393 }
3394 return err;
3395}
3396
Mathias Agopian13127d82013-03-05 17:47:11 -08003397status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003398{
Mathias Agopian67106042013-03-14 19:18:13 -07003399 // called by ~LayerCleaner() when all references to the IBinder (handle)
3400 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003401 sp<Layer> l = layer.promote();
3402 if (l == nullptr) {
3403 // The layer has already been removed, carry on
3404 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003405 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003406 // If we have a parent, then we can continue to live as long as it does.
3407 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003408}
3409
Mathias Agopianb60314a2012-04-10 22:09:54 -07003410// ---------------------------------------------------------------------------
3411
Andy McFadden13a082e2012-08-24 10:16:42 -07003412void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003413 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003414 Vector<ComposerState> state;
3415 Vector<DisplayState> displays;
3416 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003417 d.what = DisplayState::eDisplayProjectionChanged |
3418 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003419 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003420 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003421 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003422 d.frame.makeInvalid();
3423 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003424 d.width = 0;
3425 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003426 displays.add(d);
3427 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003428 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3429 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003430
David Sodman105b7dc2017-11-04 20:28:14 -07003431 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003432 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003433 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003434
Brian Andersond0010582017-03-07 13:20:31 -08003435 // Use phase of 0 since phase is not known.
3436 // Use latency of 0, which will snap to the ideal latency.
3437 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003438}
3439
3440void SurfaceFlinger::initializeDisplays() {
3441 class MessageScreenInitialized : public MessageBase {
3442 SurfaceFlinger* flinger;
3443 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003444 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003445 virtual bool handler() {
3446 flinger->onInitializeDisplays();
3447 return true;
3448 }
3449 };
3450 sp<MessageBase> msg = new MessageScreenInitialized(this);
3451 postMessageAsync(msg); // we may be called from main thread, use async message
3452}
3453
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003454void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003455 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003456 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3457 this);
3458 int32_t type = hw->getDisplayType();
3459 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003460
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003461 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003462 return;
3463 }
3464
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003465 hw->setPowerMode(mode);
3466 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3467 ALOGW("Trying to set power mode for virtual display");
3468 return;
3469 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003470
Irvelffc9efc2016-07-27 15:16:37 -07003471 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003472 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003473 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3474 if (idx < 0) {
3475 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3476 return;
3477 }
3478 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3479 }
3480
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003481 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003482 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003483 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003484 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3485 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003486 // FIXME: eventthread only knows about the main display right now
3487 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003488 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003491 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003492 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003493 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003494
3495 struct sched_param param = {0};
3496 param.sched_priority = 1;
3497 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3498 ALOGW("Couldn't set SCHED_FIFO on display on");
3499 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003500 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003501 // Turn off the display
3502 struct sched_param param = {0};
3503 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3504 ALOGW("Couldn't set SCHED_OTHER on display off");
3505 }
3506
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003507 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3508 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003509 disableHardwareVsync(true); // also cancels any in-progress resync
3510
Mathias Agopiancde87a32012-09-13 14:09:01 -07003511 // FIXME: eventthread only knows about the main display right now
3512 mEventThread->onScreenReleased();
3513 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003514
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003515 getHwComposer().setPowerMode(type, mode);
3516 mVisibleRegionsDirty = true;
3517 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003518 } else if (mode == HWC_POWER_MODE_DOZE ||
3519 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003520 // Update display while dozing
3521 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003522 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3523 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003524 // FIXME: eventthread only knows about the main display right now
3525 mEventThread->onScreenAcquired();
3526 resyncToHardwareVsync(true);
3527 }
3528 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3529 // Leave display going to doze
3530 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3531 disableHardwareVsync(true); // also cancels any in-progress resync
3532 // FIXME: eventthread only knows about the main display right now
3533 mEventThread->onScreenReleased();
3534 }
3535 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003536 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003537 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003538 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003539 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003540}
3541
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003542void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3543 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003544 SurfaceFlinger& mFlinger;
3545 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003547 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003548 MessageSetPowerMode(SurfaceFlinger& flinger,
3549 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3550 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003551 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003552 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003553 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003554 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003555 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003556 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003557 ALOGW("Attempt to set power mode = %d for virtual display",
3558 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003559 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003560 mFlinger.setPowerModeInternal(
3561 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003562 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003563 return true;
3564 }
3565 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003566 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003567 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003568}
3569
3570// ---------------------------------------------------------------------------
3571
Lloyd Pique755e3192018-01-31 16:46:15 -08003572status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3573 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003575
Mathias Agopianbd115332013-04-18 16:41:04 -07003576 IPCThreadState* ipc = IPCThreadState::self();
3577 const int pid = ipc->getCallingPid();
3578 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003579
Mathias Agopianbd115332013-04-18 16:41:04 -07003580 if ((uid != AID_SHELL) &&
3581 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003582 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003583 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003585 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003586 // (this would indicate SF is stuck, but we want to be able to
3587 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003588 status_t err = mStateLock.timedLock(s2ns(1));
3589 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003590 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003591 result.appendFormat(
3592 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3593 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003594 }
3595
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003596 bool dumpAll = true;
3597 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003598 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003599
3600 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003601 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003602 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3603 dumpAll = false;
3604 }
3605
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003606 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003607 if ((index < numArgs) &&
3608 (args[index] == String16("--list"))) {
3609 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003610 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003611 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003612 }
3613
3614 if ((index < numArgs) &&
3615 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003616 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003617 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003618 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003619 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003620
3621 if ((index < numArgs) &&
3622 (args[index] == String16("--latency-clear"))) {
3623 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003624 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003625 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003626 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003627
3628 if ((index < numArgs) &&
3629 (args[index] == String16("--dispsync"))) {
3630 index++;
3631 mPrimaryDispSync.dump(result);
3632 dumpAll = false;
3633 }
Dan Stozab90cf072015-03-05 11:05:59 -08003634
3635 if ((index < numArgs) &&
3636 (args[index] == String16("--static-screen"))) {
3637 index++;
3638 dumpStaticScreenStats(result);
3639 dumpAll = false;
3640 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003641
3642 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003643 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003644 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003645 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003646 dumpAll = false;
3647 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003648
3649 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3650 index++;
3651 dumpWideColorInfo(result);
3652 dumpAll = false;
3653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003655
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003656 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003657 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003658 }
3659
Mathias Agopian9795c422009-08-26 16:36:26 -07003660 if (locked) {
3661 mStateLock.unlock();
3662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663 }
3664 write(fd, result.string(), result.size());
3665 return NO_ERROR;
3666}
3667
Dan Stozac7014012014-02-14 15:03:43 -08003668void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3669 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003670{
Robert Carr2047fae2016-11-28 14:09:09 -08003671 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003672 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003673 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003674}
3675
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003676void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003677 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003678{
3679 String8 name;
3680 if (index < args.size()) {
3681 name = String8(args[index]);
3682 index++;
3683 }
3684
David Sodman105b7dc2017-11-04 20:28:14 -07003685 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003686 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003687 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003688
3689 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003690 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003691 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003692 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003693 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003694 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003695 }
Robert Carr2047fae2016-11-28 14:09:09 -08003696 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003697 }
3698}
3699
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003700void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003701 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003702{
3703 String8 name;
3704 if (index < args.size()) {
3705 name = String8(args[index]);
3706 index++;
3707 }
3708
Robert Carr2047fae2016-11-28 14:09:09 -08003709 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003710 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003711 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003712 }
Robert Carr2047fae2016-11-28 14:09:09 -08003713 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003714
Svetoslavd85084b2014-03-20 10:28:31 -07003715 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003716}
3717
Jamie Gennis6547ff42013-07-16 20:12:42 -07003718// This should only be called from the main thread. Otherwise it would need
3719// the lock and should use mCurrentState rather than mDrawingState.
3720void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003721 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003722 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003723 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003724
3725 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3726}
3727
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003728void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003729{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003730 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003731
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003732 if (isLayerTripleBufferingDisabled())
3733 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003734
3735 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003736 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003737 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003738 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003739 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3740 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003741 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003742}
3743
Dan Stozab90cf072015-03-05 11:05:59 -08003744void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3745{
3746 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003747 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3748 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003749 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003750 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003751 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3752 b + 1, bucketTimeSec, percent);
3753 }
David Sodman4a36e932017-11-07 14:29:47 -08003754 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003755 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003756 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003757 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003758 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003759}
3760
Dan Stozae77c7662016-05-13 11:37:28 -07003761void SurfaceFlinger::recordBufferingStats(const char* layerName,
3762 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003763 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3764 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003765 for (const auto& segment : history) {
3766 if (!segment.usedThirdBuffer) {
3767 stats.twoBufferTime += segment.totalTime;
3768 }
3769 if (segment.occupancyAverage < 1.0f) {
3770 stats.doubleBufferedTime += segment.totalTime;
3771 } else if (segment.occupancyAverage < 2.0f) {
3772 stats.tripleBufferedTime += segment.totalTime;
3773 }
3774 ++stats.numSegments;
3775 stats.totalTime += segment.totalTime;
3776 }
3777}
3778
Brian Andersond6927fb2016-07-23 23:37:30 -07003779void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3780 result.appendFormat("Layer frame timestamps:\n");
3781
3782 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3783 const size_t count = currentLayers.size();
3784 for (size_t i=0 ; i<count ; i++) {
3785 currentLayers[i]->dumpFrameEvents(result);
3786 }
3787}
3788
Dan Stozae77c7662016-05-13 11:37:28 -07003789void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3790 result.append("Buffering stats:\n");
3791 result.append(" [Layer name] <Active time> <Two buffer> "
3792 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003793 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003794 typedef std::tuple<std::string, float, float, float> BufferTuple;
3795 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003796 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003797 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003798 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003799 if (stats.numSegments == 0) {
3800 continue;
3801 }
3802 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3803 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3804 stats.totalTime;
3805 float doubleBufferRatio = static_cast<float>(
3806 stats.doubleBufferedTime) / stats.totalTime;
3807 float tripleBufferRatio = static_cast<float>(
3808 stats.tripleBufferedTime) / stats.totalTime;
3809 sorted.insert({activeTime, {name, twoBufferRatio,
3810 doubleBufferRatio, tripleBufferRatio}});
3811 }
3812 for (const auto& sortedPair : sorted) {
3813 float activeTime = sortedPair.first;
3814 const BufferTuple& values = sortedPair.second;
3815 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3816 std::get<0>(values).c_str(), activeTime,
3817 std::get<1>(values), std::get<2>(values),
3818 std::get<3>(values));
3819 }
3820 result.append("\n");
3821}
3822
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003823void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3824 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003825 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003826
3827 // TODO: print out if wide-color mode is active or not
3828
3829 for (size_t d = 0; d < mDisplays.size(); d++) {
3830 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3831 int32_t hwcId = displayDevice->getHwcDisplayId();
3832 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3833 continue;
3834 }
3835
3836 result.appendFormat("Display %d color modes:\n", hwcId);
3837 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3838 for (auto&& mode : modes) {
3839 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3840 }
3841
3842 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3843 result.appendFormat(" Current color mode: %s (%d)\n",
3844 decodeColorMode(currentMode).c_str(), currentMode);
3845 }
3846 result.append("\n");
3847}
3848
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003849LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003850 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003851 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3852 const State& state = useDrawing ? mDrawingState : mCurrentState;
3853 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003854 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003855 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003856 });
3857
3858 return layersProto;
3859}
3860
Mathias Agopian74d211a2013-04-22 16:55:35 +02003861void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3862 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003863{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003864 bool colorize = false;
3865 if (index < args.size()
3866 && (args[index] == String16("--color"))) {
3867 colorize = true;
3868 index++;
3869 }
3870
3871 Colorizer colorizer(colorize);
3872
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003873 // figure out if we're stuck somewhere
3874 const nsecs_t now = systemTime();
3875 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3876 const nsecs_t inTransaction(mDebugInTransaction);
3877 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3878 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3879
3880 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003881 * Dump library configuration.
3882 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003883
3884 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003885 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003886 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003887 appendSfConfigString(result);
3888 appendUiConfigString(result);
3889 appendGuiConfigString(result);
3890 result.append("\n");
3891
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003892 result.append("\nWide-Color information:\n");
3893 dumpWideColorInfo(result);
3894
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003895 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003896 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003897 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003898 result.append(SyncFeatures::getInstance().toString());
3899 result.append("\n");
3900
David Sodman105b7dc2017-11-04 20:28:14 -07003901 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003902
Andy McFadden41d67d72014-04-25 16:58:34 -07003903 colorizer.bold(result);
3904 result.append("DispSync configuration: ");
3905 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003906 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003907 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003908 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003909 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003910 result.append("\n");
3911
Dan Stozab90cf072015-03-05 11:05:59 -08003912 // Dump static screen stats
3913 result.append("\n");
3914 dumpStaticScreenStats(result);
3915 result.append("\n");
3916
Dan Stozae77c7662016-05-13 11:37:28 -07003917 dumpBufferingStats(result);
3918
Andy McFadden4803b742012-09-24 19:07:20 -07003919 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003920 * Dump the visible layer list
3921 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003922 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003923 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003924 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003925
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003926 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003927 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3928 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929
3930 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003931 * Dump Display state
3932 */
3933
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003934 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003935 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003936 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003937 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3938 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003939 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003940 }
3941
3942 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943 * Dump SurfaceFlinger global state
3944 */
3945
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003946 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003947 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003948 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949
Mathias Agopian888c8222012-08-04 21:10:38 -07003950 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003951 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003952
David Sodmanbc815282017-11-05 18:57:52 -08003953 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003954
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003955 if (hw) {
3956 hw->undefinedRegion.dump(result, "undefinedRegion");
3957 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3958 hw->getOrientation(), hw->isDisplayOn());
3959 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003960 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 " last eglSwapBuffers() time: %f us\n"
3962 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003963 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003964 " refresh-rate : %f fps\n"
3965 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003966 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003967 " gpu_to_cpu_unsupported : %d\n"
3968 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003969 mLastSwapBufferTime/1000.0,
3970 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003971 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003972 1e9 / activeConfig->getVsyncPeriod(),
3973 activeConfig->getDpiX(),
3974 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003975 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976
Mathias Agopian74d211a2013-04-22 16:55:35 +02003977 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003978 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003979
Mathias Agopian74d211a2013-04-22 16:55:35 +02003980 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003981 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003982
3983 /*
3984 * VSYNC state
3985 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003986 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003987 result.append("\n");
3988
3989 /*
3990 * HWC layer minidump
3991 */
3992 for (size_t d = 0; d < mDisplays.size(); d++) {
3993 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3994 int32_t hwcId = displayDevice->getHwcDisplayId();
3995 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3996 continue;
3997 }
3998
3999 result.appendFormat("Display %d HWC layers:\n", hwcId);
4000 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004001 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004002 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004003 });
Dan Stozae22aec72016-08-01 13:20:59 -07004004 result.append("\n");
4005 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004006
4007 /*
4008 * Dump HWComposer state
4009 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004010 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004011 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004012 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004013 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004014 result.appendFormat(" h/w composer %s\n",
4015 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004016 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004017
4018 /*
4019 * Dump gralloc state
4020 */
4021 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4022 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004023
4024 /*
4025 * Dump VrFlinger state if in use.
4026 */
4027 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4028 result.append("VrFlinger state:\n");
4029 result.append(mVrFlinger->Dump().c_str());
4030 result.append("\n");
4031 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032}
4033
Mathias Agopian13127d82013-03-05 17:47:11 -08004034const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004035SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004036 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004037 wp<IBinder> dpy;
4038 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4039 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4040 dpy = mDisplays.keyAt(i);
4041 break;
4042 }
4043 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004044 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004045 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4046 // Just use the primary display so we have something to return
4047 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4048 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004049 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004050}
4051
Keun young Park63f165f2012-08-31 10:53:36 -07004052bool SurfaceFlinger::startDdmConnection()
4053{
4054 void* libddmconnection_dso =
4055 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4056 if (!libddmconnection_dso) {
4057 return false;
4058 }
4059 void (*DdmConnection_start)(const char* name);
4060 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004061 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004062 if (!DdmConnection_start) {
4063 dlclose(libddmconnection_dso);
4064 return false;
4065 }
4066 (*DdmConnection_start)(getServiceName());
4067 return true;
4068}
4069
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004070status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 switch (code) {
4072 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004073 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004075 case CLEAR_ANIMATION_FRAME_STATS:
4076 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004077 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004078 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004079 case ENABLE_VSYNC_INJECTIONS:
4080 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 {
4082 // codes that require permission check
4083 IPCThreadState* ipc = IPCThreadState::self();
4084 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004085 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004086 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004087 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004088 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004089 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004091 break;
4092 }
Robert Carr1db73f62016-12-21 12:58:51 -08004093 /*
4094 * Calling setTransactionState is safe, because you need to have been
4095 * granted a reference to Client* and Handle* to do anything with it.
4096 *
4097 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4098 */
4099 case SET_TRANSACTION_STATE:
4100 case CREATE_SCOPED_CONNECTION:
4101 {
4102 return OK;
4103 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004104 case CAPTURE_SCREEN:
4105 {
4106 // codes that require permission check
4107 IPCThreadState* ipc = IPCThreadState::self();
4108 const int pid = ipc->getCallingPid();
4109 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004110 if ((uid != AID_GRAPHICS) &&
4111 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004112 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004113 return PERMISSION_DENIED;
4114 }
4115 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 }
chaviwa76b2712017-09-20 12:02:26 -07004117 case CAPTURE_LAYERS: {
4118 IPCThreadState* ipc = IPCThreadState::self();
4119 const int pid = ipc->getCallingPid();
4120 const int uid = ipc->getCallingUid();
4121 if ((uid != AID_GRAPHICS) &&
4122 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4123 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4124 return PERMISSION_DENIED;
4125 }
4126 break;
4127 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004129 return OK;
4130}
4131
4132status_t SurfaceFlinger::onTransact(
4133 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4134{
4135 status_t credentialCheck = CheckTransactCodeCredentials(code);
4136 if (credentialCheck != OK) {
4137 return credentialCheck;
4138 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4141 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004142 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004143 IPCThreadState* ipc = IPCThreadState::self();
4144 const int uid = ipc->getCallingUid();
4145 if (CC_UNLIKELY(uid != AID_SYSTEM
4146 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004147 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004148 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004149 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 return PERMISSION_DENIED;
4151 }
4152 int n;
4153 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004154 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004155 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 return NO_ERROR;
4157 case 1002: // SHOW_UPDATES
4158 n = data.readInt32();
4159 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004160 invalidateHwcGeometry();
4161 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004162 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004163 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004164 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004165 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004166 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004167 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004168 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004169 setTransactionFlags(
4170 eTransactionNeeded|
4171 eDisplayTransactionNeeded|
4172 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004173 return NO_ERROR;
4174 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004175 case 1006:{ // send empty update
4176 signalRefresh();
4177 return NO_ERROR;
4178 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004179 case 1008: // toggle use of hw composer
4180 n = data.readInt32();
4181 mDebugDisableHWC = n ? 1 : 0;
4182 invalidateHwcGeometry();
4183 repaintEverything();
4184 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004185 case 1009: // toggle use of transform hint
4186 n = data.readInt32();
4187 mDebugDisableTransformHint = n ? 1 : 0;
4188 invalidateHwcGeometry();
4189 repaintEverything();
4190 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004191 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004192 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 reply->writeInt32(0);
4194 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004195 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004196 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197 return NO_ERROR;
4198 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004199 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004200 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004201 return NO_ERROR;
4202 }
4203 case 1014: {
4204 // daltonize
4205 n = data.readInt32();
4206 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004207 case 1:
4208 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4209 break;
4210 case 2:
4211 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4212 break;
4213 case 3:
4214 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4215 break;
4216 default:
4217 mDaltonizer.setType(ColorBlindnessType::None);
4218 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004219 }
4220 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004221 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004222 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004223 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004224 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004225 invalidateHwcGeometry();
4226 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004227 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004229 case 1015: {
4230 // apply a color matrix
4231 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004232 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004233 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004234 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004235 for (size_t j = 0; j < 4; j++) {
4236 mColorMatrix[i][j] = data.readFloat();
4237 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004238 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004239 } else {
4240 mColorMatrix = mat4();
4241 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004242
4243 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4244 // the division by w in the fragment shader
4245 float4 lastRow(transpose(mColorMatrix)[3]);
4246 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4247 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4248 }
4249
Alan Viverette9c5a3332013-09-12 20:04:35 -07004250 invalidateHwcGeometry();
4251 repaintEverything();
4252 return NO_ERROR;
4253 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004254 // This is an experimental interface
4255 // Needs to be shifted to proper binder interface when we productize
4256 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004257 n = data.readInt32();
4258 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004259 return NO_ERROR;
4260 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004261 case 1017: {
4262 n = data.readInt32();
4263 mForceFullDamage = static_cast<bool>(n);
4264 return NO_ERROR;
4265 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004266 case 1018: { // Modify Choreographer's phase offset
4267 n = data.readInt32();
4268 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4269 return NO_ERROR;
4270 }
4271 case 1019: { // Modify SurfaceFlinger's phase offset
4272 n = data.readInt32();
4273 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4274 return NO_ERROR;
4275 }
Irvel468051e2016-06-13 16:44:44 -07004276 case 1020: { // Layer updates interceptor
4277 n = data.readInt32();
4278 if (n) {
4279 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004280 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004281 }
4282 else{
4283 ALOGV("Interceptor disabled");
4284 mInterceptor.disable();
4285 }
4286 return NO_ERROR;
4287 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004288 case 1021: { // Disable HWC virtual displays
4289 n = data.readInt32();
4290 mUseHwcVirtualDisplays = !n;
4291 return NO_ERROR;
4292 }
Romain Guy0147a172017-06-01 13:53:56 -07004293 case 1022: { // Set saturation boost
4294 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4295
4296 invalidateHwcGeometry();
4297 repaintEverything();
4298 return NO_ERROR;
4299 }
Romain Guy54f154a2017-10-24 21:40:32 +01004300 case 1023: { // Set native mode
4301 mForceNativeColorMode = data.readInt32() == 1;
4302
4303 invalidateHwcGeometry();
4304 repaintEverything();
4305 return NO_ERROR;
4306 }
4307 case 1024: { // Is wide color gamut rendering/color management supported?
4308 reply->writeBool(hasWideColorDisplay);
4309 return NO_ERROR;
4310 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004311 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004312 n = data.readInt32();
4313 if (n) {
4314 ALOGV("LayerTracing enabled");
4315 mTracing.enable();
4316 doTracing("tracing.enable");
4317 reply->writeInt32(NO_ERROR);
4318 } else {
4319 ALOGV("LayerTracing disabled");
4320 status_t err = mTracing.disable();
4321 reply->writeInt32(err);
4322 }
4323 return NO_ERROR;
4324 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004325 case 1026: { // Get layer tracing status
4326 reply->writeBool(mTracing.isEnabled());
4327 return NO_ERROR;
4328 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004329 }
4330 }
4331 return err;
4332}
4333
Steven Thomas6d8110b2017-08-31 18:24:21 -07004334void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004335 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004336 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004337}
4338
Steven Thomas6d8110b2017-08-31 18:24:21 -07004339void SurfaceFlinger::repaintEverything() {
4340 ConditionalLock _l(mStateLock,
4341 std::this_thread::get_id() != mMainThreadId);
4342 repaintEverythingLocked();
4343}
4344
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004345// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4346class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004347public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004348 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4349 ~WindowDisconnector() {
4350 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004351 }
4352
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004353private:
4354 ANativeWindow* mWindow;
4355 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004356};
4357
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004358status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4359 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4360 int32_t minLayerZ, int32_t maxLayerZ,
4361 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004362 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004363 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004364
chaviwa76b2712017-09-20 12:02:26 -07004365 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4366
4367 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4368 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4369
4370 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4371 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004372 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004373}
4374
4375status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004376 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004377 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004378 ATRACE_CALL();
4379
4380 class LayerRenderArea : public RenderArea {
4381 public:
chaviw7206d492017-11-10 16:16:12 -08004382 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004383 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004384 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004385 const Transform& getTransform() const override {
4386 // Make the top level transform the inverse the transform and it's parent so it sets
4387 // the whole capture back to 0,0
4388 return *new Transform(mLayer->getTransform().inverse());
4389 }
4390 Rect getBounds() const override {
4391 const Layer::State& layerState(mLayer->getDrawingState());
4392 return Rect(layerState.active.w, layerState.active.h);
4393 }
4394 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4395 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4396 bool isSecure() const override { return false; }
4397 bool needsFiltering() const override { return false; }
4398
chaviw7206d492017-11-10 16:16:12 -08004399 Rect getSourceCrop() const override {
4400 if (mCrop.isEmpty()) {
4401 return getBounds();
4402 } else {
4403 return mCrop;
4404 }
4405 }
chaviwa76b2712017-09-20 12:02:26 -07004406 bool getWideColorSupport() const override { return false; }
4407 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4408
4409 private:
chaviw7206d492017-11-10 16:16:12 -08004410 const sp<Layer> mLayer;
4411 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004412 };
4413
4414 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4415 auto parent = layerHandle->owner.promote();
4416
chaviw7206d492017-11-10 16:16:12 -08004417 if (parent == nullptr || parent->isPendingRemoval()) {
4418 ALOGE("captureLayers called with a removed parent");
4419 return NAME_NOT_FOUND;
4420 }
4421
4422 Rect crop(sourceCrop);
4423 if (sourceCrop.width() <= 0) {
4424 crop.left = 0;
4425 crop.right = parent->getCurrentState().active.w;
4426 }
4427
4428 if (sourceCrop.height() <= 0) {
4429 crop.top = 0;
4430 crop.bottom = parent->getCurrentState().active.h;
4431 }
4432
4433 int32_t reqWidth = crop.width() * frameScale;
4434 int32_t reqHeight = crop.height() * frameScale;
4435
4436 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4437
chaviwa76b2712017-09-20 12:02:26 -07004438 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4439 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4440 if (!layer->isVisible()) {
4441 return;
4442 }
4443 visitor(layer);
4444 });
4445 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004446 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004447}
4448
4449status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4450 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004451 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004452 bool useIdentityTransform) {
4453 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004454
chaviwa76b2712017-09-20 12:02:26 -07004455 renderArea.updateDimensions();
4456
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004457 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4458 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4459 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4460 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004461
4462 // This mutex protects syncFd and captureResult for communication of the return values from the
4463 // main thread back to this Binder thread
4464 std::mutex captureMutex;
4465 std::condition_variable captureCondition;
4466 std::unique_lock<std::mutex> captureLock(captureMutex);
4467 int syncFd = -1;
4468 std::optional<status_t> captureResult;
4469
Robert Carr03480e22018-01-04 16:02:06 -08004470 const int uid = IPCThreadState::self()->getCallingUid();
4471 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4472
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004473 sp<LambdaMessage> message = new LambdaMessage([&]() {
4474 // If there is a refresh pending, bug out early and tell the binder thread to try again
4475 // after the refresh.
4476 if (mRefreshPending) {
4477 ATRACE_NAME("Skipping screenshot for now");
4478 std::unique_lock<std::mutex> captureLock(captureMutex);
4479 captureResult = std::make_optional<status_t>(EAGAIN);
4480 captureCondition.notify_one();
4481 return;
4482 }
4483
4484 status_t result = NO_ERROR;
4485 int fd = -1;
4486 {
4487 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004488 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004489 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004490 }
4491
4492 {
4493 std::unique_lock<std::mutex> captureLock(captureMutex);
4494 syncFd = fd;
4495 captureResult = std::make_optional<status_t>(result);
4496 captureCondition.notify_one();
4497 }
4498 });
4499
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004500 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004501 if (result == NO_ERROR) {
4502 captureCondition.wait(captureLock, [&]() { return captureResult; });
4503 while (*captureResult == EAGAIN) {
4504 captureResult.reset();
4505 result = postMessageAsync(message);
4506 if (result != NO_ERROR) {
4507 return result;
4508 }
4509 captureCondition.wait(captureLock, [&]() { return captureResult; });
4510 }
4511 result = *captureResult;
4512 }
4513
4514 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004515 sync_wait(syncFd, -1);
4516 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004517 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004519 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004520}
4521
chaviwa76b2712017-09-20 12:02:26 -07004522void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4523 TraverseLayersFunction traverseLayers, bool yswap,
4524 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004525 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004526
Mathias Agopian3f844832013-08-07 21:24:32 -07004527 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004528
4529 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004530 const auto raWidth = renderArea.getWidth();
4531 const auto raHeight = renderArea.getHeight();
4532
4533 const auto reqWidth = renderArea.getReqWidth();
4534 const auto reqHeight = renderArea.getReqHeight();
4535 Rect sourceCrop = renderArea.getSourceCrop();
4536
4537 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4538 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004539
Dan Stozac1879002014-05-22 15:59:05 -07004540 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004541 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004542 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004543 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004544 }
4545
4546 // ensure that sourceCrop is inside screen
4547 if (sourceCrop.left < 0) {
4548 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4549 }
chaviwa76b2712017-09-20 12:02:26 -07004550 if (sourceCrop.right > raWidth) {
4551 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004552 }
4553 if (sourceCrop.top < 0) {
4554 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4555 }
chaviwa76b2712017-09-20 12:02:26 -07004556 if (sourceCrop.bottom > raHeight) {
4557 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004558 }
4559
chaviwa76b2712017-09-20 12:02:26 -07004560 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004561 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4562 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004563
Mathias Agopian180f10d2013-04-10 22:55:41 -07004564 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004565 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004566
4567 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004568 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4569 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004570 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004571
4572 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004573 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004574
chaviwa76b2712017-09-20 12:02:26 -07004575 traverseLayers([&](Layer* layer) {
4576 if (filtering) layer->setFiltering(true);
4577 layer->draw(renderArea, useIdentityTransform);
4578 if (filtering) layer->setFiltering(false);
4579 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004580}
4581
chaviwa76b2712017-09-20 12:02:26 -07004582status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4583 TraverseLayersFunction traverseLayers,
4584 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004585 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004586 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004587 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004588 ATRACE_CALL();
4589
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004590 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004591
4592 traverseLayers([&](Layer* layer) {
4593 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4594 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004595
Robert Carr03480e22018-01-04 16:02:06 -08004596 // We allow the system server to take screenshots of secure layers for
4597 // use in situations like the Screen-rotation animation and place
4598 // the impetus on WindowManager to not persist them.
4599 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004600 ALOGW("FB is protected: PERMISSION_DENIED");
4601 return PERMISSION_DENIED;
4602 }
4603
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004604 // this binds the given EGLImage as a framebuffer for the
4605 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004606 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4607 if (bufferBond.getStatus() != NO_ERROR) {
4608 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004609 return INVALID_OPERATION;
4610 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004611
Dan Stozaabcda352017-06-01 14:37:39 -07004612 // this will in fact render into our dequeued buffer
4613 // via an FBO, which means we didn't have to create
4614 // an EGLSurface and therefore we're not
4615 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004616 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004617
Dan Stozaabcda352017-06-01 14:37:39 -07004618 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004619 getRenderEngine().finish();
4620 *outSyncFd = -1;
4621
chaviwa76b2712017-09-20 12:02:26 -07004622 const auto reqWidth = renderArea.getReqWidth();
4623 const auto reqHeight = renderArea.getReqHeight();
4624
Dan Stozaabcda352017-06-01 14:37:39 -07004625 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4626 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004627 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004628 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004629 } else {
4630 base::unique_fd syncFd = getRenderEngine().flush();
4631 if (syncFd < 0) {
4632 getRenderEngine().finish();
4633 }
4634 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004635 }
4636
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004637 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004638}
4639
Mathias Agopiand5556842013-09-19 17:08:37 -07004640void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004641 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004642 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004643 for (size_t y = 0; y < h; y++) {
4644 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4645 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004646 if (p[x] != 0xFF000000) return;
4647 }
4648 }
chaviwa76b2712017-09-20 12:02:26 -07004649 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004650
Robert Carr2047fae2016-11-28 14:09:09 -08004651 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004652 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004653 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004654 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4655 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4656 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4657 static_cast<float>(state.color.a));
4658 i++;
4659 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004660 }
4661}
4662
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004663// ---------------------------------------------------------------------------
4664
Dan Stoza412903f2017-04-27 13:42:17 -07004665void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4666 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004667}
4668
Dan Stoza412903f2017-04-27 13:42:17 -07004669void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4670 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004671}
4672
chaviwa76b2712017-09-20 12:02:26 -07004673void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4674 int32_t maxLayerZ,
4675 const LayerVector::Visitor& visitor) {
4676 // We loop through the first level of layers without traversing,
4677 // as we need to interpret min/max layer Z in the top level Z space.
4678 for (const auto& layer : mDrawingState.layersSortedByZ) {
4679 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4680 continue;
4681 }
4682 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004683 // relative layers are traversed in Layer::traverseInZOrder
4684 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004685 continue;
4686 }
4687 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004688 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4689 return;
4690 }
chaviwa76b2712017-09-20 12:02:26 -07004691 if (!layer->isVisible()) {
4692 return;
4693 }
4694 visitor(layer);
4695 });
4696 }
4697}
4698
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004699}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004700
4701
4702#if defined(__gl_h_)
4703#error "don't include gl/gl.h in this file"
4704#endif
4705
4706#if defined(__gl2_h_)
4707#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004708#endif