blob: d8740d973e6380596739b978eba62640de08a928 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
David Sodman0c69cad2017-08-21 12:12:51 -070073#include "BufferLayer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070075#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
chaviw1d044282017-09-27 12:19:28 -070092#include <layerproto/LayerProtoParser.h>
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094#define DISPLAY_COUNT 1
95
Mathias Agopianfee2b462013-07-03 12:34:01 -070096/*
97 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
98 * black pixels.
99 */
100#define DEBUG_SCREENSHOTS false
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Steven Thomasb02664d2017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700132int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700133bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800134uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800135bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800136bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800137int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800138// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
Kalle Raitaa099a242017-01-11 11:17:29 -0800141
142std::string getHwcServiceName() {
143 char value[PROPERTY_VALUE_MAX] = {};
144 property_get("debug.sf.hwc_service_name", value, "default");
145 ALOGI("Using HWComposer service: '%s'", value);
146 return std::string(value);
147}
148
149bool useTrebleTestingOverride() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.treble_testing_override", value, "false");
152 ALOGI("Treble testing override: '%s'", value);
153 return std::string(value) == "true";
154}
155
David Sodmanbc815282017-11-05 18:57:52 -0800156SurfaceFlingerBE::SurfaceFlingerBE()
157 : mHwcServiceName(getHwcServiceName()),
158 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800162 mComposerSequenceId(0) {
163}
164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700166 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700168 mTransactionPending(false),
169 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700170 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700171 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700172 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800174 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800176 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800177 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700180 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700181 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700182 mDebugInSwapBuffers(0),
183 mLastSwapBufferTime(0),
184 mDebugInTransaction(0),
185 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700186 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700187 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800188 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
David Sodman105b7dc2017-11-04 20:28:14 -0700196 mMainThreadId(std::this_thread::get_id())
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
211
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
214
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800215 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
217
Steven Thomas050b2c82017-03-06 11:45:16 -0800218 // Vr flinger is only enabled on Daydream ready devices.
219 useVrFlinger = getBool< ISurfaceFlingerConfigs,
220 &ISurfaceFlingerConfigs::useVrFlinger>(false);
221
Fabien Sanglard1971b632017-03-10 14:50:03 -0800222 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
224
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600225 hasWideColorDisplay =
226 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
227
David Sodman99974d22017-11-28 12:04:33 -0800228 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 // debugging stuff...
231 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700232
Mathias Agopianb4b17302013-03-20 18:36:41 -0700233 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700234 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 property_get("debug.sf.showupdates", value, "0");
237 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700238
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239 property_get("debug.sf.ddms", value, "0");
240 mDebugDDMS = atoi(value);
241 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700242 if (!startDdmConnection()) {
243 // start failed, and DDMS debugging not enabled
244 mDebugDDMS = 0;
245 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700246 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700247 ALOGI_IF(mDebugRegion, "showupdates enabled");
248 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700249
250 property_get("debug.sf.disable_backpressure", value, "0");
251 mPropagateBackpressure = !atoi(value);
252 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700253
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800254 property_get("debug.sf.enable_hwc_vds", value, "0");
255 mUseHwcVirtualDisplays = atoi(value);
256 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800257
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800258 property_get("ro.sf.disable_triple_buffer", value, "1");
259 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700261
Romain Guy11d63f42017-07-20 12:47:14 -0700262 // We should be reading 'persist.sys.sf.color_saturation' here
263 // but since /data may be encrypted, we need to wait until after vold
264 // comes online to attempt to read the property. The property is
265 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800266
267 if (useTrebleTestingOverride()) {
268 // Without the override SurfaceFlinger cannot connect to HIDL
269 // services that are not listed in the manifests. Considered
270 // deriving the setting from the set service name, but it
271 // would be brittle if the name that's not 'default' is used
272 // for production purposes later on.
273 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800277void SurfaceFlinger::onFirstRef()
278{
279 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280}
281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282SurfaceFlinger::~SurfaceFlinger()
283{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Dan Stozac7014012014-02-14 15:03:43 -0800286void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800287{
288 // the window manager died on us. prepare its eulogy.
289
Andy McFadden13a082e2012-08-24 10:16:42 -0700290 // restore initial conditions (default device unblank, etc)
291 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800292
293 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700294 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295}
296
Robert Carr1db73f62016-12-21 12:58:51 -0800297static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700298 status_t err = client->initCheck();
299 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800300 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 }
Robert Carr1db73f62016-12-21 12:58:51 -0800302 return nullptr;
303}
304
305sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
306 return initClient(new Client(this));
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
310 const sp<IGraphicBufferProducer>& gbp) {
311 if (authenticateSurfaceTexture(gbp) == false) {
312 return nullptr;
313 }
314 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
315 if (layer == nullptr) {
316 return nullptr;
317 }
318
319 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320}
321
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700322sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
323 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324{
325 class DisplayToken : public BBinder {
326 sp<SurfaceFlinger> flinger;
327 virtual ~DisplayToken() {
328 // no more references, this display must be terminated
329 Mutex::Autolock _l(flinger->mStateLock);
330 flinger->mCurrentState.displays.removeItem(this);
331 flinger->setTransactionFlags(eDisplayTransactionNeeded);
332 }
333 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700334 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335 : flinger(flinger) {
336 }
337 };
338
339 sp<BBinder> token = new DisplayToken(this);
340
341 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700342 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700343 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700344 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700345 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346 return token;
347}
348
Jesse Hall6c913be2013-08-08 12:15:49 -0700349void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
350 Mutex::Autolock _l(mStateLock);
351
352 ssize_t idx = mCurrentState.displays.indexOfKey(display);
353 if (idx < 0) {
354 ALOGW("destroyDisplay: invalid display token");
355 return;
356 }
357
358 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
359 if (!info.isVirtualDisplay()) {
360 ALOGE("destroyDisplay called for non-virtual display");
361 return;
362 }
Irvelffc9efc2016-07-27 15:16:37 -0700363 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700364 mCurrentState.displays.removeItemsAt(idx);
365 setTransactionFlags(eDisplayTransactionNeeded);
366}
367
Mathias Agopiane57f2922012-08-09 16:29:12 -0700368sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700369 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700370 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800371 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700372 }
Jesse Hall692c7232012-11-08 15:41:56 -0800373 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376void SurfaceFlinger::bootFinished()
377{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700378 if (mStartPropertySetThread->join() != NO_ERROR) {
379 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 const nsecs_t now = systemTime();
382 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000383 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700384
385 // wait patiently for the window manager death
386 const String16 name("window");
387 sp<IBinder> window(defaultServiceManager()->getService(name));
388 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700390 }
391
Steven Thomas050b2c82017-03-06 11:45:16 -0800392 if (mVrFlinger) {
393 mVrFlinger->OnBootFinished();
394 }
395
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700396 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700397 // formerly we would just kill the process, but we now ask it to exit so it
398 // can choose where to stop the animation.
399 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700400
401 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
402 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
403 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700404
Thierry Strudel2924d012017-08-14 15:19:37 -0700405 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700406 readPersistentProperties();
407 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700408 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Mathias Agopian3f844832013-08-07 21:24:32 -0700411void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700412 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700413 RenderEngine& engine;
414 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700415 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700416 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
417 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700418 }
419 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700420 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700421 return true;
422 }
423 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700424 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425}
426
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427class DispSyncSource : public VSyncSource, private DispSync::Callback {
428public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* name) :
431 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
435 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 mDispSync(dispSync),
437 mCallbackMutex(),
438 mCallback(),
439 mVsyncMutex(),
440 mPhaseOffset(phaseOffset),
441 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700442
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 virtual ~DispSyncSource() {}
444
445 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 static_cast<DispSync::Callback*>(this));
450 if (err != NO_ERROR) {
451 ALOGE("error registering vsync callback: %s (%d)",
452 strerror(-err), err);
453 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 } else {
456 status_t err = mDispSync->removeEventListener(
457 static_cast<DispSync::Callback*>(this));
458 if (err != NO_ERROR) {
459 ALOGE("error unregistering vsync callback: %s (%d)",
460 strerror(-err), err);
461 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700462 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700464 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700465 }
466
467 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 mCallback = callback;
470 }
471
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 virtual void setPhaseOffset(nsecs_t phaseOffset) {
473 Mutex::Autolock lock(mVsyncMutex);
474
475 // Normalize phaseOffset to [0, period)
476 auto period = mDispSync->getPeriod();
477 phaseOffset %= period;
478 if (phaseOffset < 0) {
479 // If we're here, then phaseOffset is in (-period, 0). After this
480 // operation, it will be in (0, period)
481 phaseOffset += period;
482 }
483 mPhaseOffset = phaseOffset;
484
485 // If we're not enabled, we don't need to mess with the listeners
486 if (!mEnabled) {
487 return;
488 }
489
490 // Remove the listener with the old offset
491 status_t err = mDispSync->removeEventListener(
492 static_cast<DispSync::Callback*>(this));
493 if (err != NO_ERROR) {
494 ALOGE("error unregistering vsync callback: %s (%d)",
495 strerror(-err), err);
496 }
497
498 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 static_cast<DispSync::Callback*>(this));
501 if (err != NO_ERROR) {
502 ALOGE("error registering vsync callback: %s (%d)",
503 strerror(-err), err);
504 }
505 }
506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507private:
508 virtual void onDispSyncEvent(nsecs_t when) {
509 sp<VSyncSource::Callback> callback;
510 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 callback = mCallback;
513
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700514 if (mTraceVsync) {
515 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700516 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700517 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 }
519
Peiyong Lin566a3b42018-01-09 18:22:43 -0800520 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 callback->onVSyncEvent(when);
522 }
523 }
524
Tim Murray4a4e4a22016-04-19 16:29:23 +0000525 const char* const mName;
526
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700527 int mValue;
528
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700529 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 const String8 mVsyncOnLabel;
531 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534
535 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537
538 Mutex mVsyncMutex; // Protects the following
539 nsecs_t mPhaseOffset;
540 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541};
542
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700543class InjectVSyncSource : public VSyncSource {
544public:
545 InjectVSyncSource() {}
546
547 virtual ~InjectVSyncSource() {}
548
549 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
550 std::lock_guard<std::mutex> lock(mCallbackMutex);
551 mCallback = callback;
552 }
553
554 virtual void onInjectSyncEvent(nsecs_t when) {
555 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700556 if (mCallback) {
557 mCallback->onVSyncEvent(when);
558 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700559 }
560
561 virtual void setVSyncEnabled(bool) {}
562 virtual void setPhaseOffset(nsecs_t) {}
563
564private:
565 std::mutex mCallbackMutex; // Protects the following
566 sp<VSyncSource::Callback> mCallback;
567};
568
Wei Wangf9b05ee2017-07-19 20:59:39 -0700569// Do not call property_set on main thread which will be blocked by init
570// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700572 ALOGI( "SurfaceFlinger's main thread ready to run. "
573 "Initializing graphics H/W...");
574
Thierry Strudel2924d012017-08-14 15:19:37 -0700575 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 // start the EventThread
David Sodman99974d22017-11-28 12:04:33 -0800580 sp<VSyncSource> vsyncSrc =
581 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 mEventThread = new EventThread(vsyncSrc, *this, false);
David Sodman99974d22017-11-28 12:04:33 -0800583 sp<VSyncSource> sfVsyncSrc =
584 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
586 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587
Steven Thomasb02664d2017-07-26 18:48:28 -0700588 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
589 struct sched_param param = {0};
590 param.sched_priority = 2;
591 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
592 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
593 }
594 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
595 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596 }
597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800599 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800601 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700602
603 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
604 "Starting with vr flinger active is not currently supported.");
David Sodmanbc815282017-11-05 18:57:52 -0800605 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700606 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800607 // Process any initial hotplug and resulting display changes.
608 processDisplayHotplugEventsLocked();
609 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
610 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800611
Lloyd Piquefcd86612017-12-14 17:15:36 -0800612 // make the default display GLContext current so that we can create textures
613 // when creating Layers (which may happens before we render something)
614 getDefaultDisplayDeviceLocked()->makeCurrent();
615
Steven Thomas050b2c82017-03-06 11:45:16 -0800616 if (useVrFlinger) {
617 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700618 // This callback is called from the vr flinger dispatch thread. We
619 // need to call signalTransaction(), which requires holding
620 // mStateLock when we're not on the main thread. Acquiring
621 // mStateLock from the vr flinger dispatch thread might trigger a
622 // deadlock in surface flinger (see b/66916578), so post a message
623 // to be handled on the main thread instead.
624 sp<LambdaMessage> message = new LambdaMessage([=]() {
625 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
626 mVrFlingerRequestsDisplay = requestDisplay;
627 signalTransaction();
628 });
629 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 };
David Sodman105b7dc2017-11-04 20:28:14 -0700631 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
632 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800633 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 if (!mVrFlinger) {
635 ALOGE("Failed to start vrflinger");
636 }
637 }
638
Jamie Gennisd1700752013-10-14 12:22:52 -0700639 mEventControlThread = new EventControlThread(this);
640 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
641
Mathias Agopian92a979a2012-08-02 18:32:23 -0700642 // initialize our drawing state
643 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700644
Andy McFadden13a082e2012-08-24 10:16:42 -0700645 // set initial conditions (e.g. unblank default device)
646 initializeDisplays();
647
David Sodmanbc815282017-11-05 18:57:52 -0800648 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700649
Wei Wangf9b05ee2017-07-19 20:59:39 -0700650 // Inform native graphics APIs whether the present timestamp is supported:
651 if (getHwComposer().hasCapability(
652 HWC2::Capability::PresentFenceIsNotReliable)) {
653 mStartPropertySetThread = new StartPropertySetThread(false);
654 } else {
655 mStartPropertySetThread = new StartPropertySetThread(true);
656 }
657
658 if (mStartPropertySetThread->Start() != NO_ERROR) {
659 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800660 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800661
Dan Stoza9e56aa02015-11-02 13:00:03 -0800662 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700663}
664
Romain Guy11d63f42017-07-20 12:47:14 -0700665void SurfaceFlinger::readPersistentProperties() {
666 char value[PROPERTY_VALUE_MAX];
667
668 property_get("persist.sys.sf.color_saturation", value, "1.0");
669 mSaturation = atof(value);
670 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100671
672 property_get("persist.sys.sf.native_mode", value, "0");
673 mForceNativeColorMode = atoi(value) == 1;
674 if (mForceNativeColorMode) {
675 ALOGV("Forcing native color mode");
676 }
Romain Guy11d63f42017-07-20 12:47:14 -0700677}
678
Mathias Agopiana67e4182012-06-19 17:26:12 -0700679void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Start boot animation service by setting a property mailbox
681 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 if (mStartPropertySetThread->join() != NO_ERROR) {
685 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800686 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687}
688
Mathias Agopian875d8e12013-06-07 15:35:48 -0700689size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800690 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700691}
692
Mathias Agopian875d8e12013-06-07 15:35:48 -0700693size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800694 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700695}
696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800698
Jamie Gennis582270d2011-08-17 18:19:00 -0700699bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800700 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800701 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800702 return authenticateSurfaceTextureLocked(bufferProducer);
703}
704
705bool SurfaceFlinger::authenticateSurfaceTextureLocked(
706 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800707 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700708 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800709}
710
Brian Anderson6b376712017-04-04 10:51:39 -0700711status_t SurfaceFlinger::getSupportedFrameTimestamps(
712 std::vector<FrameEvent>* outSupported) const {
713 *outSupported = {
714 FrameEvent::REQUESTED_PRESENT,
715 FrameEvent::ACQUIRE,
716 FrameEvent::LATCH,
717 FrameEvent::FIRST_REFRESH_START,
718 FrameEvent::LAST_REFRESH_START,
719 FrameEvent::GPU_COMPOSITION_DONE,
720 FrameEvent::DEQUEUE_READY,
721 FrameEvent::RELEASE,
722 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700723 ConditionalLock _l(mStateLock,
724 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700725 if (!getHwComposer().hasCapability(
726 HWC2::Capability::PresentFenceIsNotReliable)) {
727 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
728 }
729 return NO_ERROR;
730}
731
Dan Stoza7f7da322014-05-02 15:26:25 -0700732status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
733 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800734 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700735 return BAD_VALUE;
736 }
737
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500738 if (!display.get())
739 return NAME_NOT_FOUND;
740
Jesse Hall692c7232012-11-08 15:41:56 -0800741 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700742 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800743 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700744 type = i;
745 break;
746 }
747 }
748
749 if (type < 0) {
750 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700751 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753 // TODO: Not sure if display density should handled by SF any longer
754 class Density {
755 static int getDensityFromProperty(char const* propName) {
756 char property[PROPERTY_VALUE_MAX];
757 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800758 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 density = atoi(property);
760 }
761 return density;
762 }
763 public:
764 static int getEmuDensity() {
765 return getDensityFromProperty("qemu.sf.lcd_density"); }
766 static int getBuildDensity() {
767 return getDensityFromProperty("ro.sf.lcd_density"); }
768 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700769
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700771
Steven Thomas6d8110b2017-08-31 18:24:21 -0700772 ConditionalLock _l(mStateLock,
773 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800774 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 DisplayInfo info = DisplayInfo();
776
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 float xdpi = hwConfig->getDpiX();
778 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700779
780 if (type == DisplayDevice::DISPLAY_PRIMARY) {
781 // The density of the device is provided by a build property
782 float density = Density::getBuildDensity() / 160.0f;
783 if (density == 0) {
784 // the build doesn't provide a density -- this is wrong!
785 // use xdpi instead
786 ALOGE("ro.sf.lcd_density must be defined as a build property");
787 density = xdpi / 160.0f;
788 }
789 if (Density::getEmuDensity()) {
790 // if "qemu.sf.lcd_density" is specified, it overrides everything
791 xdpi = ydpi = density = Density::getEmuDensity();
792 density /= 160.0f;
793 }
794 info.density = density;
795
796 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700797 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800798 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 } else {
800 // TODO: where should this value come from?
801 static const int TV_DENSITY = 213;
802 info.density = TV_DENSITY / 160.0f;
803 info.orientation = 0;
804 }
805
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 info.w = hwConfig->getWidth();
807 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 info.xdpi = xdpi;
809 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900811 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812
Andy McFadden91b2ca82014-06-13 14:04:23 -0700813 // This is how far in advance a buffer must be queued for
814 // presentation at a given time. If you want a buffer to appear
815 // on the screen at time N, you must submit the buffer before
816 // (N - presentationDeadline).
817 //
818 // Normally it's one full refresh period (to give SF a chance to
819 // latch the buffer), but this can be reduced by configuring a
820 // DispSync offset. Any additional delays introduced by the hardware
821 // composer or panel must be accounted for here.
822 //
823 // We add an additional 1ms to allow for processing time and
824 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800826 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
828 // All non-virtual displays are currently considered secure.
829 info.secure = true;
830
Michael Wright28f24d02016-07-12 13:30:53 -0700831 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 }
833
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 return NO_ERROR;
835}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700836
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800837status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700838 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800839 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700840 return BAD_VALUE;
841 }
842
843 // FIXME for now we always return stats for the primary display
844 memset(stats, 0, sizeof(*stats));
845 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
846 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
847 return NO_ERROR;
848}
849
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700850int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800851 if (display == nullptr) {
852 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800853 return BAD_VALUE;
854 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700855
856 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800857 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700858 return device->getActiveConfig();
859 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700860
Dan Stoza24a42e92015-03-09 10:04:11 -0700861 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700862}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700863
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700864void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
865 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
866 this);
867 int32_t type = hw->getDisplayType();
868 int currentMode = hw->getActiveConfig();
869
870 if (mode == currentMode) {
871 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
872 return;
873 }
874
875 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
876 ALOGW("Trying to set config for virtual display");
877 return;
878 }
879
880 hw->setActiveConfig(mode);
881 getHwComposer().setActiveConfig(type, mode);
882}
883
884status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
885 class MessageSetActiveConfig: public MessageBase {
886 SurfaceFlinger& mFlinger;
887 sp<IBinder> mDisplay;
888 int mMode;
889 public:
890 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
891 int mode) :
892 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
893 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700894 Vector<DisplayInfo> configs;
895 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700896 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700897 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700898 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700899 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700900 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700901 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800902 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700903 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700904 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700905 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
906 ALOGW("Attempt to set active config = %d for virtual display",
907 mMode);
908 } else {
909 mFlinger.setActiveConfigInternal(hw, mMode);
910 }
911 return true;
912 }
913 };
914 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
915 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700916 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700917}
Michael Wright28f24d02016-07-12 13:30:53 -0700918status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
919 Vector<android_color_mode_t>* outColorModes) {
920 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
921 return BAD_VALUE;
922 }
923
924 if (!display.get()) {
925 return NAME_NOT_FOUND;
926 }
927
928 int32_t type = NAME_NOT_FOUND;
929 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
930 if (display == mBuiltinDisplays[i]) {
931 type = i;
932 break;
933 }
934 }
935
936 if (type < 0) {
937 return type;
938 }
939
Steven Thomas6d8110b2017-08-31 18:24:21 -0700940 std::vector<android_color_mode_t> modes;
941 {
942 ConditionalLock _l(mStateLock,
943 std::this_thread::get_id() != mMainThreadId);
944 modes = getHwComposer().getColorModes(type);
945 }
Michael Wright28f24d02016-07-12 13:30:53 -0700946 outColorModes->clear();
947 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
948
949 return NO_ERROR;
950}
951
952android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700954 if (device != nullptr) {
955 return device->getActiveColorMode();
956 }
957 return static_cast<android_color_mode_t>(BAD_VALUE);
958}
959
960void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
961 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 int32_t type = hw->getDisplayType();
963 android_color_mode_t currentMode = hw->getActiveColorMode();
964
965 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700966 return;
967 }
968
969 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
970 ALOGW("Trying to set config for virtual display");
971 return;
972 }
973
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600974 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
975 hw->getDisplayType());
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 hw->setActiveColorMode(mode);
978 getHwComposer().setActiveColorMode(type, mode);
979}
980
981
982status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
983 android_color_mode_t colorMode) {
984 class MessageSetActiveColorMode: public MessageBase {
985 SurfaceFlinger& mFlinger;
986 sp<IBinder> mDisplay;
987 android_color_mode_t mMode;
988 public:
989 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
990 android_color_mode_t mode) :
991 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
992 virtual bool handler() {
993 Vector<android_color_mode_t> modes;
994 mFlinger.getDisplayColorModes(mDisplay, &modes);
995 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
996 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600997 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
998 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700999 return true;
1000 }
1001 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1002 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1004 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001005 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGW("Attempt to set active color mode %s %d for virtual display",
1007 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else {
1009 mFlinger.setActiveColorModeInternal(hw, mMode);
1010 }
1011 return true;
1012 }
1013 };
1014 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1015 postMessageSync(msg);
1016 return NO_ERROR;
1017}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001018
Svetoslavd85084b2014-03-20 10:28:31 -07001019status_t SurfaceFlinger::clearAnimationFrameStats() {
1020 Mutex::Autolock _l(mStateLock);
1021 mAnimFrameTracker.clearStats();
1022 return NO_ERROR;
1023}
1024
1025status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1026 Mutex::Autolock _l(mStateLock);
1027 mAnimFrameTracker.getStats(outStats);
1028 return NO_ERROR;
1029}
1030
Dan Stozac4f471e2016-03-24 09:31:08 -07001031status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1032 HdrCapabilities* outCapabilities) const {
1033 Mutex::Autolock _l(mStateLock);
1034
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001035 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001036 if (displayDevice == nullptr) {
1037 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1038 return BAD_VALUE;
1039 }
1040
1041 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001042 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001043 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001044 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1045 // insert HDR10 as we will force client composition for HDR10
1046 // layers
1047 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1048 types.push_back(HAL_HDR_HDR10);
1049
1050 *outCapabilities = HdrCapabilities(types,
1051 capabilities->getDesiredMaxLuminance(),
1052 capabilities->getDesiredMaxAverageLuminance(),
1053 capabilities->getDesiredMinLuminance());
1054 } else {
1055 *outCapabilities = std::move(*capabilities);
1056 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001057 } else {
1058 return BAD_VALUE;
1059 }
1060
1061 return NO_ERROR;
1062}
1063
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001064status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1066 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 if (mInjectVSyncs == enable) {
1069 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071
1072 if (enable) {
1073 ALOGV("VSync Injections enabled");
1074 if (mVSyncInjector.get() == nullptr) {
1075 mVSyncInjector = new InjectVSyncSource();
1076 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1077 }
1078 mEventQueue.setEventThread(mInjectorEventThread);
1079 } else {
1080 ALOGV("VSync Injections disabled");
1081 mEventQueue.setEventThread(mSFEventThread);
1082 }
1083
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 });
1086 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001087 return NO_ERROR;
1088}
1089
1090status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001091 Mutex::Autolock _l(mStateLock);
1092
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001093 if (!mInjectVSyncs) {
1094 ALOGE("VSync Injections not enabled");
1095 return BAD_VALUE;
1096 }
1097 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1098 ALOGV("Injecting VSync inside SurfaceFlinger");
1099 mVSyncInjector->onInjectSyncEvent(when);
1100 }
1101 return NO_ERROR;
1102}
1103
Kalle Raitaa099a242017-01-11 11:17:29 -08001104status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1105 IPCThreadState* ipc = IPCThreadState::self();
1106 const int pid = ipc->getCallingPid();
1107 const int uid = ipc->getCallingUid();
1108 if ((uid != AID_SHELL) &&
1109 !PermissionCache::checkPermission(sDump, pid, uid)) {
1110 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1111 return PERMISSION_DENIED;
1112 }
1113
1114 // Try to acquire a lock for 1s, fail gracefully
1115 const status_t err = mStateLock.timedLock(s2ns(1));
1116 const bool locked = (err == NO_ERROR);
1117 if (!locked) {
1118 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1119 return TIMED_OUT;
1120 }
1121
1122 outLayers->clear();
1123 mCurrentState.traverseInZOrder([&](Layer* layer) {
1124 outLayers->push_back(layer->getLayerDebugInfo());
1125 });
1126
1127 mStateLock.unlock();
1128 return NO_ERROR;
1129}
1130
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001131// ----------------------------------------------------------------------------
1132
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001133sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1134 ISurfaceComposer::VsyncSource vsyncSource) {
1135 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1136 return mSFEventThread->createEventConnection();
1137 } else {
1138 return mEventThread->createEventConnection();
1139 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001140}
1141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143
1144void SurfaceFlinger::waitForEvent() {
1145 mEventQueue.waitMessage();
1146}
1147
1148void SurfaceFlinger::signalTransaction() {
1149 mEventQueue.invalidate();
1150}
1151
1152void SurfaceFlinger::signalLayerUpdate() {
1153 mEventQueue.invalidate();
1154}
1155
1156void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001157 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158 mEventQueue.refresh();
1159}
1160
1161status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001162 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 return mEventQueue.postMessage(msg, reltime);
1164}
1165
1166status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001167 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001168 status_t res = mEventQueue.postMessage(msg, reltime);
1169 if (res == NO_ERROR) {
1170 msg->wait();
1171 }
1172 return res;
1173}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001175void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001176 do {
1177 waitForEvent();
1178 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179}
1180
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181void SurfaceFlinger::enableHardwareVsync() {
1182 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001183 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001185 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1186 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001188 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189}
1190
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192 Mutex::Autolock _l(mHWVsyncLock);
1193
Jesse Hall948fe0c2013-10-14 12:56:09 -07001194 if (makeAvailable) {
1195 mHWVsyncAvailable = true;
1196 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001197 // Hardware vsync is not currently available, so abort the resync
1198 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001199 return;
1200 }
1201
David Sodman105b7dc2017-11-04 20:28:14 -07001202 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001204
1205 mPrimaryDispSync.reset();
1206 mPrimaryDispSync.setPeriod(period);
1207
1208 if (!mPrimaryHWVsyncEnabled) {
1209 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001210 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1211 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryHWVsyncEnabled = true;
1213 }
1214}
1215
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 Mutex::Autolock _l(mHWVsyncLock);
1218 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1220 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryDispSync.endResync();
1222 mPrimaryHWVsyncEnabled = false;
1223 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 if (makeUnavailable) {
1225 mHWVsyncAvailable = false;
1226 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227}
1228
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229void SurfaceFlinger::resyncWithRateLimit() {
1230 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001231
1232 // No explicit locking is needed here since EventThread holds a lock while calling this method
1233 static nsecs_t sLastResyncAttempted = 0;
1234 const nsecs_t now = systemTime();
1235 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237 }
Dan Stoza57164302017-05-08 14:03:54 -07001238 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239}
1240
Steven Thomasb02664d2017-07-26 18:48:28 -07001241void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1242 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001243 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001245 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 return;
1247 }
1248
1249 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001250 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001251 return;
1252 }
1253
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 { // Scope for the lock
1257 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001258 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001261 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001262
1263 if (needsHwVsync) {
1264 enableHardwareVsync();
1265 } else {
1266 disableHardwareVsync(false);
1267 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001268}
1269
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001270void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001271 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1272 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001273}
1274
Lloyd Pique715a2c12017-12-14 17:18:08 -08001275void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1276 HWC2::Connection connection) {
1277 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1278 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001279
Lloyd Piqueba04e622017-12-14 17:11:26 -08001280 // Ignore events that do not have the right sequenceId.
1281 if (sequenceId != getBE().mComposerSequenceId) {
1282 return;
1283 }
1284
Steven Thomasb02664d2017-07-26 18:48:28 -07001285 // Only lock if we're not on the main thread. This function is normally
1286 // called on a hwbinder thread, but for the primary display it's called on
1287 // the main thread with the state lock already held, so don't attempt to
1288 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001289 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001290
Lloyd Pique715a2c12017-12-14 17:18:08 -08001291 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001292
Lloyd Piqueba04e622017-12-14 17:11:26 -08001293 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001294}
1295
Steven Thomasb02664d2017-07-26 18:48:28 -07001296void SurfaceFlinger::onRefreshReceived(int sequenceId,
1297 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001298 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001299 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001300 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001301 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001302 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001303}
1304
Dan Stoza9e56aa02015-11-02 13:00:03 -08001305void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001308 getHwComposer().setVsyncEnabled(disp,
1309 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001310}
1311
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001313void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001314 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315 // Clear the drawing state so that the logic inside of
1316 // handleTransactionLocked will fire. It will determine the delta between
1317 // mCurrentState and mDrawingState and re-apply all changes when we make the
1318 // transition.
1319 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001320 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321 mDisplays.clear();
1322}
1323
Steven Thomas050b2c82017-03-06 11:45:16 -08001324void SurfaceFlinger::updateVrFlinger() {
1325 if (!mVrFlinger)
1326 return;
1327 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001328 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001329 return;
1330 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331
David Sodman105b7dc2017-11-04 20:28:14 -07001332 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 ALOGE("Vr flinger is only supported for remote hardware composer"
1334 " service connections. Ignoring request to transition to vr"
1335 " flinger.");
1336 mVrFlingerRequestsDisplay = false;
1337 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001338 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 int currentDisplayPowerMode = getDisplayDeviceLocked(
1343 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001346 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001350 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001351 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001352 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
David Sodman105b7dc2017-11-04 20:28:14 -07001354 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1355 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001356
1357 if (vrFlingerRequestsDisplay) {
1358 mVrFlinger->GrantDisplayOwnership();
1359 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362
1363 mVisibleRegionsDirty = true;
1364 invalidateHwcGeometry();
1365
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001366 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1368 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1369 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001370
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001372 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 const nsecs_t period = activeConfig->getVsyncPeriod();
1374 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Use phase of 0 since phase is not known.
1377 // Use latency of 0, which will snap to the ideal latency.
1378 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001379
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001380 android_atomic_or(1, &mRepaintEverything);
1381 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382}
1383
Mathias Agopian4fec8732012-06-29 14:12:52 -07001384void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001385 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001386 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001388 bool frameMissed = !mHadClientComposition &&
1389 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001390 (mPreviousPresentFence->getSignalTime() ==
1391 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001392 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001393 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001394 signalLayerUpdate();
1395 break;
1396 }
1397
Steven Thomas050b2c82017-03-06 11:45:16 -08001398 // Now that we're going to make it to the handleMessageTransaction()
1399 // call below it's safe to call updateVrFlinger(), which will
1400 // potentially trigger a display handoff.
1401 updateVrFlinger();
1402
Dan Stoza6b9454d2014-11-07 16:00:59 -08001403 bool refreshNeeded = handleMessageTransaction();
1404 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001405 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001406 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001407 // Signal a refresh if a transaction modified the window state,
1408 // a new buffer was latched, or if HWC has requested a full
1409 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001410 signalRefresh();
1411 }
1412 break;
1413 }
1414 case MessageQueue::REFRESH: {
1415 handleMessageRefresh();
1416 break;
1417 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001418 }
1419}
1420
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001422 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001423 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001424 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001425 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001426 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001428}
1429
Dan Stoza6b9454d2014-11-07 16:00:59 -08001430bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001431 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001433}
1434
1435void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001437
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001438 mRefreshPending = false;
1439
Pablo Ceballos40845df2016-01-25 17:41:15 -08001440 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001441
Brian Andersond6927fb2016-07-23 23:37:30 -07001442 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001443 rebuildLayerStacks();
1444 setUpHWComposer();
1445 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001446 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001447 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001448 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001449
David Sodman105b7dc2017-11-04 20:28:14 -07001450 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001451
1452 mHadClientComposition = false;
1453 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1454 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1455 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001456 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001457 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001458
Dan Stoza9e56aa02015-11-02 13:00:03 -08001459 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461
Mathias Agopiancd60f992012-08-16 16:28:27 -07001462void SurfaceFlinger::doDebugFlashRegions()
1463{
1464 // is debugging enabled
1465 if (CC_LIKELY(!mDebugRegion))
1466 return;
1467
1468 const bool repaintEverything = mRepaintEverything;
1469 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1470 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001471 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 // transform the dirty region into this screen's coordinate space
1473 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1474 if (!dirtyRegion.isEmpty()) {
1475 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001476 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477
1478 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001480 RenderEngine& engine(getRenderEngine());
1481 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1482
Mathias Agopianda27af92012-09-13 18:17:13 -07001483 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 }
1485 }
1486 }
1487
1488 postFramebuffer();
1489
1490 if (mDebugRegion > 1) {
1491 usleep(mDebugRegion * 1000);
1492 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001493
Dan Stoza9e56aa02015-11-02 13:00:03 -08001494 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001495 auto& displayDevice = mDisplays[displayId];
1496 if (!displayDevice->isDisplayOn()) {
1497 continue;
1498 }
1499
David Sodman105b7dc2017-11-04 20:28:14 -07001500 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1501 ALOGE_IF(result != NO_ERROR,
1502 "prepareFrame for display %zd failed:"
1503 " %d (%s)",
1504 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001505 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001506}
1507
Adrian Roos1e1a1282017-11-01 19:05:31 +01001508void SurfaceFlinger::doTracing(const char* where) {
1509 ATRACE_CALL();
1510 ATRACE_NAME(where);
1511 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001512 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001513 }
1514}
1515
Brian Andersond6927fb2016-07-23 23:37:30 -07001516void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001518 ATRACE_CALL();
1519 ALOGV("preComposition");
1520
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001522 mDrawingState.traverseInZOrder([&](Layer* layer) {
1523 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 needExtraInvalidate = true;
1525 }
Robert Carr2047fae2016-11-28 14:09:09 -08001526 });
1527
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528 if (needExtraInvalidate) {
1529 signalLayerUpdate();
1530 }
1531}
1532
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533void SurfaceFlinger::updateCompositorTiming(
1534 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1535 std::shared_ptr<FenceTime>& presentFenceTime) {
1536 // Update queue of past composite+present times and determine the
1537 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001538 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001540 while (!getBE().mCompositePresentTimes.empty()) {
1541 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 // Cached values should have been updated before calling this method,
1543 // which helps avoid duplicate syscalls.
1544 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1545 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1546 break;
1547 }
1548 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001549 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001550 }
1551
1552 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001553 while (getBE().mCompositePresentTimes.size() > 16) {
1554 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001555 }
1556
Brian Andersond0010582017-03-07 13:20:31 -08001557 setCompositorTimingSnapped(
1558 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1559}
1560
1561void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1562 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001563 // Integer division and modulo round toward 0 not -inf, so we need to
1564 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001565 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001566 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1567 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1568
Brian Andersond0010582017-03-07 13:20:31 -08001569 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1570 if (idealLatency <= 0) {
1571 idealLatency = vsyncInterval;
1572 }
1573
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574 // Snap the latency to a value that removes scheduling jitter from the
1575 // composition and present times, which often have >1ms of jitter.
1576 // Reducing jitter is important if an app attempts to extrapolate
1577 // something (such as user input) to an accurate diasplay time.
1578 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1579 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001580 nsecs_t bias = vsyncInterval / 2;
1581 int64_t extraVsyncs =
1582 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1583 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1584 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585
David Sodman99974d22017-11-28 12:04:33 -08001586 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1587 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1588 getBE().mCompositorTiming.interval = vsyncInterval;
1589 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590}
1591
1592void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001594 ATRACE_CALL();
1595 ALOGV("postComposition");
1596
Brian Anderson3546a3f2016-07-14 11:51:14 -07001597 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001598 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001599 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001600 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001601 }
1602
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001603 // |mStateLock| not needed as we are on the main thread
1604 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001605
David Sodman73beded2017-11-15 11:56:06 -08001606 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001607 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001608 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001609 glCompositionDoneFenceTime =
1610 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001611 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001612 } else {
1613 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1614 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001615
David Sodman73beded2017-11-15 11:56:06 -08001616 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001617 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001618 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001619 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001620
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001621 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1622 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1623
1624 // We use the refreshStartTime which might be sampled a little later than
1625 // when we started doing work for this frame, but that should be okay
1626 // since updateCompositorTiming has snapping logic.
1627 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001628 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001629 CompositorTiming compositorTiming;
1630 {
David Sodman99974d22017-11-28 12:04:33 -08001631 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1632 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001633 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634
Robert Carr2047fae2016-11-28 14:09:09 -08001635 mDrawingState.traverseInZOrder([&](Layer* layer) {
1636 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001637 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001638 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001639 recordBufferingStats(layer->getName().string(),
1640 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001641 }
Robert Carr2047fae2016-11-28 14:09:09 -08001642 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001643
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001644 if (presentFenceTime->isValid()) {
1645 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001646 enableHardwareVsync();
1647 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001648 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001649 }
1650 }
1651
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001652 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001653 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001654 enableHardwareVsync();
1655 }
1656 }
1657
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001658 if (mAnimCompositionPending) {
1659 mAnimCompositionPending = false;
1660
Brian Anderson4e606e32017-03-16 15:34:57 -07001661 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001662 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001663 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001664 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001665 // The HWC doesn't support present fences, so use the refresh
1666 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001667 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001668 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001669 mAnimFrameTracker.setActualPresentTime(presentTime);
1670 }
1671 mAnimFrameTracker.advanceFrame();
1672 }
Dan Stozab90cf072015-03-05 11:05:59 -08001673
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001674 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1675 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001676 return;
1677 }
1678
1679 nsecs_t currentTime = systemTime();
1680 if (mHasPoweredOff) {
1681 mHasPoweredOff = false;
1682 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001683 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001685 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1686 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001687 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001688 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001689 }
David Sodman4a36e932017-11-07 14:29:47 -08001690 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001691 }
David Sodman4a36e932017-11-07 14:29:47 -08001692 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693}
1694
1695void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 ATRACE_CALL();
1697 ALOGV("rebuildLayerStacks");
1698
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001700 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001701 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001702 mVisibleRegionsDirty = false;
1703 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001704
Jeff Sharkey76488112017-02-27 14:15:18 -07001705 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1706 Region opaqueRegion;
1707 Region dirtyRegion;
1708 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001709 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001710 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1711 const Transform& tr(displayDevice->getTransform());
1712 const Rect bounds(displayDevice->getBounds());
1713 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001714 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001715
Jeff Sharkey76488112017-02-27 14:15:18 -07001716 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001717 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001718 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1719 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001720 Region drawRegion(tr.transform(
1721 layer->visibleNonTransparentRegion));
1722 drawRegion.andSelf(bounds);
1723 if (!drawRegion.isEmpty()) {
1724 layersSortedByZ.add(layer);
1725 } else {
1726 // Clear out the HWC layer if this layer was
1727 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001728 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001729 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001730 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001731 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001732 // WM changes displayDevice->layerStack upon sleep/awake.
1733 // Here we make sure we delete the HWC layers even if
1734 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001735 hwcLayerDestroyed = layer->destroyHwcLayer(
1736 displayDevice->getHwcDisplayId());
1737 }
1738
1739 // If a layer is not going to get a release fence because
1740 // it is invisible, but it is also going to release its
1741 // old buffer, add it to the list of layers needing
1742 // fences.
1743 if (hwcLayerDestroyed) {
1744 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1745 mLayersWithQueuedFrames.cend(), layer);
1746 if (found != mLayersWithQueuedFrames.cend()) {
1747 layersNeedingFences.add(layer);
1748 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001749 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 });
1751 }
1752 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001753 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001754 displayDevice->undefinedRegion.set(bounds);
1755 displayDevice->undefinedRegion.subtractSelf(
1756 tr.transform(opaqueRegion));
1757 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001758 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001759 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001760}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001761
Romain Guy0147a172017-06-01 13:53:56 -07001762mat4 SurfaceFlinger::computeSaturationMatrix() const {
1763 if (mSaturation == 1.0f) {
1764 return mat4();
1765 }
1766
1767 // Rec.709 luma coefficients
1768 float3 luminance{0.213f, 0.715f, 0.072f};
1769 luminance *= 1.0f - mSaturation;
1770 return mat4(
1771 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1772 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1773 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1774 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1775 );
1776}
1777
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001778// pickColorMode translates a given dataspace into the best available color mode.
1779// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001780android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001781 if (mForceNativeColorMode) {
1782 return HAL_COLOR_MODE_NATIVE;
1783 }
1784
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001785 switch (dataSpace) {
1786 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1787 // system expects.
1788 case HAL_DATASPACE_UNKNOWN:
1789 case HAL_DATASPACE_SRGB:
1790 case HAL_DATASPACE_V0_SRGB:
1791 return HAL_COLOR_MODE_SRGB;
1792 break;
1793
1794 case HAL_DATASPACE_DISPLAY_P3:
1795 return HAL_COLOR_MODE_DISPLAY_P3;
1796 break;
1797
1798 default:
1799 // TODO (courtneygo): Do we want to assert an error here?
1800 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1801 dataSpace);
1802 return HAL_COLOR_MODE_SRGB;
1803 break;
1804 }
1805}
1806
Romain Guy0147a172017-06-01 13:53:56 -07001807android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001808 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001809 // Only support sRGB and Display-P3 right now.
1810 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1811 return HAL_DATASPACE_DISPLAY_P3;
1812 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001813 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1814 return HAL_DATASPACE_DISPLAY_P3;
1815 }
1816 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1817 return HAL_DATASPACE_DISPLAY_P3;
1818 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001819 if (!hasHdr) {
1820 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1821 return HAL_DATASPACE_DISPLAY_P3;
1822 }
1823 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1824 return HAL_DATASPACE_DISPLAY_P3;
1825 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001826 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001827
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001828 return HAL_DATASPACE_V0_SRGB;
1829}
1830
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 ATRACE_CALL();
1833 ALOGV("setUpHWComposer");
1834
Jesse Hall028dc8f2013-08-20 16:35:32 -07001835 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001836 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1837 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1838 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1839
1840 // If nothing has changed (!dirty), don't recompose.
1841 // If something changed, but we don't currently have any visible layers,
1842 // and didn't when we last did a composition, then skip it this time.
1843 // The second rule does two things:
1844 // - When all layers are removed from a display, we'll emit one black
1845 // frame, then nothing more until we get new layers.
1846 // - When a display is created with a private layer stack, we won't
1847 // emit any black frames until a layer is added to the layer stack.
1848 bool mustRecompose = dirty && !(empty && wasEmpty);
1849
1850 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1851 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1852 mustRecompose ? "doing" : "skipping",
1853 dirty ? "+" : "-",
1854 empty ? "+" : "-",
1855 wasEmpty ? "+" : "-");
1856
Dan Stoza71433162014-02-04 16:22:36 -08001857 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001858
1859 if (mustRecompose) {
1860 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1861 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001862 }
1863
Dan Stoza9e56aa02015-11-02 13:00:03 -08001864 // build the h/w work list
1865 if (CC_UNLIKELY(mGeometryInvalid)) {
1866 mGeometryInvalid = false;
1867 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1868 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1869 const auto hwcId = displayDevice->getHwcDisplayId();
1870 if (hwcId >= 0) {
1871 const Vector<sp<Layer>>& currentLayers(
1872 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001873 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001874 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001876 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001878 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001879 }
1880 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001881
Robert Carrae060832016-11-28 10:51:00 -08001882 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001883 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001885 }
1886 }
1887 }
1888 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 }
Riley Andrews03414a12014-07-01 14:22:59 -07001890
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001891
Romain Guy0147a172017-06-01 13:53:56 -07001892 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001893
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 // Set the per-frame data
1895 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1896 auto& displayDevice = mDisplays[displayId];
1897 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001898
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 if (hwcId < 0) {
1900 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001901 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001902 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001903 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1905 "display %zd: %d", displayId, result);
1906 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001908 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1909 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001910 !displayDevice->getHdrSupport()) {
1911 layer->forceClientComposition(hwcId);
1912 }
1913
chaviwc9232ed2017-11-14 15:31:15 -08001914 if (layer->getForceClientComposition(hwcId)) {
1915 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1916 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1917 continue;
1918 }
1919
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 layer->setPerFrameData(displayDevice);
1921 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001922
1923 if (hasWideColorDisplay) {
1924 android_color_mode newColorMode;
1925 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1926
1927 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001928 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1929 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001930 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1931 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1932 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1933 }
1934 newColorMode = pickColorMode(newDataSpace);
1935
Thierry Strudel2924d012017-08-14 15:19:37 -07001936 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 }
1939
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001940 mPreviousColorMatrix = colorMatrix;
1941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001943 auto& displayDevice = mDisplays[displayId];
1944 if (!displayDevice->isDisplayOn()) {
1945 continue;
1946 }
1947
David Sodman105b7dc2017-11-04 20:28:14 -07001948 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1950 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001953
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954void SurfaceFlinger::doComposition() {
1955 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 ALOGV("doComposition");
1957
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001959 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001960 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001961 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 // transform the dirty region into this screen's coordinate space
1963 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001964
1965 // repaint the framebuffer (if needed)
1966 doDisplayComposition(hw, dirtyRegion);
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08001969 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07001970 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001971 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001972 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001973}
1974
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975void SurfaceFlinger::postFramebuffer()
1976{
Mathias Agopian841cde52012-03-01 15:44:37 -08001977 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001978 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001979
Mathias Agopiana44b0412011-10-16 18:46:35 -07001980 const nsecs_t now = systemTime();
1981 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001982
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1984 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001985 if (!displayDevice->isDisplayOn()) {
1986 continue;
1987 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 const auto hwcId = displayDevice->getHwcDisplayId();
1989 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07001990 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001991 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001992 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08001993 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001995 // The layer buffer from the previous frame (if any) is released
1996 // by HWC only when the release fence from this frame (if any) is
1997 // signaled. Always get the release fence from HWC first.
1998 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07001999 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002000
2001 // If the layer was client composited in the previous frame, we
2002 // need to merge with the previous client target acquire fence.
2003 // Since we do not track that, always merge with the current
2004 // client target acquire fence when it is available, even though
2005 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002007 releaseFence = Fence::merge("LayerRelease", releaseFence,
2008 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002009 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002010
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 layer->onLayerDisplayed(releaseFence);
2012 }
Chia-I Wu83806892017-11-16 10:50:20 -08002013
2014 // We've got a list of layers needing fences, that are disjoint with
2015 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2016 // supply them with the present fence.
2017 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002018 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002019 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2020 layer->onLayerDisplayed(presentFence);
2021 }
2022 }
2023
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002025 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002026 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002027 }
2028
Mathias Agopiana44b0412011-10-16 18:46:35 -07002029 mLastSwapBufferTime = systemTime() - now;
2030 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002031
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002032 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002033 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2034 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2035 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2036 logFrameStats();
2037 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039}
2040
Mathias Agopian87baae12012-07-31 12:38:26 -07002041void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042{
Mathias Agopian841cde52012-03-01 15:44:37 -08002043 ATRACE_CALL();
2044
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002045 // here we keep a copy of the drawing state (that is the state that's
2046 // going to be overwritten by handleTransactionLocked()) outside of
2047 // mStateLock so that the side-effects of the State assignment
2048 // don't happen with mStateLock held (which can cause deadlocks).
2049 State drawingState(mDrawingState);
2050
Mathias Agopianca4d3602011-05-19 15:38:14 -07002051 Mutex::Autolock _l(mStateLock);
2052 const nsecs_t now = systemTime();
2053 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002054
Mathias Agopianca4d3602011-05-19 15:38:14 -07002055 // Here we're guaranteed that some transaction flags are set
2056 // so we can call handleTransactionLocked() unconditionally.
2057 // We call getTransactionFlags(), which will also clear the flags,
2058 // with mStateLock held to guarantee that mCurrentState won't change
2059 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002060
Mathias Agopiane57f2922012-08-09 16:29:12 -07002061 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002062 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002063
Mathias Agopianca4d3602011-05-19 15:38:14 -07002064 mLastTransactionTime = systemTime() - now;
2065 mDebugInTransaction = 0;
2066 invalidateHwcGeometry();
2067 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002068}
2069
Lloyd Pique715a2c12017-12-14 17:18:08 -08002070DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
2071 HWC2::Connection connection) const {
2072 // Figure out whether the event is for the primary display or an
2073 // external display by matching the Hwc display id against one for a
2074 // connected display. If we did not find a match, we then check what
2075 // displays are not already connected to determine the type. If we don't
2076 // have a connected primary display, we assume the new display is meant to
2077 // be the primary display, and then if we don't have an external display,
2078 // we assume it is that.
2079 const auto primaryDisplayId =
2080 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2081 const auto externalDisplayId =
2082 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2083 if (primaryDisplayId && primaryDisplayId == display) {
2084 return DisplayDevice::DISPLAY_PRIMARY;
2085 } else if (externalDisplayId && externalDisplayId == display) {
2086 return DisplayDevice::DISPLAY_EXTERNAL;
2087 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2088 return DisplayDevice::DISPLAY_PRIMARY;
2089 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2090 return DisplayDevice::DISPLAY_EXTERNAL;
2091 }
2092
2093 return DisplayDevice::DISPLAY_ID_INVALID;
2094}
2095
Lloyd Piqueba04e622017-12-14 17:11:26 -08002096void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2097 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002098 auto displayType = determineDisplayType(event.display, event.connection);
2099 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2100 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2101 continue;
2102 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002103
2104 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2105 ALOGE("External displays are not supported by the vr hardware composer.");
2106 continue;
2107 }
2108
Lloyd Pique715a2c12017-12-14 17:18:08 -08002109 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002110
2111 if (event.connection == HWC2::Connection::Connected) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002112 ALOGV("Creating built in display %d", displayType);
2113 ALOGW_IF(mBuiltinDisplays[displayType],
2114 "Overwriting display token for display type %d", displayType);
2115 mBuiltinDisplays[displayType] = new BBinder();
2116 // All non-virtual displays are currently considered secure.
2117 DisplayDeviceState info(displayType, true);
2118 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2119 "Built-in Screen" : "External Screen";
2120 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2121 mInterceptor.saveDisplayCreation(info);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002122 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002123 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002124
Lloyd Piquefcd86612017-12-14 17:15:36 -08002125 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2126 if (idx >= 0) {
2127 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
2128 mInterceptor.saveDisplayDeletion(info.displayId);
2129 mCurrentState.displays.removeItemsAt(idx);
2130 }
2131 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002132 }
2133
2134 processDisplayChangesLocked();
2135 }
2136
2137 mPendingHotplugEvents.clear();
2138}
2139
Lloyd Pique347200f2017-12-14 17:00:15 -08002140void SurfaceFlinger::processDisplayChangesLocked() {
2141 // here we take advantage of Vector's copy-on-write semantics to
2142 // improve performance by skipping the transaction entirely when
2143 // know that the lists are identical
2144 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2145 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2146 if (!curr.isIdenticalTo(draw)) {
2147 mVisibleRegionsDirty = true;
2148 const size_t cc = curr.size();
2149 size_t dc = draw.size();
2150
2151 // find the displays that were removed
2152 // (ie: in drawing state but not in current state)
2153 // also handle displays that changed
2154 // (ie: displays that are in both lists)
2155 for (size_t i = 0; i < dc;) {
2156 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2157 if (j < 0) {
2158 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002159 // Call makeCurrent() on the primary display so we can
2160 // be sure that nothing associated with this display
2161 // is current.
2162 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2163 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2164 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2165 if (hw != nullptr) hw->disconnect(getHwComposer());
2166 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2167 mEventThread->onHotplugReceived(draw[i].type, false);
2168 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002169 } else {
2170 // this display is in both lists. see if something changed.
2171 const DisplayDeviceState& state(curr[j]);
2172 const wp<IBinder>& display(curr.keyAt(j));
2173 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2174 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2175 if (state_binder != draw_binder) {
2176 // changing the surface is like destroying and
2177 // recreating the DisplayDevice, so we just remove it
2178 // from the drawing state, so that it get re-added
2179 // below.
2180 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2181 if (hw != nullptr) hw->disconnect(getHwComposer());
2182 mDisplays.removeItem(display);
2183 mDrawingState.displays.removeItemsAt(i);
2184 dc--;
2185 // at this point we must loop to the next item
2186 continue;
2187 }
2188
2189 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2190 if (disp != nullptr) {
2191 if (state.layerStack != draw[i].layerStack) {
2192 disp->setLayerStack(state.layerStack);
2193 }
2194 if ((state.orientation != draw[i].orientation) ||
2195 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2196 disp->setProjection(state.orientation, state.viewport, state.frame);
2197 }
2198 if (state.width != draw[i].width || state.height != draw[i].height) {
2199 disp->setDisplaySize(state.width, state.height);
2200 }
2201 }
2202 }
2203 ++i;
2204 }
2205
2206 // find displays that were added
2207 // (ie: in current state but not in drawing state)
2208 for (size_t i = 0; i < cc; i++) {
2209 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2210 const DisplayDeviceState& state(curr[i]);
2211
2212 sp<DisplaySurface> dispSurface;
2213 sp<IGraphicBufferProducer> producer;
2214 sp<IGraphicBufferProducer> bqProducer;
2215 sp<IGraphicBufferConsumer> bqConsumer;
2216 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2217
2218 int32_t hwcId = -1;
2219 if (state.isVirtualDisplay()) {
2220 // Virtual displays without a surface are dormant:
2221 // they have external state (layer stack, projection,
2222 // etc.) but no internal state (i.e. a DisplayDevice).
2223 if (state.surface != nullptr) {
2224 // Allow VR composer to use virtual displays.
2225 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2226 int width = 0;
2227 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2228 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2229 int height = 0;
2230 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2231 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2232 int intFormat = 0;
2233 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2234 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2235 auto format = static_cast<android_pixel_format_t>(intFormat);
2236
2237 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2238 }
2239
2240 // TODO: Plumb requested format back up to consumer
2241
2242 sp<VirtualDisplaySurface> vds =
2243 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2244 bqProducer, bqConsumer,
2245 state.displayName);
2246
2247 dispSurface = vds;
2248 producer = vds;
2249 }
2250 } else {
2251 ALOGE_IF(state.surface != nullptr,
2252 "adding a supported display, but rendering "
2253 "surface is provided (%p), ignoring it",
2254 state.surface.get());
2255
2256 hwcId = state.type;
2257 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2258 producer = bqProducer;
2259 }
2260
2261 const wp<IBinder>& display(curr.keyAt(i));
Lloyd Piquefcd86612017-12-14 17:15:36 -08002262
Lloyd Pique347200f2017-12-14 17:00:15 -08002263 if (dispSurface != nullptr) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002264 bool useWideColorMode = hasWideColorDisplay;
Lloyd Piquec5208312018-01-08 17:59:02 -08002265 if (!mForceNativeColorMode) {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002266 bool hasWideColorModes = false;
2267 std::vector<android_color_mode_t> modes =
2268 getHwComposer().getColorModes(state.type);
2269 for (android_color_mode_t colorMode : modes) {
2270 switch (colorMode) {
2271 case HAL_COLOR_MODE_DISPLAY_P3:
2272 case HAL_COLOR_MODE_ADOBE_RGB:
2273 case HAL_COLOR_MODE_DCI_P3:
2274 hasWideColorModes = true;
2275 break;
2276 default:
2277 break;
2278 }
2279 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002280 useWideColorMode = hasWideColorModes && hasWideColorDisplay;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002281 }
2282
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002283 bool hasHdrSupport = false;
2284 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2285 getHwComposer().getHdrCapabilities(state.type);
2286 if (hdrCapabilities) {
2287 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2288 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2289 hasHdrSupport = iter != types.cend();
2290 }
2291
Lloyd Pique347200f2017-12-14 17:00:15 -08002292 sp<DisplayDevice> hw =
2293 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002294 dispSurface, producer, useWideColorMode,
2295 hasHdrSupport);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002296
Lloyd Piquec5208312018-01-08 17:59:02 -08002297 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
2298 if (useWideColorMode) {
2299 defaultColorMode = HAL_COLOR_MODE_SRGB;
Lloyd Piquefcd86612017-12-14 17:15:36 -08002300 }
Lloyd Piquec5208312018-01-08 17:59:02 -08002301 setActiveColorModeInternal(hw, defaultColorMode);
2302 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Lloyd Pique347200f2017-12-14 17:00:15 -08002303 hw->setLayerStack(state.layerStack);
2304 hw->setProjection(state.orientation, state.viewport, state.frame);
2305 hw->setDisplayName(state.displayName);
Lloyd Piquec5208312018-01-08 17:59:02 -08002306
Lloyd Pique347200f2017-12-14 17:00:15 -08002307 mDisplays.add(display, hw);
2308 if (!state.isVirtualDisplay()) {
2309 mEventThread->onHotplugReceived(state.type, true);
2310 }
2311 }
2312 }
2313 }
2314 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315
2316 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002317}
2318
Mathias Agopian87baae12012-07-31 12:38:26 -07002319void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002320{
Dan Stoza7dde5992015-05-22 09:51:44 -07002321 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002322 mCurrentState.traverseInZOrder([](Layer* layer) {
2323 layer->notifyAvailableFrames();
2324 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326 /*
2327 * Traversal of the children
2328 * (perform the transaction for each of them if needed)
2329 */
2330
Mathias Agopian3559b072012-08-15 13:46:03 -07002331 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002332 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002334 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335
2336 const uint32_t flags = layer->doTransaction(0);
2337 if (flags & Layer::eVisibleRegion)
2338 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002339 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340 }
2341
2342 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002343 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 */
2345
Mathias Agopiane57f2922012-08-09 16:29:12 -07002346 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002347 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002348 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350
Mathias Agopian84300952012-11-21 16:02:13 -08002351 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2352 // The transform hint might have changed for some layers
2353 // (either because a display has changed, or because a layer
2354 // as changed).
2355 //
2356 // Walk through all the layers in currentLayers,
2357 // and update their transform hint.
2358 //
2359 // If a layer is visible only on a single display, then that
2360 // display is used to calculate the hint, otherwise we use the
2361 // default display.
2362 //
2363 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2364 // the hint is set before we acquire a buffer from the surface texture.
2365 //
2366 // NOTE: layer transactions have taken place already, so we use their
2367 // drawing state. However, SurfaceFlinger's own transaction has not
2368 // happened yet, so we must use the current state layer list
2369 // (soon to become the drawing state list).
2370 //
2371 sp<const DisplayDevice> disp;
2372 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002373 bool first = true;
2374 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002375 // NOTE: we rely on the fact that layers are sorted by
2376 // layerStack first (so we don't have to traverse the list
2377 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002378 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002379 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002380 currentlayerStack = layerStack;
2381 // figure out if this layerstack is mirrored
2382 // (more than one display) if so, pick the default display,
2383 // if not, pick the only display it's on.
2384 disp.clear();
2385 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2386 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002387 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002388 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002389 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002390 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002391 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002392 break;
2393 }
2394 }
2395 }
2396 }
Chet Haase91d25932013-04-11 15:24:55 -07002397
Robert Carr56a0b9a2017-12-04 16:06:13 -08002398 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002399 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002400 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2401 // redraw after transform hint changes. See bug 8508397.
2402
2403 // could be null when this layer is using a layerStack
2404 // that is not visible on any display. Also can occur at
2405 // screen off/on times.
2406 disp = getDefaultDisplayDeviceLocked();
2407 }
2408 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002409 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002410 if (disp != nullptr) {
2411 layer->updateTransformHint(disp);
2412 }
Robert Carr2047fae2016-11-28 14:09:09 -08002413
2414 first = false;
2415 });
Mathias Agopian84300952012-11-21 16:02:13 -08002416 }
2417
2418
Mathias Agopian3559b072012-08-15 13:46:03 -07002419 /*
2420 * Perform our own transaction if needed
2421 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422
2423 if (mLayersAdded) {
2424 mLayersAdded = false;
2425 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002426 mVisibleRegionsDirty = true;
2427 }
2428
2429 // some layers might have been removed, so
2430 // we need to update the regions they're exposing.
2431 if (mLayersRemoved) {
2432 mLayersRemoved = false;
2433 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002434 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002435 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002436 // this layer is not visible anymore
2437 // TODO: we could traverse the tree from front to back and
2438 // compute the actual visible region
2439 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002440 Region visibleReg;
2441 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002442 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002443 }
Robert Carr2047fae2016-11-28 14:09:09 -08002444 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 }
2446
2447 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002448
2449 updateCursorAsync();
2450}
2451
2452void SurfaceFlinger::updateCursorAsync()
2453{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002454 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2455 auto& displayDevice = mDisplays[displayId];
2456 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002457 continue;
2458 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459
2460 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2461 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002462 }
2463 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002464}
2465
2466void SurfaceFlinger::commitTransaction()
2467{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002468 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002469 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002470 for (const auto& l : mLayersPendingRemoval) {
2471 recordBufferingStats(l->getName().string(),
2472 l->getOccupancyHistory(true));
2473 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002474 }
2475 mLayersPendingRemoval.clear();
2476 }
2477
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002478 // If this transaction is part of a window animation then the next frame
2479 // we composite should be considered an animation as well.
2480 mAnimCompositionPending = mAnimTransactionPending;
2481
Mathias Agopian4fec8732012-06-29 14:12:52 -07002482 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002483 mDrawingState.traverseInZOrder([](Layer* layer) {
2484 layer->commitChildList();
2485 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002486 mTransactionPending = false;
2487 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002488 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489}
2490
Chia-I Wuab0c3192017-08-01 11:29:00 -07002491void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002492 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493{
Mathias Agopian841cde52012-03-01 15:44:37 -08002494 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002496
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 Region aboveOpaqueLayers;
2498 Region aboveCoveredLayers;
2499 Region dirty;
2500
Mathias Agopian87baae12012-07-31 12:38:26 -07002501 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502
Robert Carr2047fae2016-11-28 14:09:09 -08002503 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002505 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Jesse Hall01e29052013-02-19 16:13:35 -08002507 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002508 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002509 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002510
Mathias Agopianab028732010-03-16 16:41:46 -07002511 /*
2512 * opaqueRegion: area of a surface that is fully opaque.
2513 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002515
2516 /*
2517 * visibleRegion: area of a surface that is visible on screen
2518 * and not fully transparent. This is essentially the layer's
2519 * footprint minus the opaque regions above it.
2520 * Areas covered by a translucent surface are considered visible.
2521 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002522 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002523
2524 /*
2525 * coveredRegion: area of a surface that is covered by all
2526 * visible regions above it (which includes the translucent areas).
2527 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002529
Jesse Halla8026d22012-09-25 13:25:04 -07002530 /*
2531 * transparentRegion: area of a surface that is hinted to be completely
2532 * transparent. This is only used to tell when the layer has no visible
2533 * non-transparent regions and can be removed from the layer list. It
2534 * does not affect the visibleRegion of this layer or any layers
2535 * beneath it. The hint may not be correct if apps don't respect the
2536 * SurfaceView restrictions (which, sadly, some don't).
2537 */
2538 Region transparentRegion;
2539
Mathias Agopianab028732010-03-16 16:41:46 -07002540
2541 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002542 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002543 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002546 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002547 if (!visibleRegion.isEmpty()) {
2548 // Remove the transparent area from the visible region
2549 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002550 if (tr.preserveRects()) {
2551 // transform the transparent region
2552 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002553 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002554 // transformation too complex, can't do the
2555 // transparent region optimization.
2556 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002557 }
Mathias Agopianab028732010-03-16 16:41:46 -07002558 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559
Mathias Agopianab028732010-03-16 16:41:46 -07002560 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002561 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002562 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002563 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2564 // the opaque region is the layer's footprint
2565 opaqueRegion = visibleRegion;
2566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 }
2568 }
2569
Robert Carre5f4f692018-01-12 13:12:28 -08002570 if (visibleRegion.isEmpty()) {
2571 layer->clearVisibilityRegions();
2572 return;
2573 }
2574
Mathias Agopianab028732010-03-16 16:41:46 -07002575 // Clip the covered region to the visible region
2576 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2577
2578 // Update aboveCoveredLayers for next (lower) layer
2579 aboveCoveredLayers.orSelf(visibleRegion);
2580
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 // subtract the opaque region covered by the layers above us
2582 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
2584 // compute this layer's dirty region
2585 if (layer->contentDirty) {
2586 // we need to invalidate the whole region
2587 dirty = visibleRegion;
2588 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002589 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 layer->contentDirty = false;
2591 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002592 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002593 * the exposed region consists of two components:
2594 * 1) what's VISIBLE now and was COVERED before
2595 * 2) what's EXPOSED now less what was EXPOSED before
2596 *
2597 * note that (1) is conservative, we start with the whole
2598 * visible region but only keep what used to be covered by
2599 * something -- which mean it may have been exposed.
2600 *
2601 * (2) handles areas that were not covered by anything but got
2602 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002603 */
Mathias Agopianab028732010-03-16 16:41:46 -07002604 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002605 const Region oldVisibleRegion = layer->visibleRegion;
2606 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002607 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2608 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 }
2610 dirty.subtractSelf(aboveOpaqueLayers);
2611
2612 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002613 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614
Mathias Agopianab028732010-03-16 16:41:46 -07002615 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002617
Jesse Halla8026d22012-09-25 13:25:04 -07002618 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 layer->setVisibleRegion(visibleRegion);
2620 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002621 layer->setVisibleNonTransparentRegion(
2622 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002623 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624
Mathias Agopian87baae12012-07-31 12:38:26 -07002625 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626}
2627
Chia-I Wuab0c3192017-08-01 11:29:00 -07002628void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002629 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002630 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002631 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002632 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002633 }
2634 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002635}
2636
Dan Stoza6b9454d2014-11-07 16:00:59 -08002637bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002639 ALOGV("handlePageFlip");
2640
Brian Andersond6927fb2016-07-23 23:37:30 -07002641 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642
Mathias Agopian4fec8732012-06-29 14:12:52 -07002643 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002644 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002645 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002646
2647 // Store the set of layers that need updates. This set must not change as
2648 // buffers are being latched, as this could result in a deadlock.
2649 // Example: Two producers share the same command stream and:
2650 // 1.) Layer 0 is latched
2651 // 2.) Layer 0 gets a new frame
2652 // 2.) Layer 1 gets a new frame
2653 // 3.) Layer 1 is latched.
2654 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2655 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002656 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002657 if (layer->hasQueuedFrame()) {
2658 frameQueued = true;
2659 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002660 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002661 } else {
2662 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002663 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002664 } else {
2665 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002666 }
Robert Carr2047fae2016-11-28 14:09:09 -08002667 });
2668
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002670 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002671 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002672 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002673 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002674 newDataLatched = true;
2675 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002676 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002677
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002678 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002679
2680 // If we will need to wake up at some time in the future to deal with a
2681 // queued frame that shouldn't be displayed during this vsync period, wake
2682 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002683 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002684 signalLayerUpdate();
2685 }
2686
2687 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002688 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689}
2690
Mathias Agopianad456f92011-01-13 17:53:01 -08002691void SurfaceFlinger::invalidateHwcGeometry()
2692{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002694}
2695
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002696
Fabien Sanglard830b8472016-11-30 16:35:58 -08002697void SurfaceFlinger::doDisplayComposition(
2698 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002699 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700{
Dan Stoza71433162014-02-04 16:22:36 -08002701 // We only need to actually compose the display if:
2702 // 1) It is being handled by hardware composer, which may need this to
2703 // keep its virtual display state machine in sync, or
2704 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002705 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002706 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002708 return;
2709 }
2710
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002712 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002713
2714 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002715 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716}
2717
Chia-I Wub02087d2017-11-09 10:19:54 -08002718bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002719{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002721
Chia-I Wub02087d2017-11-09 10:19:54 -08002722 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002723 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002724 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002725
2726 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002727 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2728 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002729 if (applyColorMatrix) {
2730 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2731 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2732 }
2733
David Sodman105b7dc2017-11-04 20:28:14 -07002734 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 if (hasClientComposition) {
2736 ALOGV("hasClientComposition");
2737
David Sodmanbc815282017-11-05 18:57:52 -08002738 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002739 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002740 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002741 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002742 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002743 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002745 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002746
2747 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002748 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002749 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2750 }
2751 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002752 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002753
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002754 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002755 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002757 // when using overlays, we assume a fully transparent framebuffer
2758 // NOTE: we could reduce how much we need to clear, for instance
2759 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002760 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002761 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002762 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002763 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002764 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002765 // we're left with the letterbox region
2766 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002768
2769 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002771
Mathias Agopianb9494d52012-04-18 02:28:45 -07002772 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002773 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002774 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002775 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002776 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002777 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002778
Dan Stoza9e56aa02015-11-02 13:00:03 -08002779 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002780 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002781 // scissor on the main display. It should never be needed
2782 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 const Rect& bounds(displayDevice->getBounds());
2784 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002785 if (scissor != bounds) {
2786 // scissor doesn't match the screen's dimensions, so we
2787 // need to clear everything outside of it and enable
2788 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002789
Mathias Agopianf45c5102012-10-24 16:29:17 -07002790 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002792 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002793 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002794 }
2795 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002796 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002797
Mathias Agopian85d751c2012-08-29 16:59:24 -07002798 /*
2799 * and then, render the layers targeted at the framebuffer
2800 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002801
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 ALOGV("Rendering client layers");
2803 const Transform& displayTransform = displayDevice->getTransform();
2804 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002805 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 bool firstLayer = true;
2807 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)));
2810 ALOGV("Layer: %s", layer->getName().string());
2811 ALOGV(" Composition type: %s",
2812 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002813 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 switch (layer->getCompositionType(hwcId)) {
2815 case HWC2::Composition::Cursor:
2816 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002817 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002819 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002821 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002823 // never clear the very first layer since we're
2824 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002825 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002826 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002827 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002828 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002830 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002831 break;
2832 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002834 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002835 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002836 } else {
2837 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002838 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002840 }
2841 } else {
2842 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002843 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002844 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002846 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002847 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002848 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002849 }
2850 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002851
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002852 if (applyColorMatrix) {
2853 getRenderEngine().setupColorTransform(oldColorMatrix);
2854 }
2855
Mathias Agopianf45c5102012-10-24 16:29:17 -07002856 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002857 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002858 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Fabien Sanglard830b8472016-11-30 16:35:58 -08002861void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2862 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002863 RenderEngine& engine(getRenderEngine());
2864 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Dan Stoza7d89d062015-04-30 13:29:25 -07002867status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002868 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002869 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870 const sp<Layer>& lbc,
2871 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002872{
Dan Stoza7d89d062015-04-30 13:29:25 -07002873 // add this layer to the current state list
2874 {
2875 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002876 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002877 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2878 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002879 return NO_MEMORY;
2880 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 if (parent == nullptr) {
2882 mCurrentState.layersSortedByZ.add(lbc);
2883 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002884 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002885 ALOGE("addClientLayer called with a removed parent");
2886 return NAME_NOT_FOUND;
2887 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002888 parent->addChild(lbc);
2889 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002890
Dan Stoza7d89d062015-04-30 13:29:25 -07002891 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 mLayersAdded = true;
2893 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002894 }
2895
Mathias Agopian96f08192010-06-02 23:28:45 -07002896 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002897 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002898
Dan Stoza7d89d062015-04-30 13:29:25 -07002899 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002900}
2901
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002902status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002903 Mutex::Autolock _l(mStateLock);
2904
chaviw8b3871a2017-11-01 17:41:01 -07002905 if (layer->isPendingRemoval()) {
2906 return NO_ERROR;
2907 }
2908
Robert Carr1f0a16a2016-10-24 16:27:39 -07002909 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002910 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002911 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002912 if (topLevelOnly) {
2913 return NO_ERROR;
2914 }
2915
Chia-I Wu98f1c102017-05-30 14:54:08 -07002916 sp<Layer> ancestor = p;
2917 while (ancestor->getParent() != nullptr) {
2918 ancestor = ancestor->getParent();
2919 }
2920 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2921 ALOGE("removeLayer called with a layer whose parent has been removed");
2922 return NAME_NOT_FOUND;
2923 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002924
2925 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002926 } else {
2927 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002928 }
2929
Robert Carr136e2f62017-02-08 17:54:29 -08002930 // As a matter of normal operation, the LayerCleaner will produce a second
2931 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2932 // so we will succeed in promoting it, but it's already been removed
2933 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2934 // otherwise something has gone wrong and we are leaking the layer.
2935 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2937 layer->getName().string(),
2938 (p != nullptr) ? p->getName().string() : "no-parent");
2939 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002940 } else if (index < 0) {
2941 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002942 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002943
Chia-I Wuc6657022017-08-15 11:18:17 -07002944 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002945 mLayersPendingRemoval.add(layer);
2946 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002947 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002948 setTransactionFlags(eTransactionNeeded);
2949 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950}
2951
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002952uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002953 return android_atomic_release_load(&mTransactionFlags);
2954}
2955
Mathias Agopian3f844832013-08-07 21:24:32 -07002956uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2958}
2959
Mathias Agopian3f844832013-08-07 21:24:32 -07002960uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2962 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002963 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 }
2965 return old;
2966}
2967
Mathias Agopian8b33f032012-07-24 20:43:54 -07002968void SurfaceFlinger::setTransactionState(
2969 const Vector<ComposerState>& state,
2970 const Vector<DisplayState>& displays,
2971 uint32_t flags)
2972{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002973 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002974 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002975 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002976
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002977 if (flags & eAnimation) {
2978 // For window updates that are part of an animation we must wait for
2979 // previous animation "frames" to be handled.
2980 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002981 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002982 if (CC_UNLIKELY(err != NO_ERROR)) {
2983 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002984 // caller after a few seconds.
2985 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2986 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002987 mAnimTransactionPending = false;
2988 break;
2989 }
2990 }
2991 }
2992
Mathias Agopiane57f2922012-08-09 16:29:12 -07002993 size_t count = displays.size();
2994 for (size_t i=0 ; i<count ; i++) {
2995 const DisplayState& s(displays[i]);
2996 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002997 }
2998
Mathias Agopiane57f2922012-08-09 16:29:12 -07002999 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07003000 for (size_t i=0 ; i<count ; i++) {
3001 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003002 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08003003 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003004 // IInterface, or one of its own or even one of our own but a
3005 // different type. All these situations would cause us to crash.
3006 //
3007 // NOTE: it would be better to use RTTI as we could directly check
3008 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08003009 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003010 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08003011 if (binder != nullptr) {
3012 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07003013 sp<Client> client( static_cast<Client *>(s.client.get()) );
3014 transactionFlags |= setClientStateLocked(client, s.state);
3015 }
3016 }
3017 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003018 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003019
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003020 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3021 // anyway. This can be used as a flush mechanism for previous async transactions.
3022 // Empty animation transaction can be used to simulate back-pressure, so also force a
3023 // transaction for empty animation transactions.
3024 if (transactionFlags == 0 &&
3025 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003026 transactionFlags = eTransactionNeeded;
3027 }
3028
Mathias Agopian386aa982011-11-07 21:58:03 -08003029 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003030 if (mInterceptor.isEnabled()) {
3031 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3032 }
Irvel468051e2016-06-13 16:44:44 -07003033
Mathias Agopian386aa982011-11-07 21:58:03 -08003034 // this triggers the transaction
3035 setTransactionFlags(transactionFlags);
3036
3037 // if this is a synchronous transaction, wait for it to take effect
3038 // before returning.
3039 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003040 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003041 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003042 if (flags & eAnimation) {
3043 mAnimTransactionPending = true;
3044 }
3045 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003046 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3047 if (CC_UNLIKELY(err != NO_ERROR)) {
3048 // just in case something goes wrong in SF, return to the
3049 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003050 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3051 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003052 break;
3053 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003054 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 }
3056}
3057
Mathias Agopiane57f2922012-08-09 16:29:12 -07003058uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3059{
Jesse Hall9a143922012-10-04 16:29:19 -07003060 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3061 if (dpyIdx < 0)
3062 return 0;
3063
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003065 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003066 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003067 const uint32_t what = s.what;
3068 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003069 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003070 disp.surface = s.surface;
3071 flags |= eDisplayTransactionNeeded;
3072 }
3073 }
3074 if (what & DisplayState::eLayerStackChanged) {
3075 if (disp.layerStack != s.layerStack) {
3076 disp.layerStack = s.layerStack;
3077 flags |= eDisplayTransactionNeeded;
3078 }
3079 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003080 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003081 if (disp.orientation != s.orientation) {
3082 disp.orientation = s.orientation;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 if (disp.frame != s.frame) {
3086 disp.frame = s.frame;
3087 flags |= eDisplayTransactionNeeded;
3088 }
3089 if (disp.viewport != s.viewport) {
3090 disp.viewport = s.viewport;
3091 flags |= eDisplayTransactionNeeded;
3092 }
3093 }
Michael Lentine47e45402014-07-18 15:34:25 -07003094 if (what & DisplayState::eDisplaySizeChanged) {
3095 if (disp.width != s.width) {
3096 disp.width = s.width;
3097 flags |= eDisplayTransactionNeeded;
3098 }
3099 if (disp.height != s.height) {
3100 disp.height = s.height;
3101 flags |= eDisplayTransactionNeeded;
3102 }
3103 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003104 }
3105 return flags;
3106}
3107
3108uint32_t SurfaceFlinger::setClientStateLocked(
3109 const sp<Client>& client,
3110 const layer_state_t& s)
3111{
Mathias Agopian13127d82013-03-05 17:47:11 -08003112 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003113 if (layer == nullptr) {
3114 return 0;
3115 }
3116
3117 if (layer->isPendingRemoval()) {
3118 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3119 return 0;
3120 }
3121
3122 uint32_t flags = 0;
3123
3124 const uint32_t what = s.what;
3125 bool geometryAppliesWithResize =
3126 what & layer_state_t::eGeometryAppliesWithResize;
3127 if (what & layer_state_t::ePositionChanged) {
3128 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3129 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003130 }
chaviw8b3871a2017-11-01 17:41:01 -07003131 }
3132 if (what & layer_state_t::eLayerChanged) {
3133 // NOTE: index needs to be calculated before we update the state
3134 const auto& p = layer->getParent();
3135 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003136 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003137 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003138 mCurrentState.layersSortedByZ.removeAt(idx);
3139 mCurrentState.layersSortedByZ.add(layer);
3140 // we need traversal (state changed)
3141 // AND transaction (list changed)
3142 flags |= eTransactionNeeded|eTraversalNeeded;
3143 }
chaviw8b3871a2017-11-01 17:41:01 -07003144 } else {
3145 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003146 flags |= eTransactionNeeded|eTraversalNeeded;
3147 }
3148 }
chaviw8b3871a2017-11-01 17:41:01 -07003149 }
3150 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003151 // NOTE: index needs to be calculated before we update the state
3152 const auto& p = layer->getParent();
3153 if (p == nullptr) {
3154 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3155 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3156 mCurrentState.layersSortedByZ.removeAt(idx);
3157 mCurrentState.layersSortedByZ.add(layer);
3158 // we need traversal (state changed)
3159 // AND transaction (list changed)
3160 flags |= eTransactionNeeded|eTraversalNeeded;
3161 }
3162 } else {
3163 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3164 flags |= eTransactionNeeded|eTraversalNeeded;
3165 }
chaviw8b3871a2017-11-01 17:41:01 -07003166 }
3167 }
3168 if (what & layer_state_t::eSizeChanged) {
3169 if (layer->setSize(s.w, s.h)) {
3170 flags |= eTraversalNeeded;
3171 }
3172 }
3173 if (what & layer_state_t::eAlphaChanged) {
3174 if (layer->setAlpha(s.alpha))
3175 flags |= eTraversalNeeded;
3176 }
3177 if (what & layer_state_t::eColorChanged) {
3178 if (layer->setColor(s.color))
3179 flags |= eTraversalNeeded;
3180 }
3181 if (what & layer_state_t::eMatrixChanged) {
3182 if (layer->setMatrix(s.matrix))
3183 flags |= eTraversalNeeded;
3184 }
3185 if (what & layer_state_t::eTransparentRegionChanged) {
3186 if (layer->setTransparentRegionHint(s.transparentRegion))
3187 flags |= eTraversalNeeded;
3188 }
3189 if (what & layer_state_t::eFlagsChanged) {
3190 if (layer->setFlags(s.flags, s.mask))
3191 flags |= eTraversalNeeded;
3192 }
3193 if (what & layer_state_t::eCropChanged) {
3194 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3195 flags |= eTraversalNeeded;
3196 }
3197 if (what & layer_state_t::eFinalCropChanged) {
3198 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3199 flags |= eTraversalNeeded;
3200 }
3201 if (what & layer_state_t::eLayerStackChanged) {
3202 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3203 // We only allow setting layer stacks for top level layers,
3204 // everything else inherits layer stack from its parent.
3205 if (layer->hasParent()) {
3206 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3207 layer->getName().string());
3208 } else if (idx < 0) {
3209 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3210 "that also does not appear in the top level layer list. Something"
3211 " has gone wrong.", layer->getName().string());
3212 } else if (layer->setLayerStack(s.layerStack)) {
3213 mCurrentState.layersSortedByZ.removeAt(idx);
3214 mCurrentState.layersSortedByZ.add(layer);
3215 // we need traversal (state changed)
3216 // AND transaction (list changed)
3217 flags |= eTransactionNeeded|eTraversalNeeded;
3218 }
3219 }
3220 if (what & layer_state_t::eDeferTransaction) {
3221 if (s.barrierHandle != nullptr) {
3222 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3223 } else if (s.barrierGbp != nullptr) {
3224 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3225 if (authenticateSurfaceTextureLocked(gbp)) {
3226 const auto& otherLayer =
3227 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3228 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3229 } else {
3230 ALOGE("Attempt to defer transaction to to an"
3231 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003232 }
3233 }
chaviw8b3871a2017-11-01 17:41:01 -07003234 // We don't trigger a traversal here because if no other state is
3235 // changed, we don't want this to cause any more work
3236 }
3237 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003238 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003239 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003240 if (!hadParent) {
3241 mCurrentState.layersSortedByZ.remove(layer);
3242 }
chaviw8b3871a2017-11-01 17:41:01 -07003243 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003244 }
chaviw8b3871a2017-11-01 17:41:01 -07003245 }
3246 if (what & layer_state_t::eReparentChildren) {
3247 if (layer->reparentChildren(s.reparentHandle)) {
3248 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003249 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003250 }
chaviw8b3871a2017-11-01 17:41:01 -07003251 if (what & layer_state_t::eDetachChildren) {
3252 layer->detachChildren();
3253 }
3254 if (what & layer_state_t::eOverrideScalingModeChanged) {
3255 layer->setOverrideScalingMode(s.overrideScalingMode);
3256 // We don't trigger a traversal here because if no other state is
3257 // changed, we don't want this to cause any more work
3258 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003259 return flags;
3260}
3261
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003262status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003263 const String8& name,
3264 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003265 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003266 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3267 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003269 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003270 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003271 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003272 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003273 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003274
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003275 status_t result = NO_ERROR;
3276
3277 sp<Layer> layer;
3278
Cody Northropbc755282017-03-31 12:00:08 -06003279 String8 uniqueName = getUniqueLayerName(name);
3280
Mathias Agopian3165cc22012-08-08 19:42:09 -07003281 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3282 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003283 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003284 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003285 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287 break;
chaviw13fdc492017-06-27 12:40:18 -07003288 case ISurfaceComposerClient::eFXSurfaceColor:
3289 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003290 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003291 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003292 break;
3293 default:
3294 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295 break;
3296 }
3297
Dan Stoza7d89d062015-04-30 13:29:25 -07003298 if (result != NO_ERROR) {
3299 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003301
Chia-I Wuab0c3192017-08-01 11:29:00 -07003302 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3303 // TODO b/64227542
3304 if (windowType == 441731) {
3305 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3306 layer->setPrimaryDisplayOnly();
3307 }
3308
Albert Chaulk479c60c2017-01-27 14:21:34 -05003309 layer->setInfo(windowType, ownerUid);
3310
Robert Carr1f0a16a2016-10-24 16:27:39 -07003311 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003312 if (result != NO_ERROR) {
3313 return result;
3314 }
Irvelffc9efc2016-07-27 15:16:37 -07003315 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003316
3317 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003318 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319}
3320
Cody Northropbc755282017-03-31 12:00:08 -06003321String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3322{
3323 bool matchFound = true;
3324 uint32_t dupeCounter = 0;
3325
3326 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3327 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3328
3329 // Loop over layers until we're sure there is no matching name
3330 while (matchFound) {
3331 matchFound = false;
3332 mDrawingState.traverseInZOrder([&](Layer* layer) {
3333 if (layer->getName() == uniqueName) {
3334 matchFound = true;
3335 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3336 }
3337 });
3338 }
3339
3340 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3341
3342 return uniqueName;
3343}
3344
David Sodman0c69cad2017-08-21 12:12:51 -07003345status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003346 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3347 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348{
3349 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003350 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 case PIXEL_FORMAT_TRANSPARENT:
3352 case PIXEL_FORMAT_TRANSLUCENT:
3353 format = PIXEL_FORMAT_RGBA_8888;
3354 break;
3355 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003356 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 break;
3358 }
3359
David Sodman0c69cad2017-08-21 12:12:51 -07003360 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3361 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003362 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003363 *handle = layer->getHandle();
3364 *gbp = layer->getProducer();
3365 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003367
David Sodman0c69cad2017-08-21 12:12:51 -07003368 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003369 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003370}
3371
chaviw13fdc492017-06-27 12:40:18 -07003372status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003373 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003374 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375{
chaviw13fdc492017-06-27 12:40:18 -07003376 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003377 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003378 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003379}
3380
Mathias Agopianac9fa422013-02-11 16:40:36 -08003381status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382{
Robert Carr9524cb32017-02-13 11:32:32 -08003383 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003384 status_t err = NO_ERROR;
3385 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003386 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003387 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003388 err = removeLayer(l);
3389 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3390 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003391 }
3392 return err;
3393}
3394
Mathias Agopian13127d82013-03-05 17:47:11 -08003395status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003396{
Mathias Agopian67106042013-03-14 19:18:13 -07003397 // called by ~LayerCleaner() when all references to the IBinder (handle)
3398 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003399 sp<Layer> l = layer.promote();
3400 if (l == nullptr) {
3401 // The layer has already been removed, carry on
3402 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003403 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003404 // If we have a parent, then we can continue to live as long as it does.
3405 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003406}
3407
Mathias Agopianb60314a2012-04-10 22:09:54 -07003408// ---------------------------------------------------------------------------
3409
Andy McFadden13a082e2012-08-24 10:16:42 -07003410void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003411 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003412 Vector<ComposerState> state;
3413 Vector<DisplayState> displays;
3414 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003415 d.what = DisplayState::eDisplayProjectionChanged |
3416 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003417 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003418 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003419 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003420 d.frame.makeInvalid();
3421 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003422 d.width = 0;
3423 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003424 displays.add(d);
3425 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003426 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3427 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003428
David Sodman105b7dc2017-11-04 20:28:14 -07003429 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003430 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003431 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003432
Brian Andersond0010582017-03-07 13:20:31 -08003433 // Use phase of 0 since phase is not known.
3434 // Use latency of 0, which will snap to the ideal latency.
3435 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003436}
3437
3438void SurfaceFlinger::initializeDisplays() {
3439 class MessageScreenInitialized : public MessageBase {
3440 SurfaceFlinger* flinger;
3441 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003442 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003443 virtual bool handler() {
3444 flinger->onInitializeDisplays();
3445 return true;
3446 }
3447 };
3448 sp<MessageBase> msg = new MessageScreenInitialized(this);
3449 postMessageAsync(msg); // we may be called from main thread, use async message
3450}
3451
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003452void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003453 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003454 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3455 this);
3456 int32_t type = hw->getDisplayType();
3457 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003458
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003460 return;
3461 }
3462
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003463 hw->setPowerMode(mode);
3464 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3465 ALOGW("Trying to set power mode for virtual display");
3466 return;
3467 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003468
Irvelffc9efc2016-07-27 15:16:37 -07003469 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003470 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003471 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3472 if (idx < 0) {
3473 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3474 return;
3475 }
3476 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3477 }
3478
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003479 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003480 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003481 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003482 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3483 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003484 // FIXME: eventthread only knows about the main display right now
3485 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003486 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003489 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003490 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003491 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003492
3493 struct sched_param param = {0};
3494 param.sched_priority = 1;
3495 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3496 ALOGW("Couldn't set SCHED_FIFO on display on");
3497 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003498 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003499 // Turn off the display
3500 struct sched_param param = {0};
3501 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3502 ALOGW("Couldn't set SCHED_OTHER on display off");
3503 }
3504
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003505 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3506 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003507 disableHardwareVsync(true); // also cancels any in-progress resync
3508
Mathias Agopiancde87a32012-09-13 14:09:01 -07003509 // FIXME: eventthread only knows about the main display right now
3510 mEventThread->onScreenReleased();
3511 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003512
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003513 getHwComposer().setPowerMode(type, mode);
3514 mVisibleRegionsDirty = true;
3515 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003516 } else if (mode == HWC_POWER_MODE_DOZE ||
3517 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003518 // Update display while dozing
3519 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003520 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3521 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003522 // FIXME: eventthread only knows about the main display right now
3523 mEventThread->onScreenAcquired();
3524 resyncToHardwareVsync(true);
3525 }
3526 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3527 // Leave display going to doze
3528 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3529 disableHardwareVsync(true); // also cancels any in-progress resync
3530 // FIXME: eventthread only knows about the main display right now
3531 mEventThread->onScreenReleased();
3532 }
3533 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003534 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003535 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003536 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003537 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003538}
3539
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003540void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3541 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003542 SurfaceFlinger& mFlinger;
3543 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003544 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003545 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003546 MessageSetPowerMode(SurfaceFlinger& flinger,
3547 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3548 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003549 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003550 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003551 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003552 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003553 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003554 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003555 ALOGW("Attempt to set power mode = %d for virtual display",
3556 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003557 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003558 mFlinger.setPowerModeInternal(
3559 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003560 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003561 return true;
3562 }
3563 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003564 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003565 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003566}
3567
3568// ---------------------------------------------------------------------------
3569
Vishnu Nair6a408532017-10-24 09:11:27 -07003570status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003572
Mathias Agopianbd115332013-04-18 16:41:04 -07003573 IPCThreadState* ipc = IPCThreadState::self();
3574 const int pid = ipc->getCallingPid();
3575 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003576
Mathias Agopianbd115332013-04-18 16:41:04 -07003577 if ((uid != AID_SHELL) &&
3578 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003579 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003580 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003582 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003583 // (this would indicate SF is stuck, but we want to be able to
3584 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003585 status_t err = mStateLock.timedLock(s2ns(1));
3586 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003587 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003588 result.appendFormat(
3589 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3590 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003591 }
3592
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003593 bool dumpAll = true;
3594 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003595 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003596
3597 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003598 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003599 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3600 dumpAll = false;
3601 }
3602
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003603 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003604 if ((index < numArgs) &&
3605 (args[index] == String16("--list"))) {
3606 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003607 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003608 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003609 }
3610
3611 if ((index < numArgs) &&
3612 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003613 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003614 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003615 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003616 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003617
3618 if ((index < numArgs) &&
3619 (args[index] == String16("--latency-clear"))) {
3620 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003621 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003622 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003623 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003624
3625 if ((index < numArgs) &&
3626 (args[index] == String16("--dispsync"))) {
3627 index++;
3628 mPrimaryDispSync.dump(result);
3629 dumpAll = false;
3630 }
Dan Stozab90cf072015-03-05 11:05:59 -08003631
3632 if ((index < numArgs) &&
3633 (args[index] == String16("--static-screen"))) {
3634 index++;
3635 dumpStaticScreenStats(result);
3636 dumpAll = false;
3637 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003638
3639 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003640 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003641 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003642 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003643 dumpAll = false;
3644 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003645
3646 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3647 index++;
3648 dumpWideColorInfo(result);
3649 dumpAll = false;
3650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003652
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003653 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003654 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003655 }
3656
Mathias Agopian9795c422009-08-26 16:36:26 -07003657 if (locked) {
3658 mStateLock.unlock();
3659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660 }
3661 write(fd, result.string(), result.size());
3662 return NO_ERROR;
3663}
3664
Dan Stozac7014012014-02-14 15:03:43 -08003665void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3666 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003667{
Robert Carr2047fae2016-11-28 14:09:09 -08003668 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003669 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003670 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003671}
3672
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003673void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003674 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003675{
3676 String8 name;
3677 if (index < args.size()) {
3678 name = String8(args[index]);
3679 index++;
3680 }
3681
David Sodman105b7dc2017-11-04 20:28:14 -07003682 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003683 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003684 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003685
3686 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003687 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003688 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003689 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003690 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003691 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003692 }
Robert Carr2047fae2016-11-28 14:09:09 -08003693 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003694 }
3695}
3696
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003697void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003698 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003699{
3700 String8 name;
3701 if (index < args.size()) {
3702 name = String8(args[index]);
3703 index++;
3704 }
3705
Robert Carr2047fae2016-11-28 14:09:09 -08003706 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003707 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003708 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003709 }
Robert Carr2047fae2016-11-28 14:09:09 -08003710 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003711
Svetoslavd85084b2014-03-20 10:28:31 -07003712 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003713}
3714
Jamie Gennis6547ff42013-07-16 20:12:42 -07003715// This should only be called from the main thread. Otherwise it would need
3716// the lock and should use mCurrentState rather than mDrawingState.
3717void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003718 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003719 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003720 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003721
3722 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3723}
3724
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003725void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003726{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003727 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003728
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003729 if (isLayerTripleBufferingDisabled())
3730 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003731
3732 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003733 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003734 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003735 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003736 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3737 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003738 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003739}
3740
Dan Stozab90cf072015-03-05 11:05:59 -08003741void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3742{
3743 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003744 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3745 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003746 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003747 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003748 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3749 b + 1, bucketTimeSec, percent);
3750 }
David Sodman4a36e932017-11-07 14:29:47 -08003751 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003752 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003753 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003754 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003755 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003756}
3757
Dan Stozae77c7662016-05-13 11:37:28 -07003758void SurfaceFlinger::recordBufferingStats(const char* layerName,
3759 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003760 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3761 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003762 for (const auto& segment : history) {
3763 if (!segment.usedThirdBuffer) {
3764 stats.twoBufferTime += segment.totalTime;
3765 }
3766 if (segment.occupancyAverage < 1.0f) {
3767 stats.doubleBufferedTime += segment.totalTime;
3768 } else if (segment.occupancyAverage < 2.0f) {
3769 stats.tripleBufferedTime += segment.totalTime;
3770 }
3771 ++stats.numSegments;
3772 stats.totalTime += segment.totalTime;
3773 }
3774}
3775
Brian Andersond6927fb2016-07-23 23:37:30 -07003776void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3777 result.appendFormat("Layer frame timestamps:\n");
3778
3779 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3780 const size_t count = currentLayers.size();
3781 for (size_t i=0 ; i<count ; i++) {
3782 currentLayers[i]->dumpFrameEvents(result);
3783 }
3784}
3785
Dan Stozae77c7662016-05-13 11:37:28 -07003786void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3787 result.append("Buffering stats:\n");
3788 result.append(" [Layer name] <Active time> <Two buffer> "
3789 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003790 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003791 typedef std::tuple<std::string, float, float, float> BufferTuple;
3792 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003793 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003794 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003795 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003796 if (stats.numSegments == 0) {
3797 continue;
3798 }
3799 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3800 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3801 stats.totalTime;
3802 float doubleBufferRatio = static_cast<float>(
3803 stats.doubleBufferedTime) / stats.totalTime;
3804 float tripleBufferRatio = static_cast<float>(
3805 stats.tripleBufferedTime) / stats.totalTime;
3806 sorted.insert({activeTime, {name, twoBufferRatio,
3807 doubleBufferRatio, tripleBufferRatio}});
3808 }
3809 for (const auto& sortedPair : sorted) {
3810 float activeTime = sortedPair.first;
3811 const BufferTuple& values = sortedPair.second;
3812 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3813 std::get<0>(values).c_str(), activeTime,
3814 std::get<1>(values), std::get<2>(values),
3815 std::get<3>(values));
3816 }
3817 result.append("\n");
3818}
3819
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003820void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3821 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003822 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003823
3824 // TODO: print out if wide-color mode is active or not
3825
3826 for (size_t d = 0; d < mDisplays.size(); d++) {
3827 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3828 int32_t hwcId = displayDevice->getHwcDisplayId();
3829 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3830 continue;
3831 }
3832
3833 result.appendFormat("Display %d color modes:\n", hwcId);
3834 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3835 for (auto&& mode : modes) {
3836 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3837 }
3838
3839 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3840 result.appendFormat(" Current color mode: %s (%d)\n",
3841 decodeColorMode(currentMode).c_str(), currentMode);
3842 }
3843 result.append("\n");
3844}
3845
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003846LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003847 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003848 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3849 const State& state = useDrawing ? mDrawingState : mCurrentState;
3850 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003851 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003852 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003853 });
3854
3855 return layersProto;
3856}
3857
Mathias Agopian74d211a2013-04-22 16:55:35 +02003858void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3859 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003860{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003861 bool colorize = false;
3862 if (index < args.size()
3863 && (args[index] == String16("--color"))) {
3864 colorize = true;
3865 index++;
3866 }
3867
3868 Colorizer colorizer(colorize);
3869
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003870 // figure out if we're stuck somewhere
3871 const nsecs_t now = systemTime();
3872 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3873 const nsecs_t inTransaction(mDebugInTransaction);
3874 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3875 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3876
3877 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003878 * Dump library configuration.
3879 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003880
3881 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003882 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003883 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003884 appendSfConfigString(result);
3885 appendUiConfigString(result);
3886 appendGuiConfigString(result);
3887 result.append("\n");
3888
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003889 result.append("\nWide-Color information:\n");
3890 dumpWideColorInfo(result);
3891
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003892 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003893 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003894 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003895 result.append(SyncFeatures::getInstance().toString());
3896 result.append("\n");
3897
David Sodman105b7dc2017-11-04 20:28:14 -07003898 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003899
Andy McFadden41d67d72014-04-25 16:58:34 -07003900 colorizer.bold(result);
3901 result.append("DispSync configuration: ");
3902 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003903 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003904 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003905 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003906 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003907 result.append("\n");
3908
Dan Stozab90cf072015-03-05 11:05:59 -08003909 // Dump static screen stats
3910 result.append("\n");
3911 dumpStaticScreenStats(result);
3912 result.append("\n");
3913
Dan Stozae77c7662016-05-13 11:37:28 -07003914 dumpBufferingStats(result);
3915
Andy McFadden4803b742012-09-24 19:07:20 -07003916 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003917 * Dump the visible layer list
3918 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003919 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003920 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003921 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003922
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003923 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003924 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3925 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926
3927 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003928 * Dump Display state
3929 */
3930
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003931 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003932 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003933 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003934 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3935 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003936 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003937 }
3938
3939 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940 * Dump SurfaceFlinger global state
3941 */
3942
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003943 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003944 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003945 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946
Mathias Agopian888c8222012-08-04 21:10:38 -07003947 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003948 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003949
David Sodmanbc815282017-11-05 18:57:52 -08003950 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003951
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003952 if (hw) {
3953 hw->undefinedRegion.dump(result, "undefinedRegion");
3954 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3955 hw->getOrientation(), hw->isDisplayOn());
3956 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02003957 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 " last eglSwapBuffers() time: %f us\n"
3959 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003960 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 " refresh-rate : %f fps\n"
3962 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003963 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003964 " gpu_to_cpu_unsupported : %d\n"
3965 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966 mLastSwapBufferTime/1000.0,
3967 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003968 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003969 1e9 / activeConfig->getVsyncPeriod(),
3970 activeConfig->getDpiX(),
3971 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003972 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003973
Mathias Agopian74d211a2013-04-22 16:55:35 +02003974 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976
Mathias Agopian74d211a2013-04-22 16:55:35 +02003977 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003978 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003979
3980 /*
3981 * VSYNC state
3982 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003983 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003984 result.append("\n");
3985
3986 /*
3987 * HWC layer minidump
3988 */
3989 for (size_t d = 0; d < mDisplays.size(); d++) {
3990 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3991 int32_t hwcId = displayDevice->getHwcDisplayId();
3992 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3993 continue;
3994 }
3995
3996 result.appendFormat("Display %d HWC layers:\n", hwcId);
3997 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003998 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003999 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004000 });
Dan Stozae22aec72016-08-01 13:20:59 -07004001 result.append("\n");
4002 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004003
4004 /*
4005 * Dump HWComposer state
4006 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004007 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004008 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004009 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004010 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004011 result.appendFormat(" h/w composer %s\n",
4012 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004013 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014
4015 /*
4016 * Dump gralloc state
4017 */
4018 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4019 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004020
4021 /*
4022 * Dump VrFlinger state if in use.
4023 */
4024 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4025 result.append("VrFlinger state:\n");
4026 result.append(mVrFlinger->Dump().c_str());
4027 result.append("\n");
4028 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004029}
4030
Mathias Agopian13127d82013-03-05 17:47:11 -08004031const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004032SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004033 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004034 wp<IBinder> dpy;
4035 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4036 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4037 dpy = mDisplays.keyAt(i);
4038 break;
4039 }
4040 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004041 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004042 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4043 // Just use the primary display so we have something to return
4044 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4045 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004046 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004047}
4048
Keun young Park63f165f2012-08-31 10:53:36 -07004049bool SurfaceFlinger::startDdmConnection()
4050{
4051 void* libddmconnection_dso =
4052 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4053 if (!libddmconnection_dso) {
4054 return false;
4055 }
4056 void (*DdmConnection_start)(const char* name);
4057 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004058 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004059 if (!DdmConnection_start) {
4060 dlclose(libddmconnection_dso);
4061 return false;
4062 }
4063 (*DdmConnection_start)(getServiceName());
4064 return true;
4065}
4066
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004067status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004068 switch (code) {
4069 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004070 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004072 case CLEAR_ANIMATION_FRAME_STATS:
4073 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004074 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004075 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004076 case ENABLE_VSYNC_INJECTIONS:
4077 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 {
4079 // codes that require permission check
4080 IPCThreadState* ipc = IPCThreadState::self();
4081 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004082 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004083 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004084 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004085 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004086 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004088 break;
4089 }
Robert Carr1db73f62016-12-21 12:58:51 -08004090 /*
4091 * Calling setTransactionState is safe, because you need to have been
4092 * granted a reference to Client* and Handle* to do anything with it.
4093 *
4094 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4095 */
4096 case SET_TRANSACTION_STATE:
4097 case CREATE_SCOPED_CONNECTION:
4098 {
4099 return OK;
4100 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004101 case CAPTURE_SCREEN:
4102 {
4103 // codes that require permission check
4104 IPCThreadState* ipc = IPCThreadState::self();
4105 const int pid = ipc->getCallingPid();
4106 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004107 if ((uid != AID_GRAPHICS) &&
4108 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004109 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004110 return PERMISSION_DENIED;
4111 }
4112 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113 }
chaviwa76b2712017-09-20 12:02:26 -07004114 case CAPTURE_LAYERS: {
4115 IPCThreadState* ipc = IPCThreadState::self();
4116 const int pid = ipc->getCallingPid();
4117 const int uid = ipc->getCallingUid();
4118 if ((uid != AID_GRAPHICS) &&
4119 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4120 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4121 return PERMISSION_DENIED;
4122 }
4123 break;
4124 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004126 return OK;
4127}
4128
4129status_t SurfaceFlinger::onTransact(
4130 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4131{
4132 status_t credentialCheck = CheckTransactCodeCredentials(code);
4133 if (credentialCheck != OK) {
4134 return credentialCheck;
4135 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004136
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4138 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004139 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004140 IPCThreadState* ipc = IPCThreadState::self();
4141 const int uid = ipc->getCallingUid();
4142 if (CC_UNLIKELY(uid != AID_SYSTEM
4143 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004144 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004145 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004146 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 return PERMISSION_DENIED;
4148 }
4149 int n;
4150 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004151 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004152 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 return NO_ERROR;
4154 case 1002: // SHOW_UPDATES
4155 n = data.readInt32();
4156 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004157 invalidateHwcGeometry();
4158 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004159 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004161 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004162 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004163 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004164 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004165 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004166 setTransactionFlags(
4167 eTransactionNeeded|
4168 eDisplayTransactionNeeded|
4169 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004170 return NO_ERROR;
4171 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004172 case 1006:{ // send empty update
4173 signalRefresh();
4174 return NO_ERROR;
4175 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004176 case 1008: // toggle use of hw composer
4177 n = data.readInt32();
4178 mDebugDisableHWC = n ? 1 : 0;
4179 invalidateHwcGeometry();
4180 repaintEverything();
4181 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004182 case 1009: // toggle use of transform hint
4183 n = data.readInt32();
4184 mDebugDisableTransformHint = n ? 1 : 0;
4185 invalidateHwcGeometry();
4186 repaintEverything();
4187 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004189 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190 reply->writeInt32(0);
4191 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004192 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004193 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004194 return NO_ERROR;
4195 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004196 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004197 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004198 return NO_ERROR;
4199 }
4200 case 1014: {
4201 // daltonize
4202 n = data.readInt32();
4203 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004204 case 1:
4205 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4206 break;
4207 case 2:
4208 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4209 break;
4210 case 3:
4211 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4212 break;
4213 default:
4214 mDaltonizer.setType(ColorBlindnessType::None);
4215 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004216 }
4217 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004218 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004219 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004220 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004221 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004222 invalidateHwcGeometry();
4223 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004224 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004225 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004226 case 1015: {
4227 // apply a color matrix
4228 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004229 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004230 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004231 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004232 for (size_t j = 0; j < 4; j++) {
4233 mColorMatrix[i][j] = data.readFloat();
4234 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004235 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004236 } else {
4237 mColorMatrix = mat4();
4238 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004239
4240 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4241 // the division by w in the fragment shader
4242 float4 lastRow(transpose(mColorMatrix)[3]);
4243 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4244 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4245 }
4246
Alan Viverette9c5a3332013-09-12 20:04:35 -07004247 invalidateHwcGeometry();
4248 repaintEverything();
4249 return NO_ERROR;
4250 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004251 // This is an experimental interface
4252 // Needs to be shifted to proper binder interface when we productize
4253 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004254 n = data.readInt32();
4255 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004256 return NO_ERROR;
4257 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004258 case 1017: {
4259 n = data.readInt32();
4260 mForceFullDamage = static_cast<bool>(n);
4261 return NO_ERROR;
4262 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004263 case 1018: { // Modify Choreographer's phase offset
4264 n = data.readInt32();
4265 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4266 return NO_ERROR;
4267 }
4268 case 1019: { // Modify SurfaceFlinger's phase offset
4269 n = data.readInt32();
4270 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4271 return NO_ERROR;
4272 }
Irvel468051e2016-06-13 16:44:44 -07004273 case 1020: { // Layer updates interceptor
4274 n = data.readInt32();
4275 if (n) {
4276 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004277 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004278 }
4279 else{
4280 ALOGV("Interceptor disabled");
4281 mInterceptor.disable();
4282 }
4283 return NO_ERROR;
4284 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004285 case 1021: { // Disable HWC virtual displays
4286 n = data.readInt32();
4287 mUseHwcVirtualDisplays = !n;
4288 return NO_ERROR;
4289 }
Romain Guy0147a172017-06-01 13:53:56 -07004290 case 1022: { // Set saturation boost
4291 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4292
4293 invalidateHwcGeometry();
4294 repaintEverything();
4295 return NO_ERROR;
4296 }
Romain Guy54f154a2017-10-24 21:40:32 +01004297 case 1023: { // Set native mode
4298 mForceNativeColorMode = data.readInt32() == 1;
4299
4300 invalidateHwcGeometry();
4301 repaintEverything();
4302 return NO_ERROR;
4303 }
4304 case 1024: { // Is wide color gamut rendering/color management supported?
4305 reply->writeBool(hasWideColorDisplay);
4306 return NO_ERROR;
4307 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004308 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004309 n = data.readInt32();
4310 if (n) {
4311 ALOGV("LayerTracing enabled");
4312 mTracing.enable();
4313 doTracing("tracing.enable");
4314 reply->writeInt32(NO_ERROR);
4315 } else {
4316 ALOGV("LayerTracing disabled");
4317 status_t err = mTracing.disable();
4318 reply->writeInt32(err);
4319 }
4320 return NO_ERROR;
4321 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004322 case 1026: { // Get layer tracing status
4323 reply->writeBool(mTracing.isEnabled());
4324 return NO_ERROR;
4325 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004326 }
4327 }
4328 return err;
4329}
4330
Steven Thomas6d8110b2017-08-31 18:24:21 -07004331void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004332 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004333 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004334}
4335
Steven Thomas6d8110b2017-08-31 18:24:21 -07004336void SurfaceFlinger::repaintEverything() {
4337 ConditionalLock _l(mStateLock,
4338 std::this_thread::get_id() != mMainThreadId);
4339 repaintEverythingLocked();
4340}
4341
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004342// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4343class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004344public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004345 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4346 ~WindowDisconnector() {
4347 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004348 }
4349
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004350private:
4351 ANativeWindow* mWindow;
4352 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004353};
4354
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004355status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4356 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4357 int32_t minLayerZ, int32_t maxLayerZ,
4358 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004359 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004360 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004361
chaviwa76b2712017-09-20 12:02:26 -07004362 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4363
4364 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4365 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4366
4367 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4368 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004369 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004370}
4371
4372status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004373 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004374 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004375 ATRACE_CALL();
4376
4377 class LayerRenderArea : public RenderArea {
4378 public:
chaviw7206d492017-11-10 16:16:12 -08004379 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004380 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004381 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004382 const Transform& getTransform() const override {
4383 // Make the top level transform the inverse the transform and it's parent so it sets
4384 // the whole capture back to 0,0
4385 return *new Transform(mLayer->getTransform().inverse());
4386 }
4387 Rect getBounds() const override {
4388 const Layer::State& layerState(mLayer->getDrawingState());
4389 return Rect(layerState.active.w, layerState.active.h);
4390 }
4391 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4392 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4393 bool isSecure() const override { return false; }
4394 bool needsFiltering() const override { return false; }
4395
chaviw7206d492017-11-10 16:16:12 -08004396 Rect getSourceCrop() const override {
4397 if (mCrop.isEmpty()) {
4398 return getBounds();
4399 } else {
4400 return mCrop;
4401 }
4402 }
chaviwa76b2712017-09-20 12:02:26 -07004403 bool getWideColorSupport() const override { return false; }
4404 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4405
4406 private:
chaviw7206d492017-11-10 16:16:12 -08004407 const sp<Layer> mLayer;
4408 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004409 };
4410
4411 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4412 auto parent = layerHandle->owner.promote();
4413
chaviw7206d492017-11-10 16:16:12 -08004414 if (parent == nullptr || parent->isPendingRemoval()) {
4415 ALOGE("captureLayers called with a removed parent");
4416 return NAME_NOT_FOUND;
4417 }
4418
4419 Rect crop(sourceCrop);
4420 if (sourceCrop.width() <= 0) {
4421 crop.left = 0;
4422 crop.right = parent->getCurrentState().active.w;
4423 }
4424
4425 if (sourceCrop.height() <= 0) {
4426 crop.top = 0;
4427 crop.bottom = parent->getCurrentState().active.h;
4428 }
4429
4430 int32_t reqWidth = crop.width() * frameScale;
4431 int32_t reqHeight = crop.height() * frameScale;
4432
4433 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4434
chaviwa76b2712017-09-20 12:02:26 -07004435 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4436 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4437 if (!layer->isVisible()) {
4438 return;
4439 }
4440 visitor(layer);
4441 });
4442 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004443 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004444}
4445
4446status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4447 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004448 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004449 bool useIdentityTransform) {
4450 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004451
chaviwa76b2712017-09-20 12:02:26 -07004452 renderArea.updateDimensions();
4453
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004454 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4455 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4456 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4457 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004458
4459 // This mutex protects syncFd and captureResult for communication of the return values from the
4460 // main thread back to this Binder thread
4461 std::mutex captureMutex;
4462 std::condition_variable captureCondition;
4463 std::unique_lock<std::mutex> captureLock(captureMutex);
4464 int syncFd = -1;
4465 std::optional<status_t> captureResult;
4466
Robert Carr03480e22018-01-04 16:02:06 -08004467 const int uid = IPCThreadState::self()->getCallingUid();
4468 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4469
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004470 sp<LambdaMessage> message = new LambdaMessage([&]() {
4471 // If there is a refresh pending, bug out early and tell the binder thread to try again
4472 // after the refresh.
4473 if (mRefreshPending) {
4474 ATRACE_NAME("Skipping screenshot for now");
4475 std::unique_lock<std::mutex> captureLock(captureMutex);
4476 captureResult = std::make_optional<status_t>(EAGAIN);
4477 captureCondition.notify_one();
4478 return;
4479 }
4480
4481 status_t result = NO_ERROR;
4482 int fd = -1;
4483 {
4484 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004485 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004486 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004487 }
4488
4489 {
4490 std::unique_lock<std::mutex> captureLock(captureMutex);
4491 syncFd = fd;
4492 captureResult = std::make_optional<status_t>(result);
4493 captureCondition.notify_one();
4494 }
4495 });
4496
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004497 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004498 if (result == NO_ERROR) {
4499 captureCondition.wait(captureLock, [&]() { return captureResult; });
4500 while (*captureResult == EAGAIN) {
4501 captureResult.reset();
4502 result = postMessageAsync(message);
4503 if (result != NO_ERROR) {
4504 return result;
4505 }
4506 captureCondition.wait(captureLock, [&]() { return captureResult; });
4507 }
4508 result = *captureResult;
4509 }
4510
4511 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004512 sync_wait(syncFd, -1);
4513 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004514 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004515
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004516 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004517}
4518
chaviwa76b2712017-09-20 12:02:26 -07004519void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4520 TraverseLayersFunction traverseLayers, bool yswap,
4521 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004522 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004523
Mathias Agopian3f844832013-08-07 21:24:32 -07004524 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004525
4526 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004527 const auto raWidth = renderArea.getWidth();
4528 const auto raHeight = renderArea.getHeight();
4529
4530 const auto reqWidth = renderArea.getReqWidth();
4531 const auto reqHeight = renderArea.getReqHeight();
4532 Rect sourceCrop = renderArea.getSourceCrop();
4533
4534 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4535 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004536
Dan Stozac1879002014-05-22 15:59:05 -07004537 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004538 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004539 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004540 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004541 }
4542
4543 // ensure that sourceCrop is inside screen
4544 if (sourceCrop.left < 0) {
4545 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4546 }
chaviwa76b2712017-09-20 12:02:26 -07004547 if (sourceCrop.right > raWidth) {
4548 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004549 }
4550 if (sourceCrop.top < 0) {
4551 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4552 }
chaviwa76b2712017-09-20 12:02:26 -07004553 if (sourceCrop.bottom > raHeight) {
4554 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004555 }
4556
chaviwa76b2712017-09-20 12:02:26 -07004557 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004558 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4559 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004560
Mathias Agopian180f10d2013-04-10 22:55:41 -07004561 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004562 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004563
4564 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004565 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4566 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004567 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004568
4569 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004570 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004571
chaviwa76b2712017-09-20 12:02:26 -07004572 traverseLayers([&](Layer* layer) {
4573 if (filtering) layer->setFiltering(true);
4574 layer->draw(renderArea, useIdentityTransform);
4575 if (filtering) layer->setFiltering(false);
4576 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004577}
4578
chaviwa76b2712017-09-20 12:02:26 -07004579status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4580 TraverseLayersFunction traverseLayers,
4581 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004582 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004583 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004584 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004585 ATRACE_CALL();
4586
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004587 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004588
4589 traverseLayers([&](Layer* layer) {
4590 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4591 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004592
Robert Carr03480e22018-01-04 16:02:06 -08004593 // We allow the system server to take screenshots of secure layers for
4594 // use in situations like the Screen-rotation animation and place
4595 // the impetus on WindowManager to not persist them.
4596 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004597 ALOGW("FB is protected: PERMISSION_DENIED");
4598 return PERMISSION_DENIED;
4599 }
4600
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004601 // this binds the given EGLImage as a framebuffer for the
4602 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004603 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4604 if (bufferBond.getStatus() != NO_ERROR) {
4605 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004606 return INVALID_OPERATION;
4607 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004608
Dan Stozaabcda352017-06-01 14:37:39 -07004609 // this will in fact render into our dequeued buffer
4610 // via an FBO, which means we didn't have to create
4611 // an EGLSurface and therefore we're not
4612 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004613 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004614
Dan Stozaabcda352017-06-01 14:37:39 -07004615 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004616 getRenderEngine().finish();
4617 *outSyncFd = -1;
4618
chaviwa76b2712017-09-20 12:02:26 -07004619 const auto reqWidth = renderArea.getReqWidth();
4620 const auto reqHeight = renderArea.getReqHeight();
4621
Dan Stozaabcda352017-06-01 14:37:39 -07004622 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4623 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004624 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004625 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004626 } else {
4627 base::unique_fd syncFd = getRenderEngine().flush();
4628 if (syncFd < 0) {
4629 getRenderEngine().finish();
4630 }
4631 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004632 }
4633
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004634 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004635}
4636
Mathias Agopiand5556842013-09-19 17:08:37 -07004637void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004638 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004639 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004640 for (size_t y = 0; y < h; y++) {
4641 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4642 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004643 if (p[x] != 0xFF000000) return;
4644 }
4645 }
chaviwa76b2712017-09-20 12:02:26 -07004646 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004647
Robert Carr2047fae2016-11-28 14:09:09 -08004648 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004649 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004650 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004651 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4652 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4653 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4654 static_cast<float>(state.color.a));
4655 i++;
4656 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004657 }
4658}
4659
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004660// ---------------------------------------------------------------------------
4661
Dan Stoza412903f2017-04-27 13:42:17 -07004662void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4663 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004664}
4665
Dan Stoza412903f2017-04-27 13:42:17 -07004666void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4667 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004668}
4669
chaviwa76b2712017-09-20 12:02:26 -07004670void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4671 int32_t maxLayerZ,
4672 const LayerVector::Visitor& visitor) {
4673 // We loop through the first level of layers without traversing,
4674 // as we need to interpret min/max layer Z in the top level Z space.
4675 for (const auto& layer : mDrawingState.layersSortedByZ) {
4676 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4677 continue;
4678 }
4679 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004680 // relative layers are traversed in Layer::traverseInZOrder
4681 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004682 continue;
4683 }
4684 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004685 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4686 return;
4687 }
chaviwa76b2712017-09-20 12:02:26 -07004688 if (!layer->isVisible()) {
4689 return;
4690 }
4691 visitor(layer);
4692 });
4693 }
4694}
4695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004696}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004697
4698
4699#if defined(__gl_h_)
4700#error "don't include gl/gl.h in this file"
4701#endif
4702
4703#if defined(__gl2_h_)
4704#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004705#endif