blob: bfa239d8c830aabba2fb3da008861c6016165617 [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;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
Kalle Raitaa099a242017-01-11 11:17:29 -0800141
142std::string getHwcServiceName() {
143 char value[PROPERTY_VALUE_MAX] = {};
144 property_get("debug.sf.hwc_service_name", value, "default");
145 ALOGI("Using HWComposer service: '%s'", value);
146 return std::string(value);
147}
148
149bool useTrebleTestingOverride() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.treble_testing_override", value, "false");
152 ALOGI("Treble testing override: '%s'", value);
153 return std::string(value) == "true";
154}
155
David Sodmanbc815282017-11-05 18:57:52 -0800156SurfaceFlingerBE::SurfaceFlingerBE()
157 : mHwcServiceName(getHwcServiceName()),
158 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800162 mComposerSequenceId(0) {
163}
164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700166 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700168 mTransactionPending(false),
169 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700170 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700171 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700172 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800174 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800176 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800177 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700180 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700181 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700182 mDebugInSwapBuffers(0),
183 mLastSwapBufferTime(0),
184 mDebugInTransaction(0),
185 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700186 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700187 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800188 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
David Sodman105b7dc2017-11-04 20:28:14 -0700196 mMainThreadId(std::this_thread::get_id())
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700209 useContextPriority = getBool< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::useContextPriority>(false);
211
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
214
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
217
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
219 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
220
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 // Vr flinger is only enabled on Daydream ready devices.
222 useVrFlinger = getBool< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::useVrFlinger>(false);
224
Fabien Sanglard1971b632017-03-10 14:50:03 -0800225 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
226 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
227
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228 hasWideColorDisplay =
229 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
230
David Sodman99974d22017-11-28 12:04:33 -0800231 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // debugging stuff...
234 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700237 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 property_get("debug.sf.showupdates", value, "0");
240 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242 property_get("debug.sf.ddms", value, "0");
243 mDebugDDMS = atoi(value);
244 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700245 if (!startDdmConnection()) {
246 // start failed, and DDMS debugging not enabled
247 mDebugDDMS = 0;
248 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700250 ALOGI_IF(mDebugRegion, "showupdates enabled");
251 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700252
253 property_get("debug.sf.disable_backpressure", value, "0");
254 mPropagateBackpressure = !atoi(value);
255 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700256
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800257 property_get("debug.sf.enable_hwc_vds", value, "0");
258 mUseHwcVirtualDisplays = atoi(value);
259 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800261 property_get("ro.sf.disable_triple_buffer", value, "1");
262 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800263 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700264
Romain Guy11d63f42017-07-20 12:47:14 -0700265 // We should be reading 'persist.sys.sf.color_saturation' here
266 // but since /data may be encrypted, we need to wait until after vold
267 // comes online to attempt to read the property. The property is
268 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800269
270 if (useTrebleTestingOverride()) {
271 // Without the override SurfaceFlinger cannot connect to HIDL
272 // services that are not listed in the manifests. Considered
273 // deriving the setting from the set service name, but it
274 // would be brittle if the name that's not 'default' is used
275 // for production purposes later on.
276 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278}
279
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280void SurfaceFlinger::onFirstRef()
281{
282 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800283}
284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285SurfaceFlinger::~SurfaceFlinger()
286{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287}
288
Dan Stozac7014012014-02-14 15:03:43 -0800289void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800290{
291 // the window manager died on us. prepare its eulogy.
292
Andy McFadden13a082e2012-08-24 10:16:42 -0700293 // restore initial conditions (default device unblank, etc)
294 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295
296 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700297 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800298}
299
Robert Carr1db73f62016-12-21 12:58:51 -0800300static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700301 status_t err = client->initCheck();
302 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800303 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 }
Robert Carr1db73f62016-12-21 12:58:51 -0800305 return nullptr;
306}
307
308sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
309 return initClient(new Client(this));
310}
311
312sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
313 const sp<IGraphicBufferProducer>& gbp) {
314 if (authenticateSurfaceTexture(gbp) == false) {
315 return nullptr;
316 }
317 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
318 if (layer == nullptr) {
319 return nullptr;
320 }
321
322 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323}
324
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700325sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
326 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700327{
328 class DisplayToken : public BBinder {
329 sp<SurfaceFlinger> flinger;
330 virtual ~DisplayToken() {
331 // no more references, this display must be terminated
332 Mutex::Autolock _l(flinger->mStateLock);
333 flinger->mCurrentState.displays.removeItem(this);
334 flinger->setTransactionFlags(eDisplayTransactionNeeded);
335 }
336 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700337 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700338 : flinger(flinger) {
339 }
340 };
341
342 sp<BBinder> token = new DisplayToken(this);
343
344 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700345 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700346 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700347 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700348 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700349 return token;
350}
351
Jesse Hall6c913be2013-08-08 12:15:49 -0700352void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
353 Mutex::Autolock _l(mStateLock);
354
355 ssize_t idx = mCurrentState.displays.indexOfKey(display);
356 if (idx < 0) {
357 ALOGW("destroyDisplay: invalid display token");
358 return;
359 }
360
361 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
362 if (!info.isVirtualDisplay()) {
363 ALOGE("destroyDisplay called for non-virtual display");
364 return;
365 }
Irvelffc9efc2016-07-27 15:16:37 -0700366 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700367 mCurrentState.displays.removeItemsAt(idx);
368 setTransactionFlags(eDisplayTransactionNeeded);
369}
370
Mathias Agopiane57f2922012-08-09 16:29:12 -0700371sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700372 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700373 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800374 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700375 }
Jesse Hall692c7232012-11-08 15:41:56 -0800376 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700377}
378
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379void SurfaceFlinger::bootFinished()
380{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700381 if (mStartPropertySetThread->join() != NO_ERROR) {
382 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800383 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800384 const nsecs_t now = systemTime();
385 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000386 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700387
388 // wait patiently for the window manager death
389 const String16 name("window");
390 sp<IBinder> window(defaultServiceManager()->getService(name));
391 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700393 }
394
Steven Thomas050b2c82017-03-06 11:45:16 -0800395 if (mVrFlinger) {
396 mVrFlinger->OnBootFinished();
397 }
398
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700400 // formerly we would just kill the process, but we now ask it to exit so it
401 // can choose where to stop the animation.
402 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700403
404 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
405 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
406 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700407
Thierry Strudel2924d012017-08-14 15:19:37 -0700408 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700409 readPersistentProperties();
410 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700411 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412}
413
Mathias Agopian3f844832013-08-07 21:24:32 -0700414void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700415 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700416 RenderEngine& engine;
417 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700419 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
420 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 }
422 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700423 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424 return true;
425 }
426 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700427 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700428}
429
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430class DispSyncSource : public VSyncSource, private DispSync::Callback {
431public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700432 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 const char* name) :
434 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700435 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700436 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
438 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 mDispSync(dispSync),
440 mCallbackMutex(),
441 mCallback(),
442 mVsyncMutex(),
443 mPhaseOffset(phaseOffset),
444 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700445
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 virtual ~DispSyncSource() {}
447
448 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700450 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000451 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 static_cast<DispSync::Callback*>(this));
453 if (err != NO_ERROR) {
454 ALOGE("error registering vsync callback: %s (%d)",
455 strerror(-err), err);
456 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700457 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 } else {
459 status_t err = mDispSync->removeEventListener(
460 static_cast<DispSync::Callback*>(this));
461 if (err != NO_ERROR) {
462 ALOGE("error unregistering vsync callback: %s (%d)",
463 strerror(-err), err);
464 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700465 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 }
469
470 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 mCallback = callback;
473 }
474
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700475 virtual void setPhaseOffset(nsecs_t phaseOffset) {
476 Mutex::Autolock lock(mVsyncMutex);
477
478 // Normalize phaseOffset to [0, period)
479 auto period = mDispSync->getPeriod();
480 phaseOffset %= period;
481 if (phaseOffset < 0) {
482 // If we're here, then phaseOffset is in (-period, 0). After this
483 // operation, it will be in (0, period)
484 phaseOffset += period;
485 }
486 mPhaseOffset = phaseOffset;
487
488 // If we're not enabled, we don't need to mess with the listeners
489 if (!mEnabled) {
490 return;
491 }
492
493 // Remove the listener with the old offset
494 status_t err = mDispSync->removeEventListener(
495 static_cast<DispSync::Callback*>(this));
496 if (err != NO_ERROR) {
497 ALOGE("error unregistering vsync callback: %s (%d)",
498 strerror(-err), err);
499 }
500
501 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000502 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503 static_cast<DispSync::Callback*>(this));
504 if (err != NO_ERROR) {
505 ALOGE("error registering vsync callback: %s (%d)",
506 strerror(-err), err);
507 }
508 }
509
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510private:
511 virtual void onDispSyncEvent(nsecs_t when) {
512 sp<VSyncSource::Callback> callback;
513 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700514 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 callback = mCallback;
516
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700517 if (mTraceVsync) {
518 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700520 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 }
522
Peiyong Lin566a3b42018-01-09 18:22:43 -0800523 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 callback->onVSyncEvent(when);
525 }
526 }
527
Tim Murray4a4e4a22016-04-19 16:29:23 +0000528 const char* const mName;
529
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 int mValue;
531
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700533 const String8 mVsyncOnLabel;
534 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537
538 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540
541 Mutex mVsyncMutex; // Protects the following
542 nsecs_t mPhaseOffset;
543 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544};
545
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700546class InjectVSyncSource : public VSyncSource {
547public:
548 InjectVSyncSource() {}
549
550 virtual ~InjectVSyncSource() {}
551
552 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
553 std::lock_guard<std::mutex> lock(mCallbackMutex);
554 mCallback = callback;
555 }
556
557 virtual void onInjectSyncEvent(nsecs_t when) {
558 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700559 if (mCallback) {
560 mCallback->onVSyncEvent(when);
561 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700562 }
563
564 virtual void setVSyncEnabled(bool) {}
565 virtual void setPhaseOffset(nsecs_t) {}
566
567private:
568 std::mutex mCallbackMutex; // Protects the following
569 sp<VSyncSource::Callback> mCallback;
570};
571
Wei Wangf9b05ee2017-07-19 20:59:39 -0700572// Do not call property_set on main thread which will be blocked by init
573// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700575 ALOGI( "SurfaceFlinger's main thread ready to run. "
576 "Initializing graphics H/W...");
577
Thierry Strudel2924d012017-08-14 15:19:37 -0700578 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900579
Steven Thomasb02664d2017-07-26 18:48:28 -0700580 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 // start the EventThread
David Sodman99974d22017-11-28 12:04:33 -0800583 sp<VSyncSource> vsyncSrc =
584 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 mEventThread = new EventThread(vsyncSrc, *this, false);
David Sodman99974d22017-11-28 12:04:33 -0800586 sp<VSyncSource> sfVsyncSrc =
587 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
589 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590
Steven Thomasb02664d2017-07-26 18:48:28 -0700591 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
592 struct sched_param param = {0};
593 param.sched_priority = 2;
594 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
595 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
596 }
597 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
598 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599 }
600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800602 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800604 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700605
606 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
607 "Starting with vr flinger active is not currently supported.");
David Sodmanbc815282017-11-05 18:57:52 -0800608 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700609 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800610 // Process any initial hotplug and resulting display changes.
611 processDisplayHotplugEventsLocked();
612 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
613 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800614
Lloyd Piquefcd86612017-12-14 17:15:36 -0800615 // make the default display GLContext current so that we can create textures
616 // when creating Layers (which may happens before we render something)
617 getDefaultDisplayDeviceLocked()->makeCurrent();
618
Steven Thomas050b2c82017-03-06 11:45:16 -0800619 if (useVrFlinger) {
620 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700621 // This callback is called from the vr flinger dispatch thread. We
622 // need to call signalTransaction(), which requires holding
623 // mStateLock when we're not on the main thread. Acquiring
624 // mStateLock from the vr flinger dispatch thread might trigger a
625 // deadlock in surface flinger (see b/66916578), so post a message
626 // to be handled on the main thread instead.
627 sp<LambdaMessage> message = new LambdaMessage([=]() {
628 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
629 mVrFlingerRequestsDisplay = requestDisplay;
630 signalTransaction();
631 });
632 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 };
David Sodman105b7dc2017-11-04 20:28:14 -0700634 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
635 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800636 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 if (!mVrFlinger) {
638 ALOGE("Failed to start vrflinger");
639 }
640 }
641
Jamie Gennisd1700752013-10-14 12:22:52 -0700642 mEventControlThread = new EventControlThread(this);
643 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
644
Mathias Agopian92a979a2012-08-02 18:32:23 -0700645 // initialize our drawing state
646 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700647
Andy McFadden13a082e2012-08-24 10:16:42 -0700648 // set initial conditions (e.g. unblank default device)
649 initializeDisplays();
650
David Sodmanbc815282017-11-05 18:57:52 -0800651 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700652
Wei Wangf9b05ee2017-07-19 20:59:39 -0700653 // Inform native graphics APIs whether the present timestamp is supported:
654 if (getHwComposer().hasCapability(
655 HWC2::Capability::PresentFenceIsNotReliable)) {
656 mStartPropertySetThread = new StartPropertySetThread(false);
657 } else {
658 mStartPropertySetThread = new StartPropertySetThread(true);
659 }
660
661 if (mStartPropertySetThread->Start() != NO_ERROR) {
662 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800664
Dan Stoza9e56aa02015-11-02 13:00:03 -0800665 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700666}
667
Romain Guy11d63f42017-07-20 12:47:14 -0700668void SurfaceFlinger::readPersistentProperties() {
669 char value[PROPERTY_VALUE_MAX];
670
671 property_get("persist.sys.sf.color_saturation", value, "1.0");
672 mSaturation = atof(value);
673 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100674
675 property_get("persist.sys.sf.native_mode", value, "0");
676 mForceNativeColorMode = atoi(value) == 1;
677 if (mForceNativeColorMode) {
678 ALOGV("Forcing native color mode");
679 }
Romain Guy11d63f42017-07-20 12:47:14 -0700680}
681
Mathias Agopiana67e4182012-06-19 17:26:12 -0700682void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Start boot animation service by setting a property mailbox
684 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800686 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687 if (mStartPropertySetThread->join() != NO_ERROR) {
688 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800689 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800693 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
Mathias Agopian875d8e12013-06-07 15:35:48 -0700696size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800697 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700698}
699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800700// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800701
Jamie Gennis582270d2011-08-17 18:19:00 -0700702bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800704 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800705 return authenticateSurfaceTextureLocked(bufferProducer);
706}
707
708bool SurfaceFlinger::authenticateSurfaceTextureLocked(
709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800710 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700711 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800712}
713
Brian Anderson6b376712017-04-04 10:51:39 -0700714status_t SurfaceFlinger::getSupportedFrameTimestamps(
715 std::vector<FrameEvent>* outSupported) const {
716 *outSupported = {
717 FrameEvent::REQUESTED_PRESENT,
718 FrameEvent::ACQUIRE,
719 FrameEvent::LATCH,
720 FrameEvent::FIRST_REFRESH_START,
721 FrameEvent::LAST_REFRESH_START,
722 FrameEvent::GPU_COMPOSITION_DONE,
723 FrameEvent::DEQUEUE_READY,
724 FrameEvent::RELEASE,
725 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700726 ConditionalLock _l(mStateLock,
727 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700728 if (!getHwComposer().hasCapability(
729 HWC2::Capability::PresentFenceIsNotReliable)) {
730 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
731 }
732 return NO_ERROR;
733}
734
Dan Stoza7f7da322014-05-02 15:26:25 -0700735status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
736 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800737 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700738 return BAD_VALUE;
739 }
740
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500741 if (!display.get())
742 return NAME_NOT_FOUND;
743
Jesse Hall692c7232012-11-08 15:41:56 -0800744 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700745 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800746 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700747 type = i;
748 break;
749 }
750 }
751
752 if (type < 0) {
753 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700754 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 // TODO: Not sure if display density should handled by SF any longer
757 class Density {
758 static int getDensityFromProperty(char const* propName) {
759 char property[PROPERTY_VALUE_MAX];
760 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800761 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 density = atoi(property);
763 }
764 return density;
765 }
766 public:
767 static int getEmuDensity() {
768 return getDensityFromProperty("qemu.sf.lcd_density"); }
769 static int getBuildDensity() {
770 return getDensityFromProperty("ro.sf.lcd_density"); }
771 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700774
Steven Thomas6d8110b2017-08-31 18:24:21 -0700775 ConditionalLock _l(mStateLock,
776 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 DisplayInfo info = DisplayInfo();
779
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 float xdpi = hwConfig->getDpiX();
781 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700782
783 if (type == DisplayDevice::DISPLAY_PRIMARY) {
784 // The density of the device is provided by a build property
785 float density = Density::getBuildDensity() / 160.0f;
786 if (density == 0) {
787 // the build doesn't provide a density -- this is wrong!
788 // use xdpi instead
789 ALOGE("ro.sf.lcd_density must be defined as a build property");
790 density = xdpi / 160.0f;
791 }
792 if (Density::getEmuDensity()) {
793 // if "qemu.sf.lcd_density" is specified, it overrides everything
794 xdpi = ydpi = density = Density::getEmuDensity();
795 density /= 160.0f;
796 }
797 info.density = density;
798
799 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800801 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 } else {
803 // TODO: where should this value come from?
804 static const int TV_DENSITY = 213;
805 info.density = TV_DENSITY / 160.0f;
806 info.orientation = 0;
807 }
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.w = hwConfig->getWidth();
810 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 info.xdpi = xdpi;
812 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900814 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815
Andy McFadden91b2ca82014-06-13 14:04:23 -0700816 // This is how far in advance a buffer must be queued for
817 // presentation at a given time. If you want a buffer to appear
818 // on the screen at time N, you must submit the buffer before
819 // (N - presentationDeadline).
820 //
821 // Normally it's one full refresh period (to give SF a chance to
822 // latch the buffer), but this can be reduced by configuring a
823 // DispSync offset. Any additional delays introduced by the hardware
824 // composer or panel must be accounted for here.
825 //
826 // We add an additional 1ms to allow for processing time and
827 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800829 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
831 // All non-virtual displays are currently considered secure.
832 info.secure = true;
833
Michael Wright28f24d02016-07-12 13:30:53 -0700834 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return NO_ERROR;
838}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700839
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800840status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800842 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700843 return BAD_VALUE;
844 }
845
846 // FIXME for now we always return stats for the primary display
847 memset(stats, 0, sizeof(*stats));
848 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
849 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
850 return NO_ERROR;
851}
852
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700853int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800854 if (display == nullptr) {
855 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800856 return BAD_VALUE;
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
859 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800860 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700861 return device->getActiveConfig();
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
Dan Stoza24a42e92015-03-09 10:04:11 -0700864 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700867void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
868 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
869 this);
870 int32_t type = hw->getDisplayType();
871 int currentMode = hw->getActiveConfig();
872
873 if (mode == currentMode) {
874 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
875 return;
876 }
877
878 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
879 ALOGW("Trying to set config for virtual display");
880 return;
881 }
882
883 hw->setActiveConfig(mode);
884 getHwComposer().setActiveConfig(type, mode);
885}
886
887status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
888 class MessageSetActiveConfig: public MessageBase {
889 SurfaceFlinger& mFlinger;
890 sp<IBinder> mDisplay;
891 int mMode;
892 public:
893 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
894 int mode) :
895 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
896 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700897 Vector<DisplayInfo> configs;
898 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700899 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700900 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700901 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700902 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700903 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800905 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700907 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
909 ALOGW("Attempt to set active config = %d for virtual display",
910 mMode);
911 } else {
912 mFlinger.setActiveConfigInternal(hw, mMode);
913 }
914 return true;
915 }
916 };
917 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
918 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700919 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700920}
Michael Wright28f24d02016-07-12 13:30:53 -0700921status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
922 Vector<android_color_mode_t>* outColorModes) {
923 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
924 return BAD_VALUE;
925 }
926
927 if (!display.get()) {
928 return NAME_NOT_FOUND;
929 }
930
931 int32_t type = NAME_NOT_FOUND;
932 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
933 if (display == mBuiltinDisplays[i]) {
934 type = i;
935 break;
936 }
937 }
938
939 if (type < 0) {
940 return type;
941 }
942
Steven Thomas6d8110b2017-08-31 18:24:21 -0700943 std::vector<android_color_mode_t> modes;
944 {
945 ConditionalLock _l(mStateLock,
946 std::this_thread::get_id() != mMainThreadId);
947 modes = getHwComposer().getColorModes(type);
948 }
Michael Wright28f24d02016-07-12 13:30:53 -0700949 outColorModes->clear();
950 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
951
952 return NO_ERROR;
953}
954
955android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700956 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700957 if (device != nullptr) {
958 return device->getActiveColorMode();
959 }
960 return static_cast<android_color_mode_t>(BAD_VALUE);
961}
962
963void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
964 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700965 int32_t type = hw->getDisplayType();
966 android_color_mode_t currentMode = hw->getActiveColorMode();
967
968 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700969 return;
970 }
971
972 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
973 ALOGW("Trying to set config for virtual display");
974 return;
975 }
976
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600977 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
978 hw->getDisplayType());
979
Michael Wright28f24d02016-07-12 13:30:53 -0700980 hw->setActiveColorMode(mode);
981 getHwComposer().setActiveColorMode(type, mode);
982}
983
984
985status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
986 android_color_mode_t colorMode) {
987 class MessageSetActiveColorMode: public MessageBase {
988 SurfaceFlinger& mFlinger;
989 sp<IBinder> mDisplay;
990 android_color_mode_t mMode;
991 public:
992 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
993 android_color_mode_t mode) :
994 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
995 virtual bool handler() {
996 Vector<android_color_mode_t> modes;
997 mFlinger.getDisplayColorModes(mDisplay, &modes);
998 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
999 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001000 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1001 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001002 return true;
1003 }
1004 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1005 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1007 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001009 ALOGW("Attempt to set active color mode %s %d for virtual display",
1010 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001011 } else {
1012 mFlinger.setActiveColorModeInternal(hw, mMode);
1013 }
1014 return true;
1015 }
1016 };
1017 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1018 postMessageSync(msg);
1019 return NO_ERROR;
1020}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001021
Svetoslavd85084b2014-03-20 10:28:31 -07001022status_t SurfaceFlinger::clearAnimationFrameStats() {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.clearStats();
1025 return NO_ERROR;
1026}
1027
1028status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1029 Mutex::Autolock _l(mStateLock);
1030 mAnimFrameTracker.getStats(outStats);
1031 return NO_ERROR;
1032}
1033
Dan Stozac4f471e2016-03-24 09:31:08 -07001034status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1035 HdrCapabilities* outCapabilities) const {
1036 Mutex::Autolock _l(mStateLock);
1037
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001038 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001039 if (displayDevice == nullptr) {
1040 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1041 return BAD_VALUE;
1042 }
1043
1044 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001045 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001046 if (capabilities) {
1047 std::swap(*outCapabilities, *capabilities);
1048 } else {
1049 return BAD_VALUE;
1050 }
1051
1052 return NO_ERROR;
1053}
1054
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001055status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001056 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1057 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001058
Chia-I Wu90f669f2017-10-05 14:24:41 -07001059 if (mInjectVSyncs == enable) {
1060 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001062
1063 if (enable) {
1064 ALOGV("VSync Injections enabled");
1065 if (mVSyncInjector.get() == nullptr) {
1066 mVSyncInjector = new InjectVSyncSource();
1067 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1068 }
1069 mEventQueue.setEventThread(mInjectorEventThread);
1070 } else {
1071 ALOGV("VSync Injections disabled");
1072 mEventQueue.setEventThread(mSFEventThread);
1073 }
1074
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001075 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001076 });
1077 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078 return NO_ERROR;
1079}
1080
1081status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 Mutex::Autolock _l(mStateLock);
1083
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 if (!mInjectVSyncs) {
1085 ALOGE("VSync Injections not enabled");
1086 return BAD_VALUE;
1087 }
1088 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1089 ALOGV("Injecting VSync inside SurfaceFlinger");
1090 mVSyncInjector->onInjectSyncEvent(when);
1091 }
1092 return NO_ERROR;
1093}
1094
Kalle Raitaa099a242017-01-11 11:17:29 -08001095status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1096 IPCThreadState* ipc = IPCThreadState::self();
1097 const int pid = ipc->getCallingPid();
1098 const int uid = ipc->getCallingUid();
1099 if ((uid != AID_SHELL) &&
1100 !PermissionCache::checkPermission(sDump, pid, uid)) {
1101 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1102 return PERMISSION_DENIED;
1103 }
1104
1105 // Try to acquire a lock for 1s, fail gracefully
1106 const status_t err = mStateLock.timedLock(s2ns(1));
1107 const bool locked = (err == NO_ERROR);
1108 if (!locked) {
1109 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1110 return TIMED_OUT;
1111 }
1112
1113 outLayers->clear();
1114 mCurrentState.traverseInZOrder([&](Layer* layer) {
1115 outLayers->push_back(layer->getLayerDebugInfo());
1116 });
1117
1118 mStateLock.unlock();
1119 return NO_ERROR;
1120}
1121
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001122// ----------------------------------------------------------------------------
1123
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001124sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1125 ISurfaceComposer::VsyncSource vsyncSource) {
1126 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1127 return mSFEventThread->createEventConnection();
1128 } else {
1129 return mEventThread->createEventConnection();
1130 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001131}
1132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001133// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001134
1135void SurfaceFlinger::waitForEvent() {
1136 mEventQueue.waitMessage();
1137}
1138
1139void SurfaceFlinger::signalTransaction() {
1140 mEventQueue.invalidate();
1141}
1142
1143void SurfaceFlinger::signalLayerUpdate() {
1144 mEventQueue.invalidate();
1145}
1146
1147void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001148 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001149 mEventQueue.refresh();
1150}
1151
1152status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001153 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001154 return mEventQueue.postMessage(msg, reltime);
1155}
1156
1157status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001158 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001159 status_t res = mEventQueue.postMessage(msg, reltime);
1160 if (res == NO_ERROR) {
1161 msg->wait();
1162 }
1163 return res;
1164}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001165
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001166void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001167 do {
1168 waitForEvent();
1169 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001170}
1171
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172void SurfaceFlinger::enableHardwareVsync() {
1173 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001174 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001176 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1177 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001179 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180}
1181
Jesse Hall948fe0c2013-10-14 12:56:09 -07001182void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 Mutex::Autolock _l(mHWVsyncLock);
1184
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185 if (makeAvailable) {
1186 mHWVsyncAvailable = true;
1187 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001188 // Hardware vsync is not currently available, so abort the resync
1189 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 return;
1191 }
1192
David Sodman105b7dc2017-11-04 20:28:14 -07001193 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195
1196 mPrimaryDispSync.reset();
1197 mPrimaryDispSync.setPeriod(period);
1198
1199 if (!mPrimaryHWVsyncEnabled) {
1200 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001201 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1202 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 mPrimaryHWVsyncEnabled = true;
1204 }
1205}
1206
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001208 Mutex::Autolock _l(mHWVsyncLock);
1209 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1211 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryDispSync.endResync();
1213 mPrimaryHWVsyncEnabled = false;
1214 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001215 if (makeUnavailable) {
1216 mHWVsyncAvailable = false;
1217 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218}
1219
Tim Murray4a4e4a22016-04-19 16:29:23 +00001220void SurfaceFlinger::resyncWithRateLimit() {
1221 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001222
1223 // No explicit locking is needed here since EventThread holds a lock while calling this method
1224 static nsecs_t sLastResyncAttempted = 0;
1225 const nsecs_t now = systemTime();
1226 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001227 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228 }
Dan Stoza57164302017-05-08 14:03:54 -07001229 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001230}
1231
Steven Thomasb02664d2017-07-26 18:48:28 -07001232void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1233 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001234 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001235 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001236 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001237 return;
1238 }
1239
1240 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001241 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001242 return;
1243 }
1244
Jamie Gennisd1700752013-10-14 12:22:52 -07001245 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246
Jamie Gennisd1700752013-10-14 12:22:52 -07001247 { // Scope for the lock
1248 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001249 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001252 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001253
1254 if (needsHwVsync) {
1255 enableHardwareVsync();
1256 } else {
1257 disableHardwareVsync(false);
1258 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001259}
1260
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001261void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001262 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1263 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001264}
1265
Lloyd Pique715a2c12017-12-14 17:18:08 -08001266void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1267 HWC2::Connection connection) {
1268 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1269 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001270
Lloyd Piqueba04e622017-12-14 17:11:26 -08001271 // Ignore events that do not have the right sequenceId.
1272 if (sequenceId != getBE().mComposerSequenceId) {
1273 return;
1274 }
1275
Steven Thomasb02664d2017-07-26 18:48:28 -07001276 // Only lock if we're not on the main thread. This function is normally
1277 // called on a hwbinder thread, but for the primary display it's called on
1278 // the main thread with the state lock already held, so don't attempt to
1279 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001280 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001281
Lloyd Pique715a2c12017-12-14 17:18:08 -08001282 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001283
Lloyd Piqueba04e622017-12-14 17:11:26 -08001284 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001285}
1286
Steven Thomasb02664d2017-07-26 18:48:28 -07001287void SurfaceFlinger::onRefreshReceived(int sequenceId,
1288 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001289 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001290 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001293 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001294}
1295
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001298 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299 getHwComposer().setVsyncEnabled(disp,
1300 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001301}
1302
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001304void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001305 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306 // Clear the drawing state so that the logic inside of
1307 // handleTransactionLocked will fire. It will determine the delta between
1308 // mCurrentState and mDrawingState and re-apply all changes when we make the
1309 // transition.
1310 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001311 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001312 mDisplays.clear();
1313}
1314
Steven Thomas050b2c82017-03-06 11:45:16 -08001315void SurfaceFlinger::updateVrFlinger() {
1316 if (!mVrFlinger)
1317 return;
1318 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001319 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001320 return;
1321 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322
David Sodman105b7dc2017-11-04 20:28:14 -07001323 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001324 ALOGE("Vr flinger is only supported for remote hardware composer"
1325 " service connections. Ignoring request to transition to vr"
1326 " flinger.");
1327 mVrFlingerRequestsDisplay = false;
1328 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001329 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001330
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 int currentDisplayPowerMode = getDisplayDeviceLocked(
1334 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001335
Steven Thomasb02664d2017-07-26 18:48:28 -07001336 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001341 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001342 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001343 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001344
David Sodman105b7dc2017-11-04 20:28:14 -07001345 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1346 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001347
1348 if (vrFlingerRequestsDisplay) {
1349 mVrFlinger->GrantDisplayOwnership();
1350 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
1354 mVisibleRegionsDirty = true;
1355 invalidateHwcGeometry();
1356
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001357 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1359 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1360 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001361
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001363 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 const nsecs_t period = activeConfig->getVsyncPeriod();
1365 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001366
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Use phase of 0 since phase is not known.
1368 // Use latency of 0, which will snap to the ideal latency.
1369 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001370
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001371 android_atomic_or(1, &mRepaintEverything);
1372 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373}
1374
Mathias Agopian4fec8732012-06-29 14:12:52 -07001375void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001376 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001377 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001378 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001379 bool frameMissed = !mHadClientComposition &&
1380 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001381 (mPreviousPresentFence->getSignalTime() ==
1382 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001383 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001384 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001385 signalLayerUpdate();
1386 break;
1387 }
1388
Steven Thomas050b2c82017-03-06 11:45:16 -08001389 // Now that we're going to make it to the handleMessageTransaction()
1390 // call below it's safe to call updateVrFlinger(), which will
1391 // potentially trigger a display handoff.
1392 updateVrFlinger();
1393
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 bool refreshNeeded = handleMessageTransaction();
1395 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001396 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001397 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001398 // Signal a refresh if a transaction modified the window state,
1399 // a new buffer was latched, or if HWC has requested a full
1400 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001401 signalRefresh();
1402 }
1403 break;
1404 }
1405 case MessageQueue::REFRESH: {
1406 handleMessageRefresh();
1407 break;
1408 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001409 }
1410}
1411
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001413 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001414 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001415 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001417 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001419}
1420
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001422 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424}
1425
1426void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001427 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001428
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001429 mRefreshPending = false;
1430
Pablo Ceballos40845df2016-01-25 17:41:15 -08001431 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001432
Brian Andersond6927fb2016-07-23 23:37:30 -07001433 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001434 rebuildLayerStacks();
1435 setUpHWComposer();
1436 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001437 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001438 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001439 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001440
David Sodman105b7dc2017-11-04 20:28:14 -07001441 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001442
1443 mHadClientComposition = false;
1444 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1445 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1446 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001447 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001448 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001449
Dan Stoza9e56aa02015-11-02 13:00:03 -08001450 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453void SurfaceFlinger::doDebugFlashRegions()
1454{
1455 // is debugging enabled
1456 if (CC_LIKELY(!mDebugRegion))
1457 return;
1458
1459 const bool repaintEverything = mRepaintEverything;
1460 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1461 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001462 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001463 // transform the dirty region into this screen's coordinate space
1464 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1465 if (!dirtyRegion.isEmpty()) {
1466 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001467 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468
1469 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001471 RenderEngine& engine(getRenderEngine());
1472 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1473
Mathias Agopianda27af92012-09-13 18:17:13 -07001474 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 }
1476 }
1477 }
1478
1479 postFramebuffer();
1480
1481 if (mDebugRegion > 1) {
1482 usleep(mDebugRegion * 1000);
1483 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001484
Dan Stoza9e56aa02015-11-02 13:00:03 -08001485 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001486 auto& displayDevice = mDisplays[displayId];
1487 if (!displayDevice->isDisplayOn()) {
1488 continue;
1489 }
1490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1492 ALOGE_IF(result != NO_ERROR,
1493 "prepareFrame for display %zd failed:"
1494 " %d (%s)",
1495 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001496 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497}
1498
Adrian Roos1e1a1282017-11-01 19:05:31 +01001499void SurfaceFlinger::doTracing(const char* where) {
1500 ATRACE_CALL();
1501 ATRACE_NAME(where);
1502 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001503 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001504 }
1505}
1506
Brian Andersond6927fb2016-07-23 23:37:30 -07001507void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001509 ATRACE_CALL();
1510 ALOGV("preComposition");
1511
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001513 mDrawingState.traverseInZOrder([&](Layer* layer) {
1514 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 needExtraInvalidate = true;
1516 }
Robert Carr2047fae2016-11-28 14:09:09 -08001517 });
1518
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 if (needExtraInvalidate) {
1520 signalLayerUpdate();
1521 }
1522}
1523
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524void SurfaceFlinger::updateCompositorTiming(
1525 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1526 std::shared_ptr<FenceTime>& presentFenceTime) {
1527 // Update queue of past composite+present times and determine the
1528 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001529 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001530 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001531 while (!getBE().mCompositePresentTimes.empty()) {
1532 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533 // Cached values should have been updated before calling this method,
1534 // which helps avoid duplicate syscalls.
1535 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1536 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1537 break;
1538 }
1539 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001540 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541 }
1542
1543 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001544 while (getBE().mCompositePresentTimes.size() > 16) {
1545 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 }
1547
Brian Andersond0010582017-03-07 13:20:31 -08001548 setCompositorTimingSnapped(
1549 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1550}
1551
1552void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1553 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001554 // Integer division and modulo round toward 0 not -inf, so we need to
1555 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001556 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1558 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1559
Brian Andersond0010582017-03-07 13:20:31 -08001560 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1561 if (idealLatency <= 0) {
1562 idealLatency = vsyncInterval;
1563 }
1564
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565 // Snap the latency to a value that removes scheduling jitter from the
1566 // composition and present times, which often have >1ms of jitter.
1567 // Reducing jitter is important if an app attempts to extrapolate
1568 // something (such as user input) to an accurate diasplay time.
1569 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1570 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001571 nsecs_t bias = vsyncInterval / 2;
1572 int64_t extraVsyncs =
1573 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1574 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1575 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001576
David Sodman99974d22017-11-28 12:04:33 -08001577 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1578 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1579 getBE().mCompositorTiming.interval = vsyncInterval;
1580 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581}
1582
1583void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001585 ATRACE_CALL();
1586 ALOGV("postComposition");
1587
Brian Anderson3546a3f2016-07-14 11:51:14 -07001588 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001589 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001590 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001591 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001592 }
1593
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594 // |mStateLock| not needed as we are on the main thread
1595 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001596
David Sodman73beded2017-11-15 11:56:06 -08001597 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001598 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001599 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001600 glCompositionDoneFenceTime =
1601 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001602 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603 } else {
1604 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1605 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001606
David Sodman73beded2017-11-15 11:56:06 -08001607 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001608 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001609 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001610 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001611
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001612 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1613 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1614
1615 // We use the refreshStartTime which might be sampled a little later than
1616 // when we started doing work for this frame, but that should be okay
1617 // since updateCompositorTiming has snapping logic.
1618 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001619 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001620 CompositorTiming compositorTiming;
1621 {
David Sodman99974d22017-11-28 12:04:33 -08001622 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1623 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001624 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625
Robert Carr2047fae2016-11-28 14:09:09 -08001626 mDrawingState.traverseInZOrder([&](Layer* layer) {
1627 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001628 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001629 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001630 recordBufferingStats(layer->getName().string(),
1631 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001632 }
Robert Carr2047fae2016-11-28 14:09:09 -08001633 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001634
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001635 if (presentFenceTime->isValid()) {
1636 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001637 enableHardwareVsync();
1638 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001639 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001640 }
1641 }
1642
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001643 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001644 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001645 enableHardwareVsync();
1646 }
1647 }
1648
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001649 if (mAnimCompositionPending) {
1650 mAnimCompositionPending = false;
1651
Brian Anderson4e606e32017-03-16 15:34:57 -07001652 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001653 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001654 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001655 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001656 // The HWC doesn't support present fences, so use the refresh
1657 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001659 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001660 mAnimFrameTracker.setActualPresentTime(presentTime);
1661 }
1662 mAnimFrameTracker.advanceFrame();
1663 }
Dan Stozab90cf072015-03-05 11:05:59 -08001664
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001665 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1666 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001667 return;
1668 }
1669
1670 nsecs_t currentTime = systemTime();
1671 if (mHasPoweredOff) {
1672 mHasPoweredOff = false;
1673 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001674 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001675 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001676 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1677 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001678 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001679 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001680 }
David Sodman4a36e932017-11-07 14:29:47 -08001681 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001682 }
David Sodman4a36e932017-11-07 14:29:47 -08001683 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684}
1685
1686void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 ATRACE_CALL();
1688 ALOGV("rebuildLayerStacks");
1689
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001691 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001692 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001693 mVisibleRegionsDirty = false;
1694 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001695
Jeff Sharkey76488112017-02-27 14:15:18 -07001696 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1697 Region opaqueRegion;
1698 Region dirtyRegion;
1699 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001700 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001701 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1702 const Transform& tr(displayDevice->getTransform());
1703 const Rect bounds(displayDevice->getBounds());
1704 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001705 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001706
Jeff Sharkey76488112017-02-27 14:15:18 -07001707 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001708 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001709 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1710 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001711 Region drawRegion(tr.transform(
1712 layer->visibleNonTransparentRegion));
1713 drawRegion.andSelf(bounds);
1714 if (!drawRegion.isEmpty()) {
1715 layersSortedByZ.add(layer);
1716 } else {
1717 // Clear out the HWC layer if this layer was
1718 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001719 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001720 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001721 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001722 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001723 // WM changes displayDevice->layerStack upon sleep/awake.
1724 // Here we make sure we delete the HWC layers even if
1725 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001726 hwcLayerDestroyed = layer->destroyHwcLayer(
1727 displayDevice->getHwcDisplayId());
1728 }
1729
1730 // If a layer is not going to get a release fence because
1731 // it is invisible, but it is also going to release its
1732 // old buffer, add it to the list of layers needing
1733 // fences.
1734 if (hwcLayerDestroyed) {
1735 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1736 mLayersWithQueuedFrames.cend(), layer);
1737 if (found != mLayersWithQueuedFrames.cend()) {
1738 layersNeedingFences.add(layer);
1739 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001740 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 });
1742 }
1743 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001744 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001745 displayDevice->undefinedRegion.set(bounds);
1746 displayDevice->undefinedRegion.subtractSelf(
1747 tr.transform(opaqueRegion));
1748 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001749 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001750 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001751}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001752
Romain Guy0147a172017-06-01 13:53:56 -07001753mat4 SurfaceFlinger::computeSaturationMatrix() const {
1754 if (mSaturation == 1.0f) {
1755 return mat4();
1756 }
1757
1758 // Rec.709 luma coefficients
1759 float3 luminance{0.213f, 0.715f, 0.072f};
1760 luminance *= 1.0f - mSaturation;
1761 return mat4(
1762 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1763 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1764 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1765 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1766 );
1767}
1768
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001769// pickColorMode translates a given dataspace into the best available color mode.
1770// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001771android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001772 if (mForceNativeColorMode) {
1773 return HAL_COLOR_MODE_NATIVE;
1774 }
1775
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001776 switch (dataSpace) {
1777 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1778 // system expects.
1779 case HAL_DATASPACE_UNKNOWN:
1780 case HAL_DATASPACE_SRGB:
1781 case HAL_DATASPACE_V0_SRGB:
1782 return HAL_COLOR_MODE_SRGB;
1783 break;
1784
1785 case HAL_DATASPACE_DISPLAY_P3:
1786 return HAL_COLOR_MODE_DISPLAY_P3;
1787 break;
1788
1789 default:
1790 // TODO (courtneygo): Do we want to assert an error here?
1791 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1792 dataSpace);
1793 return HAL_COLOR_MODE_SRGB;
1794 break;
1795 }
1796}
1797
Romain Guy0147a172017-06-01 13:53:56 -07001798android_dataspace SurfaceFlinger::bestTargetDataSpace(
1799 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001800 // Only support sRGB and Display-P3 right now.
1801 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1802 return HAL_DATASPACE_DISPLAY_P3;
1803 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001804 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1805 return HAL_DATASPACE_DISPLAY_P3;
1806 }
1807 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1808 return HAL_DATASPACE_DISPLAY_P3;
1809 }
1810
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001811 return HAL_DATASPACE_V0_SRGB;
1812}
1813
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 ATRACE_CALL();
1816 ALOGV("setUpHWComposer");
1817
Jesse Hall028dc8f2013-08-20 16:35:32 -07001818 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001819 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1820 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1821 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1822
1823 // If nothing has changed (!dirty), don't recompose.
1824 // If something changed, but we don't currently have any visible layers,
1825 // and didn't when we last did a composition, then skip it this time.
1826 // The second rule does two things:
1827 // - When all layers are removed from a display, we'll emit one black
1828 // frame, then nothing more until we get new layers.
1829 // - When a display is created with a private layer stack, we won't
1830 // emit any black frames until a layer is added to the layer stack.
1831 bool mustRecompose = dirty && !(empty && wasEmpty);
1832
1833 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1834 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1835 mustRecompose ? "doing" : "skipping",
1836 dirty ? "+" : "-",
1837 empty ? "+" : "-",
1838 wasEmpty ? "+" : "-");
1839
Dan Stoza71433162014-02-04 16:22:36 -08001840 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001841
1842 if (mustRecompose) {
1843 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1844 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001845 }
1846
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 // build the h/w work list
1848 if (CC_UNLIKELY(mGeometryInvalid)) {
1849 mGeometryInvalid = false;
1850 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1851 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1852 const auto hwcId = displayDevice->getHwcDisplayId();
1853 if (hwcId >= 0) {
1854 const Vector<sp<Layer>>& currentLayers(
1855 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001856 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001857 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001859 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001860 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001862 }
1863 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001864
Robert Carrae060832016-11-28 10:51:00 -08001865 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001866 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001868 }
1869 }
1870 }
1871 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 }
Riley Andrews03414a12014-07-01 14:22:59 -07001873
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001874
Romain Guy0147a172017-06-01 13:53:56 -07001875 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001876
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 // Set the per-frame data
1878 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1879 auto& displayDevice = mDisplays[displayId];
1880 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001881
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 if (hwcId < 0) {
1883 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001884 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001885 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001886 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001887 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1888 "display %zd: %d", displayId, result);
1889 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001891 if (layer->getForceClientComposition(hwcId)) {
1892 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1893 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1894 continue;
1895 }
1896
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 layer->setPerFrameData(displayDevice);
1898 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001899
1900 if (hasWideColorDisplay) {
1901 android_color_mode newColorMode;
1902 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1903
1904 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1905 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1906 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1907 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1908 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1909 }
1910 newColorMode = pickColorMode(newDataSpace);
1911
Thierry Strudel2924d012017-08-14 15:19:37 -07001912 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001913 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 }
1915
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001916 mPreviousColorMatrix = colorMatrix;
1917
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001919 auto& displayDevice = mDisplays[displayId];
1920 if (!displayDevice->isDisplayOn()) {
1921 continue;
1922 }
1923
David Sodman105b7dc2017-11-04 20:28:14 -07001924 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1926 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001927 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001928}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001929
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930void SurfaceFlinger::doComposition() {
1931 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 ALOGV("doComposition");
1933
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001934 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001935 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001936 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001937 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 // transform the dirty region into this screen's coordinate space
1939 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001940
1941 // repaint the framebuffer (if needed)
1942 doDisplayComposition(hw, dirtyRegion);
1943
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001945 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001946 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001947 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001948 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001949}
1950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001951void SurfaceFlinger::postFramebuffer()
1952{
Mathias Agopian841cde52012-03-01 15:44:37 -08001953 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001955
Mathias Agopiana44b0412011-10-16 18:46:35 -07001956 const nsecs_t now = systemTime();
1957 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001958
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1960 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001961 if (!displayDevice->isDisplayOn()) {
1962 continue;
1963 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 const auto hwcId = displayDevice->getHwcDisplayId();
1965 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001966 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001967 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001968 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001969 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001971 // The layer buffer from the previous frame (if any) is released
1972 // by HWC only when the release fence from this frame (if any) is
1973 // signaled. Always get the release fence from HWC first.
1974 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001975 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08001976
1977 // If the layer was client composited in the previous frame, we
1978 // need to merge with the previous client target acquire fence.
1979 // Since we do not track that, always merge with the current
1980 // client target acquire fence when it is available, even though
1981 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001983 releaseFence = Fence::merge("LayerRelease", releaseFence,
1984 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001985 }
Chia-I Wu7b549592017-11-15 09:14:57 -08001986
Dan Stoza9e56aa02015-11-02 13:00:03 -08001987 layer->onLayerDisplayed(releaseFence);
1988 }
Chia-I Wu83806892017-11-16 10:50:20 -08001989
1990 // We've got a list of layers needing fences, that are disjoint with
1991 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
1992 // supply them with the present fence.
1993 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07001994 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08001995 for (auto& layer : displayDevice->getLayersNeedingFences()) {
1996 layer->onLayerDisplayed(presentFence);
1997 }
1998 }
1999
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002001 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002002 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002003 }
2004
Mathias Agopiana44b0412011-10-16 18:46:35 -07002005 mLastSwapBufferTime = systemTime() - now;
2006 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002007
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002008 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002009 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2010 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2011 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2012 logFrameStats();
2013 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002014 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015}
2016
Mathias Agopian87baae12012-07-31 12:38:26 -07002017void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018{
Mathias Agopian841cde52012-03-01 15:44:37 -08002019 ATRACE_CALL();
2020
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002021 // here we keep a copy of the drawing state (that is the state that's
2022 // going to be overwritten by handleTransactionLocked()) outside of
2023 // mStateLock so that the side-effects of the State assignment
2024 // don't happen with mStateLock held (which can cause deadlocks).
2025 State drawingState(mDrawingState);
2026
Mathias Agopianca4d3602011-05-19 15:38:14 -07002027 Mutex::Autolock _l(mStateLock);
2028 const nsecs_t now = systemTime();
2029 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002030
Mathias Agopianca4d3602011-05-19 15:38:14 -07002031 // Here we're guaranteed that some transaction flags are set
2032 // so we can call handleTransactionLocked() unconditionally.
2033 // We call getTransactionFlags(), which will also clear the flags,
2034 // with mStateLock held to guarantee that mCurrentState won't change
2035 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002036
Mathias Agopiane57f2922012-08-09 16:29:12 -07002037 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002038 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002039
Mathias Agopianca4d3602011-05-19 15:38:14 -07002040 mLastTransactionTime = systemTime() - now;
2041 mDebugInTransaction = 0;
2042 invalidateHwcGeometry();
2043 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002044}
2045
Lloyd Pique715a2c12017-12-14 17:18:08 -08002046DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2047 HWC2::Connection connection) const {
2048 // Figure out whether the event is for the primary display or an
2049 // external display by matching the Hwc display id against one for a
2050 // connected display. If we did not find a match, we then check what
2051 // displays are not already connected to determine the type. If we don't
2052 // have a connected primary display, we assume the new display is meant to
2053 // be the primary display, and then if we don't have an external display,
2054 // we assume it is that.
2055 const auto primaryDisplayId =
2056 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2057 const auto externalDisplayId =
2058 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2059 if (primaryDisplayId && primaryDisplayId == display) {
2060 return DisplayDevice::DISPLAY_PRIMARY;
2061 } else if (externalDisplayId && externalDisplayId == display) {
2062 return DisplayDevice::DISPLAY_EXTERNAL;
2063 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2064 return DisplayDevice::DISPLAY_PRIMARY;
2065 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2066 return DisplayDevice::DISPLAY_EXTERNAL;
2067 }
2068
2069 return DisplayDevice::DISPLAY_ID_INVALID;
2070}
2071
Lloyd Piqueba04e622017-12-14 17:11:26 -08002072void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2073 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002074 auto displayType = determineDisplayType(event.display, event.connection);
2075 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2076 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2077 continue;
2078 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002079
2080 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2081 ALOGE("External displays are not supported by the vr hardware composer.");
2082 continue;
2083 }
2084
Lloyd Pique715a2c12017-12-14 17:18:08 -08002085 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002086
2087 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002088 ALOGV("Creating built in display %d", displayType);
2089 ALOGW_IF(mBuiltinDisplays[displayType],
2090 "Overwriting display token for display type %d", displayType);
2091 mBuiltinDisplays[displayType] = new BBinder();
2092 // All non-virtual displays are currently considered secure.
2093 DisplayDeviceState info(displayType, true);
2094 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2095 "Built-in Screen" : "External Screen";
2096 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2097 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002098 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002099 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002100
Lloyd Piquefcd86612017-12-14 17:15:36 -08002101 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2102 if (idx >= 0) {
2103 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2104 mInterceptor.saveDisplayDeletion(info.displayId);
2105 mCurrentState.displays.removeItemsAt(idx);
2106 }
2107 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002108 }
2109
2110 processDisplayChangesLocked();
2111 }
2112
2113 mPendingHotplugEvents.clear();
2114}
2115
Lloyd Pique347200f2017-12-14 17:00:15 -08002116void SurfaceFlinger::processDisplayChangesLocked() {
2117 // here we take advantage of Vector's copy-on-write semantics to
2118 // improve performance by skipping the transaction entirely when
2119 // know that the lists are identical
2120 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2121 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2122 if (!curr.isIdenticalTo(draw)) {
2123 mVisibleRegionsDirty = true;
2124 const size_t cc = curr.size();
2125 size_t dc = draw.size();
2126
2127 // find the displays that were removed
2128 // (ie: in drawing state but not in current state)
2129 // also handle displays that changed
2130 // (ie: displays that are in both lists)
2131 for (size_t i = 0; i < dc;) {
2132 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2133 if (j < 0) {
2134 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002135 // Call makeCurrent() on the primary display so we can
2136 // be sure that nothing associated with this display
2137 // is current.
2138 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2139 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2140 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2141 if (hw != nullptr) hw->disconnect(getHwComposer());
2142 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2143 mEventThread->onHotplugReceived(draw[i].type, false);
2144 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002145 } else {
2146 // this display is in both lists. see if something changed.
2147 const DisplayDeviceState& state(curr[j]);
2148 const wp<IBinder>& display(curr.keyAt(j));
2149 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2150 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2151 if (state_binder != draw_binder) {
2152 // changing the surface is like destroying and
2153 // recreating the DisplayDevice, so we just remove it
2154 // from the drawing state, so that it get re-added
2155 // below.
2156 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2157 if (hw != nullptr) hw->disconnect(getHwComposer());
2158 mDisplays.removeItem(display);
2159 mDrawingState.displays.removeItemsAt(i);
2160 dc--;
2161 // at this point we must loop to the next item
2162 continue;
2163 }
2164
2165 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2166 if (disp != nullptr) {
2167 if (state.layerStack != draw[i].layerStack) {
2168 disp->setLayerStack(state.layerStack);
2169 }
2170 if ((state.orientation != draw[i].orientation) ||
2171 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2172 disp->setProjection(state.orientation, state.viewport, state.frame);
2173 }
2174 if (state.width != draw[i].width || state.height != draw[i].height) {
2175 disp->setDisplaySize(state.width, state.height);
2176 }
2177 }
2178 }
2179 ++i;
2180 }
2181
2182 // find displays that were added
2183 // (ie: in current state but not in drawing state)
2184 for (size_t i = 0; i < cc; i++) {
2185 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2186 const DisplayDeviceState& state(curr[i]);
2187
2188 sp<DisplaySurface> dispSurface;
2189 sp<IGraphicBufferProducer> producer;
2190 sp<IGraphicBufferProducer> bqProducer;
2191 sp<IGraphicBufferConsumer> bqConsumer;
2192 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2193
2194 int32_t hwcId = -1;
2195 if (state.isVirtualDisplay()) {
2196 // Virtual displays without a surface are dormant:
2197 // they have external state (layer stack, projection,
2198 // etc.) but no internal state (i.e. a DisplayDevice).
2199 if (state.surface != nullptr) {
2200 // Allow VR composer to use virtual displays.
2201 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2202 int width = 0;
2203 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2204 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2205 int height = 0;
2206 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2207 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2208 int intFormat = 0;
2209 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2210 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2211 auto format = static_cast<android_pixel_format_t>(intFormat);
2212
2213 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2214 }
2215
2216 // TODO: Plumb requested format back up to consumer
2217
2218 sp<VirtualDisplaySurface> vds =
2219 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2220 bqProducer, bqConsumer,
2221 state.displayName);
2222
2223 dispSurface = vds;
2224 producer = vds;
2225 }
2226 } else {
2227 ALOGE_IF(state.surface != nullptr,
2228 "adding a supported display, but rendering "
2229 "surface is provided (%p), ignoring it",
2230 state.surface.get());
2231
2232 hwcId = state.type;
2233 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2234 producer = bqProducer;
2235 }
2236
2237 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002238
Lloyd Pique347200f2017-12-14 17:00:15 -08002239 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002240 bool useWideColorMode = hasWideColorDisplay;
2241 if (state.isMainDisplay()) {
2242 bool hasWideColorModes = false;
2243 std::vector<android_color_mode_t> modes =
2244 getHwComposer().getColorModes(state.type);
2245 for (android_color_mode_t colorMode : modes) {
2246 switch (colorMode) {
2247 case HAL_COLOR_MODE_DISPLAY_P3:
2248 case HAL_COLOR_MODE_ADOBE_RGB:
2249 case HAL_COLOR_MODE_DCI_P3:
2250 hasWideColorModes = true;
2251 break;
2252 default:
2253 break;
2254 }
2255 }
2256 useWideColorMode = hasWideColorModes && hasWideColorDisplay &&
2257 !mForceNativeColorMode;
2258 }
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
2264 if (state.isMainDisplay()) {
2265 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2266 if (useWideColorMode) {
2267 defaultColorMode = HAL_COLOR_MODE_SRGB;
2268 }
2269 setActiveColorModeInternal(hw, defaultColorMode);
2270 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2271 }
2272
Lloyd Pique347200f2017-12-14 17:00:15 -08002273 hw->setLayerStack(state.layerStack);
2274 hw->setProjection(state.orientation, state.viewport, state.frame);
2275 hw->setDisplayName(state.displayName);
2276 mDisplays.add(display, hw);
2277 if (!state.isVirtualDisplay()) {
2278 mEventThread->onHotplugReceived(state.type, true);
2279 }
2280 }
2281 }
2282 }
2283 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002284
2285 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002286}
2287
Mathias Agopian87baae12012-07-31 12:38:26 -07002288void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002289{
Dan Stoza7dde5992015-05-22 09:51:44 -07002290 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002291 mCurrentState.traverseInZOrder([](Layer* layer) {
2292 layer->notifyAvailableFrames();
2293 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002294
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295 /*
2296 * Traversal of the children
2297 * (perform the transaction for each of them if needed)
2298 */
2299
Mathias Agopian3559b072012-08-15 13:46:03 -07002300 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002301 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002303 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002304
2305 const uint32_t flags = layer->doTransaction(0);
2306 if (flags & Layer::eVisibleRegion)
2307 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002308 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309 }
2310
2311 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002312 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313 */
2314
Mathias Agopiane57f2922012-08-09 16:29:12 -07002315 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002316 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002317 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002318 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Mathias Agopian84300952012-11-21 16:02:13 -08002320 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2321 // The transform hint might have changed for some layers
2322 // (either because a display has changed, or because a layer
2323 // as changed).
2324 //
2325 // Walk through all the layers in currentLayers,
2326 // and update their transform hint.
2327 //
2328 // If a layer is visible only on a single display, then that
2329 // display is used to calculate the hint, otherwise we use the
2330 // default display.
2331 //
2332 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2333 // the hint is set before we acquire a buffer from the surface texture.
2334 //
2335 // NOTE: layer transactions have taken place already, so we use their
2336 // drawing state. However, SurfaceFlinger's own transaction has not
2337 // happened yet, so we must use the current state layer list
2338 // (soon to become the drawing state list).
2339 //
2340 sp<const DisplayDevice> disp;
2341 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002342 bool first = true;
2343 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002344 // NOTE: we rely on the fact that layers are sorted by
2345 // layerStack first (so we don't have to traverse the list
2346 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002347 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002348 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002349 currentlayerStack = layerStack;
2350 // figure out if this layerstack is mirrored
2351 // (more than one display) if so, pick the default display,
2352 // if not, pick the only display it's on.
2353 disp.clear();
2354 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2355 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002356 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002357 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002358 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002359 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002360 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002361 break;
2362 }
2363 }
2364 }
2365 }
Chet Haase91d25932013-04-11 15:24:55 -07002366
Robert Carr56a0b9a2017-12-04 16:06:13 -08002367 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002368 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002369 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2370 // redraw after transform hint changes. See bug 8508397.
2371
2372 // could be null when this layer is using a layerStack
2373 // that is not visible on any display. Also can occur at
2374 // screen off/on times.
2375 disp = getDefaultDisplayDeviceLocked();
2376 }
2377 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002378 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002379 if (disp != nullptr) {
2380 layer->updateTransformHint(disp);
2381 }
Robert Carr2047fae2016-11-28 14:09:09 -08002382
2383 first = false;
2384 });
Mathias Agopian84300952012-11-21 16:02:13 -08002385 }
2386
2387
Mathias Agopian3559b072012-08-15 13:46:03 -07002388 /*
2389 * Perform our own transaction if needed
2390 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002391
2392 if (mLayersAdded) {
2393 mLayersAdded = false;
2394 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002395 mVisibleRegionsDirty = true;
2396 }
2397
2398 // some layers might have been removed, so
2399 // we need to update the regions they're exposing.
2400 if (mLayersRemoved) {
2401 mLayersRemoved = false;
2402 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002403 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002404 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002405 // this layer is not visible anymore
2406 // TODO: we could traverse the tree from front to back and
2407 // compute the actual visible region
2408 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002409 Region visibleReg;
2410 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002411 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002412 }
Robert Carr2047fae2016-11-28 14:09:09 -08002413 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414 }
2415
2416 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002417
2418 updateCursorAsync();
2419}
2420
2421void SurfaceFlinger::updateCursorAsync()
2422{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2424 auto& displayDevice = mDisplays[displayId];
2425 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002426 continue;
2427 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428
2429 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2430 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002431 }
2432 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002433}
2434
2435void SurfaceFlinger::commitTransaction()
2436{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002437 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002438 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002439 for (const auto& l : mLayersPendingRemoval) {
2440 recordBufferingStats(l->getName().string(),
2441 l->getOccupancyHistory(true));
2442 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002443 }
2444 mLayersPendingRemoval.clear();
2445 }
2446
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002447 // If this transaction is part of a window animation then the next frame
2448 // we composite should be considered an animation as well.
2449 mAnimCompositionPending = mAnimTransactionPending;
2450
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 mDrawingState.traverseInZOrder([](Layer* layer) {
2453 layer->commitChildList();
2454 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002455 mTransactionPending = false;
2456 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002457 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458}
2459
Chia-I Wuab0c3192017-08-01 11:29:00 -07002460void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002461 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462{
Mathias Agopian841cde52012-03-01 15:44:37 -08002463 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002464 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002465
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 Region aboveOpaqueLayers;
2467 Region aboveCoveredLayers;
2468 Region dirty;
2469
Mathias Agopian87baae12012-07-31 12:38:26 -07002470 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471
Robert Carr2047fae2016-11-28 14:09:09 -08002472 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002474 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475
Jesse Hall01e29052013-02-19 16:13:35 -08002476 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002477 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002478 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002479
Mathias Agopianab028732010-03-16 16:41:46 -07002480 /*
2481 * opaqueRegion: area of a surface that is fully opaque.
2482 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002484
2485 /*
2486 * visibleRegion: area of a surface that is visible on screen
2487 * and not fully transparent. This is essentially the layer's
2488 * footprint minus the opaque regions above it.
2489 * Areas covered by a translucent surface are considered visible.
2490 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002492
2493 /*
2494 * coveredRegion: area of a surface that is covered by all
2495 * visible regions above it (which includes the translucent areas).
2496 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002498
Jesse Halla8026d22012-09-25 13:25:04 -07002499 /*
2500 * transparentRegion: area of a surface that is hinted to be completely
2501 * transparent. This is only used to tell when the layer has no visible
2502 * non-transparent regions and can be removed from the layer list. It
2503 * does not affect the visibleRegion of this layer or any layers
2504 * beneath it. The hint may not be correct if apps don't respect the
2505 * SurfaceView restrictions (which, sadly, some don't).
2506 */
2507 Region transparentRegion;
2508
Mathias Agopianab028732010-03-16 16:41:46 -07002509
2510 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002511 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002512 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002515 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002516 if (!visibleRegion.isEmpty()) {
2517 // Remove the transparent area from the visible region
2518 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002519 if (tr.preserveRects()) {
2520 // transform the transparent region
2521 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002522 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002523 // transformation too complex, can't do the
2524 // transparent region optimization.
2525 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002526 }
Mathias Agopianab028732010-03-16 16:41:46 -07002527 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528
Mathias Agopianab028732010-03-16 16:41:46 -07002529 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002531 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002532 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2533 // the opaque region is the layer's footprint
2534 opaqueRegion = visibleRegion;
2535 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536 }
2537 }
2538
Mathias Agopianab028732010-03-16 16:41:46 -07002539 // Clip the covered region to the visible region
2540 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2541
2542 // Update aboveCoveredLayers for next (lower) layer
2543 aboveCoveredLayers.orSelf(visibleRegion);
2544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 // subtract the opaque region covered by the layers above us
2546 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547
2548 // compute this layer's dirty region
2549 if (layer->contentDirty) {
2550 // we need to invalidate the whole region
2551 dirty = visibleRegion;
2552 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 layer->contentDirty = false;
2555 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002556 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002557 * the exposed region consists of two components:
2558 * 1) what's VISIBLE now and was COVERED before
2559 * 2) what's EXPOSED now less what was EXPOSED before
2560 *
2561 * note that (1) is conservative, we start with the whole
2562 * visible region but only keep what used to be covered by
2563 * something -- which mean it may have been exposed.
2564 *
2565 * (2) handles areas that were not covered by anything but got
2566 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002567 */
Mathias Agopianab028732010-03-16 16:41:46 -07002568 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 const Region oldVisibleRegion = layer->visibleRegion;
2570 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002571 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2572 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573 }
2574 dirty.subtractSelf(aboveOpaqueLayers);
2575
2576 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002577 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578
Mathias Agopianab028732010-03-16 16:41:46 -07002579 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002581
Jesse Halla8026d22012-09-25 13:25:04 -07002582 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 layer->setVisibleRegion(visibleRegion);
2584 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002585 layer->setVisibleNonTransparentRegion(
2586 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002587 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588
Mathias Agopian87baae12012-07-31 12:38:26 -07002589 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Chia-I Wuab0c3192017-08-01 11:29:00 -07002592void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002593 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002594 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002595 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002596 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002597 }
2598 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002599}
2600
Dan Stoza6b9454d2014-11-07 16:00:59 -08002601bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 ALOGV("handlePageFlip");
2604
Brian Andersond6927fb2016-07-23 23:37:30 -07002605 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606
Mathias Agopian4fec8732012-06-29 14:12:52 -07002607 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002608 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002609 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002610
2611 // Store the set of layers that need updates. This set must not change as
2612 // buffers are being latched, as this could result in a deadlock.
2613 // Example: Two producers share the same command stream and:
2614 // 1.) Layer 0 is latched
2615 // 2.) Layer 0 gets a new frame
2616 // 2.) Layer 1 gets a new frame
2617 // 3.) Layer 1 is latched.
2618 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2619 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002620 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002621 if (layer->hasQueuedFrame()) {
2622 frameQueued = true;
2623 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002624 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002625 } else {
2626 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002627 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002628 } else {
2629 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002630 }
Robert Carr2047fae2016-11-28 14:09:09 -08002631 });
2632
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002634 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002635 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002636 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002637 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002638 newDataLatched = true;
2639 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002640 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002641
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002642 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002643
2644 // If we will need to wake up at some time in the future to deal with a
2645 // queued frame that shouldn't be displayed during this vsync period, wake
2646 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002647 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002648 signalLayerUpdate();
2649 }
2650
2651 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002652 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653}
2654
Mathias Agopianad456f92011-01-13 17:53:01 -08002655void SurfaceFlinger::invalidateHwcGeometry()
2656{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002657 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002658}
2659
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002660
Fabien Sanglard830b8472016-11-30 16:35:58 -08002661void SurfaceFlinger::doDisplayComposition(
2662 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002663 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664{
Dan Stoza71433162014-02-04 16:22:36 -08002665 // We only need to actually compose the display if:
2666 // 1) It is being handled by hardware composer, which may need this to
2667 // keep its virtual display state machine in sync, or
2668 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002669 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002670 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002672 return;
2673 }
2674
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002676 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002677
2678 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002679 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680}
2681
Chia-I Wub02087d2017-11-09 10:19:54 -08002682bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002683{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002684 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002685
Chia-I Wub02087d2017-11-09 10:19:54 -08002686 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002687 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002688 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002689
2690 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002691 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2692 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002693 if (applyColorMatrix) {
2694 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2695 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2696 }
2697
David Sodman105b7dc2017-11-04 20:28:14 -07002698 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 if (hasClientComposition) {
2700 ALOGV("hasClientComposition");
2701
David Sodmanbc815282017-11-05 18:57:52 -08002702 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002703 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002704 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002705 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002706 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002707 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002709 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002710
2711 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002712 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002713 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2714 }
2715 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002716 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002717
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002718 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002719 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002721 // when using overlays, we assume a fully transparent framebuffer
2722 // NOTE: we could reduce how much we need to clear, for instance
2723 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002724 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002725 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002726 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002727 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002728 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002729 // we're left with the letterbox region
2730 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002731 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002732
2733 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002735
Mathias Agopianb9494d52012-04-18 02:28:45 -07002736 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002737 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002738 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002740 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002741 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002742
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002744 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002745 // scissor on the main display. It should never be needed
2746 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 const Rect& bounds(displayDevice->getBounds());
2748 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002749 if (scissor != bounds) {
2750 // scissor doesn't match the screen's dimensions, so we
2751 // need to clear everything outside of it and enable
2752 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002753
Mathias Agopianf45c5102012-10-24 16:29:17 -07002754 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002755 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002756 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002757 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002758 }
2759 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002761
Mathias Agopian85d751c2012-08-29 16:59:24 -07002762 /*
2763 * and then, render the layers targeted at the framebuffer
2764 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002765
Dan Stoza9e56aa02015-11-02 13:00:03 -08002766 ALOGV("Rendering client layers");
2767 const Transform& displayTransform = displayDevice->getTransform();
2768 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002769 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 bool firstLayer = true;
2771 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002772 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 displayTransform.transform(layer->visibleRegion)));
2774 ALOGV("Layer: %s", layer->getName().string());
2775 ALOGV(" Composition type: %s",
2776 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002777 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002778 switch (layer->getCompositionType(hwcId)) {
2779 case HWC2::Composition::Cursor:
2780 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002781 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002783 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002785 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002787 // never clear the very first layer since we're
2788 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002789 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002790 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002791 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002792 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002794 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002795 break;
2796 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002798 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002799 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 } else {
2801 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002802 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002804 }
2805 } else {
2806 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002808 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002809 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002810 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002811 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002812 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002813 }
2814 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002815
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002816 if (applyColorMatrix) {
2817 getRenderEngine().setupColorTransform(oldColorMatrix);
2818 }
2819
Mathias Agopianf45c5102012-10-24 16:29:17 -07002820 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002821 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002822 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823}
2824
Fabien Sanglard830b8472016-11-30 16:35:58 -08002825void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2826 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002827 RenderEngine& engine(getRenderEngine());
2828 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829}
2830
Dan Stoza7d89d062015-04-30 13:29:25 -07002831status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002832 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002833 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002834 const sp<Layer>& lbc,
2835 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002836{
Dan Stoza7d89d062015-04-30 13:29:25 -07002837 // add this layer to the current state list
2838 {
2839 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002840 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002841 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2842 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002843 return NO_MEMORY;
2844 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002845 if (parent == nullptr) {
2846 mCurrentState.layersSortedByZ.add(lbc);
2847 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002848 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002849 ALOGE("addClientLayer called with a removed parent");
2850 return NAME_NOT_FOUND;
2851 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002852 parent->addChild(lbc);
2853 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002854
Dan Stoza7d89d062015-04-30 13:29:25 -07002855 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 mLayersAdded = true;
2857 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002858 }
2859
Mathias Agopian96f08192010-06-02 23:28:45 -07002860 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002861 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002862
Dan Stoza7d89d062015-04-30 13:29:25 -07002863 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002864}
2865
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002866status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002867 Mutex::Autolock _l(mStateLock);
2868
chaviw8b3871a2017-11-01 17:41:01 -07002869 if (layer->isPendingRemoval()) {
2870 return NO_ERROR;
2871 }
2872
Robert Carr1f0a16a2016-10-24 16:27:39 -07002873 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002874 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002875 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002876 if (topLevelOnly) {
2877 return NO_ERROR;
2878 }
2879
Chia-I Wu98f1c102017-05-30 14:54:08 -07002880 sp<Layer> ancestor = p;
2881 while (ancestor->getParent() != nullptr) {
2882 ancestor = ancestor->getParent();
2883 }
2884 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2885 ALOGE("removeLayer called with a layer whose parent has been removed");
2886 return NAME_NOT_FOUND;
2887 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002888
2889 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002890 } else {
2891 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002892 }
2893
Robert Carr136e2f62017-02-08 17:54:29 -08002894 // As a matter of normal operation, the LayerCleaner will produce a second
2895 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2896 // so we will succeed in promoting it, but it's already been removed
2897 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2898 // otherwise something has gone wrong and we are leaking the layer.
2899 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002900 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2901 layer->getName().string(),
2902 (p != nullptr) ? p->getName().string() : "no-parent");
2903 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002904 } else if (index < 0) {
2905 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002906 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002907
Chia-I Wuc6657022017-08-15 11:18:17 -07002908 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909 mLayersPendingRemoval.add(layer);
2910 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002911 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 setTransactionFlags(eTransactionNeeded);
2913 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914}
2915
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002916uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002917 return android_atomic_release_load(&mTransactionFlags);
2918}
2919
Mathias Agopian3f844832013-08-07 21:24:32 -07002920uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2922}
2923
Mathias Agopian3f844832013-08-07 21:24:32 -07002924uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2926 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002927 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 }
2929 return old;
2930}
2931
Mathias Agopian8b33f032012-07-24 20:43:54 -07002932void SurfaceFlinger::setTransactionState(
2933 const Vector<ComposerState>& state,
2934 const Vector<DisplayState>& displays,
2935 uint32_t flags)
2936{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002937 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002938 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002939 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002940
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002941 if (flags & eAnimation) {
2942 // For window updates that are part of an animation we must wait for
2943 // previous animation "frames" to be handled.
2944 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002945 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002946 if (CC_UNLIKELY(err != NO_ERROR)) {
2947 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002948 // caller after a few seconds.
2949 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2950 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002951 mAnimTransactionPending = false;
2952 break;
2953 }
2954 }
2955 }
2956
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957 size_t count = displays.size();
2958 for (size_t i=0 ; i<count ; i++) {
2959 const DisplayState& s(displays[i]);
2960 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002961 }
2962
Mathias Agopiane57f2922012-08-09 16:29:12 -07002963 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002964 for (size_t i=0 ; i<count ; i++) {
2965 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002966 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08002967 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002968 // IInterface, or one of its own or even one of our own but a
2969 // different type. All these situations would cause us to crash.
2970 //
2971 // NOTE: it would be better to use RTTI as we could directly check
2972 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08002973 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002974 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08002975 if (binder != nullptr) {
2976 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002977 sp<Client> client( static_cast<Client *>(s.client.get()) );
2978 transactionFlags |= setClientStateLocked(client, s.state);
2979 }
2980 }
2981 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002982 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002983
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002984 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2985 // anyway. This can be used as a flush mechanism for previous async transactions.
2986 // Empty animation transaction can be used to simulate back-pressure, so also force a
2987 // transaction for empty animation transactions.
2988 if (transactionFlags == 0 &&
2989 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002990 transactionFlags = eTransactionNeeded;
2991 }
2992
Mathias Agopian386aa982011-11-07 21:58:03 -08002993 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002994 if (mInterceptor.isEnabled()) {
2995 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2996 }
Irvel468051e2016-06-13 16:44:44 -07002997
Mathias Agopian386aa982011-11-07 21:58:03 -08002998 // this triggers the transaction
2999 setTransactionFlags(transactionFlags);
3000
3001 // if this is a synchronous transaction, wait for it to take effect
3002 // before returning.
3003 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003004 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003005 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003006 if (flags & eAnimation) {
3007 mAnimTransactionPending = true;
3008 }
3009 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003010 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3011 if (CC_UNLIKELY(err != NO_ERROR)) {
3012 // just in case something goes wrong in SF, return to the
3013 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003014 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3015 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003016 break;
3017 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003018 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019 }
3020}
3021
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3023{
Jesse Hall9a143922012-10-04 16:29:19 -07003024 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3025 if (dpyIdx < 0)
3026 return 0;
3027
Mathias Agopiane57f2922012-08-09 16:29:12 -07003028 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003029 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003030 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003031 const uint32_t what = s.what;
3032 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003033 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003034 disp.surface = s.surface;
3035 flags |= eDisplayTransactionNeeded;
3036 }
3037 }
3038 if (what & DisplayState::eLayerStackChanged) {
3039 if (disp.layerStack != s.layerStack) {
3040 disp.layerStack = s.layerStack;
3041 flags |= eDisplayTransactionNeeded;
3042 }
3043 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003044 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003045 if (disp.orientation != s.orientation) {
3046 disp.orientation = s.orientation;
3047 flags |= eDisplayTransactionNeeded;
3048 }
3049 if (disp.frame != s.frame) {
3050 disp.frame = s.frame;
3051 flags |= eDisplayTransactionNeeded;
3052 }
3053 if (disp.viewport != s.viewport) {
3054 disp.viewport = s.viewport;
3055 flags |= eDisplayTransactionNeeded;
3056 }
3057 }
Michael Lentine47e45402014-07-18 15:34:25 -07003058 if (what & DisplayState::eDisplaySizeChanged) {
3059 if (disp.width != s.width) {
3060 disp.width = s.width;
3061 flags |= eDisplayTransactionNeeded;
3062 }
3063 if (disp.height != s.height) {
3064 disp.height = s.height;
3065 flags |= eDisplayTransactionNeeded;
3066 }
3067 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003068 }
3069 return flags;
3070}
3071
3072uint32_t SurfaceFlinger::setClientStateLocked(
3073 const sp<Client>& client,
3074 const layer_state_t& s)
3075{
Mathias Agopian13127d82013-03-05 17:47:11 -08003076 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003077 if (layer == nullptr) {
3078 return 0;
3079 }
3080
3081 if (layer->isPendingRemoval()) {
3082 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3083 return 0;
3084 }
3085
3086 uint32_t flags = 0;
3087
3088 const uint32_t what = s.what;
3089 bool geometryAppliesWithResize =
3090 what & layer_state_t::eGeometryAppliesWithResize;
3091 if (what & layer_state_t::ePositionChanged) {
3092 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3093 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003094 }
chaviw8b3871a2017-11-01 17:41:01 -07003095 }
3096 if (what & layer_state_t::eLayerChanged) {
3097 // NOTE: index needs to be calculated before we update the state
3098 const auto& p = layer->getParent();
3099 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003100 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003101 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 mCurrentState.layersSortedByZ.removeAt(idx);
3103 mCurrentState.layersSortedByZ.add(layer);
3104 // we need traversal (state changed)
3105 // AND transaction (list changed)
3106 flags |= eTransactionNeeded|eTraversalNeeded;
3107 }
chaviw8b3871a2017-11-01 17:41:01 -07003108 } else {
3109 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003110 flags |= eTransactionNeeded|eTraversalNeeded;
3111 }
3112 }
chaviw8b3871a2017-11-01 17:41:01 -07003113 }
3114 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003115 // NOTE: index needs to be calculated before we update the state
3116 const auto& p = layer->getParent();
3117 if (p == nullptr) {
3118 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3119 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3120 mCurrentState.layersSortedByZ.removeAt(idx);
3121 mCurrentState.layersSortedByZ.add(layer);
3122 // we need traversal (state changed)
3123 // AND transaction (list changed)
3124 flags |= eTransactionNeeded|eTraversalNeeded;
3125 }
3126 } else {
3127 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3128 flags |= eTransactionNeeded|eTraversalNeeded;
3129 }
chaviw8b3871a2017-11-01 17:41:01 -07003130 }
3131 }
3132 if (what & layer_state_t::eSizeChanged) {
3133 if (layer->setSize(s.w, s.h)) {
3134 flags |= eTraversalNeeded;
3135 }
3136 }
3137 if (what & layer_state_t::eAlphaChanged) {
3138 if (layer->setAlpha(s.alpha))
3139 flags |= eTraversalNeeded;
3140 }
3141 if (what & layer_state_t::eColorChanged) {
3142 if (layer->setColor(s.color))
3143 flags |= eTraversalNeeded;
3144 }
3145 if (what & layer_state_t::eMatrixChanged) {
3146 if (layer->setMatrix(s.matrix))
3147 flags |= eTraversalNeeded;
3148 }
3149 if (what & layer_state_t::eTransparentRegionChanged) {
3150 if (layer->setTransparentRegionHint(s.transparentRegion))
3151 flags |= eTraversalNeeded;
3152 }
3153 if (what & layer_state_t::eFlagsChanged) {
3154 if (layer->setFlags(s.flags, s.mask))
3155 flags |= eTraversalNeeded;
3156 }
3157 if (what & layer_state_t::eCropChanged) {
3158 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3159 flags |= eTraversalNeeded;
3160 }
3161 if (what & layer_state_t::eFinalCropChanged) {
3162 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3163 flags |= eTraversalNeeded;
3164 }
3165 if (what & layer_state_t::eLayerStackChanged) {
3166 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3167 // We only allow setting layer stacks for top level layers,
3168 // everything else inherits layer stack from its parent.
3169 if (layer->hasParent()) {
3170 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3171 layer->getName().string());
3172 } else if (idx < 0) {
3173 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3174 "that also does not appear in the top level layer list. Something"
3175 " has gone wrong.", layer->getName().string());
3176 } else if (layer->setLayerStack(s.layerStack)) {
3177 mCurrentState.layersSortedByZ.removeAt(idx);
3178 mCurrentState.layersSortedByZ.add(layer);
3179 // we need traversal (state changed)
3180 // AND transaction (list changed)
3181 flags |= eTransactionNeeded|eTraversalNeeded;
3182 }
3183 }
3184 if (what & layer_state_t::eDeferTransaction) {
3185 if (s.barrierHandle != nullptr) {
3186 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3187 } else if (s.barrierGbp != nullptr) {
3188 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3189 if (authenticateSurfaceTextureLocked(gbp)) {
3190 const auto& otherLayer =
3191 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3192 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3193 } else {
3194 ALOGE("Attempt to defer transaction to to an"
3195 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003196 }
3197 }
chaviw8b3871a2017-11-01 17:41:01 -07003198 // We don't trigger a traversal here because if no other state is
3199 // changed, we don't want this to cause any more work
3200 }
3201 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003202 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003203 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003204 if (!hadParent) {
3205 mCurrentState.layersSortedByZ.remove(layer);
3206 }
chaviw8b3871a2017-11-01 17:41:01 -07003207 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003208 }
chaviw8b3871a2017-11-01 17:41:01 -07003209 }
3210 if (what & layer_state_t::eReparentChildren) {
3211 if (layer->reparentChildren(s.reparentHandle)) {
3212 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003213 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003214 }
chaviw8b3871a2017-11-01 17:41:01 -07003215 if (what & layer_state_t::eDetachChildren) {
3216 layer->detachChildren();
3217 }
3218 if (what & layer_state_t::eOverrideScalingModeChanged) {
3219 layer->setOverrideScalingMode(s.overrideScalingMode);
3220 // We don't trigger a traversal here because if no other state is
3221 // changed, we don't want this to cause any more work
3222 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003223 return flags;
3224}
3225
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003226status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003227 const String8& name,
3228 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003229 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003230 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3231 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003233 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003234 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003235 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003236 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003237 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003238
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003239 status_t result = NO_ERROR;
3240
3241 sp<Layer> layer;
3242
Cody Northropbc755282017-03-31 12:00:08 -06003243 String8 uniqueName = getUniqueLayerName(name);
3244
Mathias Agopian3165cc22012-08-08 19:42:09 -07003245 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3246 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003247 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003248 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003249 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003250
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251 break;
chaviw13fdc492017-06-27 12:40:18 -07003252 case ISurfaceComposerClient::eFXSurfaceColor:
3253 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003254 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003255 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003256 break;
3257 default:
3258 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259 break;
3260 }
3261
Dan Stoza7d89d062015-04-30 13:29:25 -07003262 if (result != NO_ERROR) {
3263 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003265
Chia-I Wuab0c3192017-08-01 11:29:00 -07003266 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3267 // TODO b/64227542
3268 if (windowType == 441731) {
3269 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3270 layer->setPrimaryDisplayOnly();
3271 }
3272
Albert Chaulk479c60c2017-01-27 14:21:34 -05003273 layer->setInfo(windowType, ownerUid);
3274
Robert Carr1f0a16a2016-10-24 16:27:39 -07003275 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003276 if (result != NO_ERROR) {
3277 return result;
3278 }
Irvelffc9efc2016-07-27 15:16:37 -07003279 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003280
3281 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003282 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283}
3284
Cody Northropbc755282017-03-31 12:00:08 -06003285String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3286{
3287 bool matchFound = true;
3288 uint32_t dupeCounter = 0;
3289
3290 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3291 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3292
3293 // Loop over layers until we're sure there is no matching name
3294 while (matchFound) {
3295 matchFound = false;
3296 mDrawingState.traverseInZOrder([&](Layer* layer) {
3297 if (layer->getName() == uniqueName) {
3298 matchFound = true;
3299 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3300 }
3301 });
3302 }
3303
3304 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3305
3306 return uniqueName;
3307}
3308
David Sodman0c69cad2017-08-21 12:12:51 -07003309status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003310 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3311 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003312{
3313 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003314 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315 case PIXEL_FORMAT_TRANSPARENT:
3316 case PIXEL_FORMAT_TRANSLUCENT:
3317 format = PIXEL_FORMAT_RGBA_8888;
3318 break;
3319 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003320 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321 break;
3322 }
3323
David Sodman0c69cad2017-08-21 12:12:51 -07003324 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3325 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003326 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003327 *handle = layer->getHandle();
3328 *gbp = layer->getProducer();
3329 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003330 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003331
David Sodman0c69cad2017-08-21 12:12:51 -07003332 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003333 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334}
3335
chaviw13fdc492017-06-27 12:40:18 -07003336status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003337 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003338 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339{
chaviw13fdc492017-06-27 12:40:18 -07003340 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003341 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003342 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003343}
3344
Mathias Agopianac9fa422013-02-11 16:40:36 -08003345status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346{
Robert Carr9524cb32017-02-13 11:32:32 -08003347 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003348 status_t err = NO_ERROR;
3349 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003350 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003351 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003352 err = removeLayer(l);
3353 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3354 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003355 }
3356 return err;
3357}
3358
Mathias Agopian13127d82013-03-05 17:47:11 -08003359status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003360{
Mathias Agopian67106042013-03-14 19:18:13 -07003361 // called by ~LayerCleaner() when all references to the IBinder (handle)
3362 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003363 sp<Layer> l = layer.promote();
3364 if (l == nullptr) {
3365 // The layer has already been removed, carry on
3366 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003367 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003368 // If we have a parent, then we can continue to live as long as it does.
3369 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003370}
3371
Mathias Agopianb60314a2012-04-10 22:09:54 -07003372// ---------------------------------------------------------------------------
3373
Andy McFadden13a082e2012-08-24 10:16:42 -07003374void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003375 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003376 Vector<ComposerState> state;
3377 Vector<DisplayState> displays;
3378 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003379 d.what = DisplayState::eDisplayProjectionChanged |
3380 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003381 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003382 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003383 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003384 d.frame.makeInvalid();
3385 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003386 d.width = 0;
3387 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003388 displays.add(d);
3389 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003390 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3391 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003392
David Sodman105b7dc2017-11-04 20:28:14 -07003393 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003394 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003395 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003396
Brian Andersond0010582017-03-07 13:20:31 -08003397 // Use phase of 0 since phase is not known.
3398 // Use latency of 0, which will snap to the ideal latency.
3399 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003400}
3401
3402void SurfaceFlinger::initializeDisplays() {
3403 class MessageScreenInitialized : public MessageBase {
3404 SurfaceFlinger* flinger;
3405 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003406 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003407 virtual bool handler() {
3408 flinger->onInitializeDisplays();
3409 return true;
3410 }
3411 };
3412 sp<MessageBase> msg = new MessageScreenInitialized(this);
3413 postMessageAsync(msg); // we may be called from main thread, use async message
3414}
3415
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003416void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003417 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003418 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3419 this);
3420 int32_t type = hw->getDisplayType();
3421 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003422
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003423 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003424 return;
3425 }
3426
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 hw->setPowerMode(mode);
3428 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3429 ALOGW("Trying to set power mode for virtual display");
3430 return;
3431 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003432
Irvelffc9efc2016-07-27 15:16:37 -07003433 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003434 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003435 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3436 if (idx < 0) {
3437 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3438 return;
3439 }
3440 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3441 }
3442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003443 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003444 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003445 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003446 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3447 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003448 // FIXME: eventthread only knows about the main display right now
3449 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003450 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003452
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003453 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003454 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003455 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003456
3457 struct sched_param param = {0};
3458 param.sched_priority = 1;
3459 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3460 ALOGW("Couldn't set SCHED_FIFO on display on");
3461 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003462 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003463 // Turn off the display
3464 struct sched_param param = {0};
3465 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3466 ALOGW("Couldn't set SCHED_OTHER on display off");
3467 }
3468
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003469 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3470 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003471 disableHardwareVsync(true); // also cancels any in-progress resync
3472
Mathias Agopiancde87a32012-09-13 14:09:01 -07003473 // FIXME: eventthread only knows about the main display right now
3474 mEventThread->onScreenReleased();
3475 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003476
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003477 getHwComposer().setPowerMode(type, mode);
3478 mVisibleRegionsDirty = true;
3479 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003480 } else if (mode == HWC_POWER_MODE_DOZE ||
3481 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003482 // Update display while dozing
3483 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003484 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3485 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003486 // FIXME: eventthread only knows about the main display right now
3487 mEventThread->onScreenAcquired();
3488 resyncToHardwareVsync(true);
3489 }
3490 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3491 // Leave display going to doze
3492 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3493 disableHardwareVsync(true); // also cancels any in-progress resync
3494 // FIXME: eventthread only knows about the main display right now
3495 mEventThread->onScreenReleased();
3496 }
3497 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003498 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003499 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003500 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003501 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003502}
3503
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003504void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3505 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003506 SurfaceFlinger& mFlinger;
3507 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003508 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003509 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003510 MessageSetPowerMode(SurfaceFlinger& flinger,
3511 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3512 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003513 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003514 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003515 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003516 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003517 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003518 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003519 ALOGW("Attempt to set power mode = %d for virtual display",
3520 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003521 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003522 mFlinger.setPowerModeInternal(
3523 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003524 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003525 return true;
3526 }
3527 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003528 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003529 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003530}
3531
3532// ---------------------------------------------------------------------------
3533
Vishnu Nair6a408532017-10-24 09:11:27 -07003534status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003536
Mathias Agopianbd115332013-04-18 16:41:04 -07003537 IPCThreadState* ipc = IPCThreadState::self();
3538 const int pid = ipc->getCallingPid();
3539 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003540
Mathias Agopianbd115332013-04-18 16:41:04 -07003541 if ((uid != AID_SHELL) &&
3542 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003543 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003544 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003546 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003547 // (this would indicate SF is stuck, but we want to be able to
3548 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003549 status_t err = mStateLock.timedLock(s2ns(1));
3550 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003551 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003552 result.appendFormat(
3553 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3554 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003555 }
3556
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003557 bool dumpAll = true;
3558 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003559 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003560
3561 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003562 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003563 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3564 dumpAll = false;
3565 }
3566
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003567 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003568 if ((index < numArgs) &&
3569 (args[index] == String16("--list"))) {
3570 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003571 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003572 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003573 }
3574
3575 if ((index < numArgs) &&
3576 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003577 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003578 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003579 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003580 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003581
3582 if ((index < numArgs) &&
3583 (args[index] == String16("--latency-clear"))) {
3584 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003585 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003586 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003587 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003588
3589 if ((index < numArgs) &&
3590 (args[index] == String16("--dispsync"))) {
3591 index++;
3592 mPrimaryDispSync.dump(result);
3593 dumpAll = false;
3594 }
Dan Stozab90cf072015-03-05 11:05:59 -08003595
3596 if ((index < numArgs) &&
3597 (args[index] == String16("--static-screen"))) {
3598 index++;
3599 dumpStaticScreenStats(result);
3600 dumpAll = false;
3601 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003602
3603 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003604 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003605 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003606 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003607 dumpAll = false;
3608 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003609
3610 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3611 index++;
3612 dumpWideColorInfo(result);
3613 dumpAll = false;
3614 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003616
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003617 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003618 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003619 }
3620
Mathias Agopian9795c422009-08-26 16:36:26 -07003621 if (locked) {
3622 mStateLock.unlock();
3623 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003624 }
3625 write(fd, result.string(), result.size());
3626 return NO_ERROR;
3627}
3628
Dan Stozac7014012014-02-14 15:03:43 -08003629void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3630 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003631{
Robert Carr2047fae2016-11-28 14:09:09 -08003632 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003633 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003634 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003635}
3636
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003637void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003638 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003639{
3640 String8 name;
3641 if (index < args.size()) {
3642 name = String8(args[index]);
3643 index++;
3644 }
3645
David Sodman105b7dc2017-11-04 20:28:14 -07003646 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003647 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003648 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003649
3650 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003651 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003652 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003653 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003654 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003655 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003656 }
Robert Carr2047fae2016-11-28 14:09:09 -08003657 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003658 }
3659}
3660
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003661void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003662 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003663{
3664 String8 name;
3665 if (index < args.size()) {
3666 name = String8(args[index]);
3667 index++;
3668 }
3669
Robert Carr2047fae2016-11-28 14:09:09 -08003670 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003671 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003672 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003673 }
Robert Carr2047fae2016-11-28 14:09:09 -08003674 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003675
Svetoslavd85084b2014-03-20 10:28:31 -07003676 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003677}
3678
Jamie Gennis6547ff42013-07-16 20:12:42 -07003679// This should only be called from the main thread. Otherwise it would need
3680// the lock and should use mCurrentState rather than mDrawingState.
3681void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003682 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003683 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003684 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003685
3686 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3687}
3688
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003689void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003690{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003691 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003692 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3693
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003694 if (isLayerTripleBufferingDisabled())
3695 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003696
3697 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003698 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003699 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003700 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003701 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3702 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003703 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003704}
3705
Dan Stozab90cf072015-03-05 11:05:59 -08003706void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3707{
3708 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003709 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3710 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003711 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003712 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003713 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3714 b + 1, bucketTimeSec, percent);
3715 }
David Sodman4a36e932017-11-07 14:29:47 -08003716 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003717 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003718 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003719 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003720 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003721}
3722
Dan Stozae77c7662016-05-13 11:37:28 -07003723void SurfaceFlinger::recordBufferingStats(const char* layerName,
3724 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003725 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3726 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003727 for (const auto& segment : history) {
3728 if (!segment.usedThirdBuffer) {
3729 stats.twoBufferTime += segment.totalTime;
3730 }
3731 if (segment.occupancyAverage < 1.0f) {
3732 stats.doubleBufferedTime += segment.totalTime;
3733 } else if (segment.occupancyAverage < 2.0f) {
3734 stats.tripleBufferedTime += segment.totalTime;
3735 }
3736 ++stats.numSegments;
3737 stats.totalTime += segment.totalTime;
3738 }
3739}
3740
Brian Andersond6927fb2016-07-23 23:37:30 -07003741void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3742 result.appendFormat("Layer frame timestamps:\n");
3743
3744 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3745 const size_t count = currentLayers.size();
3746 for (size_t i=0 ; i<count ; i++) {
3747 currentLayers[i]->dumpFrameEvents(result);
3748 }
3749}
3750
Dan Stozae77c7662016-05-13 11:37:28 -07003751void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3752 result.append("Buffering stats:\n");
3753 result.append(" [Layer name] <Active time> <Two buffer> "
3754 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003755 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003756 typedef std::tuple<std::string, float, float, float> BufferTuple;
3757 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003758 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003759 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003760 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003761 if (stats.numSegments == 0) {
3762 continue;
3763 }
3764 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3765 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3766 stats.totalTime;
3767 float doubleBufferRatio = static_cast<float>(
3768 stats.doubleBufferedTime) / stats.totalTime;
3769 float tripleBufferRatio = static_cast<float>(
3770 stats.tripleBufferedTime) / stats.totalTime;
3771 sorted.insert({activeTime, {name, twoBufferRatio,
3772 doubleBufferRatio, tripleBufferRatio}});
3773 }
3774 for (const auto& sortedPair : sorted) {
3775 float activeTime = sortedPair.first;
3776 const BufferTuple& values = sortedPair.second;
3777 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3778 std::get<0>(values).c_str(), activeTime,
3779 std::get<1>(values), std::get<2>(values),
3780 std::get<3>(values));
3781 }
3782 result.append("\n");
3783}
3784
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003785void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3786 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003787 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003788
3789 // TODO: print out if wide-color mode is active or not
3790
3791 for (size_t d = 0; d < mDisplays.size(); d++) {
3792 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3793 int32_t hwcId = displayDevice->getHwcDisplayId();
3794 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3795 continue;
3796 }
3797
3798 result.appendFormat("Display %d color modes:\n", hwcId);
3799 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3800 for (auto&& mode : modes) {
3801 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3802 }
3803
3804 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3805 result.appendFormat(" Current color mode: %s (%d)\n",
3806 decodeColorMode(currentMode).c_str(), currentMode);
3807 }
3808 result.append("\n");
3809}
3810
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003811LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003812 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003813 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3814 const State& state = useDrawing ? mDrawingState : mCurrentState;
3815 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003816 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003817 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003818 });
3819
3820 return layersProto;
3821}
3822
Mathias Agopian74d211a2013-04-22 16:55:35 +02003823void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3824 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003825{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003826 bool colorize = false;
3827 if (index < args.size()
3828 && (args[index] == String16("--color"))) {
3829 colorize = true;
3830 index++;
3831 }
3832
3833 Colorizer colorizer(colorize);
3834
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003835 // figure out if we're stuck somewhere
3836 const nsecs_t now = systemTime();
3837 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3838 const nsecs_t inTransaction(mDebugInTransaction);
3839 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3840 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3841
3842 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003843 * Dump library configuration.
3844 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003845
3846 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003847 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003848 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003849 appendSfConfigString(result);
3850 appendUiConfigString(result);
3851 appendGuiConfigString(result);
3852 result.append("\n");
3853
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003854 result.append("\nWide-Color information:\n");
3855 dumpWideColorInfo(result);
3856
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003857 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003858 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003859 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003860 result.append(SyncFeatures::getInstance().toString());
3861 result.append("\n");
3862
David Sodman105b7dc2017-11-04 20:28:14 -07003863 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003864
Andy McFadden41d67d72014-04-25 16:58:34 -07003865 colorizer.bold(result);
3866 result.append("DispSync configuration: ");
3867 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003868 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003869 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003870 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003871 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003872 result.append("\n");
3873
Dan Stozab90cf072015-03-05 11:05:59 -08003874 // Dump static screen stats
3875 result.append("\n");
3876 dumpStaticScreenStats(result);
3877 result.append("\n");
3878
Dan Stozae77c7662016-05-13 11:37:28 -07003879 dumpBufferingStats(result);
3880
Andy McFadden4803b742012-09-24 19:07:20 -07003881 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003882 * Dump the visible layer list
3883 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003884 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003885 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003886 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003887
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003888 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003889 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3890 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003891
3892 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003893 * Dump Display state
3894 */
3895
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003896 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003897 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003898 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003899 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3900 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003901 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003902 }
3903
3904 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003905 * Dump SurfaceFlinger global state
3906 */
3907
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003908 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003910 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911
Mathias Agopian888c8222012-08-04 21:10:38 -07003912 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003913 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003914
David Sodmanbc815282017-11-05 18:57:52 -08003915 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003916
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003917 if (hw) {
3918 hw->undefinedRegion.dump(result, "undefinedRegion");
3919 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3920 hw->getOrientation(), hw->isDisplayOn());
3921 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003922 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003923 " last eglSwapBuffers() time: %f us\n"
3924 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003925 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926 " refresh-rate : %f fps\n"
3927 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003928 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003929 " gpu_to_cpu_unsupported : %d\n"
3930 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003931 mLastSwapBufferTime/1000.0,
3932 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003933 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003934 1e9 / activeConfig->getVsyncPeriod(),
3935 activeConfig->getDpiX(),
3936 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003937 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938
Mathias Agopian74d211a2013-04-22 16:55:35 +02003939 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003941
Mathias Agopian74d211a2013-04-22 16:55:35 +02003942 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003944
3945 /*
3946 * VSYNC state
3947 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003948 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003949 result.append("\n");
3950
3951 /*
3952 * HWC layer minidump
3953 */
3954 for (size_t d = 0; d < mDisplays.size(); d++) {
3955 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3956 int32_t hwcId = displayDevice->getHwcDisplayId();
3957 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3958 continue;
3959 }
3960
3961 result.appendFormat("Display %d HWC layers:\n", hwcId);
3962 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003963 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003964 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003965 });
Dan Stozae22aec72016-08-01 13:20:59 -07003966 result.append("\n");
3967 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003968
3969 /*
3970 * Dump HWComposer state
3971 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003972 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003973 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003974 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003975 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003976 result.appendFormat(" h/w composer %s\n",
3977 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003978 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003979
3980 /*
3981 * Dump gralloc state
3982 */
3983 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3984 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003985
3986 /*
3987 * Dump VrFlinger state if in use.
3988 */
3989 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3990 result.append("VrFlinger state:\n");
3991 result.append(mVrFlinger->Dump().c_str());
3992 result.append("\n");
3993 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003994}
3995
Mathias Agopian13127d82013-03-05 17:47:11 -08003996const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003997SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003998 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003999 wp<IBinder> dpy;
4000 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4001 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4002 dpy = mDisplays.keyAt(i);
4003 break;
4004 }
4005 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004006 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004007 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4008 // Just use the primary display so we have something to return
4009 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4010 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004011 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004012}
4013
Keun young Park63f165f2012-08-31 10:53:36 -07004014bool SurfaceFlinger::startDdmConnection()
4015{
4016 void* libddmconnection_dso =
4017 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4018 if (!libddmconnection_dso) {
4019 return false;
4020 }
4021 void (*DdmConnection_start)(const char* name);
4022 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004023 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004024 if (!DdmConnection_start) {
4025 dlclose(libddmconnection_dso);
4026 return false;
4027 }
4028 (*DdmConnection_start)(getServiceName());
4029 return true;
4030}
4031
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004032status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 switch (code) {
4034 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004035 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004036 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004037 case CLEAR_ANIMATION_FRAME_STATS:
4038 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004039 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004040 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004041 case ENABLE_VSYNC_INJECTIONS:
4042 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043 {
4044 // codes that require permission check
4045 IPCThreadState* ipc = IPCThreadState::self();
4046 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004047 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004048 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004049 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004050 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004051 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004053 break;
4054 }
Robert Carr1db73f62016-12-21 12:58:51 -08004055 /*
4056 * Calling setTransactionState is safe, because you need to have been
4057 * granted a reference to Client* and Handle* to do anything with it.
4058 *
4059 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4060 */
4061 case SET_TRANSACTION_STATE:
4062 case CREATE_SCOPED_CONNECTION:
4063 {
4064 return OK;
4065 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004066 case CAPTURE_SCREEN:
4067 {
4068 // codes that require permission check
4069 IPCThreadState* ipc = IPCThreadState::self();
4070 const int pid = ipc->getCallingPid();
4071 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004072 if ((uid != AID_GRAPHICS) &&
4073 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004074 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004075 return PERMISSION_DENIED;
4076 }
4077 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 }
chaviwa76b2712017-09-20 12:02:26 -07004079 case CAPTURE_LAYERS: {
4080 IPCThreadState* ipc = IPCThreadState::self();
4081 const int pid = ipc->getCallingPid();
4082 const int uid = ipc->getCallingUid();
4083 if ((uid != AID_GRAPHICS) &&
4084 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4085 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4086 return PERMISSION_DENIED;
4087 }
4088 break;
4089 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004091 return OK;
4092}
4093
4094status_t SurfaceFlinger::onTransact(
4095 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4096{
4097 status_t credentialCheck = CheckTransactCodeCredentials(code);
4098 if (credentialCheck != OK) {
4099 return credentialCheck;
4100 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4103 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004104 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004105 IPCThreadState* ipc = IPCThreadState::self();
4106 const int uid = ipc->getCallingUid();
4107 if (CC_UNLIKELY(uid != AID_SYSTEM
4108 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004109 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004110 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004111 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 return PERMISSION_DENIED;
4113 }
4114 int n;
4115 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004116 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004117 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 return NO_ERROR;
4119 case 1002: // SHOW_UPDATES
4120 n = data.readInt32();
4121 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004122 invalidateHwcGeometry();
4123 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004126 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004127 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004129 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004130 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004131 setTransactionFlags(
4132 eTransactionNeeded|
4133 eDisplayTransactionNeeded|
4134 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004135 return NO_ERROR;
4136 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004137 case 1006:{ // send empty update
4138 signalRefresh();
4139 return NO_ERROR;
4140 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004141 case 1008: // toggle use of hw composer
4142 n = data.readInt32();
4143 mDebugDisableHWC = n ? 1 : 0;
4144 invalidateHwcGeometry();
4145 repaintEverything();
4146 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004147 case 1009: // toggle use of transform hint
4148 n = data.readInt32();
4149 mDebugDisableTransformHint = n ? 1 : 0;
4150 invalidateHwcGeometry();
4151 repaintEverything();
4152 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004154 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 reply->writeInt32(0);
4156 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004157 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004158 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004159 return NO_ERROR;
4160 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004161 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004162 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004163 return NO_ERROR;
4164 }
4165 case 1014: {
4166 // daltonize
4167 n = data.readInt32();
4168 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004169 case 1:
4170 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4171 break;
4172 case 2:
4173 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4174 break;
4175 case 3:
4176 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4177 break;
4178 default:
4179 mDaltonizer.setType(ColorBlindnessType::None);
4180 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004181 }
4182 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004183 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004184 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004185 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004186 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004187 invalidateHwcGeometry();
4188 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004189 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004191 case 1015: {
4192 // apply a color matrix
4193 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004194 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004195 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004196 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004197 for (size_t j = 0; j < 4; j++) {
4198 mColorMatrix[i][j] = data.readFloat();
4199 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004200 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004201 } else {
4202 mColorMatrix = mat4();
4203 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004204
4205 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4206 // the division by w in the fragment shader
4207 float4 lastRow(transpose(mColorMatrix)[3]);
4208 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4209 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4210 }
4211
Alan Viverette9c5a3332013-09-12 20:04:35 -07004212 invalidateHwcGeometry();
4213 repaintEverything();
4214 return NO_ERROR;
4215 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004216 // This is an experimental interface
4217 // Needs to be shifted to proper binder interface when we productize
4218 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004219 n = data.readInt32();
4220 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004221 return NO_ERROR;
4222 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004223 case 1017: {
4224 n = data.readInt32();
4225 mForceFullDamage = static_cast<bool>(n);
4226 return NO_ERROR;
4227 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004228 case 1018: { // Modify Choreographer's phase offset
4229 n = data.readInt32();
4230 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4231 return NO_ERROR;
4232 }
4233 case 1019: { // Modify SurfaceFlinger's phase offset
4234 n = data.readInt32();
4235 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4236 return NO_ERROR;
4237 }
Irvel468051e2016-06-13 16:44:44 -07004238 case 1020: { // Layer updates interceptor
4239 n = data.readInt32();
4240 if (n) {
4241 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004242 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004243 }
4244 else{
4245 ALOGV("Interceptor disabled");
4246 mInterceptor.disable();
4247 }
4248 return NO_ERROR;
4249 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004250 case 1021: { // Disable HWC virtual displays
4251 n = data.readInt32();
4252 mUseHwcVirtualDisplays = !n;
4253 return NO_ERROR;
4254 }
Romain Guy0147a172017-06-01 13:53:56 -07004255 case 1022: { // Set saturation boost
4256 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4257
4258 invalidateHwcGeometry();
4259 repaintEverything();
4260 return NO_ERROR;
4261 }
Romain Guy54f154a2017-10-24 21:40:32 +01004262 case 1023: { // Set native mode
4263 mForceNativeColorMode = data.readInt32() == 1;
4264
4265 invalidateHwcGeometry();
4266 repaintEverything();
4267 return NO_ERROR;
4268 }
4269 case 1024: { // Is wide color gamut rendering/color management supported?
4270 reply->writeBool(hasWideColorDisplay);
4271 return NO_ERROR;
4272 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004273 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004274 n = data.readInt32();
4275 if (n) {
4276 ALOGV("LayerTracing enabled");
4277 mTracing.enable();
4278 doTracing("tracing.enable");
4279 reply->writeInt32(NO_ERROR);
4280 } else {
4281 ALOGV("LayerTracing disabled");
4282 status_t err = mTracing.disable();
4283 reply->writeInt32(err);
4284 }
4285 return NO_ERROR;
4286 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004287 case 1026: { // Get layer tracing status
4288 reply->writeBool(mTracing.isEnabled());
4289 return NO_ERROR;
4290 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004291 }
4292 }
4293 return err;
4294}
4295
Steven Thomas6d8110b2017-08-31 18:24:21 -07004296void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004297 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004298 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004299}
4300
Steven Thomas6d8110b2017-08-31 18:24:21 -07004301void SurfaceFlinger::repaintEverything() {
4302 ConditionalLock _l(mStateLock,
4303 std::this_thread::get_id() != mMainThreadId);
4304 repaintEverythingLocked();
4305}
4306
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004307// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4308class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004309public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004310 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4311 ~WindowDisconnector() {
4312 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004313 }
4314
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004315private:
4316 ANativeWindow* mWindow;
4317 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004318};
4319
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004320status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4321 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4322 int32_t minLayerZ, int32_t maxLayerZ,
4323 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004324 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004325 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004326
chaviwa76b2712017-09-20 12:02:26 -07004327 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4328
4329 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4330 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4331
4332 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4333 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004334 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004335}
4336
4337status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004338 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004339 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004340 ATRACE_CALL();
4341
4342 class LayerRenderArea : public RenderArea {
4343 public:
chaviw7206d492017-11-10 16:16:12 -08004344 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004345 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004346 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004347 const Transform& getTransform() const override {
4348 // Make the top level transform the inverse the transform and it's parent so it sets
4349 // the whole capture back to 0,0
4350 return *new Transform(mLayer->getTransform().inverse());
4351 }
4352 Rect getBounds() const override {
4353 const Layer::State& layerState(mLayer->getDrawingState());
4354 return Rect(layerState.active.w, layerState.active.h);
4355 }
4356 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4357 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4358 bool isSecure() const override { return false; }
4359 bool needsFiltering() const override { return false; }
4360
chaviw7206d492017-11-10 16:16:12 -08004361 Rect getSourceCrop() const override {
4362 if (mCrop.isEmpty()) {
4363 return getBounds();
4364 } else {
4365 return mCrop;
4366 }
4367 }
chaviwa76b2712017-09-20 12:02:26 -07004368 bool getWideColorSupport() const override { return false; }
4369 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4370
4371 private:
chaviw7206d492017-11-10 16:16:12 -08004372 const sp<Layer> mLayer;
4373 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004374 };
4375
4376 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4377 auto parent = layerHandle->owner.promote();
4378
chaviw7206d492017-11-10 16:16:12 -08004379 if (parent == nullptr || parent->isPendingRemoval()) {
4380 ALOGE("captureLayers called with a removed parent");
4381 return NAME_NOT_FOUND;
4382 }
4383
4384 Rect crop(sourceCrop);
4385 if (sourceCrop.width() <= 0) {
4386 crop.left = 0;
4387 crop.right = parent->getCurrentState().active.w;
4388 }
4389
4390 if (sourceCrop.height() <= 0) {
4391 crop.top = 0;
4392 crop.bottom = parent->getCurrentState().active.h;
4393 }
4394
4395 int32_t reqWidth = crop.width() * frameScale;
4396 int32_t reqHeight = crop.height() * frameScale;
4397
4398 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4399
chaviwa76b2712017-09-20 12:02:26 -07004400 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4401 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4402 if (!layer->isVisible()) {
4403 return;
4404 }
4405 visitor(layer);
4406 });
4407 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004408 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004409}
4410
4411status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4412 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004413 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004414 bool useIdentityTransform) {
4415 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004416
chaviwa76b2712017-09-20 12:02:26 -07004417 renderArea.updateDimensions();
4418
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004419 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4420 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4421 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4422 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004423
4424 // This mutex protects syncFd and captureResult for communication of the return values from the
4425 // main thread back to this Binder thread
4426 std::mutex captureMutex;
4427 std::condition_variable captureCondition;
4428 std::unique_lock<std::mutex> captureLock(captureMutex);
4429 int syncFd = -1;
4430 std::optional<status_t> captureResult;
4431
Robert Carr03480e22018-01-04 16:02:06 -08004432 const int uid = IPCThreadState::self()->getCallingUid();
4433 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4434
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004435 sp<LambdaMessage> message = new LambdaMessage([&]() {
4436 // If there is a refresh pending, bug out early and tell the binder thread to try again
4437 // after the refresh.
4438 if (mRefreshPending) {
4439 ATRACE_NAME("Skipping screenshot for now");
4440 std::unique_lock<std::mutex> captureLock(captureMutex);
4441 captureResult = std::make_optional<status_t>(EAGAIN);
4442 captureCondition.notify_one();
4443 return;
4444 }
4445
4446 status_t result = NO_ERROR;
4447 int fd = -1;
4448 {
4449 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004450 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004451 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004452 }
4453
4454 {
4455 std::unique_lock<std::mutex> captureLock(captureMutex);
4456 syncFd = fd;
4457 captureResult = std::make_optional<status_t>(result);
4458 captureCondition.notify_one();
4459 }
4460 });
4461
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004462 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004463 if (result == NO_ERROR) {
4464 captureCondition.wait(captureLock, [&]() { return captureResult; });
4465 while (*captureResult == EAGAIN) {
4466 captureResult.reset();
4467 result = postMessageAsync(message);
4468 if (result != NO_ERROR) {
4469 return result;
4470 }
4471 captureCondition.wait(captureLock, [&]() { return captureResult; });
4472 }
4473 result = *captureResult;
4474 }
4475
4476 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004477 sync_wait(syncFd, -1);
4478 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004479 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004480
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004481 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004482}
4483
chaviwa76b2712017-09-20 12:02:26 -07004484void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4485 TraverseLayersFunction traverseLayers, bool yswap,
4486 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004487 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004488
Mathias Agopian3f844832013-08-07 21:24:32 -07004489 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004490
4491 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004492 const auto raWidth = renderArea.getWidth();
4493 const auto raHeight = renderArea.getHeight();
4494
4495 const auto reqWidth = renderArea.getReqWidth();
4496 const auto reqHeight = renderArea.getReqHeight();
4497 Rect sourceCrop = renderArea.getSourceCrop();
4498
4499 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4500 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004501
Dan Stozac1879002014-05-22 15:59:05 -07004502 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004503 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004504 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004505 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004506 }
4507
4508 // ensure that sourceCrop is inside screen
4509 if (sourceCrop.left < 0) {
4510 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4511 }
chaviwa76b2712017-09-20 12:02:26 -07004512 if (sourceCrop.right > raWidth) {
4513 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004514 }
4515 if (sourceCrop.top < 0) {
4516 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4517 }
chaviwa76b2712017-09-20 12:02:26 -07004518 if (sourceCrop.bottom > raHeight) {
4519 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004520 }
4521
chaviwa76b2712017-09-20 12:02:26 -07004522 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004523 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4524 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004525
Mathias Agopian180f10d2013-04-10 22:55:41 -07004526 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004527 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004528
4529 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004530 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4531 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004532 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004533
4534 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004535 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004536
chaviwa76b2712017-09-20 12:02:26 -07004537 traverseLayers([&](Layer* layer) {
4538 if (filtering) layer->setFiltering(true);
4539 layer->draw(renderArea, useIdentityTransform);
4540 if (filtering) layer->setFiltering(false);
4541 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004542}
4543
chaviwa76b2712017-09-20 12:02:26 -07004544status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4545 TraverseLayersFunction traverseLayers,
4546 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004547 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004548 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004549 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004550 ATRACE_CALL();
4551
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004552 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004553
4554 traverseLayers([&](Layer* layer) {
4555 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4556 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004557
Robert Carr03480e22018-01-04 16:02:06 -08004558 // We allow the system server to take screenshots of secure layers for
4559 // use in situations like the Screen-rotation animation and place
4560 // the impetus on WindowManager to not persist them.
4561 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004562 ALOGW("FB is protected: PERMISSION_DENIED");
4563 return PERMISSION_DENIED;
4564 }
4565
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004566 // this binds the given EGLImage as a framebuffer for the
4567 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004568 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4569 if (bufferBond.getStatus() != NO_ERROR) {
4570 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004571 return INVALID_OPERATION;
4572 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004573
Dan Stozaabcda352017-06-01 14:37:39 -07004574 // this will in fact render into our dequeued buffer
4575 // via an FBO, which means we didn't have to create
4576 // an EGLSurface and therefore we're not
4577 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004578 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004579
Dan Stozaabcda352017-06-01 14:37:39 -07004580 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004581 getRenderEngine().finish();
4582 *outSyncFd = -1;
4583
chaviwa76b2712017-09-20 12:02:26 -07004584 const auto reqWidth = renderArea.getReqWidth();
4585 const auto reqHeight = renderArea.getReqHeight();
4586
Dan Stozaabcda352017-06-01 14:37:39 -07004587 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4588 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004589 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004590 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004591 } else {
4592 base::unique_fd syncFd = getRenderEngine().flush();
4593 if (syncFd < 0) {
4594 getRenderEngine().finish();
4595 }
4596 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004597 }
4598
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004599 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004600}
4601
Mathias Agopiand5556842013-09-19 17:08:37 -07004602void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004603 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004604 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004605 for (size_t y = 0; y < h; y++) {
4606 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4607 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004608 if (p[x] != 0xFF000000) return;
4609 }
4610 }
chaviwa76b2712017-09-20 12:02:26 -07004611 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004612
Robert Carr2047fae2016-11-28 14:09:09 -08004613 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004614 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004615 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004616 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4617 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4618 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4619 static_cast<float>(state.color.a));
4620 i++;
4621 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004622 }
4623}
4624
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004625// ---------------------------------------------------------------------------
4626
Dan Stoza412903f2017-04-27 13:42:17 -07004627void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4628 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004629}
4630
Dan Stoza412903f2017-04-27 13:42:17 -07004631void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4632 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004633}
4634
chaviwa76b2712017-09-20 12:02:26 -07004635void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4636 int32_t maxLayerZ,
4637 const LayerVector::Visitor& visitor) {
4638 // We loop through the first level of layers without traversing,
4639 // as we need to interpret min/max layer Z in the top level Z space.
4640 for (const auto& layer : mDrawingState.layersSortedByZ) {
4641 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4642 continue;
4643 }
4644 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004645 // relative layers are traversed in Layer::traverseInZOrder
4646 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004647 continue;
4648 }
4649 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4650 if (!layer->isVisible()) {
4651 return;
4652 }
4653 visitor(layer);
4654 });
4655 }
4656}
4657
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004659
4660
4661#if defined(__gl_h_)
4662#error "don't include gl/gl.h in this file"
4663#endif
4664
4665#if defined(__gl2_h_)
4666#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004667#endif