blob: 0fd5050c7ff345de9674596d17618993312dca70 [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 Sanglardc93afd52017-03-13 13:02:42 -0700132bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
David Sodmanbc815282017-11-05 18:57:52 -0800157SurfaceFlingerBE::SurfaceFlingerBE()
158 : mHwcServiceName(getHwcServiceName()),
159 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800160 mFrameBuckets(),
161 mTotalTime(0),
162 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800163 mComposerSequenceId(0) {
164}
165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700167 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700169 mTransactionPending(false),
170 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700171 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700172 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700173 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800175 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800177 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800178 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700181 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700182 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700183 mDebugInSwapBuffers(0),
184 mLastSwapBufferTime(0),
185 mDebugInTransaction(0),
186 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700187 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700188 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800189 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000190 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700191 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700192 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700193 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800194 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800195 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700196 mVrFlingerRequestsDisplay(false),
David Sodman105b7dc2017-11-04 20:28:14 -0700197 mMainThreadId(std::this_thread::get_id())
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800200
201 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
203
204 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
206
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800207 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700210 useContextPriority = getBool< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::useContextPriority>(false);
212
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700213 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
215
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700216 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
218
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800219 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
220 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
221
Steven Thomas050b2c82017-03-06 11:45:16 -0800222 // Vr flinger is only enabled on Daydream ready devices.
223 useVrFlinger = getBool< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::useVrFlinger>(false);
225
Fabien Sanglard1971b632017-03-10 14:50:03 -0800226 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
227 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
228
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229 hasWideColorDisplay =
230 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
231
David Sodman99974d22017-11-28 12:04:33 -0800232 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 // debugging stuff...
235 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700236
Mathias Agopianb4b17302013-03-20 18:36:41 -0700237 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700238 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700239
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240 property_get("debug.sf.showupdates", value, "0");
241 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700243 property_get("debug.sf.ddms", value, "0");
244 mDebugDDMS = atoi(value);
245 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700246 if (!startDdmConnection()) {
247 // start failed, and DDMS debugging not enabled
248 mDebugDDMS = 0;
249 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700250 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700251 ALOGI_IF(mDebugRegion, "showupdates enabled");
252 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700253
254 property_get("debug.sf.disable_backpressure", value, "0");
255 mPropagateBackpressure = !atoi(value);
256 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700257
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800258 property_get("debug.sf.enable_hwc_vds", value, "0");
259 mUseHwcVirtualDisplays = atoi(value);
260 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800262 property_get("ro.sf.disable_triple_buffer", value, "1");
263 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800264 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700265
Romain Guy11d63f42017-07-20 12:47:14 -0700266 // We should be reading 'persist.sys.sf.color_saturation' here
267 // but since /data may be encrypted, we need to wait until after vold
268 // comes online to attempt to read the property. The property is
269 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800270
271 if (useTrebleTestingOverride()) {
272 // Without the override SurfaceFlinger cannot connect to HIDL
273 // services that are not listed in the manifests. Considered
274 // deriving the setting from the set service name, but it
275 // would be brittle if the name that's not 'default' is used
276 // for production purposes later on.
277 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
278 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279}
280
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281void SurfaceFlinger::onFirstRef()
282{
283 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800284}
285
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286SurfaceFlinger::~SurfaceFlinger()
287{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Mathias Agopiane57f2922012-08-09 16:29:12 -0700372sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700373 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700374 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800375 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700376 }
Jesse Hall692c7232012-11-08 15:41:56 -0800377 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700378}
379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380void SurfaceFlinger::bootFinished()
381{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700382 if (mStartPropertySetThread->join() != NO_ERROR) {
383 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800384 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 const nsecs_t now = systemTime();
386 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000387 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700388
389 // wait patiently for the window manager death
390 const String16 name("window");
391 sp<IBinder> window(defaultServiceManager()->getService(name));
392 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700393 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700394 }
395
Steven Thomas050b2c82017-03-06 11:45:16 -0800396 if (mVrFlinger) {
397 mVrFlinger->OnBootFinished();
398 }
399
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700400 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700401 // formerly we would just kill the process, but we now ask it to exit so it
402 // can choose where to stop the animation.
403 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700404
405 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
406 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
407 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700408
Thierry Strudel2924d012017-08-14 15:19:37 -0700409 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700410 readPersistentProperties();
411 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700412 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Mathias Agopian3f844832013-08-07 21:24:32 -0700415void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700416 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700417 RenderEngine& engine;
418 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700419 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
421 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700422 }
423 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425 return true;
426 }
427 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700428 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700429}
430
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431class DispSyncSource : public VSyncSource, private DispSync::Callback {
432public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700433 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 const char* name) :
435 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700436 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700437 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000438 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
439 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700440 mDispSync(dispSync),
441 mCallbackMutex(),
442 mCallback(),
443 mVsyncMutex(),
444 mPhaseOffset(phaseOffset),
445 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700446
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 virtual ~DispSyncSource() {}
448
449 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700450 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700451 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000452 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 static_cast<DispSync::Callback*>(this));
454 if (err != NO_ERROR) {
455 ALOGE("error registering vsync callback: %s (%d)",
456 strerror(-err), err);
457 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700458 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700459 } else {
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700466 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 }
470
471 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473 mCallback = callback;
474 }
475
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700476 virtual void setPhaseOffset(nsecs_t phaseOffset) {
477 Mutex::Autolock lock(mVsyncMutex);
478
479 // Normalize phaseOffset to [0, period)
480 auto period = mDispSync->getPeriod();
481 phaseOffset %= period;
482 if (phaseOffset < 0) {
483 // If we're here, then phaseOffset is in (-period, 0). After this
484 // operation, it will be in (0, period)
485 phaseOffset += period;
486 }
487 mPhaseOffset = phaseOffset;
488
489 // If we're not enabled, we don't need to mess with the listeners
490 if (!mEnabled) {
491 return;
492 }
493
494 // Remove the listener with the old offset
495 status_t err = mDispSync->removeEventListener(
496 static_cast<DispSync::Callback*>(this));
497 if (err != NO_ERROR) {
498 ALOGE("error unregistering vsync callback: %s (%d)",
499 strerror(-err), err);
500 }
501
502 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000503 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 static_cast<DispSync::Callback*>(this));
505 if (err != NO_ERROR) {
506 ALOGE("error registering vsync callback: %s (%d)",
507 strerror(-err), err);
508 }
509 }
510
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511private:
512 virtual void onDispSyncEvent(nsecs_t when) {
513 sp<VSyncSource::Callback> callback;
514 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 callback = mCallback;
517
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700518 if (mTraceVsync) {
519 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700520 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 }
523
Peiyong Lin566a3b42018-01-09 18:22:43 -0800524 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 callback->onVSyncEvent(when);
526 }
527 }
528
Tim Murray4a4e4a22016-04-19 16:29:23 +0000529 const char* const mName;
530
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 int mValue;
532
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700533 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700534 const String8 mVsyncOnLabel;
535 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700536
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538
539 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700541
542 Mutex mVsyncMutex; // Protects the following
543 nsecs_t mPhaseOffset;
544 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700545};
546
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700547class InjectVSyncSource : public VSyncSource {
548public:
549 InjectVSyncSource() {}
550
551 virtual ~InjectVSyncSource() {}
552
553 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
554 std::lock_guard<std::mutex> lock(mCallbackMutex);
555 mCallback = callback;
556 }
557
558 virtual void onInjectSyncEvent(nsecs_t when) {
559 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700560 if (mCallback) {
561 mCallback->onVSyncEvent(when);
562 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700563 }
564
565 virtual void setVSyncEnabled(bool) {}
566 virtual void setPhaseOffset(nsecs_t) {}
567
568private:
569 std::mutex mCallbackMutex; // Protects the following
570 sp<VSyncSource::Callback> mCallback;
571};
572
Wei Wangf9b05ee2017-07-19 20:59:39 -0700573// Do not call property_set on main thread which will be blocked by init
574// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700576 ALOGI( "SurfaceFlinger's main thread ready to run. "
577 "Initializing graphics H/W...");
578
Thierry Strudel2924d012017-08-14 15:19:37 -0700579 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 // start the EventThread
David Sodman99974d22017-11-28 12:04:33 -0800584 sp<VSyncSource> vsyncSrc =
585 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Steven Thomasb02664d2017-07-26 18:48:28 -0700586 mEventThread = new EventThread(vsyncSrc, *this, false);
David Sodman99974d22017-11-28 12:04:33 -0800587 sp<VSyncSource> sfVsyncSrc =
588 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Steven Thomasb02664d2017-07-26 18:48:28 -0700589 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
590 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
593 struct sched_param param = {0};
594 param.sched_priority = 2;
595 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
596 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
597 }
598 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
599 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600 }
601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800603 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700604 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800605 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700606
607 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
608 "Starting with vr flinger active is not currently supported.");
David Sodmanbc815282017-11-05 18:57:52 -0800609 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700610 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800611 // Process any initial hotplug and resulting display changes.
612 processDisplayHotplugEventsLocked();
613 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
614 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800615
Lloyd Piquefcd86612017-12-14 17:15:36 -0800616 // make the default display GLContext current so that we can create textures
617 // when creating Layers (which may happens before we render something)
618 getDefaultDisplayDeviceLocked()->makeCurrent();
619
Steven Thomas050b2c82017-03-06 11:45:16 -0800620 if (useVrFlinger) {
621 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700622 // This callback is called from the vr flinger dispatch thread. We
623 // need to call signalTransaction(), which requires holding
624 // mStateLock when we're not on the main thread. Acquiring
625 // mStateLock from the vr flinger dispatch thread might trigger a
626 // deadlock in surface flinger (see b/66916578), so post a message
627 // to be handled on the main thread instead.
628 sp<LambdaMessage> message = new LambdaMessage([=]() {
629 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
630 mVrFlingerRequestsDisplay = requestDisplay;
631 signalTransaction();
632 });
633 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 };
David Sodman105b7dc2017-11-04 20:28:14 -0700635 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
636 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800637 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800638 if (!mVrFlinger) {
639 ALOGE("Failed to start vrflinger");
640 }
641 }
642
Jamie Gennisd1700752013-10-14 12:22:52 -0700643 mEventControlThread = new EventControlThread(this);
644 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
645
Mathias Agopian92a979a2012-08-02 18:32:23 -0700646 // initialize our drawing state
647 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700648
Andy McFadden13a082e2012-08-24 10:16:42 -0700649 // set initial conditions (e.g. unblank default device)
650 initializeDisplays();
651
David Sodmanbc815282017-11-05 18:57:52 -0800652 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700653
Wei Wangf9b05ee2017-07-19 20:59:39 -0700654 // Inform native graphics APIs whether the present timestamp is supported:
655 if (getHwComposer().hasCapability(
656 HWC2::Capability::PresentFenceIsNotReliable)) {
657 mStartPropertySetThread = new StartPropertySetThread(false);
658 } else {
659 mStartPropertySetThread = new StartPropertySetThread(true);
660 }
661
662 if (mStartPropertySetThread->Start() != NO_ERROR) {
663 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800664 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800665
Dan Stoza9e56aa02015-11-02 13:00:03 -0800666 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700667}
668
Romain Guy11d63f42017-07-20 12:47:14 -0700669void SurfaceFlinger::readPersistentProperties() {
670 char value[PROPERTY_VALUE_MAX];
671
672 property_get("persist.sys.sf.color_saturation", value, "1.0");
673 mSaturation = atof(value);
674 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100675
676 property_get("persist.sys.sf.native_mode", value, "0");
677 mForceNativeColorMode = atoi(value) == 1;
678 if (mForceNativeColorMode) {
679 ALOGV("Forcing native color mode");
680 }
Romain Guy11d63f42017-07-20 12:47:14 -0700681}
682
Mathias Agopiana67e4182012-06-19 17:26:12 -0700683void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800684 // Start boot animation service by setting a property mailbox
685 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700686 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800687 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688 if (mStartPropertySetThread->join() != NO_ERROR) {
689 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800690 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700691}
692
Mathias Agopian875d8e12013-06-07 15:35:48 -0700693size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800694 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700695}
696
Mathias Agopian875d8e12013-06-07 15:35:48 -0700697size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800698 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700699}
700
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800702
Jamie Gennis582270d2011-08-17 18:19:00 -0700703bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800704 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800705 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800706 return authenticateSurfaceTextureLocked(bufferProducer);
707}
708
709bool SurfaceFlinger::authenticateSurfaceTextureLocked(
710 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800711 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700712 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800713}
714
Brian Anderson6b376712017-04-04 10:51:39 -0700715status_t SurfaceFlinger::getSupportedFrameTimestamps(
716 std::vector<FrameEvent>* outSupported) const {
717 *outSupported = {
718 FrameEvent::REQUESTED_PRESENT,
719 FrameEvent::ACQUIRE,
720 FrameEvent::LATCH,
721 FrameEvent::FIRST_REFRESH_START,
722 FrameEvent::LAST_REFRESH_START,
723 FrameEvent::GPU_COMPOSITION_DONE,
724 FrameEvent::DEQUEUE_READY,
725 FrameEvent::RELEASE,
726 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700727 ConditionalLock _l(mStateLock,
728 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700729 if (!getHwComposer().hasCapability(
730 HWC2::Capability::PresentFenceIsNotReliable)) {
731 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
732 }
733 return NO_ERROR;
734}
735
Dan Stoza7f7da322014-05-02 15:26:25 -0700736status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
737 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800738 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700739 return BAD_VALUE;
740 }
741
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500742 if (!display.get())
743 return NAME_NOT_FOUND;
744
Jesse Hall692c7232012-11-08 15:41:56 -0800745 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700746 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800747 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700748 type = i;
749 break;
750 }
751 }
752
753 if (type < 0) {
754 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700755 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757 // TODO: Not sure if display density should handled by SF any longer
758 class Density {
759 static int getDensityFromProperty(char const* propName) {
760 char property[PROPERTY_VALUE_MAX];
761 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800762 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700763 density = atoi(property);
764 }
765 return density;
766 }
767 public:
768 static int getEmuDensity() {
769 return getDensityFromProperty("qemu.sf.lcd_density"); }
770 static int getBuildDensity() {
771 return getDensityFromProperty("ro.sf.lcd_density"); }
772 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700773
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700775
Steven Thomas6d8110b2017-08-31 18:24:21 -0700776 ConditionalLock _l(mStateLock,
777 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800778 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 DisplayInfo info = DisplayInfo();
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 float xdpi = hwConfig->getDpiX();
782 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783
784 if (type == DisplayDevice::DISPLAY_PRIMARY) {
785 // The density of the device is provided by a build property
786 float density = Density::getBuildDensity() / 160.0f;
787 if (density == 0) {
788 // the build doesn't provide a density -- this is wrong!
789 // use xdpi instead
790 ALOGE("ro.sf.lcd_density must be defined as a build property");
791 density = xdpi / 160.0f;
792 }
793 if (Density::getEmuDensity()) {
794 // if "qemu.sf.lcd_density" is specified, it overrides everything
795 xdpi = ydpi = density = Density::getEmuDensity();
796 density /= 160.0f;
797 }
798 info.density = density;
799
800 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700801 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800802 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 } else {
804 // TODO: where should this value come from?
805 static const int TV_DENSITY = 213;
806 info.density = TV_DENSITY / 160.0f;
807 info.orientation = 0;
808 }
809
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 info.w = hwConfig->getWidth();
811 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 info.xdpi = xdpi;
813 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900815 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816
Andy McFadden91b2ca82014-06-13 14:04:23 -0700817 // This is how far in advance a buffer must be queued for
818 // presentation at a given time. If you want a buffer to appear
819 // on the screen at time N, you must submit the buffer before
820 // (N - presentationDeadline).
821 //
822 // Normally it's one full refresh period (to give SF a chance to
823 // latch the buffer), but this can be reduced by configuring a
824 // DispSync offset. Any additional delays introduced by the hardware
825 // composer or panel must be accounted for here.
826 //
827 // We add an additional 1ms to allow for processing time and
828 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800830 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
832 // All non-virtual displays are currently considered secure.
833 info.secure = true;
834
Michael Wright28f24d02016-07-12 13:30:53 -0700835 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 }
837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 return NO_ERROR;
839}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700840
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800841status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700842 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800843 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700844 return BAD_VALUE;
845 }
846
847 // FIXME for now we always return stats for the primary display
848 memset(stats, 0, sizeof(*stats));
849 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
850 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
851 return NO_ERROR;
852}
853
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700854int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800855 if (display == nullptr) {
856 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800857 return BAD_VALUE;
858 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700859
860 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800861 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700862 return device->getActiveConfig();
863 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700864
Dan Stoza24a42e92015-03-09 10:04:11 -0700865 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700868void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
869 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
870 this);
871 int32_t type = hw->getDisplayType();
872 int currentMode = hw->getActiveConfig();
873
874 if (mode == currentMode) {
875 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
876 return;
877 }
878
879 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
880 ALOGW("Trying to set config for virtual display");
881 return;
882 }
883
884 hw->setActiveConfig(mode);
885 getHwComposer().setActiveConfig(type, mode);
886}
887
888status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
889 class MessageSetActiveConfig: public MessageBase {
890 SurfaceFlinger& mFlinger;
891 sp<IBinder> mDisplay;
892 int mMode;
893 public:
894 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
895 int mode) :
896 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
897 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700898 Vector<DisplayInfo> configs;
899 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700900 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700901 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700902 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700903 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700904 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700905 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800906 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700907 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700908 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
910 ALOGW("Attempt to set active config = %d for virtual display",
911 mMode);
912 } else {
913 mFlinger.setActiveConfigInternal(hw, mMode);
914 }
915 return true;
916 }
917 };
918 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
919 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700920 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700921}
Michael Wright28f24d02016-07-12 13:30:53 -0700922status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
923 Vector<android_color_mode_t>* outColorModes) {
924 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
925 return BAD_VALUE;
926 }
927
928 if (!display.get()) {
929 return NAME_NOT_FOUND;
930 }
931
932 int32_t type = NAME_NOT_FOUND;
933 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
934 if (display == mBuiltinDisplays[i]) {
935 type = i;
936 break;
937 }
938 }
939
940 if (type < 0) {
941 return type;
942 }
943
Steven Thomas6d8110b2017-08-31 18:24:21 -0700944 std::vector<android_color_mode_t> modes;
945 {
946 ConditionalLock _l(mStateLock,
947 std::this_thread::get_id() != mMainThreadId);
948 modes = getHwComposer().getColorModes(type);
949 }
Michael Wright28f24d02016-07-12 13:30:53 -0700950 outColorModes->clear();
951 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
952
953 return NO_ERROR;
954}
955
956android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700957 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700958 if (device != nullptr) {
959 return device->getActiveColorMode();
960 }
961 return static_cast<android_color_mode_t>(BAD_VALUE);
962}
963
964void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
965 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700966 int32_t type = hw->getDisplayType();
967 android_color_mode_t currentMode = hw->getActiveColorMode();
968
969 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700970 return;
971 }
972
973 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
974 ALOGW("Trying to set config for virtual display");
975 return;
976 }
977
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600978 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
979 hw->getDisplayType());
980
Michael Wright28f24d02016-07-12 13:30:53 -0700981 hw->setActiveColorMode(mode);
982 getHwComposer().setActiveColorMode(type, mode);
983}
984
985
986status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
987 android_color_mode_t colorMode) {
988 class MessageSetActiveColorMode: public MessageBase {
989 SurfaceFlinger& mFlinger;
990 sp<IBinder> mDisplay;
991 android_color_mode_t mMode;
992 public:
993 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
994 android_color_mode_t mode) :
995 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
996 virtual bool handler() {
997 Vector<android_color_mode_t> modes;
998 mFlinger.getDisplayColorModes(mDisplay, &modes);
999 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1000 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001001 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1002 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001003 return true;
1004 }
1005 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1006 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001007 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1008 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001009 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001010 ALOGW("Attempt to set active color mode %s %d for virtual display",
1011 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001012 } else {
1013 mFlinger.setActiveColorModeInternal(hw, mMode);
1014 }
1015 return true;
1016 }
1017 };
1018 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1019 postMessageSync(msg);
1020 return NO_ERROR;
1021}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001022
Svetoslavd85084b2014-03-20 10:28:31 -07001023status_t SurfaceFlinger::clearAnimationFrameStats() {
1024 Mutex::Autolock _l(mStateLock);
1025 mAnimFrameTracker.clearStats();
1026 return NO_ERROR;
1027}
1028
1029status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1030 Mutex::Autolock _l(mStateLock);
1031 mAnimFrameTracker.getStats(outStats);
1032 return NO_ERROR;
1033}
1034
Dan Stozac4f471e2016-03-24 09:31:08 -07001035status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1036 HdrCapabilities* outCapabilities) const {
1037 Mutex::Autolock _l(mStateLock);
1038
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001039 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001040 if (displayDevice == nullptr) {
1041 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1042 return BAD_VALUE;
1043 }
1044
1045 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001046 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001047 if (capabilities) {
1048 std::swap(*outCapabilities, *capabilities);
1049 } else {
1050 return BAD_VALUE;
1051 }
1052
1053 return NO_ERROR;
1054}
1055
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001056status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001057 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1058 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001059
Chia-I Wu90f669f2017-10-05 14:24:41 -07001060 if (mInjectVSyncs == enable) {
1061 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001062 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001063
1064 if (enable) {
1065 ALOGV("VSync Injections enabled");
1066 if (mVSyncInjector.get() == nullptr) {
1067 mVSyncInjector = new InjectVSyncSource();
1068 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1069 }
1070 mEventQueue.setEventThread(mInjectorEventThread);
1071 } else {
1072 ALOGV("VSync Injections disabled");
1073 mEventQueue.setEventThread(mSFEventThread);
1074 }
1075
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077 });
1078 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001079 return NO_ERROR;
1080}
1081
1082status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 Mutex::Autolock _l(mStateLock);
1084
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 if (!mInjectVSyncs) {
1086 ALOGE("VSync Injections not enabled");
1087 return BAD_VALUE;
1088 }
1089 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1090 ALOGV("Injecting VSync inside SurfaceFlinger");
1091 mVSyncInjector->onInjectSyncEvent(when);
1092 }
1093 return NO_ERROR;
1094}
1095
Kalle Raitaa099a242017-01-11 11:17:29 -08001096status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1097 IPCThreadState* ipc = IPCThreadState::self();
1098 const int pid = ipc->getCallingPid();
1099 const int uid = ipc->getCallingUid();
1100 if ((uid != AID_SHELL) &&
1101 !PermissionCache::checkPermission(sDump, pid, uid)) {
1102 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1103 return PERMISSION_DENIED;
1104 }
1105
1106 // Try to acquire a lock for 1s, fail gracefully
1107 const status_t err = mStateLock.timedLock(s2ns(1));
1108 const bool locked = (err == NO_ERROR);
1109 if (!locked) {
1110 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1111 return TIMED_OUT;
1112 }
1113
1114 outLayers->clear();
1115 mCurrentState.traverseInZOrder([&](Layer* layer) {
1116 outLayers->push_back(layer->getLayerDebugInfo());
1117 });
1118
1119 mStateLock.unlock();
1120 return NO_ERROR;
1121}
1122
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001123// ----------------------------------------------------------------------------
1124
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001125sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1126 ISurfaceComposer::VsyncSource vsyncSource) {
1127 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1128 return mSFEventThread->createEventConnection();
1129 } else {
1130 return mEventThread->createEventConnection();
1131 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001132}
1133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001134// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001135
1136void SurfaceFlinger::waitForEvent() {
1137 mEventQueue.waitMessage();
1138}
1139
1140void SurfaceFlinger::signalTransaction() {
1141 mEventQueue.invalidate();
1142}
1143
1144void SurfaceFlinger::signalLayerUpdate() {
1145 mEventQueue.invalidate();
1146}
1147
1148void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001149 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150 mEventQueue.refresh();
1151}
1152
1153status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001154 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155 return mEventQueue.postMessage(msg, reltime);
1156}
1157
1158status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001159 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160 status_t res = mEventQueue.postMessage(msg, reltime);
1161 if (res == NO_ERROR) {
1162 msg->wait();
1163 }
1164 return res;
1165}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001166
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001167void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001168 do {
1169 waitForEvent();
1170 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171}
1172
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001173void SurfaceFlinger::enableHardwareVsync() {
1174 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001175 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001177 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1178 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001180 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181}
1182
Jesse Hall948fe0c2013-10-14 12:56:09 -07001183void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 Mutex::Autolock _l(mHWVsyncLock);
1185
Jesse Hall948fe0c2013-10-14 12:56:09 -07001186 if (makeAvailable) {
1187 mHWVsyncAvailable = true;
1188 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001189 // Hardware vsync is not currently available, so abort the resync
1190 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191 return;
1192 }
1193
David Sodman105b7dc2017-11-04 20:28:14 -07001194 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001195 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001196
1197 mPrimaryDispSync.reset();
1198 mPrimaryDispSync.setPeriod(period);
1199
1200 if (!mPrimaryHWVsyncEnabled) {
1201 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001202 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1203 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204 mPrimaryHWVsyncEnabled = true;
1205 }
1206}
1207
Jesse Hall948fe0c2013-10-14 12:56:09 -07001208void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 Mutex::Autolock _l(mHWVsyncLock);
1210 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001211 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1212 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001213 mPrimaryDispSync.endResync();
1214 mPrimaryHWVsyncEnabled = false;
1215 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216 if (makeUnavailable) {
1217 mHWVsyncAvailable = false;
1218 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219}
1220
Tim Murray4a4e4a22016-04-19 16:29:23 +00001221void SurfaceFlinger::resyncWithRateLimit() {
1222 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001223
1224 // No explicit locking is needed here since EventThread holds a lock while calling this method
1225 static nsecs_t sLastResyncAttempted = 0;
1226 const nsecs_t now = systemTime();
1227 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001228 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229 }
Dan Stoza57164302017-05-08 14:03:54 -07001230 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001231}
1232
Steven Thomasb02664d2017-07-26 18:48:28 -07001233void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1234 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001235 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001236 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001237 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001238 return;
1239 }
1240
1241 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001242 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001243 return;
1244 }
1245
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001247
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 { // Scope for the lock
1249 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001250 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001253 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001254
1255 if (needsHwVsync) {
1256 enableHardwareVsync();
1257 } else {
1258 disableHardwareVsync(false);
1259 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001260}
1261
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001262void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001263 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1264 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001265}
1266
Lloyd Pique715a2c12017-12-14 17:18:08 -08001267void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1268 HWC2::Connection connection) {
1269 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1270 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001271
Lloyd Piqueba04e622017-12-14 17:11:26 -08001272 // Ignore events that do not have the right sequenceId.
1273 if (sequenceId != getBE().mComposerSequenceId) {
1274 return;
1275 }
1276
Steven Thomasb02664d2017-07-26 18:48:28 -07001277 // Only lock if we're not on the main thread. This function is normally
1278 // called on a hwbinder thread, but for the primary display it's called on
1279 // the main thread with the state lock already held, so don't attempt to
1280 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001281 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001282
Lloyd Pique715a2c12017-12-14 17:18:08 -08001283 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001284
Lloyd Piqueba04e622017-12-14 17:11:26 -08001285 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001286}
1287
Steven Thomasb02664d2017-07-26 18:48:28 -07001288void SurfaceFlinger::onRefreshReceived(int sequenceId,
1289 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001290 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001291 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001293 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001294 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001295}
1296
Dan Stoza9e56aa02015-11-02 13:00:03 -08001297void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001299 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001300 getHwComposer().setVsyncEnabled(disp,
1301 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001302}
1303
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001305void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001307 // Clear the drawing state so that the logic inside of
1308 // handleTransactionLocked will fire. It will determine the delta between
1309 // mCurrentState and mDrawingState and re-apply all changes when we make the
1310 // transition.
1311 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001312 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001313 mDisplays.clear();
1314}
1315
Steven Thomas050b2c82017-03-06 11:45:16 -08001316void SurfaceFlinger::updateVrFlinger() {
1317 if (!mVrFlinger)
1318 return;
1319 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001321 return;
1322 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323
David Sodman105b7dc2017-11-04 20:28:14 -07001324 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001325 ALOGE("Vr flinger is only supported for remote hardware composer"
1326 " service connections. Ignoring request to transition to vr"
1327 " flinger.");
1328 mVrFlingerRequestsDisplay = false;
1329 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001330 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001331
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 int currentDisplayPowerMode = getDisplayDeviceLocked(
1335 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336
Steven Thomasb02664d2017-07-26 18:48:28 -07001337 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001342 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001343 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001344 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345
David Sodman105b7dc2017-11-04 20:28:14 -07001346 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1347 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001348
1349 if (vrFlingerRequestsDisplay) {
1350 mVrFlinger->GrantDisplayOwnership();
1351 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354
1355 mVisibleRegionsDirty = true;
1356 invalidateHwcGeometry();
1357
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001358 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1360 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1361 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001364 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 const nsecs_t period = activeConfig->getVsyncPeriod();
1366 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001367
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 // Use phase of 0 since phase is not known.
1369 // Use latency of 0, which will snap to the ideal latency.
1370 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001371
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001372 android_atomic_or(1, &mRepaintEverything);
1373 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374}
1375
Mathias Agopian4fec8732012-06-29 14:12:52 -07001376void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001377 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001378 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001379 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001380 bool frameMissed = !mHadClientComposition &&
1381 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001382 (mPreviousPresentFence->getSignalTime() ==
1383 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001384 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001385 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001386 signalLayerUpdate();
1387 break;
1388 }
1389
Steven Thomas050b2c82017-03-06 11:45:16 -08001390 // Now that we're going to make it to the handleMessageTransaction()
1391 // call below it's safe to call updateVrFlinger(), which will
1392 // potentially trigger a display handoff.
1393 updateVrFlinger();
1394
Dan Stoza6b9454d2014-11-07 16:00:59 -08001395 bool refreshNeeded = handleMessageTransaction();
1396 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001397 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001398 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001399 // Signal a refresh if a transaction modified the window state,
1400 // a new buffer was latched, or if HWC has requested a full
1401 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001402 signalRefresh();
1403 }
1404 break;
1405 }
1406 case MessageQueue::REFRESH: {
1407 handleMessageRefresh();
1408 break;
1409 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001410 }
1411}
1412
Dan Stoza6b9454d2014-11-07 16:00:59 -08001413bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001414 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001415 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001416 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001417 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001418 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001420}
1421
Dan Stoza6b9454d2014-11-07 16:00:59 -08001422bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001423 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001425}
1426
1427void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001428 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001429
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001430 mRefreshPending = false;
1431
Pablo Ceballos40845df2016-01-25 17:41:15 -08001432 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001433
Brian Andersond6927fb2016-07-23 23:37:30 -07001434 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001435 rebuildLayerStacks();
1436 setUpHWComposer();
1437 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001438 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001439 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001440 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001441
David Sodman105b7dc2017-11-04 20:28:14 -07001442 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001443
1444 mHadClientComposition = false;
1445 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1446 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1447 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001448 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001449 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001450
Dan Stoza9e56aa02015-11-02 13:00:03 -08001451 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001452}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001453
Mathias Agopiancd60f992012-08-16 16:28:27 -07001454void SurfaceFlinger::doDebugFlashRegions()
1455{
1456 // is debugging enabled
1457 if (CC_LIKELY(!mDebugRegion))
1458 return;
1459
1460 const bool repaintEverything = mRepaintEverything;
1461 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1462 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001463 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001464 // transform the dirty region into this screen's coordinate space
1465 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1466 if (!dirtyRegion.isEmpty()) {
1467 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001468 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469
1470 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001472 RenderEngine& engine(getRenderEngine());
1473 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1474
Mathias Agopianda27af92012-09-13 18:17:13 -07001475 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476 }
1477 }
1478 }
1479
1480 postFramebuffer();
1481
1482 if (mDebugRegion > 1) {
1483 usleep(mDebugRegion * 1000);
1484 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001485
Dan Stoza9e56aa02015-11-02 13:00:03 -08001486 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001487 auto& displayDevice = mDisplays[displayId];
1488 if (!displayDevice->isDisplayOn()) {
1489 continue;
1490 }
1491
David Sodman105b7dc2017-11-04 20:28:14 -07001492 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1493 ALOGE_IF(result != NO_ERROR,
1494 "prepareFrame for display %zd failed:"
1495 " %d (%s)",
1496 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001497 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498}
1499
Adrian Roos1e1a1282017-11-01 19:05:31 +01001500void SurfaceFlinger::doTracing(const char* where) {
1501 ATRACE_CALL();
1502 ATRACE_NAME(where);
1503 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001504 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001505 }
1506}
1507
Brian Andersond6927fb2016-07-23 23:37:30 -07001508void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001510 ATRACE_CALL();
1511 ALOGV("preComposition");
1512
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001514 mDrawingState.traverseInZOrder([&](Layer* layer) {
1515 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 needExtraInvalidate = true;
1517 }
Robert Carr2047fae2016-11-28 14:09:09 -08001518 });
1519
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 if (needExtraInvalidate) {
1521 signalLayerUpdate();
1522 }
1523}
1524
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001525void SurfaceFlinger::updateCompositorTiming(
1526 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1527 std::shared_ptr<FenceTime>& presentFenceTime) {
1528 // Update queue of past composite+present times and determine the
1529 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001530 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001531 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001532 while (!getBE().mCompositePresentTimes.empty()) {
1533 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001534 // Cached values should have been updated before calling this method,
1535 // which helps avoid duplicate syscalls.
1536 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1537 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1538 break;
1539 }
1540 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001541 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 }
1543
1544 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001545 while (getBE().mCompositePresentTimes.size() > 16) {
1546 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001547 }
1548
Brian Andersond0010582017-03-07 13:20:31 -08001549 setCompositorTimingSnapped(
1550 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1551}
1552
1553void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1554 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001555 // Integer division and modulo round toward 0 not -inf, so we need to
1556 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001557 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001558 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1559 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1560
Brian Andersond0010582017-03-07 13:20:31 -08001561 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1562 if (idealLatency <= 0) {
1563 idealLatency = vsyncInterval;
1564 }
1565
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001566 // Snap the latency to a value that removes scheduling jitter from the
1567 // composition and present times, which often have >1ms of jitter.
1568 // Reducing jitter is important if an app attempts to extrapolate
1569 // something (such as user input) to an accurate diasplay time.
1570 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1571 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001572 nsecs_t bias = vsyncInterval / 2;
1573 int64_t extraVsyncs =
1574 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1575 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1576 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001577
David Sodman99974d22017-11-28 12:04:33 -08001578 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1579 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1580 getBE().mCompositorTiming.interval = vsyncInterval;
1581 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582}
1583
1584void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 ATRACE_CALL();
1587 ALOGV("postComposition");
1588
Brian Anderson3546a3f2016-07-14 11:51:14 -07001589 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001590 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001591 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001592 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001593 }
1594
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595 // |mStateLock| not needed as we are on the main thread
1596 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001597
David Sodman73beded2017-11-15 11:56:06 -08001598 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001599 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001600 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001601 glCompositionDoneFenceTime =
1602 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001603 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001604 } else {
1605 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1606 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001607
David Sodman73beded2017-11-15 11:56:06 -08001608 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001609 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001610 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001611 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001612
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1614 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1615
1616 // We use the refreshStartTime which might be sampled a little later than
1617 // when we started doing work for this frame, but that should be okay
1618 // since updateCompositorTiming has snapping logic.
1619 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001620 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001621 CompositorTiming compositorTiming;
1622 {
David Sodman99974d22017-11-28 12:04:33 -08001623 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1624 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001625 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626
Robert Carr2047fae2016-11-28 14:09:09 -08001627 mDrawingState.traverseInZOrder([&](Layer* layer) {
1628 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001629 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001630 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001631 recordBufferingStats(layer->getName().string(),
1632 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001633 }
Robert Carr2047fae2016-11-28 14:09:09 -08001634 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001635
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001636 if (presentFenceTime->isValid()) {
1637 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001638 enableHardwareVsync();
1639 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001640 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001641 }
1642 }
1643
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001644 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001645 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001646 enableHardwareVsync();
1647 }
1648 }
1649
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001650 if (mAnimCompositionPending) {
1651 mAnimCompositionPending = false;
1652
Brian Anderson4e606e32017-03-16 15:34:57 -07001653 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001654 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001655 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001656 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001657 // The HWC doesn't support present fences, so use the refresh
1658 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001660 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001661 mAnimFrameTracker.setActualPresentTime(presentTime);
1662 }
1663 mAnimFrameTracker.advanceFrame();
1664 }
Dan Stozab90cf072015-03-05 11:05:59 -08001665
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001666 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1667 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001668 return;
1669 }
1670
1671 nsecs_t currentTime = systemTime();
1672 if (mHasPoweredOff) {
1673 mHasPoweredOff = false;
1674 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001675 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001677 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1678 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001679 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001680 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001681 }
David Sodman4a36e932017-11-07 14:29:47 -08001682 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001683 }
David Sodman4a36e932017-11-07 14:29:47 -08001684 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685}
1686
1687void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001688 ATRACE_CALL();
1689 ALOGV("rebuildLayerStacks");
1690
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001692 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001693 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001694 mVisibleRegionsDirty = false;
1695 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001696
Jeff Sharkey76488112017-02-27 14:15:18 -07001697 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1698 Region opaqueRegion;
1699 Region dirtyRegion;
1700 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001701 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001702 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1703 const Transform& tr(displayDevice->getTransform());
1704 const Rect bounds(displayDevice->getBounds());
1705 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001706 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001707
Jeff Sharkey76488112017-02-27 14:15:18 -07001708 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001709 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001710 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1711 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001712 Region drawRegion(tr.transform(
1713 layer->visibleNonTransparentRegion));
1714 drawRegion.andSelf(bounds);
1715 if (!drawRegion.isEmpty()) {
1716 layersSortedByZ.add(layer);
1717 } else {
1718 // Clear out the HWC layer if this layer was
1719 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001720 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001721 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001723 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001724 // WM changes displayDevice->layerStack upon sleep/awake.
1725 // Here we make sure we delete the HWC layers even if
1726 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001727 hwcLayerDestroyed = layer->destroyHwcLayer(
1728 displayDevice->getHwcDisplayId());
1729 }
1730
1731 // If a layer is not going to get a release fence because
1732 // it is invisible, but it is also going to release its
1733 // old buffer, add it to the list of layers needing
1734 // fences.
1735 if (hwcLayerDestroyed) {
1736 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1737 mLayersWithQueuedFrames.cend(), layer);
1738 if (found != mLayersWithQueuedFrames.cend()) {
1739 layersNeedingFences.add(layer);
1740 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001741 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001742 });
1743 }
1744 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001745 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001746 displayDevice->undefinedRegion.set(bounds);
1747 displayDevice->undefinedRegion.subtractSelf(
1748 tr.transform(opaqueRegion));
1749 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001750 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001751 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001753
Romain Guy0147a172017-06-01 13:53:56 -07001754mat4 SurfaceFlinger::computeSaturationMatrix() const {
1755 if (mSaturation == 1.0f) {
1756 return mat4();
1757 }
1758
1759 // Rec.709 luma coefficients
1760 float3 luminance{0.213f, 0.715f, 0.072f};
1761 luminance *= 1.0f - mSaturation;
1762 return mat4(
1763 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1764 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1765 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1766 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1767 );
1768}
1769
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001770// pickColorMode translates a given dataspace into the best available color mode.
1771// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001772android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001773 if (mForceNativeColorMode) {
1774 return HAL_COLOR_MODE_NATIVE;
1775 }
1776
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001777 switch (dataSpace) {
1778 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1779 // system expects.
1780 case HAL_DATASPACE_UNKNOWN:
1781 case HAL_DATASPACE_SRGB:
1782 case HAL_DATASPACE_V0_SRGB:
1783 return HAL_COLOR_MODE_SRGB;
1784 break;
1785
1786 case HAL_DATASPACE_DISPLAY_P3:
1787 return HAL_COLOR_MODE_DISPLAY_P3;
1788 break;
1789
1790 default:
1791 // TODO (courtneygo): Do we want to assert an error here?
1792 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1793 dataSpace);
1794 return HAL_COLOR_MODE_SRGB;
1795 break;
1796 }
1797}
1798
Romain Guy0147a172017-06-01 13:53:56 -07001799android_dataspace SurfaceFlinger::bestTargetDataSpace(
1800 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001801 // Only support sRGB and Display-P3 right now.
1802 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1803 return HAL_DATASPACE_DISPLAY_P3;
1804 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001805 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1806 return HAL_DATASPACE_DISPLAY_P3;
1807 }
1808 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1809 return HAL_DATASPACE_DISPLAY_P3;
1810 }
1811
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001812 return HAL_DATASPACE_V0_SRGB;
1813}
1814
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 ATRACE_CALL();
1817 ALOGV("setUpHWComposer");
1818
Jesse Hall028dc8f2013-08-20 16:35:32 -07001819 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001820 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1821 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1822 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1823
1824 // If nothing has changed (!dirty), don't recompose.
1825 // If something changed, but we don't currently have any visible layers,
1826 // and didn't when we last did a composition, then skip it this time.
1827 // The second rule does two things:
1828 // - When all layers are removed from a display, we'll emit one black
1829 // frame, then nothing more until we get new layers.
1830 // - When a display is created with a private layer stack, we won't
1831 // emit any black frames until a layer is added to the layer stack.
1832 bool mustRecompose = dirty && !(empty && wasEmpty);
1833
1834 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1835 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1836 mustRecompose ? "doing" : "skipping",
1837 dirty ? "+" : "-",
1838 empty ? "+" : "-",
1839 wasEmpty ? "+" : "-");
1840
Dan Stoza71433162014-02-04 16:22:36 -08001841 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001842
1843 if (mustRecompose) {
1844 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1845 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001846 }
1847
Dan Stoza9e56aa02015-11-02 13:00:03 -08001848 // build the h/w work list
1849 if (CC_UNLIKELY(mGeometryInvalid)) {
1850 mGeometryInvalid = false;
1851 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1852 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1853 const auto hwcId = displayDevice->getHwcDisplayId();
1854 if (hwcId >= 0) {
1855 const Vector<sp<Layer>>& currentLayers(
1856 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001857 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001858 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001859 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001860 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001863 }
1864 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001865
Robert Carrae060832016-11-28 10:51:00 -08001866 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001867 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001869 }
1870 }
1871 }
1872 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 }
Riley Andrews03414a12014-07-01 14:22:59 -07001874
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001875
Romain Guy0147a172017-06-01 13:53:56 -07001876 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001877
Dan Stoza9e56aa02015-11-02 13:00:03 -08001878 // Set the per-frame data
1879 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1880 auto& displayDevice = mDisplays[displayId];
1881 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001882
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 if (hwcId < 0) {
1884 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001885 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001886 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001887 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001888 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1889 "display %zd: %d", displayId, result);
1890 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001892 if (layer->getForceClientComposition(hwcId)) {
1893 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1894 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1895 continue;
1896 }
1897
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 layer->setPerFrameData(displayDevice);
1899 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001900
1901 if (hasWideColorDisplay) {
1902 android_color_mode newColorMode;
1903 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1904
1905 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1907 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1908 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1909 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1910 }
1911 newColorMode = pickColorMode(newDataSpace);
1912
Thierry Strudel2924d012017-08-14 15:19:37 -07001913 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 }
1916
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001917 mPreviousColorMatrix = colorMatrix;
1918
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001920 auto& displayDevice = mDisplays[displayId];
1921 if (!displayDevice->isDisplayOn()) {
1922 continue;
1923 }
1924
David Sodman105b7dc2017-11-04 20:28:14 -07001925 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1927 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001928 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001930
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931void SurfaceFlinger::doComposition() {
1932 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 ALOGV("doComposition");
1934
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001935 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001936 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001937 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001938 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939 // transform the dirty region into this screen's coordinate space
1940 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001941
1942 // repaint the framebuffer (if needed)
1943 doDisplayComposition(hw, dirtyRegion);
1944
Mathias Agopiancd60f992012-08-16 16:28:27 -07001945 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001946 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001947 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001948 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001949 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001950}
1951
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001952void SurfaceFlinger::postFramebuffer()
1953{
Mathias Agopian841cde52012-03-01 15:44:37 -08001954 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001956
Mathias Agopiana44b0412011-10-16 18:46:35 -07001957 const nsecs_t now = systemTime();
1958 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001959
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1961 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001962 if (!displayDevice->isDisplayOn()) {
1963 continue;
1964 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 const auto hwcId = displayDevice->getHwcDisplayId();
1966 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001967 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001968 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001969 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001970 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001971 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001972 // The layer buffer from the previous frame (if any) is released
1973 // by HWC only when the release fence from this frame (if any) is
1974 // signaled. Always get the release fence from HWC first.
1975 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001976 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08001977
1978 // If the layer was client composited in the previous frame, we
1979 // need to merge with the previous client target acquire fence.
1980 // Since we do not track that, always merge with the current
1981 // client target acquire fence when it is available, even though
1982 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001984 releaseFence = Fence::merge("LayerRelease", releaseFence,
1985 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001986 }
Chia-I Wu7b549592017-11-15 09:14:57 -08001987
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 layer->onLayerDisplayed(releaseFence);
1989 }
Chia-I Wu83806892017-11-16 10:50:20 -08001990
1991 // We've got a list of layers needing fences, that are disjoint with
1992 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
1993 // supply them with the present fence.
1994 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07001995 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08001996 for (auto& layer : displayDevice->getLayersNeedingFences()) {
1997 layer->onLayerDisplayed(presentFence);
1998 }
1999 }
2000
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002002 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002003 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002004 }
2005
Mathias Agopiana44b0412011-10-16 18:46:35 -07002006 mLastSwapBufferTime = systemTime() - now;
2007 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002008
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002009 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002010 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2011 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2012 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2013 logFrameStats();
2014 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002015 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016}
2017
Mathias Agopian87baae12012-07-31 12:38:26 -07002018void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002019{
Mathias Agopian841cde52012-03-01 15:44:37 -08002020 ATRACE_CALL();
2021
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002022 // here we keep a copy of the drawing state (that is the state that's
2023 // going to be overwritten by handleTransactionLocked()) outside of
2024 // mStateLock so that the side-effects of the State assignment
2025 // don't happen with mStateLock held (which can cause deadlocks).
2026 State drawingState(mDrawingState);
2027
Mathias Agopianca4d3602011-05-19 15:38:14 -07002028 Mutex::Autolock _l(mStateLock);
2029 const nsecs_t now = systemTime();
2030 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031
Mathias Agopianca4d3602011-05-19 15:38:14 -07002032 // Here we're guaranteed that some transaction flags are set
2033 // so we can call handleTransactionLocked() unconditionally.
2034 // We call getTransactionFlags(), which will also clear the flags,
2035 // with mStateLock held to guarantee that mCurrentState won't change
2036 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002037
Mathias Agopiane57f2922012-08-09 16:29:12 -07002038 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002039 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002040
Mathias Agopianca4d3602011-05-19 15:38:14 -07002041 mLastTransactionTime = systemTime() - now;
2042 mDebugInTransaction = 0;
2043 invalidateHwcGeometry();
2044 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002045}
2046
Lloyd Pique715a2c12017-12-14 17:18:08 -08002047DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2048 HWC2::Connection connection) const {
2049 // Figure out whether the event is for the primary display or an
2050 // external display by matching the Hwc display id against one for a
2051 // connected display. If we did not find a match, we then check what
2052 // displays are not already connected to determine the type. If we don't
2053 // have a connected primary display, we assume the new display is meant to
2054 // be the primary display, and then if we don't have an external display,
2055 // we assume it is that.
2056 const auto primaryDisplayId =
2057 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2058 const auto externalDisplayId =
2059 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2060 if (primaryDisplayId && primaryDisplayId == display) {
2061 return DisplayDevice::DISPLAY_PRIMARY;
2062 } else if (externalDisplayId && externalDisplayId == display) {
2063 return DisplayDevice::DISPLAY_EXTERNAL;
2064 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2065 return DisplayDevice::DISPLAY_PRIMARY;
2066 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2067 return DisplayDevice::DISPLAY_EXTERNAL;
2068 }
2069
2070 return DisplayDevice::DISPLAY_ID_INVALID;
2071}
2072
Lloyd Piqueba04e622017-12-14 17:11:26 -08002073void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2074 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002075 auto displayType = determineDisplayType(event.display, event.connection);
2076 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2077 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2078 continue;
2079 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002080
2081 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2082 ALOGE("External displays are not supported by the vr hardware composer.");
2083 continue;
2084 }
2085
Lloyd Pique715a2c12017-12-14 17:18:08 -08002086 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002087
2088 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002089 ALOGV("Creating built in display %d", displayType);
2090 ALOGW_IF(mBuiltinDisplays[displayType],
2091 "Overwriting display token for display type %d", displayType);
2092 mBuiltinDisplays[displayType] = new BBinder();
2093 // All non-virtual displays are currently considered secure.
2094 DisplayDeviceState info(displayType, true);
2095 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2096 "Built-in Screen" : "External Screen";
2097 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2098 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002099 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002100 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002101
Lloyd Piquefcd86612017-12-14 17:15:36 -08002102 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2103 if (idx >= 0) {
2104 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2105 mInterceptor.saveDisplayDeletion(info.displayId);
2106 mCurrentState.displays.removeItemsAt(idx);
2107 }
2108 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002109 }
2110
2111 processDisplayChangesLocked();
2112 }
2113
2114 mPendingHotplugEvents.clear();
2115}
2116
Lloyd Pique347200f2017-12-14 17:00:15 -08002117void SurfaceFlinger::processDisplayChangesLocked() {
2118 // here we take advantage of Vector's copy-on-write semantics to
2119 // improve performance by skipping the transaction entirely when
2120 // know that the lists are identical
2121 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2122 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2123 if (!curr.isIdenticalTo(draw)) {
2124 mVisibleRegionsDirty = true;
2125 const size_t cc = curr.size();
2126 size_t dc = draw.size();
2127
2128 // find the displays that were removed
2129 // (ie: in drawing state but not in current state)
2130 // also handle displays that changed
2131 // (ie: displays that are in both lists)
2132 for (size_t i = 0; i < dc;) {
2133 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2134 if (j < 0) {
2135 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002136 // Call makeCurrent() on the primary display so we can
2137 // be sure that nothing associated with this display
2138 // is current.
2139 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2140 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2141 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2142 if (hw != nullptr) hw->disconnect(getHwComposer());
2143 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2144 mEventThread->onHotplugReceived(draw[i].type, false);
2145 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002146 } else {
2147 // this display is in both lists. see if something changed.
2148 const DisplayDeviceState& state(curr[j]);
2149 const wp<IBinder>& display(curr.keyAt(j));
2150 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2151 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2152 if (state_binder != draw_binder) {
2153 // changing the surface is like destroying and
2154 // recreating the DisplayDevice, so we just remove it
2155 // from the drawing state, so that it get re-added
2156 // below.
2157 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2158 if (hw != nullptr) hw->disconnect(getHwComposer());
2159 mDisplays.removeItem(display);
2160 mDrawingState.displays.removeItemsAt(i);
2161 dc--;
2162 // at this point we must loop to the next item
2163 continue;
2164 }
2165
2166 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2167 if (disp != nullptr) {
2168 if (state.layerStack != draw[i].layerStack) {
2169 disp->setLayerStack(state.layerStack);
2170 }
2171 if ((state.orientation != draw[i].orientation) ||
2172 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2173 disp->setProjection(state.orientation, state.viewport, state.frame);
2174 }
2175 if (state.width != draw[i].width || state.height != draw[i].height) {
2176 disp->setDisplaySize(state.width, state.height);
2177 }
2178 }
2179 }
2180 ++i;
2181 }
2182
2183 // find displays that were added
2184 // (ie: in current state but not in drawing state)
2185 for (size_t i = 0; i < cc; i++) {
2186 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2187 const DisplayDeviceState& state(curr[i]);
2188
2189 sp<DisplaySurface> dispSurface;
2190 sp<IGraphicBufferProducer> producer;
2191 sp<IGraphicBufferProducer> bqProducer;
2192 sp<IGraphicBufferConsumer> bqConsumer;
2193 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2194
2195 int32_t hwcId = -1;
2196 if (state.isVirtualDisplay()) {
2197 // Virtual displays without a surface are dormant:
2198 // they have external state (layer stack, projection,
2199 // etc.) but no internal state (i.e. a DisplayDevice).
2200 if (state.surface != nullptr) {
2201 // Allow VR composer to use virtual displays.
2202 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2203 int width = 0;
2204 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2205 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2206 int height = 0;
2207 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2208 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2209 int intFormat = 0;
2210 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2211 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2212 auto format = static_cast<android_pixel_format_t>(intFormat);
2213
2214 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2215 }
2216
2217 // TODO: Plumb requested format back up to consumer
2218
2219 sp<VirtualDisplaySurface> vds =
2220 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2221 bqProducer, bqConsumer,
2222 state.displayName);
2223
2224 dispSurface = vds;
2225 producer = vds;
2226 }
2227 } else {
2228 ALOGE_IF(state.surface != nullptr,
2229 "adding a supported display, but rendering "
2230 "surface is provided (%p), ignoring it",
2231 state.surface.get());
2232
2233 hwcId = state.type;
2234 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2235 producer = bqProducer;
2236 }
2237
2238 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002239
Lloyd Pique347200f2017-12-14 17:00:15 -08002240 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002241 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002242 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002243 bool hasWideColorModes = false;
2244 std::vector<android_color_mode_t> modes =
2245 getHwComposer().getColorModes(state.type);
2246 for (android_color_mode_t colorMode : modes) {
2247 switch (colorMode) {
2248 case HAL_COLOR_MODE_DISPLAY_P3:
2249 case HAL_COLOR_MODE_ADOBE_RGB:
2250 case HAL_COLOR_MODE_DCI_P3:
2251 hasWideColorModes = true;
2252 break;
2253 default:
2254 break;
2255 }
2256 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002257 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002258 }
2259
Lloyd Pique347200f2017-12-14 17:00:15 -08002260 sp<DisplayDevice> hw =
2261 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Lloyd Piquefcd86612017-12-14 17:15:36 -08002262 dispSurface, producer, useWideColorMode);
2263
Lloyd Piquec5208312018-01-08 17:59:02 -08002264 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2265 if (useWideColorMode) {
2266 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002267 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002268 setActiveColorModeInternal(hw, defaultColorMode);
2269 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002270 hw->setLayerStack(state.layerStack);
2271 hw->setProjection(state.orientation, state.viewport, state.frame);
2272 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002273
Lloyd Pique347200f2017-12-14 17:00:15 -08002274 mDisplays.add(display, hw);
2275 if (!state.isVirtualDisplay()) {
2276 mEventThread->onHotplugReceived(state.type, true);
2277 }
2278 }
2279 }
2280 }
2281 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002282
2283 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002284}
2285
Mathias Agopian87baae12012-07-31 12:38:26 -07002286void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002287{
Dan Stoza7dde5992015-05-22 09:51:44 -07002288 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002289 mCurrentState.traverseInZOrder([](Layer* layer) {
2290 layer->notifyAvailableFrames();
2291 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002293 /*
2294 * Traversal of the children
2295 * (perform the transaction for each of them if needed)
2296 */
2297
Mathias Agopian3559b072012-08-15 13:46:03 -07002298 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002299 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002301 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302
2303 const uint32_t flags = layer->doTransaction(0);
2304 if (flags & Layer::eVisibleRegion)
2305 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002306 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 }
2308
2309 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002310 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002311 */
2312
Mathias Agopiane57f2922012-08-09 16:29:12 -07002313 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002314 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002316 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317
Mathias Agopian84300952012-11-21 16:02:13 -08002318 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2319 // The transform hint might have changed for some layers
2320 // (either because a display has changed, or because a layer
2321 // as changed).
2322 //
2323 // Walk through all the layers in currentLayers,
2324 // and update their transform hint.
2325 //
2326 // If a layer is visible only on a single display, then that
2327 // display is used to calculate the hint, otherwise we use the
2328 // default display.
2329 //
2330 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2331 // the hint is set before we acquire a buffer from the surface texture.
2332 //
2333 // NOTE: layer transactions have taken place already, so we use their
2334 // drawing state. However, SurfaceFlinger's own transaction has not
2335 // happened yet, so we must use the current state layer list
2336 // (soon to become the drawing state list).
2337 //
2338 sp<const DisplayDevice> disp;
2339 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002340 bool first = true;
2341 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002342 // NOTE: we rely on the fact that layers are sorted by
2343 // layerStack first (so we don't have to traverse the list
2344 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002345 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002346 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002347 currentlayerStack = layerStack;
2348 // figure out if this layerstack is mirrored
2349 // (more than one display) if so, pick the default display,
2350 // if not, pick the only display it's on.
2351 disp.clear();
2352 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2353 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002354 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002355 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002356 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002357 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002358 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002359 break;
2360 }
2361 }
2362 }
2363 }
Chet Haase91d25932013-04-11 15:24:55 -07002364
Robert Carr56a0b9a2017-12-04 16:06:13 -08002365 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002366 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002367 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2368 // redraw after transform hint changes. See bug 8508397.
2369
2370 // could be null when this layer is using a layerStack
2371 // that is not visible on any display. Also can occur at
2372 // screen off/on times.
2373 disp = getDefaultDisplayDeviceLocked();
2374 }
2375 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002376 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002377 if (disp != nullptr) {
2378 layer->updateTransformHint(disp);
2379 }
Robert Carr2047fae2016-11-28 14:09:09 -08002380
2381 first = false;
2382 });
Mathias Agopian84300952012-11-21 16:02:13 -08002383 }
2384
2385
Mathias Agopian3559b072012-08-15 13:46:03 -07002386 /*
2387 * Perform our own transaction if needed
2388 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002389
2390 if (mLayersAdded) {
2391 mLayersAdded = false;
2392 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002393 mVisibleRegionsDirty = true;
2394 }
2395
2396 // some layers might have been removed, so
2397 // we need to update the regions they're exposing.
2398 if (mLayersRemoved) {
2399 mLayersRemoved = false;
2400 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002401 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002402 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002403 // this layer is not visible anymore
2404 // TODO: we could traverse the tree from front to back and
2405 // compute the actual visible region
2406 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002407 Region visibleReg;
2408 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002409 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002410 }
Robert Carr2047fae2016-11-28 14:09:09 -08002411 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002412 }
2413
2414 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002415
2416 updateCursorAsync();
2417}
2418
2419void SurfaceFlinger::updateCursorAsync()
2420{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2422 auto& displayDevice = mDisplays[displayId];
2423 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002424 continue;
2425 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426
2427 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2428 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002429 }
2430 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431}
2432
2433void SurfaceFlinger::commitTransaction()
2434{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002435 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002436 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002437 for (const auto& l : mLayersPendingRemoval) {
2438 recordBufferingStats(l->getName().string(),
2439 l->getOccupancyHistory(true));
2440 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002441 }
2442 mLayersPendingRemoval.clear();
2443 }
2444
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002445 // If this transaction is part of a window animation then the next frame
2446 // we composite should be considered an animation as well.
2447 mAnimCompositionPending = mAnimTransactionPending;
2448
Mathias Agopian4fec8732012-06-29 14:12:52 -07002449 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 mDrawingState.traverseInZOrder([](Layer* layer) {
2451 layer->commitChildList();
2452 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002453 mTransactionPending = false;
2454 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002455 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456}
2457
Chia-I Wuab0c3192017-08-01 11:29:00 -07002458void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002459 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460{
Mathias Agopian841cde52012-03-01 15:44:37 -08002461 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002463
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464 Region aboveOpaqueLayers;
2465 Region aboveCoveredLayers;
2466 Region dirty;
2467
Mathias Agopian87baae12012-07-31 12:38:26 -07002468 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469
Robert Carr2047fae2016-11-28 14:09:09 -08002470 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002472 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473
Jesse Hall01e29052013-02-19 16:13:35 -08002474 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002475 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002476 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002477
Mathias Agopianab028732010-03-16 16:41:46 -07002478 /*
2479 * opaqueRegion: area of a surface that is fully opaque.
2480 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002482
2483 /*
2484 * visibleRegion: area of a surface that is visible on screen
2485 * and not fully transparent. This is essentially the layer's
2486 * footprint minus the opaque regions above it.
2487 * Areas covered by a translucent surface are considered visible.
2488 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002490
2491 /*
2492 * coveredRegion: area of a surface that is covered by all
2493 * visible regions above it (which includes the translucent areas).
2494 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002496
Jesse Halla8026d22012-09-25 13:25:04 -07002497 /*
2498 * transparentRegion: area of a surface that is hinted to be completely
2499 * transparent. This is only used to tell when the layer has no visible
2500 * non-transparent regions and can be removed from the layer list. It
2501 * does not affect the visibleRegion of this layer or any layers
2502 * beneath it. The hint may not be correct if apps don't respect the
2503 * SurfaceView restrictions (which, sadly, some don't).
2504 */
2505 Region transparentRegion;
2506
Mathias Agopianab028732010-03-16 16:41:46 -07002507
2508 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002509 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002510 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002511 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002514 if (!visibleRegion.isEmpty()) {
2515 // Remove the transparent area from the visible region
2516 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002517 if (tr.preserveRects()) {
2518 // transform the transparent region
2519 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002520 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002521 // transformation too complex, can't do the
2522 // transparent region optimization.
2523 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002524 }
Mathias Agopianab028732010-03-16 16:41:46 -07002525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
Mathias Agopianab028732010-03-16 16:41:46 -07002527 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002528 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002529 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002530 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2531 // the opaque region is the layer's footprint
2532 opaqueRegion = visibleRegion;
2533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534 }
2535 }
2536
Mathias Agopianab028732010-03-16 16:41:46 -07002537 // Clip the covered region to the visible region
2538 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2539
2540 // Update aboveCoveredLayers for next (lower) layer
2541 aboveCoveredLayers.orSelf(visibleRegion);
2542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 // subtract the opaque region covered by the layers above us
2544 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545
2546 // compute this layer's dirty region
2547 if (layer->contentDirty) {
2548 // we need to invalidate the whole region
2549 dirty = visibleRegion;
2550 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002551 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 layer->contentDirty = false;
2553 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002554 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002555 * the exposed region consists of two components:
2556 * 1) what's VISIBLE now and was COVERED before
2557 * 2) what's EXPOSED now less what was EXPOSED before
2558 *
2559 * note that (1) is conservative, we start with the whole
2560 * visible region but only keep what used to be covered by
2561 * something -- which mean it may have been exposed.
2562 *
2563 * (2) handles areas that were not covered by anything but got
2564 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002565 */
Mathias Agopianab028732010-03-16 16:41:46 -07002566 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002567 const Region oldVisibleRegion = layer->visibleRegion;
2568 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002569 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2570 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 }
2572 dirty.subtractSelf(aboveOpaqueLayers);
2573
2574 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002575 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576
Mathias Agopianab028732010-03-16 16:41:46 -07002577 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002579
Jesse Halla8026d22012-09-25 13:25:04 -07002580 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 layer->setVisibleRegion(visibleRegion);
2582 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002583 layer->setVisibleNonTransparentRegion(
2584 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002585 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586
Mathias Agopian87baae12012-07-31 12:38:26 -07002587 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588}
2589
Chia-I Wuab0c3192017-08-01 11:29:00 -07002590void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002591 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002592 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002593 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002594 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002595 }
2596 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002597}
2598
Dan Stoza6b9454d2014-11-07 16:00:59 -08002599bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 ALOGV("handlePageFlip");
2602
Brian Andersond6927fb2016-07-23 23:37:30 -07002603 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604
Mathias Agopian4fec8732012-06-29 14:12:52 -07002605 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002606 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002607 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002608
2609 // Store the set of layers that need updates. This set must not change as
2610 // buffers are being latched, as this could result in a deadlock.
2611 // Example: Two producers share the same command stream and:
2612 // 1.) Layer 0 is latched
2613 // 2.) Layer 0 gets a new frame
2614 // 2.) Layer 1 gets a new frame
2615 // 3.) Layer 1 is latched.
2616 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2617 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002618 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002619 if (layer->hasQueuedFrame()) {
2620 frameQueued = true;
2621 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002622 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002623 } else {
2624 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002625 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002626 } else {
2627 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002628 }
Robert Carr2047fae2016-11-28 14:09:09 -08002629 });
2630
Dan Stoza9e56aa02015-11-02 13:00:03 -08002631 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002632 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002633 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002634 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002635 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002636 newDataLatched = true;
2637 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002639
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002640 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002641
2642 // If we will need to wake up at some time in the future to deal with a
2643 // queued frame that shouldn't be displayed during this vsync period, wake
2644 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002645 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002646 signalLayerUpdate();
2647 }
2648
2649 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002650 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651}
2652
Mathias Agopianad456f92011-01-13 17:53:01 -08002653void SurfaceFlinger::invalidateHwcGeometry()
2654{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002656}
2657
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002658
Fabien Sanglard830b8472016-11-30 16:35:58 -08002659void SurfaceFlinger::doDisplayComposition(
2660 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002661 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662{
Dan Stoza71433162014-02-04 16:22:36 -08002663 // We only need to actually compose the display if:
2664 // 1) It is being handled by hardware composer, which may need this to
2665 // keep its virtual display state machine in sync, or
2666 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002667 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002668 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002670 return;
2671 }
2672
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002674 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002675
2676 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002677 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678}
2679
Chia-I Wub02087d2017-11-09 10:19:54 -08002680bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002681{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002683
Chia-I Wub02087d2017-11-09 10:19:54 -08002684 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002685 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002687
2688 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002689 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2690 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002691 if (applyColorMatrix) {
2692 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2693 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2694 }
2695
David Sodman105b7dc2017-11-04 20:28:14 -07002696 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 if (hasClientComposition) {
2698 ALOGV("hasClientComposition");
2699
David Sodmanbc815282017-11-05 18:57:52 -08002700 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002701 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002702 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002703 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002704 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002705 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002707 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002708
2709 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002710 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002711 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2712 }
2713 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002714 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002715
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002716 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002717 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002719 // when using overlays, we assume a fully transparent framebuffer
2720 // NOTE: we could reduce how much we need to clear, for instance
2721 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002722 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002723 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002724 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002725 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002726 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002727 // we're left with the letterbox region
2728 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002730
2731 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002733
Mathias Agopianb9494d52012-04-18 02:28:45 -07002734 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002735 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002736 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002738 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002739 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002740
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002742 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002743 // scissor on the main display. It should never be needed
2744 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 const Rect& bounds(displayDevice->getBounds());
2746 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002747 if (scissor != bounds) {
2748 // scissor doesn't match the screen's dimensions, so we
2749 // need to clear everything outside of it and enable
2750 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002751
Mathias Agopianf45c5102012-10-24 16:29:17 -07002752 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002754 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002755 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002756 }
2757 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002758 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002759
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 /*
2761 * and then, render the layers targeted at the framebuffer
2762 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002763
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 ALOGV("Rendering client layers");
2765 const Transform& displayTransform = displayDevice->getTransform();
2766 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002767 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 bool firstLayer = true;
2769 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002770 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 displayTransform.transform(layer->visibleRegion)));
2772 ALOGV("Layer: %s", layer->getName().string());
2773 ALOGV(" Composition type: %s",
2774 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002775 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 switch (layer->getCompositionType(hwcId)) {
2777 case HWC2::Composition::Cursor:
2778 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002779 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002781 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002783 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002785 // never clear the very first layer since we're
2786 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002787 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002788 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002789 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002790 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002792 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002793 break;
2794 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002796 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002797 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 } else {
2799 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002800 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002802 }
2803 } else {
2804 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002806 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002808 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002809 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002810 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002811 }
2812 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002813
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002814 if (applyColorMatrix) {
2815 getRenderEngine().setupColorTransform(oldColorMatrix);
2816 }
2817
Mathias Agopianf45c5102012-10-24 16:29:17 -07002818 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002819 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002820 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821}
2822
Fabien Sanglard830b8472016-11-30 16:35:58 -08002823void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2824 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002825 RenderEngine& engine(getRenderEngine());
2826 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827}
2828
Dan Stoza7d89d062015-04-30 13:29:25 -07002829status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002830 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002831 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 const sp<Layer>& lbc,
2833 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002834{
Dan Stoza7d89d062015-04-30 13:29:25 -07002835 // add this layer to the current state list
2836 {
2837 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002839 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2840 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002841 return NO_MEMORY;
2842 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 if (parent == nullptr) {
2844 mCurrentState.layersSortedByZ.add(lbc);
2845 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002846 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002847 ALOGE("addClientLayer called with a removed parent");
2848 return NAME_NOT_FOUND;
2849 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 parent->addChild(lbc);
2851 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002852
Dan Stoza7d89d062015-04-30 13:29:25 -07002853 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002854 mLayersAdded = true;
2855 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002856 }
2857
Mathias Agopian96f08192010-06-02 23:28:45 -07002858 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002859 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002860
Dan Stoza7d89d062015-04-30 13:29:25 -07002861 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002862}
2863
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002864status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002865 Mutex::Autolock _l(mStateLock);
2866
chaviw8b3871a2017-11-01 17:41:01 -07002867 if (layer->isPendingRemoval()) {
2868 return NO_ERROR;
2869 }
2870
Robert Carr1f0a16a2016-10-24 16:27:39 -07002871 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002872 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002873 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002874 if (topLevelOnly) {
2875 return NO_ERROR;
2876 }
2877
Chia-I Wu98f1c102017-05-30 14:54:08 -07002878 sp<Layer> ancestor = p;
2879 while (ancestor->getParent() != nullptr) {
2880 ancestor = ancestor->getParent();
2881 }
2882 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2883 ALOGE("removeLayer called with a layer whose parent has been removed");
2884 return NAME_NOT_FOUND;
2885 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002886
2887 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002888 } else {
2889 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002890 }
2891
Robert Carr136e2f62017-02-08 17:54:29 -08002892 // As a matter of normal operation, the LayerCleaner will produce a second
2893 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2894 // so we will succeed in promoting it, but it's already been removed
2895 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2896 // otherwise something has gone wrong and we are leaking the layer.
2897 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002898 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2899 layer->getName().string(),
2900 (p != nullptr) ? p->getName().string() : "no-parent");
2901 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002902 } else if (index < 0) {
2903 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002904 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905
Chia-I Wuc6657022017-08-15 11:18:17 -07002906 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002907 mLayersPendingRemoval.add(layer);
2908 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002909 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910 setTransactionFlags(eTransactionNeeded);
2911 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912}
2913
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002914uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002915 return android_atomic_release_load(&mTransactionFlags);
2916}
2917
Mathias Agopian3f844832013-08-07 21:24:32 -07002918uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2920}
2921
Mathias Agopian3f844832013-08-07 21:24:32 -07002922uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2924 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002925 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 }
2927 return old;
2928}
2929
Mathias Agopian8b33f032012-07-24 20:43:54 -07002930void SurfaceFlinger::setTransactionState(
2931 const Vector<ComposerState>& state,
2932 const Vector<DisplayState>& displays,
2933 uint32_t flags)
2934{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002935 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002936 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002937 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002938
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002939 if (flags & eAnimation) {
2940 // For window updates that are part of an animation we must wait for
2941 // previous animation "frames" to be handled.
2942 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002943 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002944 if (CC_UNLIKELY(err != NO_ERROR)) {
2945 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002946 // caller after a few seconds.
2947 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2948 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002949 mAnimTransactionPending = false;
2950 break;
2951 }
2952 }
2953 }
2954
Mathias Agopiane57f2922012-08-09 16:29:12 -07002955 size_t count = displays.size();
2956 for (size_t i=0 ; i<count ; i++) {
2957 const DisplayState& s(displays[i]);
2958 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002959 }
2960
Mathias Agopiane57f2922012-08-09 16:29:12 -07002961 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002962 for (size_t i=0 ; i<count ; i++) {
2963 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002964 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08002965 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002966 // IInterface, or one of its own or even one of our own but a
2967 // different type. All these situations would cause us to crash.
2968 //
2969 // NOTE: it would be better to use RTTI as we could directly check
2970 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08002971 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002972 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08002973 if (binder != nullptr) {
2974 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002975 sp<Client> client( static_cast<Client *>(s.client.get()) );
2976 transactionFlags |= setClientStateLocked(client, s.state);
2977 }
2978 }
2979 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002980 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002981
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002982 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2983 // anyway. This can be used as a flush mechanism for previous async transactions.
2984 // Empty animation transaction can be used to simulate back-pressure, so also force a
2985 // transaction for empty animation transactions.
2986 if (transactionFlags == 0 &&
2987 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002988 transactionFlags = eTransactionNeeded;
2989 }
2990
Mathias Agopian386aa982011-11-07 21:58:03 -08002991 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002992 if (mInterceptor.isEnabled()) {
2993 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2994 }
Irvel468051e2016-06-13 16:44:44 -07002995
Mathias Agopian386aa982011-11-07 21:58:03 -08002996 // this triggers the transaction
2997 setTransactionFlags(transactionFlags);
2998
2999 // if this is a synchronous transaction, wait for it to take effect
3000 // before returning.
3001 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003002 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003003 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003004 if (flags & eAnimation) {
3005 mAnimTransactionPending = true;
3006 }
3007 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003008 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3009 if (CC_UNLIKELY(err != NO_ERROR)) {
3010 // just in case something goes wrong in SF, return to the
3011 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003012 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3013 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003014 break;
3015 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003016 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017 }
3018}
3019
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3021{
Jesse Hall9a143922012-10-04 16:29:19 -07003022 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3023 if (dpyIdx < 0)
3024 return 0;
3025
Mathias Agopiane57f2922012-08-09 16:29:12 -07003026 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003027 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003028 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003029 const uint32_t what = s.what;
3030 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003031 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003032 disp.surface = s.surface;
3033 flags |= eDisplayTransactionNeeded;
3034 }
3035 }
3036 if (what & DisplayState::eLayerStackChanged) {
3037 if (disp.layerStack != s.layerStack) {
3038 disp.layerStack = s.layerStack;
3039 flags |= eDisplayTransactionNeeded;
3040 }
3041 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003042 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003043 if (disp.orientation != s.orientation) {
3044 disp.orientation = s.orientation;
3045 flags |= eDisplayTransactionNeeded;
3046 }
3047 if (disp.frame != s.frame) {
3048 disp.frame = s.frame;
3049 flags |= eDisplayTransactionNeeded;
3050 }
3051 if (disp.viewport != s.viewport) {
3052 disp.viewport = s.viewport;
3053 flags |= eDisplayTransactionNeeded;
3054 }
3055 }
Michael Lentine47e45402014-07-18 15:34:25 -07003056 if (what & DisplayState::eDisplaySizeChanged) {
3057 if (disp.width != s.width) {
3058 disp.width = s.width;
3059 flags |= eDisplayTransactionNeeded;
3060 }
3061 if (disp.height != s.height) {
3062 disp.height = s.height;
3063 flags |= eDisplayTransactionNeeded;
3064 }
3065 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 }
3067 return flags;
3068}
3069
3070uint32_t SurfaceFlinger::setClientStateLocked(
3071 const sp<Client>& client,
3072 const layer_state_t& s)
3073{
Mathias Agopian13127d82013-03-05 17:47:11 -08003074 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003075 if (layer == nullptr) {
3076 return 0;
3077 }
3078
3079 if (layer->isPendingRemoval()) {
3080 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3081 return 0;
3082 }
3083
3084 uint32_t flags = 0;
3085
3086 const uint32_t what = s.what;
3087 bool geometryAppliesWithResize =
3088 what & layer_state_t::eGeometryAppliesWithResize;
3089 if (what & layer_state_t::ePositionChanged) {
3090 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3091 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003092 }
chaviw8b3871a2017-11-01 17:41:01 -07003093 }
3094 if (what & layer_state_t::eLayerChanged) {
3095 // NOTE: index needs to be calculated before we update the state
3096 const auto& p = layer->getParent();
3097 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003098 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003099 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003100 mCurrentState.layersSortedByZ.removeAt(idx);
3101 mCurrentState.layersSortedByZ.add(layer);
3102 // we need traversal (state changed)
3103 // AND transaction (list changed)
3104 flags |= eTransactionNeeded|eTraversalNeeded;
3105 }
chaviw8b3871a2017-11-01 17:41:01 -07003106 } else {
3107 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003108 flags |= eTransactionNeeded|eTraversalNeeded;
3109 }
3110 }
chaviw8b3871a2017-11-01 17:41:01 -07003111 }
3112 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003113 // NOTE: index needs to be calculated before we update the state
3114 const auto& p = layer->getParent();
3115 if (p == nullptr) {
3116 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3117 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3118 mCurrentState.layersSortedByZ.removeAt(idx);
3119 mCurrentState.layersSortedByZ.add(layer);
3120 // we need traversal (state changed)
3121 // AND transaction (list changed)
3122 flags |= eTransactionNeeded|eTraversalNeeded;
3123 }
3124 } else {
3125 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3126 flags |= eTransactionNeeded|eTraversalNeeded;
3127 }
chaviw8b3871a2017-11-01 17:41:01 -07003128 }
3129 }
3130 if (what & layer_state_t::eSizeChanged) {
3131 if (layer->setSize(s.w, s.h)) {
3132 flags |= eTraversalNeeded;
3133 }
3134 }
3135 if (what & layer_state_t::eAlphaChanged) {
3136 if (layer->setAlpha(s.alpha))
3137 flags |= eTraversalNeeded;
3138 }
3139 if (what & layer_state_t::eColorChanged) {
3140 if (layer->setColor(s.color))
3141 flags |= eTraversalNeeded;
3142 }
3143 if (what & layer_state_t::eMatrixChanged) {
3144 if (layer->setMatrix(s.matrix))
3145 flags |= eTraversalNeeded;
3146 }
3147 if (what & layer_state_t::eTransparentRegionChanged) {
3148 if (layer->setTransparentRegionHint(s.transparentRegion))
3149 flags |= eTraversalNeeded;
3150 }
3151 if (what & layer_state_t::eFlagsChanged) {
3152 if (layer->setFlags(s.flags, s.mask))
3153 flags |= eTraversalNeeded;
3154 }
3155 if (what & layer_state_t::eCropChanged) {
3156 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3157 flags |= eTraversalNeeded;
3158 }
3159 if (what & layer_state_t::eFinalCropChanged) {
3160 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3161 flags |= eTraversalNeeded;
3162 }
3163 if (what & layer_state_t::eLayerStackChanged) {
3164 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3165 // We only allow setting layer stacks for top level layers,
3166 // everything else inherits layer stack from its parent.
3167 if (layer->hasParent()) {
3168 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3169 layer->getName().string());
3170 } else if (idx < 0) {
3171 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3172 "that also does not appear in the top level layer list. Something"
3173 " has gone wrong.", layer->getName().string());
3174 } else if (layer->setLayerStack(s.layerStack)) {
3175 mCurrentState.layersSortedByZ.removeAt(idx);
3176 mCurrentState.layersSortedByZ.add(layer);
3177 // we need traversal (state changed)
3178 // AND transaction (list changed)
3179 flags |= eTransactionNeeded|eTraversalNeeded;
3180 }
3181 }
3182 if (what & layer_state_t::eDeferTransaction) {
3183 if (s.barrierHandle != nullptr) {
3184 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3185 } else if (s.barrierGbp != nullptr) {
3186 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3187 if (authenticateSurfaceTextureLocked(gbp)) {
3188 const auto& otherLayer =
3189 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3190 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3191 } else {
3192 ALOGE("Attempt to defer transaction to to an"
3193 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003194 }
3195 }
chaviw8b3871a2017-11-01 17:41:01 -07003196 // We don't trigger a traversal here because if no other state is
3197 // changed, we don't want this to cause any more work
3198 }
3199 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003200 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003201 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003202 if (!hadParent) {
3203 mCurrentState.layersSortedByZ.remove(layer);
3204 }
chaviw8b3871a2017-11-01 17:41:01 -07003205 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003206 }
chaviw8b3871a2017-11-01 17:41:01 -07003207 }
3208 if (what & layer_state_t::eReparentChildren) {
3209 if (layer->reparentChildren(s.reparentHandle)) {
3210 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003211 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003212 }
chaviw8b3871a2017-11-01 17:41:01 -07003213 if (what & layer_state_t::eDetachChildren) {
3214 layer->detachChildren();
3215 }
3216 if (what & layer_state_t::eOverrideScalingModeChanged) {
3217 layer->setOverrideScalingMode(s.overrideScalingMode);
3218 // We don't trigger a traversal here because if no other state is
3219 // changed, we don't want this to cause any more work
3220 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003221 return flags;
3222}
3223
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003224status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003225 const String8& name,
3226 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003227 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003228 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3229 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003231 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003232 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003233 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003234 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003235 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003236
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003237 status_t result = NO_ERROR;
3238
3239 sp<Layer> layer;
3240
Cody Northropbc755282017-03-31 12:00:08 -06003241 String8 uniqueName = getUniqueLayerName(name);
3242
Mathias Agopian3165cc22012-08-08 19:42:09 -07003243 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3244 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003245 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003246 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003247 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003248
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 break;
chaviw13fdc492017-06-27 12:40:18 -07003250 case ISurfaceComposerClient::eFXSurfaceColor:
3251 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003252 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003253 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003254 break;
3255 default:
3256 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257 break;
3258 }
3259
Dan Stoza7d89d062015-04-30 13:29:25 -07003260 if (result != NO_ERROR) {
3261 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003263
Chia-I Wuab0c3192017-08-01 11:29:00 -07003264 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3265 // TODO b/64227542
3266 if (windowType == 441731) {
3267 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3268 layer->setPrimaryDisplayOnly();
3269 }
3270
Albert Chaulk479c60c2017-01-27 14:21:34 -05003271 layer->setInfo(windowType, ownerUid);
3272
Robert Carr1f0a16a2016-10-24 16:27:39 -07003273 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003274 if (result != NO_ERROR) {
3275 return result;
3276 }
Irvelffc9efc2016-07-27 15:16:37 -07003277 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003278
3279 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003280 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281}
3282
Cody Northropbc755282017-03-31 12:00:08 -06003283String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3284{
3285 bool matchFound = true;
3286 uint32_t dupeCounter = 0;
3287
3288 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3289 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3290
3291 // Loop over layers until we're sure there is no matching name
3292 while (matchFound) {
3293 matchFound = false;
3294 mDrawingState.traverseInZOrder([&](Layer* layer) {
3295 if (layer->getName() == uniqueName) {
3296 matchFound = true;
3297 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3298 }
3299 });
3300 }
3301
3302 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3303
3304 return uniqueName;
3305}
3306
David Sodman0c69cad2017-08-21 12:12:51 -07003307status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003308 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3309 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003310{
3311 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003312 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313 case PIXEL_FORMAT_TRANSPARENT:
3314 case PIXEL_FORMAT_TRANSLUCENT:
3315 format = PIXEL_FORMAT_RGBA_8888;
3316 break;
3317 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003318 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319 break;
3320 }
3321
David Sodman0c69cad2017-08-21 12:12:51 -07003322 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3323 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003324 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003325 *handle = layer->getHandle();
3326 *gbp = layer->getProducer();
3327 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003329
David Sodman0c69cad2017-08-21 12:12:51 -07003330 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003331 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332}
3333
chaviw13fdc492017-06-27 12:40:18 -07003334status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003335 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003336 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337{
chaviw13fdc492017-06-27 12:40:18 -07003338 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003339 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003340 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003341}
3342
Mathias Agopianac9fa422013-02-11 16:40:36 -08003343status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344{
Robert Carr9524cb32017-02-13 11:32:32 -08003345 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003346 status_t err = NO_ERROR;
3347 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003348 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003349 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003350 err = removeLayer(l);
3351 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3352 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003353 }
3354 return err;
3355}
3356
Mathias Agopian13127d82013-03-05 17:47:11 -08003357status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003358{
Mathias Agopian67106042013-03-14 19:18:13 -07003359 // called by ~LayerCleaner() when all references to the IBinder (handle)
3360 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003361 sp<Layer> l = layer.promote();
3362 if (l == nullptr) {
3363 // The layer has already been removed, carry on
3364 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003365 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003366 // If we have a parent, then we can continue to live as long as it does.
3367 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003368}
3369
Mathias Agopianb60314a2012-04-10 22:09:54 -07003370// ---------------------------------------------------------------------------
3371
Andy McFadden13a082e2012-08-24 10:16:42 -07003372void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003373 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003374 Vector<ComposerState> state;
3375 Vector<DisplayState> displays;
3376 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003377 d.what = DisplayState::eDisplayProjectionChanged |
3378 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003379 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003380 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003381 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003382 d.frame.makeInvalid();
3383 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003384 d.width = 0;
3385 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003386 displays.add(d);
3387 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003388 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3389 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003390
David Sodman105b7dc2017-11-04 20:28:14 -07003391 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003392 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003393 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003394
Brian Andersond0010582017-03-07 13:20:31 -08003395 // Use phase of 0 since phase is not known.
3396 // Use latency of 0, which will snap to the ideal latency.
3397 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003398}
3399
3400void SurfaceFlinger::initializeDisplays() {
3401 class MessageScreenInitialized : public MessageBase {
3402 SurfaceFlinger* flinger;
3403 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003404 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003405 virtual bool handler() {
3406 flinger->onInitializeDisplays();
3407 return true;
3408 }
3409 };
3410 sp<MessageBase> msg = new MessageScreenInitialized(this);
3411 postMessageAsync(msg); // we may be called from main thread, use async message
3412}
3413
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003414void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003415 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003416 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3417 this);
3418 int32_t type = hw->getDisplayType();
3419 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003420
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003421 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003422 return;
3423 }
3424
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003425 hw->setPowerMode(mode);
3426 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3427 ALOGW("Trying to set power mode for virtual display");
3428 return;
3429 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003430
Irvelffc9efc2016-07-27 15:16:37 -07003431 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003432 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003433 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3434 if (idx < 0) {
3435 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3436 return;
3437 }
3438 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3439 }
3440
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003441 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003442 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003443 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003444 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3445 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003446 // FIXME: eventthread only knows about the main display right now
3447 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003448 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003451 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003452 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003453 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003454
3455 struct sched_param param = {0};
3456 param.sched_priority = 1;
3457 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3458 ALOGW("Couldn't set SCHED_FIFO on display on");
3459 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003460 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003461 // Turn off the display
3462 struct sched_param param = {0};
3463 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3464 ALOGW("Couldn't set SCHED_OTHER on display off");
3465 }
3466
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003467 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3468 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003469 disableHardwareVsync(true); // also cancels any in-progress resync
3470
Mathias Agopiancde87a32012-09-13 14:09:01 -07003471 // FIXME: eventthread only knows about the main display right now
3472 mEventThread->onScreenReleased();
3473 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003474
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003475 getHwComposer().setPowerMode(type, mode);
3476 mVisibleRegionsDirty = true;
3477 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003478 } else if (mode == HWC_POWER_MODE_DOZE ||
3479 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003480 // Update display while dozing
3481 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003482 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3483 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003484 // FIXME: eventthread only knows about the main display right now
3485 mEventThread->onScreenAcquired();
3486 resyncToHardwareVsync(true);
3487 }
3488 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3489 // Leave display going to doze
3490 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3491 disableHardwareVsync(true); // also cancels any in-progress resync
3492 // FIXME: eventthread only knows about the main display right now
3493 mEventThread->onScreenReleased();
3494 }
3495 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003496 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003497 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003498 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003499 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003500}
3501
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003502void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3503 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003504 SurfaceFlinger& mFlinger;
3505 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003506 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003507 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003508 MessageSetPowerMode(SurfaceFlinger& flinger,
3509 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3510 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003511 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003512 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003513 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003514 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003515 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003516 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003517 ALOGW("Attempt to set power mode = %d for virtual display",
3518 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003519 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003520 mFlinger.setPowerModeInternal(
3521 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003522 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003523 return true;
3524 }
3525 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003526 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003527 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003528}
3529
3530// ---------------------------------------------------------------------------
3531
Vishnu Nair6a408532017-10-24 09:11:27 -07003532status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003534
Mathias Agopianbd115332013-04-18 16:41:04 -07003535 IPCThreadState* ipc = IPCThreadState::self();
3536 const int pid = ipc->getCallingPid();
3537 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003538
Mathias Agopianbd115332013-04-18 16:41:04 -07003539 if ((uid != AID_SHELL) &&
3540 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003541 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003542 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003544 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003545 // (this would indicate SF is stuck, but we want to be able to
3546 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003547 status_t err = mStateLock.timedLock(s2ns(1));
3548 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003549 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003550 result.appendFormat(
3551 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3552 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003553 }
3554
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003555 bool dumpAll = true;
3556 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003557 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003558
3559 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003560 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003561 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3562 dumpAll = false;
3563 }
3564
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003565 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003566 if ((index < numArgs) &&
3567 (args[index] == String16("--list"))) {
3568 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003569 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003570 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003571 }
3572
3573 if ((index < numArgs) &&
3574 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003575 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003576 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003577 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003579
3580 if ((index < numArgs) &&
3581 (args[index] == String16("--latency-clear"))) {
3582 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003583 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003584 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003585 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003586
3587 if ((index < numArgs) &&
3588 (args[index] == String16("--dispsync"))) {
3589 index++;
3590 mPrimaryDispSync.dump(result);
3591 dumpAll = false;
3592 }
Dan Stozab90cf072015-03-05 11:05:59 -08003593
3594 if ((index < numArgs) &&
3595 (args[index] == String16("--static-screen"))) {
3596 index++;
3597 dumpStaticScreenStats(result);
3598 dumpAll = false;
3599 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003600
3601 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003602 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003603 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003604 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003605 dumpAll = false;
3606 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003607
3608 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3609 index++;
3610 dumpWideColorInfo(result);
3611 dumpAll = false;
3612 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003614
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003615 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003616 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003617 }
3618
Mathias Agopian9795c422009-08-26 16:36:26 -07003619 if (locked) {
3620 mStateLock.unlock();
3621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 }
3623 write(fd, result.string(), result.size());
3624 return NO_ERROR;
3625}
3626
Dan Stozac7014012014-02-14 15:03:43 -08003627void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3628 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003629{
Robert Carr2047fae2016-11-28 14:09:09 -08003630 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003631 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003632 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003633}
3634
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003635void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003636 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003637{
3638 String8 name;
3639 if (index < args.size()) {
3640 name = String8(args[index]);
3641 index++;
3642 }
3643
David Sodman105b7dc2017-11-04 20:28:14 -07003644 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003645 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003646 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003647
3648 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003649 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003650 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003651 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003652 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003653 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003654 }
Robert Carr2047fae2016-11-28 14:09:09 -08003655 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003656 }
3657}
3658
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003659void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003660 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003661{
3662 String8 name;
3663 if (index < args.size()) {
3664 name = String8(args[index]);
3665 index++;
3666 }
3667
Robert Carr2047fae2016-11-28 14:09:09 -08003668 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003669 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003670 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003671 }
Robert Carr2047fae2016-11-28 14:09:09 -08003672 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003673
Svetoslavd85084b2014-03-20 10:28:31 -07003674 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003675}
3676
Jamie Gennis6547ff42013-07-16 20:12:42 -07003677// This should only be called from the main thread. Otherwise it would need
3678// the lock and should use mCurrentState rather than mDrawingState.
3679void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003680 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003681 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003682 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003683
3684 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3685}
3686
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003687void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003688{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003689 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003690 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3691
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003692 if (isLayerTripleBufferingDisabled())
3693 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003694
3695 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003696 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003697 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003698 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003699 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3700 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003701 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003702}
3703
Dan Stozab90cf072015-03-05 11:05:59 -08003704void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3705{
3706 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003707 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3708 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003709 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003710 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003711 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3712 b + 1, bucketTimeSec, percent);
3713 }
David Sodman4a36e932017-11-07 14:29:47 -08003714 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003715 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003716 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003717 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003718 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003719}
3720
Dan Stozae77c7662016-05-13 11:37:28 -07003721void SurfaceFlinger::recordBufferingStats(const char* layerName,
3722 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003723 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3724 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003725 for (const auto& segment : history) {
3726 if (!segment.usedThirdBuffer) {
3727 stats.twoBufferTime += segment.totalTime;
3728 }
3729 if (segment.occupancyAverage < 1.0f) {
3730 stats.doubleBufferedTime += segment.totalTime;
3731 } else if (segment.occupancyAverage < 2.0f) {
3732 stats.tripleBufferedTime += segment.totalTime;
3733 }
3734 ++stats.numSegments;
3735 stats.totalTime += segment.totalTime;
3736 }
3737}
3738
Brian Andersond6927fb2016-07-23 23:37:30 -07003739void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3740 result.appendFormat("Layer frame timestamps:\n");
3741
3742 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3743 const size_t count = currentLayers.size();
3744 for (size_t i=0 ; i<count ; i++) {
3745 currentLayers[i]->dumpFrameEvents(result);
3746 }
3747}
3748
Dan Stozae77c7662016-05-13 11:37:28 -07003749void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3750 result.append("Buffering stats:\n");
3751 result.append(" [Layer name] <Active time> <Two buffer> "
3752 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003753 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003754 typedef std::tuple<std::string, float, float, float> BufferTuple;
3755 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003756 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003757 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003758 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003759 if (stats.numSegments == 0) {
3760 continue;
3761 }
3762 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3763 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3764 stats.totalTime;
3765 float doubleBufferRatio = static_cast<float>(
3766 stats.doubleBufferedTime) / stats.totalTime;
3767 float tripleBufferRatio = static_cast<float>(
3768 stats.tripleBufferedTime) / stats.totalTime;
3769 sorted.insert({activeTime, {name, twoBufferRatio,
3770 doubleBufferRatio, tripleBufferRatio}});
3771 }
3772 for (const auto& sortedPair : sorted) {
3773 float activeTime = sortedPair.first;
3774 const BufferTuple& values = sortedPair.second;
3775 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3776 std::get<0>(values).c_str(), activeTime,
3777 std::get<1>(values), std::get<2>(values),
3778 std::get<3>(values));
3779 }
3780 result.append("\n");
3781}
3782
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003783void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3784 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003785 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003786
3787 // TODO: print out if wide-color mode is active or not
3788
3789 for (size_t d = 0; d < mDisplays.size(); d++) {
3790 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3791 int32_t hwcId = displayDevice->getHwcDisplayId();
3792 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3793 continue;
3794 }
3795
3796 result.appendFormat("Display %d color modes:\n", hwcId);
3797 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3798 for (auto&& mode : modes) {
3799 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3800 }
3801
3802 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3803 result.appendFormat(" Current color mode: %s (%d)\n",
3804 decodeColorMode(currentMode).c_str(), currentMode);
3805 }
3806 result.append("\n");
3807}
3808
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003809LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003810 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003811 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3812 const State& state = useDrawing ? mDrawingState : mCurrentState;
3813 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003814 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003815 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003816 });
3817
3818 return layersProto;
3819}
3820
Mathias Agopian74d211a2013-04-22 16:55:35 +02003821void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3822 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003823{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 bool colorize = false;
3825 if (index < args.size()
3826 && (args[index] == String16("--color"))) {
3827 colorize = true;
3828 index++;
3829 }
3830
3831 Colorizer colorizer(colorize);
3832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 // figure out if we're stuck somewhere
3834 const nsecs_t now = systemTime();
3835 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3836 const nsecs_t inTransaction(mDebugInTransaction);
3837 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3838 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3839
3840 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003841 * Dump library configuration.
3842 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003843
3844 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003845 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003846 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003847 appendSfConfigString(result);
3848 appendUiConfigString(result);
3849 appendGuiConfigString(result);
3850 result.append("\n");
3851
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003852 result.append("\nWide-Color information:\n");
3853 dumpWideColorInfo(result);
3854
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003855 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003856 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003857 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003858 result.append(SyncFeatures::getInstance().toString());
3859 result.append("\n");
3860
David Sodman105b7dc2017-11-04 20:28:14 -07003861 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003862
Andy McFadden41d67d72014-04-25 16:58:34 -07003863 colorizer.bold(result);
3864 result.append("DispSync configuration: ");
3865 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003866 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003867 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003868 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003869 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003870 result.append("\n");
3871
Dan Stozab90cf072015-03-05 11:05:59 -08003872 // Dump static screen stats
3873 result.append("\n");
3874 dumpStaticScreenStats(result);
3875 result.append("\n");
3876
Dan Stozae77c7662016-05-13 11:37:28 -07003877 dumpBufferingStats(result);
3878
Andy McFadden4803b742012-09-24 19:07:20 -07003879 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003880 * Dump the visible layer list
3881 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003882 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003883 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003884 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003885
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003886 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003887 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3888 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003889
3890 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003891 * Dump Display state
3892 */
3893
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003894 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003895 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003896 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3898 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003899 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003900 }
3901
3902 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003903 * Dump SurfaceFlinger global state
3904 */
3905
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003906 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003907 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003908 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909
Mathias Agopian888c8222012-08-04 21:10:38 -07003910 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003911 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003912
David Sodmanbc815282017-11-05 18:57:52 -08003913 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003914
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003915 if (hw) {
3916 hw->undefinedRegion.dump(result, "undefinedRegion");
3917 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3918 hw->getOrientation(), hw->isDisplayOn());
3919 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921 " last eglSwapBuffers() time: %f us\n"
3922 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003923 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924 " refresh-rate : %f fps\n"
3925 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003926 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003927 " gpu_to_cpu_unsupported : %d\n"
3928 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929 mLastSwapBufferTime/1000.0,
3930 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003931 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003932 1e9 / activeConfig->getVsyncPeriod(),
3933 activeConfig->getDpiX(),
3934 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003935 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003936
Mathias Agopian74d211a2013-04-22 16:55:35 +02003937 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003939
Mathias Agopian74d211a2013-04-22 16:55:35 +02003940 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003941 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003942
3943 /*
3944 * VSYNC state
3945 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003946 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003947 result.append("\n");
3948
3949 /*
3950 * HWC layer minidump
3951 */
3952 for (size_t d = 0; d < mDisplays.size(); d++) {
3953 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3954 int32_t hwcId = displayDevice->getHwcDisplayId();
3955 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3956 continue;
3957 }
3958
3959 result.appendFormat("Display %d HWC layers:\n", hwcId);
3960 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003961 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003962 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003963 });
Dan Stozae22aec72016-08-01 13:20:59 -07003964 result.append("\n");
3965 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966
3967 /*
3968 * Dump HWComposer state
3969 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003970 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003971 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003972 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003973 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003974 result.appendFormat(" h/w composer %s\n",
3975 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003976 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003977
3978 /*
3979 * Dump gralloc state
3980 */
3981 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3982 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003983
3984 /*
3985 * Dump VrFlinger state if in use.
3986 */
3987 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3988 result.append("VrFlinger state:\n");
3989 result.append(mVrFlinger->Dump().c_str());
3990 result.append("\n");
3991 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003992}
3993
Mathias Agopian13127d82013-03-05 17:47:11 -08003994const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003995SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003996 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003997 wp<IBinder> dpy;
3998 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3999 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4000 dpy = mDisplays.keyAt(i);
4001 break;
4002 }
4003 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004004 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004005 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4006 // Just use the primary display so we have something to return
4007 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004009 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004010}
4011
Keun young Park63f165f2012-08-31 10:53:36 -07004012bool SurfaceFlinger::startDdmConnection()
4013{
4014 void* libddmconnection_dso =
4015 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4016 if (!libddmconnection_dso) {
4017 return false;
4018 }
4019 void (*DdmConnection_start)(const char* name);
4020 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004021 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004022 if (!DdmConnection_start) {
4023 dlclose(libddmconnection_dso);
4024 return false;
4025 }
4026 (*DdmConnection_start)(getServiceName());
4027 return true;
4028}
4029
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004030status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 switch (code) {
4032 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004033 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004034 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004035 case CLEAR_ANIMATION_FRAME_STATS:
4036 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004037 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004038 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004039 case ENABLE_VSYNC_INJECTIONS:
4040 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041 {
4042 // codes that require permission check
4043 IPCThreadState* ipc = IPCThreadState::self();
4044 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004045 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004046 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004047 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004048 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004049 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004051 break;
4052 }
Robert Carr1db73f62016-12-21 12:58:51 -08004053 /*
4054 * Calling setTransactionState is safe, because you need to have been
4055 * granted a reference to Client* and Handle* to do anything with it.
4056 *
4057 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4058 */
4059 case SET_TRANSACTION_STATE:
4060 case CREATE_SCOPED_CONNECTION:
4061 {
4062 return OK;
4063 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004064 case CAPTURE_SCREEN:
4065 {
4066 // codes that require permission check
4067 IPCThreadState* ipc = IPCThreadState::self();
4068 const int pid = ipc->getCallingPid();
4069 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004070 if ((uid != AID_GRAPHICS) &&
4071 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004072 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004073 return PERMISSION_DENIED;
4074 }
4075 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004076 }
chaviwa76b2712017-09-20 12:02:26 -07004077 case CAPTURE_LAYERS: {
4078 IPCThreadState* ipc = IPCThreadState::self();
4079 const int pid = ipc->getCallingPid();
4080 const int uid = ipc->getCallingUid();
4081 if ((uid != AID_GRAPHICS) &&
4082 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4083 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4084 return PERMISSION_DENIED;
4085 }
4086 break;
4087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004089 return OK;
4090}
4091
4092status_t SurfaceFlinger::onTransact(
4093 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4094{
4095 status_t credentialCheck = CheckTransactCodeCredentials(code);
4096 if (credentialCheck != OK) {
4097 return credentialCheck;
4098 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004099
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004100 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4101 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004102 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004103 IPCThreadState* ipc = IPCThreadState::self();
4104 const int uid = ipc->getCallingUid();
4105 if (CC_UNLIKELY(uid != AID_SYSTEM
4106 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004107 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004108 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004109 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 return PERMISSION_DENIED;
4111 }
4112 int n;
4113 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004114 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004115 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 return NO_ERROR;
4117 case 1002: // SHOW_UPDATES
4118 n = data.readInt32();
4119 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004120 invalidateHwcGeometry();
4121 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004122 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004124 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004125 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004127 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004128 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004129 setTransactionFlags(
4130 eTransactionNeeded|
4131 eDisplayTransactionNeeded|
4132 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004133 return NO_ERROR;
4134 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004135 case 1006:{ // send empty update
4136 signalRefresh();
4137 return NO_ERROR;
4138 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004139 case 1008: // toggle use of hw composer
4140 n = data.readInt32();
4141 mDebugDisableHWC = n ? 1 : 0;
4142 invalidateHwcGeometry();
4143 repaintEverything();
4144 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004145 case 1009: // toggle use of transform hint
4146 n = data.readInt32();
4147 mDebugDisableTransformHint = n ? 1 : 0;
4148 invalidateHwcGeometry();
4149 repaintEverything();
4150 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004151 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004152 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 reply->writeInt32(0);
4154 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004155 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004156 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004157 return NO_ERROR;
4158 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004159 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004160 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004161 return NO_ERROR;
4162 }
4163 case 1014: {
4164 // daltonize
4165 n = data.readInt32();
4166 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004167 case 1:
4168 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4169 break;
4170 case 2:
4171 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4172 break;
4173 case 3:
4174 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4175 break;
4176 default:
4177 mDaltonizer.setType(ColorBlindnessType::None);
4178 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004179 }
4180 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004181 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004182 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004183 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004184 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004185 invalidateHwcGeometry();
4186 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004187 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004189 case 1015: {
4190 // apply a color matrix
4191 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004192 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004193 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004194 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004195 for (size_t j = 0; j < 4; j++) {
4196 mColorMatrix[i][j] = data.readFloat();
4197 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004198 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004199 } else {
4200 mColorMatrix = mat4();
4201 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004202
4203 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4204 // the division by w in the fragment shader
4205 float4 lastRow(transpose(mColorMatrix)[3]);
4206 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4207 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4208 }
4209
Alan Viverette9c5a3332013-09-12 20:04:35 -07004210 invalidateHwcGeometry();
4211 repaintEverything();
4212 return NO_ERROR;
4213 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004214 // This is an experimental interface
4215 // Needs to be shifted to proper binder interface when we productize
4216 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004217 n = data.readInt32();
4218 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004219 return NO_ERROR;
4220 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004221 case 1017: {
4222 n = data.readInt32();
4223 mForceFullDamage = static_cast<bool>(n);
4224 return NO_ERROR;
4225 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004226 case 1018: { // Modify Choreographer's phase offset
4227 n = data.readInt32();
4228 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4229 return NO_ERROR;
4230 }
4231 case 1019: { // Modify SurfaceFlinger's phase offset
4232 n = data.readInt32();
4233 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4234 return NO_ERROR;
4235 }
Irvel468051e2016-06-13 16:44:44 -07004236 case 1020: { // Layer updates interceptor
4237 n = data.readInt32();
4238 if (n) {
4239 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004240 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004241 }
4242 else{
4243 ALOGV("Interceptor disabled");
4244 mInterceptor.disable();
4245 }
4246 return NO_ERROR;
4247 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004248 case 1021: { // Disable HWC virtual displays
4249 n = data.readInt32();
4250 mUseHwcVirtualDisplays = !n;
4251 return NO_ERROR;
4252 }
Romain Guy0147a172017-06-01 13:53:56 -07004253 case 1022: { // Set saturation boost
4254 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4255
4256 invalidateHwcGeometry();
4257 repaintEverything();
4258 return NO_ERROR;
4259 }
Romain Guy54f154a2017-10-24 21:40:32 +01004260 case 1023: { // Set native mode
4261 mForceNativeColorMode = data.readInt32() == 1;
4262
4263 invalidateHwcGeometry();
4264 repaintEverything();
4265 return NO_ERROR;
4266 }
4267 case 1024: { // Is wide color gamut rendering/color management supported?
4268 reply->writeBool(hasWideColorDisplay);
4269 return NO_ERROR;
4270 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004271 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004272 n = data.readInt32();
4273 if (n) {
4274 ALOGV("LayerTracing enabled");
4275 mTracing.enable();
4276 doTracing("tracing.enable");
4277 reply->writeInt32(NO_ERROR);
4278 } else {
4279 ALOGV("LayerTracing disabled");
4280 status_t err = mTracing.disable();
4281 reply->writeInt32(err);
4282 }
4283 return NO_ERROR;
4284 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004285 case 1026: { // Get layer tracing status
4286 reply->writeBool(mTracing.isEnabled());
4287 return NO_ERROR;
4288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 }
4290 }
4291 return err;
4292}
4293
Steven Thomas6d8110b2017-08-31 18:24:21 -07004294void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004295 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004296 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004297}
4298
Steven Thomas6d8110b2017-08-31 18:24:21 -07004299void SurfaceFlinger::repaintEverything() {
4300 ConditionalLock _l(mStateLock,
4301 std::this_thread::get_id() != mMainThreadId);
4302 repaintEverythingLocked();
4303}
4304
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004305// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4306class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004307public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004308 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4309 ~WindowDisconnector() {
4310 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004311 }
4312
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004313private:
4314 ANativeWindow* mWindow;
4315 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004316};
4317
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004318status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4319 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4320 int32_t minLayerZ, int32_t maxLayerZ,
4321 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004322 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004323 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004324
chaviwa76b2712017-09-20 12:02:26 -07004325 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4326
4327 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4328 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4329
4330 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4331 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004332 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004333}
4334
4335status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004336 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004337 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004338 ATRACE_CALL();
4339
4340 class LayerRenderArea : public RenderArea {
4341 public:
chaviw7206d492017-11-10 16:16:12 -08004342 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004343 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004344 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004345 const Transform& getTransform() const override {
4346 // Make the top level transform the inverse the transform and it's parent so it sets
4347 // the whole capture back to 0,0
4348 return *new Transform(mLayer->getTransform().inverse());
4349 }
4350 Rect getBounds() const override {
4351 const Layer::State& layerState(mLayer->getDrawingState());
4352 return Rect(layerState.active.w, layerState.active.h);
4353 }
4354 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4355 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4356 bool isSecure() const override { return false; }
4357 bool needsFiltering() const override { return false; }
4358
chaviw7206d492017-11-10 16:16:12 -08004359 Rect getSourceCrop() const override {
4360 if (mCrop.isEmpty()) {
4361 return getBounds();
4362 } else {
4363 return mCrop;
4364 }
4365 }
chaviwa76b2712017-09-20 12:02:26 -07004366 bool getWideColorSupport() const override { return false; }
4367 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4368
4369 private:
chaviw7206d492017-11-10 16:16:12 -08004370 const sp<Layer> mLayer;
4371 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004372 };
4373
4374 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4375 auto parent = layerHandle->owner.promote();
4376
chaviw7206d492017-11-10 16:16:12 -08004377 if (parent == nullptr || parent->isPendingRemoval()) {
4378 ALOGE("captureLayers called with a removed parent");
4379 return NAME_NOT_FOUND;
4380 }
4381
4382 Rect crop(sourceCrop);
4383 if (sourceCrop.width() <= 0) {
4384 crop.left = 0;
4385 crop.right = parent->getCurrentState().active.w;
4386 }
4387
4388 if (sourceCrop.height() <= 0) {
4389 crop.top = 0;
4390 crop.bottom = parent->getCurrentState().active.h;
4391 }
4392
4393 int32_t reqWidth = crop.width() * frameScale;
4394 int32_t reqHeight = crop.height() * frameScale;
4395
4396 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4397
chaviwa76b2712017-09-20 12:02:26 -07004398 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4399 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4400 if (!layer->isVisible()) {
4401 return;
4402 }
4403 visitor(layer);
4404 });
4405 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004406 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004407}
4408
4409status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4410 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004411 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004412 bool useIdentityTransform) {
4413 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004414
chaviwa76b2712017-09-20 12:02:26 -07004415 renderArea.updateDimensions();
4416
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004417 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4418 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4419 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4420 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004421
4422 // This mutex protects syncFd and captureResult for communication of the return values from the
4423 // main thread back to this Binder thread
4424 std::mutex captureMutex;
4425 std::condition_variable captureCondition;
4426 std::unique_lock<std::mutex> captureLock(captureMutex);
4427 int syncFd = -1;
4428 std::optional<status_t> captureResult;
4429
Robert Carr03480e22018-01-04 16:02:06 -08004430 const int uid = IPCThreadState::self()->getCallingUid();
4431 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4432
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004433 sp<LambdaMessage> message = new LambdaMessage([&]() {
4434 // If there is a refresh pending, bug out early and tell the binder thread to try again
4435 // after the refresh.
4436 if (mRefreshPending) {
4437 ATRACE_NAME("Skipping screenshot for now");
4438 std::unique_lock<std::mutex> captureLock(captureMutex);
4439 captureResult = std::make_optional<status_t>(EAGAIN);
4440 captureCondition.notify_one();
4441 return;
4442 }
4443
4444 status_t result = NO_ERROR;
4445 int fd = -1;
4446 {
4447 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004448 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004449 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004450 }
4451
4452 {
4453 std::unique_lock<std::mutex> captureLock(captureMutex);
4454 syncFd = fd;
4455 captureResult = std::make_optional<status_t>(result);
4456 captureCondition.notify_one();
4457 }
4458 });
4459
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004460 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004461 if (result == NO_ERROR) {
4462 captureCondition.wait(captureLock, [&]() { return captureResult; });
4463 while (*captureResult == EAGAIN) {
4464 captureResult.reset();
4465 result = postMessageAsync(message);
4466 if (result != NO_ERROR) {
4467 return result;
4468 }
4469 captureCondition.wait(captureLock, [&]() { return captureResult; });
4470 }
4471 result = *captureResult;
4472 }
4473
4474 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004475 sync_wait(syncFd, -1);
4476 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004477 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004478
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004479 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004480}
4481
chaviwa76b2712017-09-20 12:02:26 -07004482void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4483 TraverseLayersFunction traverseLayers, bool yswap,
4484 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004485 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004486
Mathias Agopian3f844832013-08-07 21:24:32 -07004487 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004488
4489 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004490 const auto raWidth = renderArea.getWidth();
4491 const auto raHeight = renderArea.getHeight();
4492
4493 const auto reqWidth = renderArea.getReqWidth();
4494 const auto reqHeight = renderArea.getReqHeight();
4495 Rect sourceCrop = renderArea.getSourceCrop();
4496
4497 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4498 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004499
Dan Stozac1879002014-05-22 15:59:05 -07004500 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004501 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004502 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004503 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004504 }
4505
4506 // ensure that sourceCrop is inside screen
4507 if (sourceCrop.left < 0) {
4508 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4509 }
chaviwa76b2712017-09-20 12:02:26 -07004510 if (sourceCrop.right > raWidth) {
4511 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004512 }
4513 if (sourceCrop.top < 0) {
4514 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4515 }
chaviwa76b2712017-09-20 12:02:26 -07004516 if (sourceCrop.bottom > raHeight) {
4517 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004518 }
4519
chaviwa76b2712017-09-20 12:02:26 -07004520 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004521 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4522 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004523
Mathias Agopian180f10d2013-04-10 22:55:41 -07004524 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004525 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004526
4527 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004528 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4529 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004530 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004531
4532 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004533 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004534
chaviwa76b2712017-09-20 12:02:26 -07004535 traverseLayers([&](Layer* layer) {
4536 if (filtering) layer->setFiltering(true);
4537 layer->draw(renderArea, useIdentityTransform);
4538 if (filtering) layer->setFiltering(false);
4539 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004540}
4541
chaviwa76b2712017-09-20 12:02:26 -07004542status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4543 TraverseLayersFunction traverseLayers,
4544 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004545 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004546 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004547 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004548 ATRACE_CALL();
4549
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004550 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004551
4552 traverseLayers([&](Layer* layer) {
4553 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4554 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004555
Robert Carr03480e22018-01-04 16:02:06 -08004556 // We allow the system server to take screenshots of secure layers for
4557 // use in situations like the Screen-rotation animation and place
4558 // the impetus on WindowManager to not persist them.
4559 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004560 ALOGW("FB is protected: PERMISSION_DENIED");
4561 return PERMISSION_DENIED;
4562 }
4563
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004564 // this binds the given EGLImage as a framebuffer for the
4565 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004566 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4567 if (bufferBond.getStatus() != NO_ERROR) {
4568 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004569 return INVALID_OPERATION;
4570 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004571
Dan Stozaabcda352017-06-01 14:37:39 -07004572 // this will in fact render into our dequeued buffer
4573 // via an FBO, which means we didn't have to create
4574 // an EGLSurface and therefore we're not
4575 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004576 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004577
Dan Stozaabcda352017-06-01 14:37:39 -07004578 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004579 getRenderEngine().finish();
4580 *outSyncFd = -1;
4581
chaviwa76b2712017-09-20 12:02:26 -07004582 const auto reqWidth = renderArea.getReqWidth();
4583 const auto reqHeight = renderArea.getReqHeight();
4584
Dan Stozaabcda352017-06-01 14:37:39 -07004585 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4586 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004587 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004588 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004589 } else {
4590 base::unique_fd syncFd = getRenderEngine().flush();
4591 if (syncFd < 0) {
4592 getRenderEngine().finish();
4593 }
4594 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004595 }
4596
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004597 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004598}
4599
Mathias Agopiand5556842013-09-19 17:08:37 -07004600void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004601 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004602 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004603 for (size_t y = 0; y < h; y++) {
4604 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4605 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004606 if (p[x] != 0xFF000000) return;
4607 }
4608 }
chaviwa76b2712017-09-20 12:02:26 -07004609 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004610
Robert Carr2047fae2016-11-28 14:09:09 -08004611 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004612 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004613 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004614 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4615 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4616 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4617 static_cast<float>(state.color.a));
4618 i++;
4619 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004620 }
4621}
4622
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004623// ---------------------------------------------------------------------------
4624
Dan Stoza412903f2017-04-27 13:42:17 -07004625void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4626 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004627}
4628
Dan Stoza412903f2017-04-27 13:42:17 -07004629void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4630 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004631}
4632
chaviwa76b2712017-09-20 12:02:26 -07004633void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4634 int32_t maxLayerZ,
4635 const LayerVector::Visitor& visitor) {
4636 // We loop through the first level of layers without traversing,
4637 // as we need to interpret min/max layer Z in the top level Z space.
4638 for (const auto& layer : mDrawingState.layersSortedByZ) {
4639 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4640 continue;
4641 }
4642 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004643 // relative layers are traversed in Layer::traverseInZOrder
4644 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004645 continue;
4646 }
4647 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004648 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4649 return;
4650 }
chaviwa76b2712017-09-20 12:02:26 -07004651 if (!layer->isVisible()) {
4652 return;
4653 }
4654 visitor(layer);
4655 });
4656 }
4657}
4658
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004660
4661
4662#if defined(__gl_h_)
4663#error "don't include gl/gl.h in this file"
4664#endif
4665
4666#if defined(__gl2_h_)
4667#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004668#endif