blob: 1e0b67df67a4d00ff8126feb335b27a5cb1e3e9b [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
David Sodman0c69cad2017-08-21 12:12:51 -070073#include "BufferLayer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070075#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
chaviw1d044282017-09-27 12:19:28 -070092#include <layerproto/LayerProtoParser.h>
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094#define DISPLAY_COUNT 1
95
Mathias Agopianfee2b462013-07-03 12:34:01 -070096/*
97 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
98 * black pixels.
99 */
100#define DEBUG_SCREENSHOTS false
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Steven Thomasb02664d2017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700132bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
Kalle Raitaa099a242017-01-11 11:17:29 -0800141
142std::string getHwcServiceName() {
143 char value[PROPERTY_VALUE_MAX] = {};
144 property_get("debug.sf.hwc_service_name", value, "default");
145 ALOGI("Using HWComposer service: '%s'", value);
146 return std::string(value);
147}
148
149bool useTrebleTestingOverride() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.treble_testing_override", value, "false");
152 ALOGI("Treble testing override: '%s'", value);
153 return std::string(value) == "true";
154}
155
David Sodmanbc815282017-11-05 18:57:52 -0800156SurfaceFlingerBE::SurfaceFlingerBE()
157 : mHwcServiceName(getHwcServiceName()),
158 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800162 mComposerSequenceId(0) {
163}
164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800165SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700166 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700168 mTransactionPending(false),
169 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700170 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700171 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700172 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800174 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800176 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800177 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700180 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700181 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700182 mDebugInSwapBuffers(0),
183 mLastSwapBufferTime(0),
184 mDebugInTransaction(0),
185 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700186 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700187 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800188 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000189 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700190 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700191 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700192 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800193 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800194 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 mVrFlingerRequestsDisplay(false),
David Sodman105b7dc2017-11-04 20:28:14 -0700196 mMainThreadId(std::this_thread::get_id())
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800198 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800199
200 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
201 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
202
203 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
205
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800206 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700209 useContextPriority = getBool< ISurfaceFlingerConfigs,
210 &ISurfaceFlingerConfigs::useContextPriority>(false);
211
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
213 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
214
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
216 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
217
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
219 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
220
Steven Thomas050b2c82017-03-06 11:45:16 -0800221 // Vr flinger is only enabled on Daydream ready devices.
222 useVrFlinger = getBool< ISurfaceFlingerConfigs,
223 &ISurfaceFlingerConfigs::useVrFlinger>(false);
224
Fabien Sanglard1971b632017-03-10 14:50:03 -0800225 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
226 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
227
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228 hasWideColorDisplay =
229 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
230
David Sodman99974d22017-11-28 12:04:33 -0800231 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 // debugging stuff...
234 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700237 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 property_get("debug.sf.showupdates", value, "0");
240 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700242 property_get("debug.sf.ddms", value, "0");
243 mDebugDDMS = atoi(value);
244 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700245 if (!startDdmConnection()) {
246 // start failed, and DDMS debugging not enabled
247 mDebugDDMS = 0;
248 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700249 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700250 ALOGI_IF(mDebugRegion, "showupdates enabled");
251 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700252
253 property_get("debug.sf.disable_backpressure", value, "0");
254 mPropagateBackpressure = !atoi(value);
255 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700256
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800257 property_get("debug.sf.enable_hwc_vds", value, "0");
258 mUseHwcVirtualDisplays = atoi(value);
259 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800260
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800261 property_get("ro.sf.disable_triple_buffer", value, "1");
262 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800263 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700264
Romain Guy11d63f42017-07-20 12:47:14 -0700265 // We should be reading 'persist.sys.sf.color_saturation' here
266 // but since /data may be encrypted, we need to wait until after vold
267 // comes online to attempt to read the property. The property is
268 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800269
270 if (useTrebleTestingOverride()) {
271 // Without the override SurfaceFlinger cannot connect to HIDL
272 // services that are not listed in the manifests. Considered
273 // deriving the setting from the set service name, but it
274 // would be brittle if the name that's not 'default' is used
275 // for production purposes later on.
276 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278}
279
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800280void SurfaceFlinger::onFirstRef()
281{
282 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800283}
284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285SurfaceFlinger::~SurfaceFlinger()
286{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287}
288
Dan Stozac7014012014-02-14 15:03:43 -0800289void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800290{
291 // the window manager died on us. prepare its eulogy.
292
Andy McFadden13a082e2012-08-24 10:16:42 -0700293 // restore initial conditions (default device unblank, etc)
294 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800295
296 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700297 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800298}
299
Robert Carr1db73f62016-12-21 12:58:51 -0800300static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700301 status_t err = client->initCheck();
302 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800303 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 }
Robert Carr1db73f62016-12-21 12:58:51 -0800305 return nullptr;
306}
307
308sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
309 return initClient(new Client(this));
310}
311
312sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
313 const sp<IGraphicBufferProducer>& gbp) {
314 if (authenticateSurfaceTexture(gbp) == false) {
315 return nullptr;
316 }
317 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
318 if (layer == nullptr) {
319 return nullptr;
320 }
321
322 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323}
324
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700325sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
326 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700327{
328 class DisplayToken : public BBinder {
329 sp<SurfaceFlinger> flinger;
330 virtual ~DisplayToken() {
331 // no more references, this display must be terminated
332 Mutex::Autolock _l(flinger->mStateLock);
333 flinger->mCurrentState.displays.removeItem(this);
334 flinger->setTransactionFlags(eDisplayTransactionNeeded);
335 }
336 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700337 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700338 : flinger(flinger) {
339 }
340 };
341
342 sp<BBinder> token = new DisplayToken(this);
343
344 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700345 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700346 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700347 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700348 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700349 return token;
350}
351
Jesse Hall6c913be2013-08-08 12:15:49 -0700352void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
353 Mutex::Autolock _l(mStateLock);
354
355 ssize_t idx = mCurrentState.displays.indexOfKey(display);
356 if (idx < 0) {
357 ALOGW("destroyDisplay: invalid display token");
358 return;
359 }
360
361 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
362 if (!info.isVirtualDisplay()) {
363 ALOGE("destroyDisplay called for non-virtual display");
364 return;
365 }
Irvelffc9efc2016-07-27 15:16:37 -0700366 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700367 mCurrentState.displays.removeItemsAt(idx);
368 setTransactionFlags(eDisplayTransactionNeeded);
369}
370
Jesse Hall692c7232012-11-08 15:41:56 -0800371void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800372 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800373 ALOGW_IF(mBuiltinDisplays[type],
374 "Overwriting display token for display type %d", type);
375 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800376 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700377 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800378 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700379 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800380}
381
Mathias Agopiane57f2922012-08-09 16:29:12 -0700382sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700383 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700384 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800385 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700386 }
Jesse Hall692c7232012-11-08 15:41:56 -0800387 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700388}
389
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390void SurfaceFlinger::bootFinished()
391{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700392 if (mStartPropertySetThread->join() != NO_ERROR) {
393 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800394 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 const nsecs_t now = systemTime();
396 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000397 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700398
399 // wait patiently for the window manager death
400 const String16 name("window");
401 sp<IBinder> window(defaultServiceManager()->getService(name));
402 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700403 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700404 }
405
Steven Thomas050b2c82017-03-06 11:45:16 -0800406 if (mVrFlinger) {
407 mVrFlinger->OnBootFinished();
408 }
409
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700410 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700411 // formerly we would just kill the process, but we now ask it to exit so it
412 // can choose where to stop the animation.
413 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700414
415 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
416 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
417 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700418
Thierry Strudel2924d012017-08-14 15:19:37 -0700419 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700420 readPersistentProperties();
421 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700422 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian3f844832013-08-07 21:24:32 -0700425void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700426 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700427 RenderEngine& engine;
428 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700429 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700430 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
431 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700432 }
433 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700434 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700435 return true;
436 }
437 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700438 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700439}
440
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441class DispSyncSource : public VSyncSource, private DispSync::Callback {
442public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700443 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000444 const char* name) :
445 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700446 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000448 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
449 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700450 mDispSync(dispSync),
451 mCallbackMutex(),
452 mCallback(),
453 mVsyncMutex(),
454 mPhaseOffset(phaseOffset),
455 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700456
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700457 virtual ~DispSyncSource() {}
458
459 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700460 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000462 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463 static_cast<DispSync::Callback*>(this));
464 if (err != NO_ERROR) {
465 ALOGE("error registering vsync callback: %s (%d)",
466 strerror(-err), err);
467 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700468 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469 } else {
470 status_t err = mDispSync->removeEventListener(
471 static_cast<DispSync::Callback*>(this));
472 if (err != NO_ERROR) {
473 ALOGE("error unregistering vsync callback: %s (%d)",
474 strerror(-err), err);
475 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700476 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700477 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 }
480
481 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700482 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483 mCallback = callback;
484 }
485
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700486 virtual void setPhaseOffset(nsecs_t phaseOffset) {
487 Mutex::Autolock lock(mVsyncMutex);
488
489 // Normalize phaseOffset to [0, period)
490 auto period = mDispSync->getPeriod();
491 phaseOffset %= period;
492 if (phaseOffset < 0) {
493 // If we're here, then phaseOffset is in (-period, 0). After this
494 // operation, it will be in (0, period)
495 phaseOffset += period;
496 }
497 mPhaseOffset = phaseOffset;
498
499 // If we're not enabled, we don't need to mess with the listeners
500 if (!mEnabled) {
501 return;
502 }
503
504 // Remove the listener with the old offset
505 status_t err = mDispSync->removeEventListener(
506 static_cast<DispSync::Callback*>(this));
507 if (err != NO_ERROR) {
508 ALOGE("error unregistering vsync callback: %s (%d)",
509 strerror(-err), err);
510 }
511
512 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000513 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700514 static_cast<DispSync::Callback*>(this));
515 if (err != NO_ERROR) {
516 ALOGE("error registering vsync callback: %s (%d)",
517 strerror(-err), err);
518 }
519 }
520
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521private:
522 virtual void onDispSyncEvent(nsecs_t when) {
523 sp<VSyncSource::Callback> callback;
524 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700525 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 callback = mCallback;
527
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 if (mTraceVsync) {
529 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
533
Peiyong Lin566a3b42018-01-09 18:22:43 -0800534 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 callback->onVSyncEvent(when);
536 }
537 }
538
Tim Murray4a4e4a22016-04-19 16:29:23 +0000539 const char* const mName;
540
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541 int mValue;
542
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700543 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700544 const String8 mVsyncOnLabel;
545 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700546
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700548
549 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551
552 Mutex mVsyncMutex; // Protects the following
553 nsecs_t mPhaseOffset;
554 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555};
556
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700557class InjectVSyncSource : public VSyncSource {
558public:
559 InjectVSyncSource() {}
560
561 virtual ~InjectVSyncSource() {}
562
563 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
564 std::lock_guard<std::mutex> lock(mCallbackMutex);
565 mCallback = callback;
566 }
567
568 virtual void onInjectSyncEvent(nsecs_t when) {
569 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700570 if (mCallback) {
571 mCallback->onVSyncEvent(when);
572 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700573 }
574
575 virtual void setVSyncEnabled(bool) {}
576 virtual void setPhaseOffset(nsecs_t) {}
577
578private:
579 std::mutex mCallbackMutex; // Protects the following
580 sp<VSyncSource::Callback> mCallback;
581};
582
Wei Wangf9b05ee2017-07-19 20:59:39 -0700583// Do not call property_set on main thread which will be blocked by init
584// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700586 ALOGI( "SurfaceFlinger's main thread ready to run. "
587 "Initializing graphics H/W...");
588
Thierry Strudel2924d012017-08-14 15:19:37 -0700589 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900590
Steven Thomasb02664d2017-07-26 18:48:28 -0700591 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800592
Steven Thomasb02664d2017-07-26 18:48:28 -0700593 // start the EventThread
David Sodman99974d22017-11-28 12:04:33 -0800594 sp<VSyncSource> vsyncSrc =
595 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 mEventThread = new EventThread(vsyncSrc, *this, false);
David Sodman99974d22017-11-28 12:04:33 -0800597 sp<VSyncSource> sfVsyncSrc =
598 new DispSyncSource(&mPrimaryDispSync, SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
600 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
603 struct sched_param param = {0};
604 param.sched_priority = 2;
605 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
606 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
607 }
608 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
609 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 }
611
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 // Get a RenderEngine for the given display / config (can't fail)
David Sodmanbc815282017-11-05 18:57:52 -0800613 getBE().mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700614 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800615 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700616
617 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
618 "Starting with vr flinger active is not currently supported.");
David Sodmanbc815282017-11-05 18:57:52 -0800619 getBE().mHwc.reset(new HWComposer(getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -0700620 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800621 // Process any initial hotplug and resulting display changes.
622 processDisplayHotplugEventsLocked();
623 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
624 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800625
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 if (useVrFlinger) {
627 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700628 // This callback is called from the vr flinger dispatch thread. We
629 // need to call signalTransaction(), which requires holding
630 // mStateLock when we're not on the main thread. Acquiring
631 // mStateLock from the vr flinger dispatch thread might trigger a
632 // deadlock in surface flinger (see b/66916578), so post a message
633 // to be handled on the main thread instead.
634 sp<LambdaMessage> message = new LambdaMessage([=]() {
635 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
636 mVrFlingerRequestsDisplay = requestDisplay;
637 signalTransaction();
638 });
639 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 };
David Sodman105b7dc2017-11-04 20:28:14 -0700641 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
642 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800643 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800644 if (!mVrFlinger) {
645 ALOGE("Failed to start vrflinger");
646 }
647 }
648
Jamie Gennisd1700752013-10-14 12:22:52 -0700649 mEventControlThread = new EventControlThread(this);
650 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
651
Mathias Agopian92a979a2012-08-02 18:32:23 -0700652 // initialize our drawing state
653 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700654
Andy McFadden13a082e2012-08-24 10:16:42 -0700655 // set initial conditions (e.g. unblank default device)
656 initializeDisplays();
657
David Sodmanbc815282017-11-05 18:57:52 -0800658 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700659
Wei Wangf9b05ee2017-07-19 20:59:39 -0700660 // Inform native graphics APIs whether the present timestamp is supported:
661 if (getHwComposer().hasCapability(
662 HWC2::Capability::PresentFenceIsNotReliable)) {
663 mStartPropertySetThread = new StartPropertySetThread(false);
664 } else {
665 mStartPropertySetThread = new StartPropertySetThread(true);
666 }
667
668 if (mStartPropertySetThread->Start() != NO_ERROR) {
669 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800670 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800671
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700673}
674
Romain Guy11d63f42017-07-20 12:47:14 -0700675void SurfaceFlinger::readPersistentProperties() {
676 char value[PROPERTY_VALUE_MAX];
677
678 property_get("persist.sys.sf.color_saturation", value, "1.0");
679 mSaturation = atof(value);
680 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100681
682 property_get("persist.sys.sf.native_mode", value, "0");
683 mForceNativeColorMode = atoi(value) == 1;
684 if (mForceNativeColorMode) {
685 ALOGV("Forcing native color mode");
686 }
Romain Guy11d63f42017-07-20 12:47:14 -0700687}
688
Mathias Agopiana67e4182012-06-19 17:26:12 -0700689void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800690 // Start boot animation service by setting a property mailbox
691 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800693 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694 if (mStartPropertySetThread->join() != NO_ERROR) {
695 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800696 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700697}
698
Mathias Agopian875d8e12013-06-07 15:35:48 -0700699size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800700 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800704 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800708
Jamie Gennis582270d2011-08-17 18:19:00 -0700709bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800710 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800711 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800712 return authenticateSurfaceTextureLocked(bufferProducer);
713}
714
715bool SurfaceFlinger::authenticateSurfaceTextureLocked(
716 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800717 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700718 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800719}
720
Brian Anderson6b376712017-04-04 10:51:39 -0700721status_t SurfaceFlinger::getSupportedFrameTimestamps(
722 std::vector<FrameEvent>* outSupported) const {
723 *outSupported = {
724 FrameEvent::REQUESTED_PRESENT,
725 FrameEvent::ACQUIRE,
726 FrameEvent::LATCH,
727 FrameEvent::FIRST_REFRESH_START,
728 FrameEvent::LAST_REFRESH_START,
729 FrameEvent::GPU_COMPOSITION_DONE,
730 FrameEvent::DEQUEUE_READY,
731 FrameEvent::RELEASE,
732 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700733 ConditionalLock _l(mStateLock,
734 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700735 if (!getHwComposer().hasCapability(
736 HWC2::Capability::PresentFenceIsNotReliable)) {
737 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
738 }
739 return NO_ERROR;
740}
741
Dan Stoza7f7da322014-05-02 15:26:25 -0700742status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
743 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800744 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700745 return BAD_VALUE;
746 }
747
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500748 if (!display.get())
749 return NAME_NOT_FOUND;
750
Jesse Hall692c7232012-11-08 15:41:56 -0800751 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700752 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800753 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700754 type = i;
755 break;
756 }
757 }
758
759 if (type < 0) {
760 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700761 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762
Mathias Agopian8b736f12012-08-13 17:54:26 -0700763 // TODO: Not sure if display density should handled by SF any longer
764 class Density {
765 static int getDensityFromProperty(char const* propName) {
766 char property[PROPERTY_VALUE_MAX];
767 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800768 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700769 density = atoi(property);
770 }
771 return density;
772 }
773 public:
774 static int getEmuDensity() {
775 return getDensityFromProperty("qemu.sf.lcd_density"); }
776 static int getBuildDensity() {
777 return getDensityFromProperty("ro.sf.lcd_density"); }
778 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700779
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700781
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800784 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700785 DisplayInfo info = DisplayInfo();
786
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787 float xdpi = hwConfig->getDpiX();
788 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700789
790 if (type == DisplayDevice::DISPLAY_PRIMARY) {
791 // The density of the device is provided by a build property
792 float density = Density::getBuildDensity() / 160.0f;
793 if (density == 0) {
794 // the build doesn't provide a density -- this is wrong!
795 // use xdpi instead
796 ALOGE("ro.sf.lcd_density must be defined as a build property");
797 density = xdpi / 160.0f;
798 }
799 if (Density::getEmuDensity()) {
800 // if "qemu.sf.lcd_density" is specified, it overrides everything
801 xdpi = ydpi = density = Density::getEmuDensity();
802 density /= 160.0f;
803 }
804 info.density = density;
805
806 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700807 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000808 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 } else {
810 // TODO: where should this value come from?
811 static const int TV_DENSITY = 213;
812 info.density = TV_DENSITY / 160.0f;
813 info.orientation = 0;
814 }
815
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816 info.w = hwConfig->getWidth();
817 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 info.xdpi = xdpi;
819 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900821 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822
Andy McFadden91b2ca82014-06-13 14:04:23 -0700823 // This is how far in advance a buffer must be queued for
824 // presentation at a given time. If you want a buffer to appear
825 // on the screen at time N, you must submit the buffer before
826 // (N - presentationDeadline).
827 //
828 // Normally it's one full refresh period (to give SF a chance to
829 // latch the buffer), but this can be reduced by configuring a
830 // DispSync offset. Any additional delays introduced by the hardware
831 // composer or panel must be accounted for here.
832 //
833 // We add an additional 1ms to allow for processing time and
834 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800836 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
838 // All non-virtual displays are currently considered secure.
839 info.secure = true;
840
Michael Wright28f24d02016-07-12 13:30:53 -0700841 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 return NO_ERROR;
845}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700846
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800847status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700848 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800849 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700850 return BAD_VALUE;
851 }
852
853 // FIXME for now we always return stats for the primary display
854 memset(stats, 0, sizeof(*stats));
855 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
856 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
857 return NO_ERROR;
858}
859
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700860int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800861 if (display == nullptr) {
862 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800863 return BAD_VALUE;
864 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700865
866 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800867 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700868 return device->getActiveConfig();
869 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700870
Dan Stoza24a42e92015-03-09 10:04:11 -0700871 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700872}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700873
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700874void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
875 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
876 this);
877 int32_t type = hw->getDisplayType();
878 int currentMode = hw->getActiveConfig();
879
880 if (mode == currentMode) {
881 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
882 return;
883 }
884
885 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
886 ALOGW("Trying to set config for virtual display");
887 return;
888 }
889
890 hw->setActiveConfig(mode);
891 getHwComposer().setActiveConfig(type, mode);
892}
893
894status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
895 class MessageSetActiveConfig: public MessageBase {
896 SurfaceFlinger& mFlinger;
897 sp<IBinder> mDisplay;
898 int mMode;
899 public:
900 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
901 int mode) :
902 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
903 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700904 Vector<DisplayInfo> configs;
905 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700906 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700907 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700908 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700909 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700910 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700911 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700914 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700915 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
916 ALOGW("Attempt to set active config = %d for virtual display",
917 mMode);
918 } else {
919 mFlinger.setActiveConfigInternal(hw, mMode);
920 }
921 return true;
922 }
923 };
924 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
925 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700926 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700927}
Michael Wright28f24d02016-07-12 13:30:53 -0700928status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
929 Vector<android_color_mode_t>* outColorModes) {
930 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
931 return BAD_VALUE;
932 }
933
934 if (!display.get()) {
935 return NAME_NOT_FOUND;
936 }
937
938 int32_t type = NAME_NOT_FOUND;
939 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
940 if (display == mBuiltinDisplays[i]) {
941 type = i;
942 break;
943 }
944 }
945
946 if (type < 0) {
947 return type;
948 }
949
Steven Thomas6d8110b2017-08-31 18:24:21 -0700950 std::vector<android_color_mode_t> modes;
951 {
952 ConditionalLock _l(mStateLock,
953 std::this_thread::get_id() != mMainThreadId);
954 modes = getHwComposer().getColorModes(type);
955 }
Michael Wright28f24d02016-07-12 13:30:53 -0700956 outColorModes->clear();
957 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
958
959 return NO_ERROR;
960}
961
962android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700963 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700964 if (device != nullptr) {
965 return device->getActiveColorMode();
966 }
967 return static_cast<android_color_mode_t>(BAD_VALUE);
968}
969
970void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
971 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700972 int32_t type = hw->getDisplayType();
973 android_color_mode_t currentMode = hw->getActiveColorMode();
974
975 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700976 return;
977 }
978
979 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
980 ALOGW("Trying to set config for virtual display");
981 return;
982 }
983
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600984 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
985 hw->getDisplayType());
986
Michael Wright28f24d02016-07-12 13:30:53 -0700987 hw->setActiveColorMode(mode);
988 getHwComposer().setActiveColorMode(type, mode);
989}
990
991
992status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
993 android_color_mode_t colorMode) {
994 class MessageSetActiveColorMode: public MessageBase {
995 SurfaceFlinger& mFlinger;
996 sp<IBinder> mDisplay;
997 android_color_mode_t mMode;
998 public:
999 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1000 android_color_mode_t mode) :
1001 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1002 virtual bool handler() {
1003 Vector<android_color_mode_t> modes;
1004 mFlinger.getDisplayColorModes(mDisplay, &modes);
1005 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1006 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001007 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1008 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001009 return true;
1010 }
1011 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1012 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001013 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1014 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001015 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001016 ALOGW("Attempt to set active color mode %s %d for virtual display",
1017 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001018 } else {
1019 mFlinger.setActiveColorModeInternal(hw, mMode);
1020 }
1021 return true;
1022 }
1023 };
1024 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1025 postMessageSync(msg);
1026 return NO_ERROR;
1027}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001028
Svetoslavd85084b2014-03-20 10:28:31 -07001029status_t SurfaceFlinger::clearAnimationFrameStats() {
1030 Mutex::Autolock _l(mStateLock);
1031 mAnimFrameTracker.clearStats();
1032 return NO_ERROR;
1033}
1034
1035status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1036 Mutex::Autolock _l(mStateLock);
1037 mAnimFrameTracker.getStats(outStats);
1038 return NO_ERROR;
1039}
1040
Dan Stozac4f471e2016-03-24 09:31:08 -07001041status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1042 HdrCapabilities* outCapabilities) const {
1043 Mutex::Autolock _l(mStateLock);
1044
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001045 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001046 if (displayDevice == nullptr) {
1047 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1048 return BAD_VALUE;
1049 }
1050
1051 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001052 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001053 if (capabilities) {
1054 std::swap(*outCapabilities, *capabilities);
1055 } else {
1056 return BAD_VALUE;
1057 }
1058
1059 return NO_ERROR;
1060}
1061
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001062status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001063 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1064 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001065
Chia-I Wu90f669f2017-10-05 14:24:41 -07001066 if (mInjectVSyncs == enable) {
1067 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001068 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069
1070 if (enable) {
1071 ALOGV("VSync Injections enabled");
1072 if (mVSyncInjector.get() == nullptr) {
1073 mVSyncInjector = new InjectVSyncSource();
1074 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1075 }
1076 mEventQueue.setEventThread(mInjectorEventThread);
1077 } else {
1078 ALOGV("VSync Injections disabled");
1079 mEventQueue.setEventThread(mSFEventThread);
1080 }
1081
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001082 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 });
1084 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001089 Mutex::Autolock _l(mStateLock);
1090
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001091 if (!mInjectVSyncs) {
1092 ALOGE("VSync Injections not enabled");
1093 return BAD_VALUE;
1094 }
1095 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1096 ALOGV("Injecting VSync inside SurfaceFlinger");
1097 mVSyncInjector->onInjectSyncEvent(when);
1098 }
1099 return NO_ERROR;
1100}
1101
Kalle Raitaa099a242017-01-11 11:17:29 -08001102status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1103 IPCThreadState* ipc = IPCThreadState::self();
1104 const int pid = ipc->getCallingPid();
1105 const int uid = ipc->getCallingUid();
1106 if ((uid != AID_SHELL) &&
1107 !PermissionCache::checkPermission(sDump, pid, uid)) {
1108 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1109 return PERMISSION_DENIED;
1110 }
1111
1112 // Try to acquire a lock for 1s, fail gracefully
1113 const status_t err = mStateLock.timedLock(s2ns(1));
1114 const bool locked = (err == NO_ERROR);
1115 if (!locked) {
1116 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1117 return TIMED_OUT;
1118 }
1119
1120 outLayers->clear();
1121 mCurrentState.traverseInZOrder([&](Layer* layer) {
1122 outLayers->push_back(layer->getLayerDebugInfo());
1123 });
1124
1125 mStateLock.unlock();
1126 return NO_ERROR;
1127}
1128
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001129// ----------------------------------------------------------------------------
1130
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001131sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1132 ISurfaceComposer::VsyncSource vsyncSource) {
1133 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1134 return mSFEventThread->createEventConnection();
1135 } else {
1136 return mEventThread->createEventConnection();
1137 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001138}
1139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001140// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001141
1142void SurfaceFlinger::waitForEvent() {
1143 mEventQueue.waitMessage();
1144}
1145
1146void SurfaceFlinger::signalTransaction() {
1147 mEventQueue.invalidate();
1148}
1149
1150void SurfaceFlinger::signalLayerUpdate() {
1151 mEventQueue.invalidate();
1152}
1153
1154void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001155 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156 mEventQueue.refresh();
1157}
1158
1159status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001160 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161 return mEventQueue.postMessage(msg, reltime);
1162}
1163
1164status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001165 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166 status_t res = mEventQueue.postMessage(msg, reltime);
1167 if (res == NO_ERROR) {
1168 msg->wait();
1169 }
1170 return res;
1171}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001172
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001174 do {
1175 waitForEvent();
1176 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001177}
1178
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179void SurfaceFlinger::enableHardwareVsync() {
1180 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001183 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1184 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001186 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001187}
1188
Jesse Hall948fe0c2013-10-14 12:56:09 -07001189void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 Mutex::Autolock _l(mHWVsyncLock);
1191
Jesse Hall948fe0c2013-10-14 12:56:09 -07001192 if (makeAvailable) {
1193 mHWVsyncAvailable = true;
1194 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001195 // Hardware vsync is not currently available, so abort the resync
1196 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197 return;
1198 }
1199
David Sodman105b7dc2017-11-04 20:28:14 -07001200 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001201 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202
1203 mPrimaryDispSync.reset();
1204 mPrimaryDispSync.setPeriod(period);
1205
1206 if (!mPrimaryHWVsyncEnabled) {
1207 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001208 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1209 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210 mPrimaryHWVsyncEnabled = true;
1211 }
1212}
1213
Jesse Hall948fe0c2013-10-14 12:56:09 -07001214void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215 Mutex::Autolock _l(mHWVsyncLock);
1216 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001217 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1218 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219 mPrimaryDispSync.endResync();
1220 mPrimaryHWVsyncEnabled = false;
1221 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001222 if (makeUnavailable) {
1223 mHWVsyncAvailable = false;
1224 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225}
1226
Tim Murray4a4e4a22016-04-19 16:29:23 +00001227void SurfaceFlinger::resyncWithRateLimit() {
1228 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001229
1230 // No explicit locking is needed here since EventThread holds a lock while calling this method
1231 static nsecs_t sLastResyncAttempted = 0;
1232 const nsecs_t now = systemTime();
1233 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001234 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235 }
Dan Stoza57164302017-05-08 14:03:54 -07001236 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237}
1238
Steven Thomasb02664d2017-07-26 18:48:28 -07001239void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1240 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001241 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001242 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001243 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 return;
1245 }
1246
1247 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001248 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 return;
1250 }
1251
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253
Jamie Gennisd1700752013-10-14 12:22:52 -07001254 { // Scope for the lock
1255 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001256 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001257 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001259 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001260
1261 if (needsHwVsync) {
1262 enableHardwareVsync();
1263 } else {
1264 disableHardwareVsync(false);
1265 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001266}
1267
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001268void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001269 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1270 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001271}
1272
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001273void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001274 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001275 wp<IBinder> token = mBuiltinDisplays[type];
1276
1277 // All non-virtual displays are currently considered secure.
1278 const bool isSecure = true;
1279
1280 sp<IGraphicBufferProducer> producer;
1281 sp<IGraphicBufferConsumer> consumer;
1282 BufferQueue::createBufferQueue(&producer, &consumer);
1283
David Sodman105b7dc2017-11-04 20:28:14 -07001284 sp<FramebufferSurface> fbs = new FramebufferSurface(*getBE().mHwc, type, consumer);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285
1286 bool hasWideColorModes = false;
1287 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1288 for (android_color_mode_t colorMode : modes) {
1289 switch (colorMode) {
1290 case HAL_COLOR_MODE_DISPLAY_P3:
1291 case HAL_COLOR_MODE_ADOBE_RGB:
1292 case HAL_COLOR_MODE_DCI_P3:
1293 hasWideColorModes = true;
1294 break;
1295 default:
1296 break;
1297 }
1298 }
Romain Guy54f154a2017-10-24 21:40:32 +01001299 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
Chia-I Wuc670d502017-11-09 23:17:51 -08001301 token, fbs, producer, useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001302 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001303 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001304 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001305 defaultColorMode = HAL_COLOR_MODE_SRGB;
1306 }
1307 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001308 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001309
1310 // Add the primary display token to mDrawingState so we don't try to
1311 // recreate the DisplayDevice for the primary display.
1312 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1313
1314 // make the GLContext current so that we can create textures when creating
1315 // Layers (which may happens before we render something)
Chia-I Wu7f402902017-11-09 12:51:10 -08001316 hw->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317}
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1320 hwc2_display_t display, HWC2::Connection connection,
1321 bool primaryDisplay) {
1322 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1323 sequenceId, display,
1324 connection == HWC2::Connection::Connected ?
1325 "connected" : "disconnected",
1326 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001327
Lloyd Piqueba04e622017-12-14 17:11:26 -08001328 // Ignore events that do not have the right sequenceId.
1329 if (sequenceId != getBE().mComposerSequenceId) {
1330 return;
1331 }
1332
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 // Only lock if we're not on the main thread. This function is normally
1334 // called on a hwbinder thread, but for the primary display it's called on
1335 // the main thread with the state lock already held, so don't attempt to
1336 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001337 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001338
Lloyd Piqueba04e622017-12-14 17:11:26 -08001339 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection, primaryDisplay});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001340
Lloyd Piqueba04e622017-12-14 17:11:26 -08001341 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001342}
1343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344void SurfaceFlinger::onRefreshReceived(int sequenceId,
1345 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001346 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001347 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001349 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001350 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001351}
1352
Dan Stoza9e56aa02015-11-02 13:00:03 -08001353void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001354 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001356 getHwComposer().setVsyncEnabled(disp,
1357 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001358}
1359
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001361void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001363 // Clear the drawing state so that the logic inside of
1364 // handleTransactionLocked will fire. It will determine the delta between
1365 // mCurrentState and mDrawingState and re-apply all changes when we make the
1366 // transition.
1367 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001368 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001369 mDisplays.clear();
1370}
1371
Steven Thomas050b2c82017-03-06 11:45:16 -08001372void SurfaceFlinger::updateVrFlinger() {
1373 if (!mVrFlinger)
1374 return;
1375 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001376 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001377 return;
1378 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379
David Sodman105b7dc2017-11-04 20:28:14 -07001380 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 ALOGE("Vr flinger is only supported for remote hardware composer"
1382 " service connections. Ignoring request to transition to vr"
1383 " flinger.");
1384 mVrFlingerRequestsDisplay = false;
1385 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001386 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 int currentDisplayPowerMode = getDisplayDeviceLocked(
1391 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001398 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001399 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001400 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
David Sodman105b7dc2017-11-04 20:28:14 -07001402 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1403 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001404
1405 if (vrFlingerRequestsDisplay) {
1406 mVrFlinger->GrantDisplayOwnership();
1407 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001410
1411 mVisibleRegionsDirty = true;
1412 invalidateHwcGeometry();
1413
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001414 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1416 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1417 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001418
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001420 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 const nsecs_t period = activeConfig->getVsyncPeriod();
1422 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 // Use phase of 0 since phase is not known.
1425 // Use latency of 0, which will snap to the ideal latency.
1426 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 android_atomic_or(1, &mRepaintEverything);
1429 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430}
1431
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001433 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001434 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001436 bool frameMissed = !mHadClientComposition &&
1437 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438 (mPreviousPresentFence->getSignalTime() ==
1439 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001440 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001441 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001442 signalLayerUpdate();
1443 break;
1444 }
1445
Steven Thomas050b2c82017-03-06 11:45:16 -08001446 // Now that we're going to make it to the handleMessageTransaction()
1447 // call below it's safe to call updateVrFlinger(), which will
1448 // potentially trigger a display handoff.
1449 updateVrFlinger();
1450
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 bool refreshNeeded = handleMessageTransaction();
1452 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001453 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001455 // Signal a refresh if a transaction modified the window state,
1456 // a new buffer was latched, or if HWC has requested a full
1457 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458 signalRefresh();
1459 }
1460 break;
1461 }
1462 case MessageQueue::REFRESH: {
1463 handleMessageRefresh();
1464 break;
1465 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001466 }
1467}
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001470 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001472 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001476}
1477
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481}
1482
1483void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001485
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001486 mRefreshPending = false;
1487
Pablo Ceballos40845df2016-01-25 17:41:15 -08001488 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001489
Brian Andersond6927fb2016-07-23 23:37:30 -07001490 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001491 rebuildLayerStacks();
1492 setUpHWComposer();
1493 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001494 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001495 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001496 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001497
David Sodman105b7dc2017-11-04 20:28:14 -07001498 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001499
1500 mHadClientComposition = false;
1501 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1502 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1503 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001504 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001505 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001506
Dan Stoza9e56aa02015-11-02 13:00:03 -08001507 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510void SurfaceFlinger::doDebugFlashRegions()
1511{
1512 // is debugging enabled
1513 if (CC_LIKELY(!mDebugRegion))
1514 return;
1515
1516 const bool repaintEverything = mRepaintEverything;
1517 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1518 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001519 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 // transform the dirty region into this screen's coordinate space
1521 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1522 if (!dirtyRegion.isEmpty()) {
1523 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001524 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525
1526 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001528 RenderEngine& engine(getRenderEngine());
1529 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1530
Mathias Agopianda27af92012-09-13 18:17:13 -07001531 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 }
1533 }
1534 }
1535
1536 postFramebuffer();
1537
1538 if (mDebugRegion > 1) {
1539 usleep(mDebugRegion * 1000);
1540 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001541
Dan Stoza9e56aa02015-11-02 13:00:03 -08001542 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001543 auto& displayDevice = mDisplays[displayId];
1544 if (!displayDevice->isDisplayOn()) {
1545 continue;
1546 }
1547
David Sodman105b7dc2017-11-04 20:28:14 -07001548 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1549 ALOGE_IF(result != NO_ERROR,
1550 "prepareFrame for display %zd failed:"
1551 " %d (%s)",
1552 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001553 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554}
1555
Adrian Roos1e1a1282017-11-01 19:05:31 +01001556void SurfaceFlinger::doTracing(const char* where) {
1557 ATRACE_CALL();
1558 ATRACE_NAME(where);
1559 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001560 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001561 }
1562}
1563
Brian Andersond6927fb2016-07-23 23:37:30 -07001564void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001566 ATRACE_CALL();
1567 ALOGV("preComposition");
1568
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001570 mDrawingState.traverseInZOrder([&](Layer* layer) {
1571 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572 needExtraInvalidate = true;
1573 }
Robert Carr2047fae2016-11-28 14:09:09 -08001574 });
1575
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576 if (needExtraInvalidate) {
1577 signalLayerUpdate();
1578 }
1579}
1580
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581void SurfaceFlinger::updateCompositorTiming(
1582 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1583 std::shared_ptr<FenceTime>& presentFenceTime) {
1584 // Update queue of past composite+present times and determine the
1585 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001586 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001588 while (!getBE().mCompositePresentTimes.empty()) {
1589 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 // Cached values should have been updated before calling this method,
1591 // which helps avoid duplicate syscalls.
1592 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1593 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1594 break;
1595 }
1596 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001597 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 }
1599
1600 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001601 while (getBE().mCompositePresentTimes.size() > 16) {
1602 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 }
1604
Brian Andersond0010582017-03-07 13:20:31 -08001605 setCompositorTimingSnapped(
1606 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1607}
1608
1609void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1610 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611 // Integer division and modulo round toward 0 not -inf, so we need to
1612 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001613 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1615 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1616
Brian Andersond0010582017-03-07 13:20:31 -08001617 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1618 if (idealLatency <= 0) {
1619 idealLatency = vsyncInterval;
1620 }
1621
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 // Snap the latency to a value that removes scheduling jitter from the
1623 // composition and present times, which often have >1ms of jitter.
1624 // Reducing jitter is important if an app attempts to extrapolate
1625 // something (such as user input) to an accurate diasplay time.
1626 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1627 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001628 nsecs_t bias = vsyncInterval / 2;
1629 int64_t extraVsyncs =
1630 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1631 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1632 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633
David Sodman99974d22017-11-28 12:04:33 -08001634 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1635 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1636 getBE().mCompositorTiming.interval = vsyncInterval;
1637 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001638}
1639
1640void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001642 ATRACE_CALL();
1643 ALOGV("postComposition");
1644
Brian Anderson3546a3f2016-07-14 11:51:14 -07001645 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001646 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001647 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001648 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001649 }
1650
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651 // |mStateLock| not needed as we are on the main thread
1652 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001653
David Sodman73beded2017-11-15 11:56:06 -08001654 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001655 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
David Sodman105b7dc2017-11-04 20:28:14 -07001656 if (getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657 glCompositionDoneFenceTime =
1658 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001659 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001660 } else {
1661 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1662 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001663
David Sodman73beded2017-11-15 11:56:06 -08001664 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001665 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001666 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001667 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1670 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1671
1672 // We use the refreshStartTime which might be sampled a little later than
1673 // when we started doing work for this frame, but that should be okay
1674 // since updateCompositorTiming has snapping logic.
1675 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001676 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001677 CompositorTiming compositorTiming;
1678 {
David Sodman99974d22017-11-28 12:04:33 -08001679 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1680 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001681 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682
Robert Carr2047fae2016-11-28 14:09:09 -08001683 mDrawingState.traverseInZOrder([&](Layer* layer) {
1684 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001685 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001686 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001687 recordBufferingStats(layer->getName().string(),
1688 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001689 }
Robert Carr2047fae2016-11-28 14:09:09 -08001690 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001691
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001692 if (presentFenceTime->isValid()) {
1693 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001694 enableHardwareVsync();
1695 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001696 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001697 }
1698 }
1699
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001700 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001701 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001702 enableHardwareVsync();
1703 }
1704 }
1705
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001706 if (mAnimCompositionPending) {
1707 mAnimCompositionPending = false;
1708
Brian Anderson4e606e32017-03-16 15:34:57 -07001709 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001710 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001711 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001712 } else {
1713 // The HWC doesn't support present fences, so use the refresh
1714 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001715 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001716 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001717 mAnimFrameTracker.setActualPresentTime(presentTime);
1718 }
1719 mAnimFrameTracker.advanceFrame();
1720 }
Dan Stozab90cf072015-03-05 11:05:59 -08001721
1722 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1723 return;
1724 }
1725
1726 nsecs_t currentTime = systemTime();
1727 if (mHasPoweredOff) {
1728 mHasPoweredOff = false;
1729 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001730 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001732 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1733 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001734 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001735 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001736 }
David Sodman4a36e932017-11-07 14:29:47 -08001737 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001738 }
David Sodman4a36e932017-11-07 14:29:47 -08001739 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740}
1741
1742void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 ATRACE_CALL();
1744 ALOGV("rebuildLayerStacks");
1745
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001747 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001748 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001749 mVisibleRegionsDirty = false;
1750 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001751
Jeff Sharkey76488112017-02-27 14:15:18 -07001752 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1753 Region opaqueRegion;
1754 Region dirtyRegion;
1755 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001756 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001757 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1758 const Transform& tr(displayDevice->getTransform());
1759 const Rect bounds(displayDevice->getBounds());
1760 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001761 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001762
Jeff Sharkey76488112017-02-27 14:15:18 -07001763 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001764 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001765 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1766 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 Region drawRegion(tr.transform(
1768 layer->visibleNonTransparentRegion));
1769 drawRegion.andSelf(bounds);
1770 if (!drawRegion.isEmpty()) {
1771 layersSortedByZ.add(layer);
1772 } else {
1773 // Clear out the HWC layer if this layer was
1774 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001775 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001776 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001777 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001778 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001779 // WM changes displayDevice->layerStack upon sleep/awake.
1780 // Here we make sure we delete the HWC layers even if
1781 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001782 hwcLayerDestroyed = layer->destroyHwcLayer(
1783 displayDevice->getHwcDisplayId());
1784 }
1785
1786 // If a layer is not going to get a release fence because
1787 // it is invisible, but it is also going to release its
1788 // old buffer, add it to the list of layers needing
1789 // fences.
1790 if (hwcLayerDestroyed) {
1791 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1792 mLayersWithQueuedFrames.cend(), layer);
1793 if (found != mLayersWithQueuedFrames.cend()) {
1794 layersNeedingFences.add(layer);
1795 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001796 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001797 });
1798 }
1799 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001800 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001801 displayDevice->undefinedRegion.set(bounds);
1802 displayDevice->undefinedRegion.subtractSelf(
1803 tr.transform(opaqueRegion));
1804 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001805 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001806 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001808
Romain Guy0147a172017-06-01 13:53:56 -07001809mat4 SurfaceFlinger::computeSaturationMatrix() const {
1810 if (mSaturation == 1.0f) {
1811 return mat4();
1812 }
1813
1814 // Rec.709 luma coefficients
1815 float3 luminance{0.213f, 0.715f, 0.072f};
1816 luminance *= 1.0f - mSaturation;
1817 return mat4(
1818 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1819 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1820 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1821 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1822 );
1823}
1824
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001825// pickColorMode translates a given dataspace into the best available color mode.
1826// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001827android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001828 if (mForceNativeColorMode) {
1829 return HAL_COLOR_MODE_NATIVE;
1830 }
1831
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001832 switch (dataSpace) {
1833 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1834 // system expects.
1835 case HAL_DATASPACE_UNKNOWN:
1836 case HAL_DATASPACE_SRGB:
1837 case HAL_DATASPACE_V0_SRGB:
1838 return HAL_COLOR_MODE_SRGB;
1839 break;
1840
1841 case HAL_DATASPACE_DISPLAY_P3:
1842 return HAL_COLOR_MODE_DISPLAY_P3;
1843 break;
1844
1845 default:
1846 // TODO (courtneygo): Do we want to assert an error here?
1847 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1848 dataSpace);
1849 return HAL_COLOR_MODE_SRGB;
1850 break;
1851 }
1852}
1853
Romain Guy0147a172017-06-01 13:53:56 -07001854android_dataspace SurfaceFlinger::bestTargetDataSpace(
1855 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001856 // Only support sRGB and Display-P3 right now.
1857 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1858 return HAL_DATASPACE_DISPLAY_P3;
1859 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001860 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1861 return HAL_DATASPACE_DISPLAY_P3;
1862 }
1863 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1864 return HAL_DATASPACE_DISPLAY_P3;
1865 }
1866
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001867 return HAL_DATASPACE_V0_SRGB;
1868}
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 ATRACE_CALL();
1872 ALOGV("setUpHWComposer");
1873
Jesse Hall028dc8f2013-08-20 16:35:32 -07001874 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001875 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1876 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1877 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1878
1879 // If nothing has changed (!dirty), don't recompose.
1880 // If something changed, but we don't currently have any visible layers,
1881 // and didn't when we last did a composition, then skip it this time.
1882 // The second rule does two things:
1883 // - When all layers are removed from a display, we'll emit one black
1884 // frame, then nothing more until we get new layers.
1885 // - When a display is created with a private layer stack, we won't
1886 // emit any black frames until a layer is added to the layer stack.
1887 bool mustRecompose = dirty && !(empty && wasEmpty);
1888
1889 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1890 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1891 mustRecompose ? "doing" : "skipping",
1892 dirty ? "+" : "-",
1893 empty ? "+" : "-",
1894 wasEmpty ? "+" : "-");
1895
Dan Stoza71433162014-02-04 16:22:36 -08001896 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001897
1898 if (mustRecompose) {
1899 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1900 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001901 }
1902
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 // build the h/w work list
1904 if (CC_UNLIKELY(mGeometryInvalid)) {
1905 mGeometryInvalid = false;
1906 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1907 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1908 const auto hwcId = displayDevice->getHwcDisplayId();
1909 if (hwcId >= 0) {
1910 const Vector<sp<Layer>>& currentLayers(
1911 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001912 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001913 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001915 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001918 }
1919 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001920
Robert Carrae060832016-11-28 10:51:00 -08001921 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001922 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001924 }
1925 }
1926 }
1927 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 }
Riley Andrews03414a12014-07-01 14:22:59 -07001929
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001930
Romain Guy0147a172017-06-01 13:53:56 -07001931 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001932
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 // Set the per-frame data
1934 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1935 auto& displayDevice = mDisplays[displayId];
1936 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 if (hwcId < 0) {
1939 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001940 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001941 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001942 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1944 "display %zd: %d", displayId, result);
1945 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001947 if (layer->getForceClientComposition(hwcId)) {
1948 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1949 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1950 continue;
1951 }
1952
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 layer->setPerFrameData(displayDevice);
1954 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001955
1956 if (hasWideColorDisplay) {
1957 android_color_mode newColorMode;
1958 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1959
1960 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1961 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1962 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1963 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1964 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1965 }
1966 newColorMode = pickColorMode(newDataSpace);
1967
Thierry Strudel2924d012017-08-14 15:19:37 -07001968 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001969 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001970 }
1971
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001972 mPreviousColorMatrix = colorMatrix;
1973
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001975 auto& displayDevice = mDisplays[displayId];
1976 if (!displayDevice->isDisplayOn()) {
1977 continue;
1978 }
1979
David Sodman105b7dc2017-11-04 20:28:14 -07001980 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1982 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001983 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001984}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001985
Mathias Agopiancd60f992012-08-16 16:28:27 -07001986void SurfaceFlinger::doComposition() {
1987 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 ALOGV("doComposition");
1989
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001990 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001991 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001992 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001993 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994 // transform the dirty region into this screen's coordinate space
1995 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001996
1997 // repaint the framebuffer (if needed)
1998 doDisplayComposition(hw, dirtyRegion);
1999
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002001 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002002 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002003 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002004 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002005}
2006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007void SurfaceFlinger::postFramebuffer()
2008{
Mathias Agopian841cde52012-03-01 15:44:37 -08002009 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002011
Mathias Agopiana44b0412011-10-16 18:46:35 -07002012 const nsecs_t now = systemTime();
2013 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002014
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2016 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002017 if (!displayDevice->isDisplayOn()) {
2018 continue;
2019 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 const auto hwcId = displayDevice->getHwcDisplayId();
2021 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002022 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002023 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002024 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002025 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002027 // The layer buffer from the previous frame (if any) is released
2028 // by HWC only when the release fence from this frame (if any) is
2029 // signaled. Always get the release fence from HWC first.
2030 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002031 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002032
2033 // If the layer was client composited in the previous frame, we
2034 // need to merge with the previous client target acquire fence.
2035 // Since we do not track that, always merge with the current
2036 // client target acquire fence when it is available, even though
2037 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002039 releaseFence = Fence::merge("LayerRelease", releaseFence,
2040 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002041 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002042
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 layer->onLayerDisplayed(releaseFence);
2044 }
Chia-I Wu83806892017-11-16 10:50:20 -08002045
2046 // We've got a list of layers needing fences, that are disjoint with
2047 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2048 // supply them with the present fence.
2049 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002050 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002051 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2052 layer->onLayerDisplayed(presentFence);
2053 }
2054 }
2055
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002057 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002058 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002059 }
2060
Mathias Agopiana44b0412011-10-16 18:46:35 -07002061 mLastSwapBufferTime = systemTime() - now;
2062 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002063
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002064 // |mStateLock| not needed as we are on the main thread
2065 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002066 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2067 logFrameStats();
2068 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002069}
2070
Mathias Agopian87baae12012-07-31 12:38:26 -07002071void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072{
Mathias Agopian841cde52012-03-01 15:44:37 -08002073 ATRACE_CALL();
2074
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002075 // here we keep a copy of the drawing state (that is the state that's
2076 // going to be overwritten by handleTransactionLocked()) outside of
2077 // mStateLock so that the side-effects of the State assignment
2078 // don't happen with mStateLock held (which can cause deadlocks).
2079 State drawingState(mDrawingState);
2080
Mathias Agopianca4d3602011-05-19 15:38:14 -07002081 Mutex::Autolock _l(mStateLock);
2082 const nsecs_t now = systemTime();
2083 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084
Mathias Agopianca4d3602011-05-19 15:38:14 -07002085 // Here we're guaranteed that some transaction flags are set
2086 // so we can call handleTransactionLocked() unconditionally.
2087 // We call getTransactionFlags(), which will also clear the flags,
2088 // with mStateLock held to guarantee that mCurrentState won't change
2089 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002090
Mathias Agopiane57f2922012-08-09 16:29:12 -07002091 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002092 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002093
Mathias Agopianca4d3602011-05-19 15:38:14 -07002094 mLastTransactionTime = systemTime() - now;
2095 mDebugInTransaction = 0;
2096 invalidateHwcGeometry();
2097 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002098}
2099
Lloyd Piqueba04e622017-12-14 17:11:26 -08002100void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2101 for (const auto& event : mPendingHotplugEvents) {
2102 DisplayDevice::DisplayType displayType = event.isPrimaryDisplay ?
2103 DisplayDevice::DISPLAY_PRIMARY : DisplayDevice::DISPLAY_EXTERNAL;
2104
2105 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2106 ALOGE("External displays are not supported by the vr hardware composer.");
2107 continue;
2108 }
2109
2110 getBE().mHwc->onHotplug(event.display, event.connection);
2111
2112 if (event.connection == HWC2::Connection::Connected) {
2113 createBuiltinDisplayLocked(displayType);
2114 } else {
2115 mCurrentState.displays.removeItem(mBuiltinDisplays[displayType]);
2116 mBuiltinDisplays[displayType].clear();
2117 }
2118
2119 if (displayType == DisplayDevice::DISPLAY_PRIMARY) {
2120 createDefaultDisplayDevice();
2121 }
2122
2123 processDisplayChangesLocked();
2124 }
2125
2126 mPendingHotplugEvents.clear();
2127}
2128
Lloyd Pique347200f2017-12-14 17:00:15 -08002129void SurfaceFlinger::processDisplayChangesLocked() {
2130 // here we take advantage of Vector's copy-on-write semantics to
2131 // improve performance by skipping the transaction entirely when
2132 // know that the lists are identical
2133 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2134 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2135 if (!curr.isIdenticalTo(draw)) {
2136 mVisibleRegionsDirty = true;
2137 const size_t cc = curr.size();
2138 size_t dc = draw.size();
2139
2140 // find the displays that were removed
2141 // (ie: in drawing state but not in current state)
2142 // also handle displays that changed
2143 // (ie: displays that are in both lists)
2144 for (size_t i = 0; i < dc;) {
2145 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2146 if (j < 0) {
2147 // in drawing state but not in current state
2148 if (!draw[i].isMainDisplay()) {
2149 // Call makeCurrent() on the primary display so we can
2150 // be sure that nothing associated with this display
2151 // is current.
2152 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2153 defaultDisplay->makeCurrent();
2154 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2155 if (hw != nullptr) hw->disconnect(getHwComposer());
2156 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2157 mEventThread->onHotplugReceived(draw[i].type, false);
2158 mDisplays.removeItem(draw.keyAt(i));
2159 } else {
2160 ALOGW("trying to remove the main display");
2161 }
2162 } else {
2163 // this display is in both lists. see if something changed.
2164 const DisplayDeviceState& state(curr[j]);
2165 const wp<IBinder>& display(curr.keyAt(j));
2166 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2167 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2168 if (state_binder != draw_binder) {
2169 // changing the surface is like destroying and
2170 // recreating the DisplayDevice, so we just remove it
2171 // from the drawing state, so that it get re-added
2172 // below.
2173 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2174 if (hw != nullptr) hw->disconnect(getHwComposer());
2175 mDisplays.removeItem(display);
2176 mDrawingState.displays.removeItemsAt(i);
2177 dc--;
2178 // at this point we must loop to the next item
2179 continue;
2180 }
2181
2182 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2183 if (disp != nullptr) {
2184 if (state.layerStack != draw[i].layerStack) {
2185 disp->setLayerStack(state.layerStack);
2186 }
2187 if ((state.orientation != draw[i].orientation) ||
2188 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2189 disp->setProjection(state.orientation, state.viewport, state.frame);
2190 }
2191 if (state.width != draw[i].width || state.height != draw[i].height) {
2192 disp->setDisplaySize(state.width, state.height);
2193 }
2194 }
2195 }
2196 ++i;
2197 }
2198
2199 // find displays that were added
2200 // (ie: in current state but not in drawing state)
2201 for (size_t i = 0; i < cc; i++) {
2202 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2203 const DisplayDeviceState& state(curr[i]);
2204
2205 sp<DisplaySurface> dispSurface;
2206 sp<IGraphicBufferProducer> producer;
2207 sp<IGraphicBufferProducer> bqProducer;
2208 sp<IGraphicBufferConsumer> bqConsumer;
2209 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2210
2211 int32_t hwcId = -1;
2212 if (state.isVirtualDisplay()) {
2213 // Virtual displays without a surface are dormant:
2214 // they have external state (layer stack, projection,
2215 // etc.) but no internal state (i.e. a DisplayDevice).
2216 if (state.surface != nullptr) {
2217 // Allow VR composer to use virtual displays.
2218 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2219 int width = 0;
2220 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2221 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2222 int height = 0;
2223 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2224 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2225 int intFormat = 0;
2226 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2227 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2228 auto format = static_cast<android_pixel_format_t>(intFormat);
2229
2230 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2231 }
2232
2233 // TODO: Plumb requested format back up to consumer
2234
2235 sp<VirtualDisplaySurface> vds =
2236 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2237 bqProducer, bqConsumer,
2238 state.displayName);
2239
2240 dispSurface = vds;
2241 producer = vds;
2242 }
2243 } else {
2244 ALOGE_IF(state.surface != nullptr,
2245 "adding a supported display, but rendering "
2246 "surface is provided (%p), ignoring it",
2247 state.surface.get());
2248
2249 hwcId = state.type;
2250 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2251 producer = bqProducer;
2252 }
2253
2254 const wp<IBinder>& display(curr.keyAt(i));
2255 if (dispSurface != nullptr) {
2256 sp<DisplayDevice> hw =
2257 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2258 dispSurface, producer, hasWideColorDisplay);
2259 hw->setLayerStack(state.layerStack);
2260 hw->setProjection(state.orientation, state.viewport, state.frame);
2261 hw->setDisplayName(state.displayName);
2262 mDisplays.add(display, hw);
2263 if (!state.isVirtualDisplay()) {
2264 mEventThread->onHotplugReceived(state.type, true);
2265 }
2266 }
2267 }
2268 }
2269 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002270
2271 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002272}
2273
Mathias Agopian87baae12012-07-31 12:38:26 -07002274void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002275{
Dan Stoza7dde5992015-05-22 09:51:44 -07002276 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002277 mCurrentState.traverseInZOrder([](Layer* layer) {
2278 layer->notifyAvailableFrames();
2279 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281 /*
2282 * Traversal of the children
2283 * (perform the transaction for each of them if needed)
2284 */
2285
Mathias Agopian3559b072012-08-15 13:46:03 -07002286 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002287 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002289 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290
2291 const uint32_t flags = layer->doTransaction(0);
2292 if (flags & Layer::eVisibleRegion)
2293 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002294 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295 }
2296
2297 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002298 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299 */
2300
Mathias Agopiane57f2922012-08-09 16:29:12 -07002301 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002302 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002303 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002304 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305
Mathias Agopian84300952012-11-21 16:02:13 -08002306 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2307 // The transform hint might have changed for some layers
2308 // (either because a display has changed, or because a layer
2309 // as changed).
2310 //
2311 // Walk through all the layers in currentLayers,
2312 // and update their transform hint.
2313 //
2314 // If a layer is visible only on a single display, then that
2315 // display is used to calculate the hint, otherwise we use the
2316 // default display.
2317 //
2318 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2319 // the hint is set before we acquire a buffer from the surface texture.
2320 //
2321 // NOTE: layer transactions have taken place already, so we use their
2322 // drawing state. However, SurfaceFlinger's own transaction has not
2323 // happened yet, so we must use the current state layer list
2324 // (soon to become the drawing state list).
2325 //
2326 sp<const DisplayDevice> disp;
2327 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002328 bool first = true;
2329 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002330 // NOTE: we rely on the fact that layers are sorted by
2331 // layerStack first (so we don't have to traverse the list
2332 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002333 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002334 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002335 currentlayerStack = layerStack;
2336 // figure out if this layerstack is mirrored
2337 // (more than one display) if so, pick the default display,
2338 // if not, pick the only display it's on.
2339 disp.clear();
2340 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2341 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002342 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002343 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002344 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002345 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002346 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002347 break;
2348 }
2349 }
2350 }
2351 }
Chet Haase91d25932013-04-11 15:24:55 -07002352
Robert Carr56a0b9a2017-12-04 16:06:13 -08002353 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002354 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002355 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2356 // redraw after transform hint changes. See bug 8508397.
2357
2358 // could be null when this layer is using a layerStack
2359 // that is not visible on any display. Also can occur at
2360 // screen off/on times.
2361 disp = getDefaultDisplayDeviceLocked();
2362 }
2363 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002364 }
Robert Carr2047fae2016-11-28 14:09:09 -08002365
2366 first = false;
2367 });
Mathias Agopian84300952012-11-21 16:02:13 -08002368 }
2369
2370
Mathias Agopian3559b072012-08-15 13:46:03 -07002371 /*
2372 * Perform our own transaction if needed
2373 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002374
2375 if (mLayersAdded) {
2376 mLayersAdded = false;
2377 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002378 mVisibleRegionsDirty = true;
2379 }
2380
2381 // some layers might have been removed, so
2382 // we need to update the regions they're exposing.
2383 if (mLayersRemoved) {
2384 mLayersRemoved = false;
2385 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002386 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002387 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002388 // this layer is not visible anymore
2389 // TODO: we could traverse the tree from front to back and
2390 // compute the actual visible region
2391 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002392 Region visibleReg;
2393 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002394 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002395 }
Robert Carr2047fae2016-11-28 14:09:09 -08002396 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397 }
2398
2399 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002400
2401 updateCursorAsync();
2402}
2403
2404void SurfaceFlinger::updateCursorAsync()
2405{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002406 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2407 auto& displayDevice = mDisplays[displayId];
2408 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002409 continue;
2410 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002411
2412 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2413 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002414 }
2415 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002416}
2417
2418void SurfaceFlinger::commitTransaction()
2419{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002420 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422 for (const auto& l : mLayersPendingRemoval) {
2423 recordBufferingStats(l->getName().string(),
2424 l->getOccupancyHistory(true));
2425 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 }
2427 mLayersPendingRemoval.clear();
2428 }
2429
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002430 // If this transaction is part of a window animation then the next frame
2431 // we composite should be considered an animation as well.
2432 mAnimCompositionPending = mAnimTransactionPending;
2433
Mathias Agopian4fec8732012-06-29 14:12:52 -07002434 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002435 mDrawingState.traverseInZOrder([](Layer* layer) {
2436 layer->commitChildList();
2437 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002438 mTransactionPending = false;
2439 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002440 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441}
2442
Chia-I Wuab0c3192017-08-01 11:29:00 -07002443void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002444 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445{
Mathias Agopian841cde52012-03-01 15:44:37 -08002446 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002448
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 Region aboveOpaqueLayers;
2450 Region aboveCoveredLayers;
2451 Region dirty;
2452
Mathias Agopian87baae12012-07-31 12:38:26 -07002453 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454
Robert Carr2047fae2016-11-28 14:09:09 -08002455 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002457 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458
Jesse Hall01e29052013-02-19 16:13:35 -08002459 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002460 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002461 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002462
Mathias Agopianab028732010-03-16 16:41:46 -07002463 /*
2464 * opaqueRegion: area of a surface that is fully opaque.
2465 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002467
2468 /*
2469 * visibleRegion: area of a surface that is visible on screen
2470 * and not fully transparent. This is essentially the layer's
2471 * footprint minus the opaque regions above it.
2472 * Areas covered by a translucent surface are considered visible.
2473 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002475
2476 /*
2477 * coveredRegion: area of a surface that is covered by all
2478 * visible regions above it (which includes the translucent areas).
2479 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002481
Jesse Halla8026d22012-09-25 13:25:04 -07002482 /*
2483 * transparentRegion: area of a surface that is hinted to be completely
2484 * transparent. This is only used to tell when the layer has no visible
2485 * non-transparent regions and can be removed from the layer list. It
2486 * does not affect the visibleRegion of this layer or any layers
2487 * beneath it. The hint may not be correct if apps don't respect the
2488 * SurfaceView restrictions (which, sadly, some don't).
2489 */
2490 Region transparentRegion;
2491
Mathias Agopianab028732010-03-16 16:41:46 -07002492
2493 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002494 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002495 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002496 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002498 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002499 if (!visibleRegion.isEmpty()) {
2500 // Remove the transparent area from the visible region
2501 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002502 if (tr.preserveRects()) {
2503 // transform the transparent region
2504 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002505 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002506 // transformation too complex, can't do the
2507 // transparent region optimization.
2508 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002509 }
Mathias Agopianab028732010-03-16 16:41:46 -07002510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
Mathias Agopianab028732010-03-16 16:41:46 -07002512 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002514 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002515 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2516 // the opaque region is the layer's footprint
2517 opaqueRegion = visibleRegion;
2518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 }
2520 }
2521
Mathias Agopianab028732010-03-16 16:41:46 -07002522 // Clip the covered region to the visible region
2523 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2524
2525 // Update aboveCoveredLayers for next (lower) layer
2526 aboveCoveredLayers.orSelf(visibleRegion);
2527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 // subtract the opaque region covered by the layers above us
2529 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530
2531 // compute this layer's dirty region
2532 if (layer->contentDirty) {
2533 // we need to invalidate the whole region
2534 dirty = visibleRegion;
2535 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002536 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537 layer->contentDirty = false;
2538 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002539 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002540 * the exposed region consists of two components:
2541 * 1) what's VISIBLE now and was COVERED before
2542 * 2) what's EXPOSED now less what was EXPOSED before
2543 *
2544 * note that (1) is conservative, we start with the whole
2545 * visible region but only keep what used to be covered by
2546 * something -- which mean it may have been exposed.
2547 *
2548 * (2) handles areas that were not covered by anything but got
2549 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002550 */
Mathias Agopianab028732010-03-16 16:41:46 -07002551 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002552 const Region oldVisibleRegion = layer->visibleRegion;
2553 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002554 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2555 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 }
2557 dirty.subtractSelf(aboveOpaqueLayers);
2558
2559 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002560 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561
Mathias Agopianab028732010-03-16 16:41:46 -07002562 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002564
Jesse Halla8026d22012-09-25 13:25:04 -07002565 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 layer->setVisibleRegion(visibleRegion);
2567 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002568 layer->setVisibleNonTransparentRegion(
2569 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002570 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571
Mathias Agopian87baae12012-07-31 12:38:26 -07002572 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573}
2574
Chia-I Wuab0c3192017-08-01 11:29:00 -07002575void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002576 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002577 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002578 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002579 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002580 }
2581 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002582}
2583
Dan Stoza6b9454d2014-11-07 16:00:59 -08002584bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 ALOGV("handlePageFlip");
2587
Brian Andersond6927fb2016-07-23 23:37:30 -07002588 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002591 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002592 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002593
2594 // Store the set of layers that need updates. This set must not change as
2595 // buffers are being latched, as this could result in a deadlock.
2596 // Example: Two producers share the same command stream and:
2597 // 1.) Layer 0 is latched
2598 // 2.) Layer 0 gets a new frame
2599 // 2.) Layer 1 gets a new frame
2600 // 3.) Layer 1 is latched.
2601 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2602 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002603 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002604 if (layer->hasQueuedFrame()) {
2605 frameQueued = true;
2606 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002607 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002608 } else {
2609 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002610 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002611 } else {
2612 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002613 }
Robert Carr2047fae2016-11-28 14:09:09 -08002614 });
2615
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002617 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002618 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002619 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002620 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002621 newDataLatched = true;
2622 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002623 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002624
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002625 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002626
2627 // If we will need to wake up at some time in the future to deal with a
2628 // queued frame that shouldn't be displayed during this vsync period, wake
2629 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002630 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002631 signalLayerUpdate();
2632 }
2633
2634 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002635 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636}
2637
Mathias Agopianad456f92011-01-13 17:53:01 -08002638void SurfaceFlinger::invalidateHwcGeometry()
2639{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002641}
2642
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002643
Fabien Sanglard830b8472016-11-30 16:35:58 -08002644void SurfaceFlinger::doDisplayComposition(
2645 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002646 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647{
Dan Stoza71433162014-02-04 16:22:36 -08002648 // We only need to actually compose the display if:
2649 // 1) It is being handled by hardware composer, which may need this to
2650 // keep its virtual display state machine in sync, or
2651 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002652 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002653 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002655 return;
2656 }
2657
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002659 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002660
2661 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002662 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663}
2664
Chia-I Wub02087d2017-11-09 10:19:54 -08002665bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002666{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002668
Chia-I Wub02087d2017-11-09 10:19:54 -08002669 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002670 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002672
2673 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002674 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2675 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002676 if (applyColorMatrix) {
2677 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2678 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2679 }
2680
David Sodman105b7dc2017-11-04 20:28:14 -07002681 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 if (hasClientComposition) {
2683 ALOGV("hasClientComposition");
2684
David Sodmanbc815282017-11-05 18:57:52 -08002685 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002686 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002687 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002688 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002689 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002690 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002691 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002692 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002693
2694 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002695 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002696 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2697 }
2698 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002699 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002700
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002701 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002702 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002704 // when using overlays, we assume a fully transparent framebuffer
2705 // NOTE: we could reduce how much we need to clear, for instance
2706 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002707 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002708 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002709 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002710 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002711 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002712 // we're left with the letterbox region
2713 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002715
2716 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002718
Mathias Agopianb9494d52012-04-18 02:28:45 -07002719 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002720 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002721 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002722 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002723 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002724 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002725
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002727 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002728 // scissor on the main display. It should never be needed
2729 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 const Rect& bounds(displayDevice->getBounds());
2731 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002732 if (scissor != bounds) {
2733 // scissor doesn't match the screen's dimensions, so we
2734 // need to clear everything outside of it and enable
2735 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002736
Mathias Agopianf45c5102012-10-24 16:29:17 -07002737 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002738 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002739 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002740 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002741 }
2742 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002743 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002744
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 /*
2746 * and then, render the layers targeted at the framebuffer
2747 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002748
Dan Stoza9e56aa02015-11-02 13:00:03 -08002749 ALOGV("Rendering client layers");
2750 const Transform& displayTransform = displayDevice->getTransform();
2751 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002752 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 bool firstLayer = true;
2754 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002755 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 displayTransform.transform(layer->visibleRegion)));
2757 ALOGV("Layer: %s", layer->getName().string());
2758 ALOGV(" Composition type: %s",
2759 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002760 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002761 switch (layer->getCompositionType(hwcId)) {
2762 case HWC2::Composition::Cursor:
2763 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002764 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002766 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002768 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002770 // never clear the very first layer since we're
2771 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002772 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002773 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002774 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002775 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002776 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002777 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002778 break;
2779 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002781 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002782 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 } else {
2784 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002785 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002787 }
2788 } else {
2789 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002791 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002793 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002794 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002795 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002796 }
2797 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002798
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002799 if (applyColorMatrix) {
2800 getRenderEngine().setupColorTransform(oldColorMatrix);
2801 }
2802
Mathias Agopianf45c5102012-10-24 16:29:17 -07002803 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002804 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002805 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806}
2807
Fabien Sanglard830b8472016-11-30 16:35:58 -08002808void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2809 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002810 RenderEngine& engine(getRenderEngine());
2811 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812}
2813
Dan Stoza7d89d062015-04-30 13:29:25 -07002814status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002815 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002816 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002817 const sp<Layer>& lbc,
2818 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002819{
Dan Stoza7d89d062015-04-30 13:29:25 -07002820 // add this layer to the current state list
2821 {
2822 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002823 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002824 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2825 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002826 return NO_MEMORY;
2827 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 if (parent == nullptr) {
2829 mCurrentState.layersSortedByZ.add(lbc);
2830 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002831 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002832 ALOGE("addClientLayer called with a removed parent");
2833 return NAME_NOT_FOUND;
2834 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 parent->addChild(lbc);
2836 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002837
Dan Stoza7d89d062015-04-30 13:29:25 -07002838 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 mLayersAdded = true;
2840 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002841 }
2842
Mathias Agopian96f08192010-06-02 23:28:45 -07002843 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002844 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002845
Dan Stoza7d89d062015-04-30 13:29:25 -07002846 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002847}
2848
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002849status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002850 Mutex::Autolock _l(mStateLock);
2851
chaviw8b3871a2017-11-01 17:41:01 -07002852 if (layer->isPendingRemoval()) {
2853 return NO_ERROR;
2854 }
2855
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002857 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002858 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002859 if (topLevelOnly) {
2860 return NO_ERROR;
2861 }
2862
Chia-I Wu98f1c102017-05-30 14:54:08 -07002863 sp<Layer> ancestor = p;
2864 while (ancestor->getParent() != nullptr) {
2865 ancestor = ancestor->getParent();
2866 }
2867 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2868 ALOGE("removeLayer called with a layer whose parent has been removed");
2869 return NAME_NOT_FOUND;
2870 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002871
2872 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002873 } else {
2874 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002875 }
2876
Robert Carr136e2f62017-02-08 17:54:29 -08002877 // As a matter of normal operation, the LayerCleaner will produce a second
2878 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2879 // so we will succeed in promoting it, but it's already been removed
2880 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2881 // otherwise something has gone wrong and we are leaking the layer.
2882 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2884 layer->getName().string(),
2885 (p != nullptr) ? p->getName().string() : "no-parent");
2886 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002887 } else if (index < 0) {
2888 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002889 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002890
Chia-I Wuc6657022017-08-15 11:18:17 -07002891 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 mLayersPendingRemoval.add(layer);
2893 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002894 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002895 setTransactionFlags(eTransactionNeeded);
2896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897}
2898
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002899uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002900 return android_atomic_release_load(&mTransactionFlags);
2901}
2902
Mathias Agopian3f844832013-08-07 21:24:32 -07002903uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2905}
2906
Mathias Agopian3f844832013-08-07 21:24:32 -07002907uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2909 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002910 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911 }
2912 return old;
2913}
2914
Mathias Agopian8b33f032012-07-24 20:43:54 -07002915void SurfaceFlinger::setTransactionState(
2916 const Vector<ComposerState>& state,
2917 const Vector<DisplayState>& displays,
2918 uint32_t flags)
2919{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002920 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002921 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002922 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002923
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002924 if (flags & eAnimation) {
2925 // For window updates that are part of an animation we must wait for
2926 // previous animation "frames" to be handled.
2927 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002928 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002929 if (CC_UNLIKELY(err != NO_ERROR)) {
2930 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002931 // caller after a few seconds.
2932 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2933 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002934 mAnimTransactionPending = false;
2935 break;
2936 }
2937 }
2938 }
2939
Mathias Agopiane57f2922012-08-09 16:29:12 -07002940 size_t count = displays.size();
2941 for (size_t i=0 ; i<count ; i++) {
2942 const DisplayState& s(displays[i]);
2943 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002944 }
2945
Mathias Agopiane57f2922012-08-09 16:29:12 -07002946 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002947 for (size_t i=0 ; i<count ; i++) {
2948 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002949 // Here we need to check that the interface we're given is indeed
Peiyong Lin566a3b42018-01-09 18:22:43 -08002950 // one of our own. A malicious client could give us a nullptr
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002951 // IInterface, or one of its own or even one of our own but a
2952 // different type. All these situations would cause us to crash.
2953 //
2954 // NOTE: it would be better to use RTTI as we could directly check
2955 // that we have a Client*. however, RTTI is disabled in Android.
Peiyong Lin566a3b42018-01-09 18:22:43 -08002956 if (s.client != nullptr) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002957 sp<IBinder> binder = IInterface::asBinder(s.client);
Peiyong Lin566a3b42018-01-09 18:22:43 -08002958 if (binder != nullptr) {
2959 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != nullptr) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002960 sp<Client> client( static_cast<Client *>(s.client.get()) );
2961 transactionFlags |= setClientStateLocked(client, s.state);
2962 }
2963 }
2964 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002965 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002966
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002967 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2968 // anyway. This can be used as a flush mechanism for previous async transactions.
2969 // Empty animation transaction can be used to simulate back-pressure, so also force a
2970 // transaction for empty animation transactions.
2971 if (transactionFlags == 0 &&
2972 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002973 transactionFlags = eTransactionNeeded;
2974 }
2975
Mathias Agopian386aa982011-11-07 21:58:03 -08002976 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002977 if (mInterceptor.isEnabled()) {
2978 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2979 }
Irvel468051e2016-06-13 16:44:44 -07002980
Mathias Agopian386aa982011-11-07 21:58:03 -08002981 // this triggers the transaction
2982 setTransactionFlags(transactionFlags);
2983
2984 // if this is a synchronous transaction, wait for it to take effect
2985 // before returning.
2986 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002987 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002988 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002989 if (flags & eAnimation) {
2990 mAnimTransactionPending = true;
2991 }
2992 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002993 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2994 if (CC_UNLIKELY(err != NO_ERROR)) {
2995 // just in case something goes wrong in SF, return to the
2996 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002997 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2998 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002999 break;
3000 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003001 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002 }
3003}
3004
Mathias Agopiane57f2922012-08-09 16:29:12 -07003005uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3006{
Jesse Hall9a143922012-10-04 16:29:19 -07003007 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3008 if (dpyIdx < 0)
3009 return 0;
3010
Mathias Agopiane57f2922012-08-09 16:29:12 -07003011 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003012 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003013 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 const uint32_t what = s.what;
3015 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003016 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 disp.surface = s.surface;
3018 flags |= eDisplayTransactionNeeded;
3019 }
3020 }
3021 if (what & DisplayState::eLayerStackChanged) {
3022 if (disp.layerStack != s.layerStack) {
3023 disp.layerStack = s.layerStack;
3024 flags |= eDisplayTransactionNeeded;
3025 }
3026 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003027 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003028 if (disp.orientation != s.orientation) {
3029 disp.orientation = s.orientation;
3030 flags |= eDisplayTransactionNeeded;
3031 }
3032 if (disp.frame != s.frame) {
3033 disp.frame = s.frame;
3034 flags |= eDisplayTransactionNeeded;
3035 }
3036 if (disp.viewport != s.viewport) {
3037 disp.viewport = s.viewport;
3038 flags |= eDisplayTransactionNeeded;
3039 }
3040 }
Michael Lentine47e45402014-07-18 15:34:25 -07003041 if (what & DisplayState::eDisplaySizeChanged) {
3042 if (disp.width != s.width) {
3043 disp.width = s.width;
3044 flags |= eDisplayTransactionNeeded;
3045 }
3046 if (disp.height != s.height) {
3047 disp.height = s.height;
3048 flags |= eDisplayTransactionNeeded;
3049 }
3050 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003051 }
3052 return flags;
3053}
3054
3055uint32_t SurfaceFlinger::setClientStateLocked(
3056 const sp<Client>& client,
3057 const layer_state_t& s)
3058{
Mathias Agopian13127d82013-03-05 17:47:11 -08003059 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003060 if (layer == nullptr) {
3061 return 0;
3062 }
3063
3064 if (layer->isPendingRemoval()) {
3065 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3066 return 0;
3067 }
3068
3069 uint32_t flags = 0;
3070
3071 const uint32_t what = s.what;
3072 bool geometryAppliesWithResize =
3073 what & layer_state_t::eGeometryAppliesWithResize;
3074 if (what & layer_state_t::ePositionChanged) {
3075 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3076 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003077 }
chaviw8b3871a2017-11-01 17:41:01 -07003078 }
3079 if (what & layer_state_t::eLayerChanged) {
3080 // NOTE: index needs to be calculated before we update the state
3081 const auto& p = layer->getParent();
3082 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003083 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003084 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003085 mCurrentState.layersSortedByZ.removeAt(idx);
3086 mCurrentState.layersSortedByZ.add(layer);
3087 // we need traversal (state changed)
3088 // AND transaction (list changed)
3089 flags |= eTransactionNeeded|eTraversalNeeded;
3090 }
chaviw8b3871a2017-11-01 17:41:01 -07003091 } else {
3092 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003093 flags |= eTransactionNeeded|eTraversalNeeded;
3094 }
3095 }
chaviw8b3871a2017-11-01 17:41:01 -07003096 }
3097 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003098 // NOTE: index needs to be calculated before we update the state
3099 const auto& p = layer->getParent();
3100 if (p == nullptr) {
3101 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3102 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3103 mCurrentState.layersSortedByZ.removeAt(idx);
3104 mCurrentState.layersSortedByZ.add(layer);
3105 // we need traversal (state changed)
3106 // AND transaction (list changed)
3107 flags |= eTransactionNeeded|eTraversalNeeded;
3108 }
3109 } else {
3110 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3111 flags |= eTransactionNeeded|eTraversalNeeded;
3112 }
chaviw8b3871a2017-11-01 17:41:01 -07003113 }
3114 }
3115 if (what & layer_state_t::eSizeChanged) {
3116 if (layer->setSize(s.w, s.h)) {
3117 flags |= eTraversalNeeded;
3118 }
3119 }
3120 if (what & layer_state_t::eAlphaChanged) {
3121 if (layer->setAlpha(s.alpha))
3122 flags |= eTraversalNeeded;
3123 }
3124 if (what & layer_state_t::eColorChanged) {
3125 if (layer->setColor(s.color))
3126 flags |= eTraversalNeeded;
3127 }
3128 if (what & layer_state_t::eMatrixChanged) {
3129 if (layer->setMatrix(s.matrix))
3130 flags |= eTraversalNeeded;
3131 }
3132 if (what & layer_state_t::eTransparentRegionChanged) {
3133 if (layer->setTransparentRegionHint(s.transparentRegion))
3134 flags |= eTraversalNeeded;
3135 }
3136 if (what & layer_state_t::eFlagsChanged) {
3137 if (layer->setFlags(s.flags, s.mask))
3138 flags |= eTraversalNeeded;
3139 }
3140 if (what & layer_state_t::eCropChanged) {
3141 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3142 flags |= eTraversalNeeded;
3143 }
3144 if (what & layer_state_t::eFinalCropChanged) {
3145 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3146 flags |= eTraversalNeeded;
3147 }
3148 if (what & layer_state_t::eLayerStackChanged) {
3149 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3150 // We only allow setting layer stacks for top level layers,
3151 // everything else inherits layer stack from its parent.
3152 if (layer->hasParent()) {
3153 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3154 layer->getName().string());
3155 } else if (idx < 0) {
3156 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3157 "that also does not appear in the top level layer list. Something"
3158 " has gone wrong.", layer->getName().string());
3159 } else if (layer->setLayerStack(s.layerStack)) {
3160 mCurrentState.layersSortedByZ.removeAt(idx);
3161 mCurrentState.layersSortedByZ.add(layer);
3162 // we need traversal (state changed)
3163 // AND transaction (list changed)
3164 flags |= eTransactionNeeded|eTraversalNeeded;
3165 }
3166 }
3167 if (what & layer_state_t::eDeferTransaction) {
3168 if (s.barrierHandle != nullptr) {
3169 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3170 } else if (s.barrierGbp != nullptr) {
3171 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3172 if (authenticateSurfaceTextureLocked(gbp)) {
3173 const auto& otherLayer =
3174 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3175 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3176 } else {
3177 ALOGE("Attempt to defer transaction to to an"
3178 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003179 }
3180 }
chaviw8b3871a2017-11-01 17:41:01 -07003181 // We don't trigger a traversal here because if no other state is
3182 // changed, we don't want this to cause any more work
3183 }
3184 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003185 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003186 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003187 if (!hadParent) {
3188 mCurrentState.layersSortedByZ.remove(layer);
3189 }
chaviw8b3871a2017-11-01 17:41:01 -07003190 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003191 }
chaviw8b3871a2017-11-01 17:41:01 -07003192 }
3193 if (what & layer_state_t::eReparentChildren) {
3194 if (layer->reparentChildren(s.reparentHandle)) {
3195 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003196 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003197 }
chaviw8b3871a2017-11-01 17:41:01 -07003198 if (what & layer_state_t::eDetachChildren) {
3199 layer->detachChildren();
3200 }
3201 if (what & layer_state_t::eOverrideScalingModeChanged) {
3202 layer->setOverrideScalingMode(s.overrideScalingMode);
3203 // We don't trigger a traversal here because if no other state is
3204 // changed, we don't want this to cause any more work
3205 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003206 return flags;
3207}
3208
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003209status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003210 const String8& name,
3211 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003212 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003213 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3214 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003216 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003217 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003218 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003219 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003220 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003221
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003222 status_t result = NO_ERROR;
3223
3224 sp<Layer> layer;
3225
Cody Northropbc755282017-03-31 12:00:08 -06003226 String8 uniqueName = getUniqueLayerName(name);
3227
Mathias Agopian3165cc22012-08-08 19:42:09 -07003228 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3229 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003230 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003231 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003232 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 break;
chaviw13fdc492017-06-27 12:40:18 -07003235 case ISurfaceComposerClient::eFXSurfaceColor:
3236 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003237 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003238 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003239 break;
3240 default:
3241 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 break;
3243 }
3244
Dan Stoza7d89d062015-04-30 13:29:25 -07003245 if (result != NO_ERROR) {
3246 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003248
Chia-I Wuab0c3192017-08-01 11:29:00 -07003249 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3250 // TODO b/64227542
3251 if (windowType == 441731) {
3252 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3253 layer->setPrimaryDisplayOnly();
3254 }
3255
Albert Chaulk479c60c2017-01-27 14:21:34 -05003256 layer->setInfo(windowType, ownerUid);
3257
Robert Carr1f0a16a2016-10-24 16:27:39 -07003258 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003259 if (result != NO_ERROR) {
3260 return result;
3261 }
Irvelffc9efc2016-07-27 15:16:37 -07003262 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003263
3264 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003265 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266}
3267
Cody Northropbc755282017-03-31 12:00:08 -06003268String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3269{
3270 bool matchFound = true;
3271 uint32_t dupeCounter = 0;
3272
3273 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3274 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3275
3276 // Loop over layers until we're sure there is no matching name
3277 while (matchFound) {
3278 matchFound = false;
3279 mDrawingState.traverseInZOrder([&](Layer* layer) {
3280 if (layer->getName() == uniqueName) {
3281 matchFound = true;
3282 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3283 }
3284 });
3285 }
3286
3287 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3288
3289 return uniqueName;
3290}
3291
David Sodman0c69cad2017-08-21 12:12:51 -07003292status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003293 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3294 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295{
3296 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003297 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298 case PIXEL_FORMAT_TRANSPARENT:
3299 case PIXEL_FORMAT_TRANSLUCENT:
3300 format = PIXEL_FORMAT_RGBA_8888;
3301 break;
3302 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003303 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304 break;
3305 }
3306
David Sodman0c69cad2017-08-21 12:12:51 -07003307 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3308 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003309 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003310 *handle = layer->getHandle();
3311 *gbp = layer->getProducer();
3312 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003314
David Sodman0c69cad2017-08-21 12:12:51 -07003315 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003316 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003317}
3318
chaviw13fdc492017-06-27 12:40:18 -07003319status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003320 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003321 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003322{
chaviw13fdc492017-06-27 12:40:18 -07003323 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003324 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003325 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003326}
3327
Mathias Agopianac9fa422013-02-11 16:40:36 -08003328status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329{
Robert Carr9524cb32017-02-13 11:32:32 -08003330 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003331 status_t err = NO_ERROR;
3332 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003333 if (l != nullptr) {
Irvelffc9efc2016-07-27 15:16:37 -07003334 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003335 err = removeLayer(l);
3336 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3337 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003338 }
3339 return err;
3340}
3341
Mathias Agopian13127d82013-03-05 17:47:11 -08003342status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003343{
Mathias Agopian67106042013-03-14 19:18:13 -07003344 // called by ~LayerCleaner() when all references to the IBinder (handle)
3345 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003346 sp<Layer> l = layer.promote();
3347 if (l == nullptr) {
3348 // The layer has already been removed, carry on
3349 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003350 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003351 // If we have a parent, then we can continue to live as long as it does.
3352 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353}
3354
Mathias Agopianb60314a2012-04-10 22:09:54 -07003355// ---------------------------------------------------------------------------
3356
Andy McFadden13a082e2012-08-24 10:16:42 -07003357void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003358 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003359 Vector<ComposerState> state;
3360 Vector<DisplayState> displays;
3361 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003362 d.what = DisplayState::eDisplayProjectionChanged |
3363 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003364 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003365 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003366 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003367 d.frame.makeInvalid();
3368 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003369 d.width = 0;
3370 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003371 displays.add(d);
3372 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003373 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3374 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003375
David Sodman105b7dc2017-11-04 20:28:14 -07003376 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003377 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003378 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003379
Brian Andersond0010582017-03-07 13:20:31 -08003380 // Use phase of 0 since phase is not known.
3381 // Use latency of 0, which will snap to the ideal latency.
3382 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003383}
3384
3385void SurfaceFlinger::initializeDisplays() {
3386 class MessageScreenInitialized : public MessageBase {
3387 SurfaceFlinger* flinger;
3388 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003389 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003390 virtual bool handler() {
3391 flinger->onInitializeDisplays();
3392 return true;
3393 }
3394 };
3395 sp<MessageBase> msg = new MessageScreenInitialized(this);
3396 postMessageAsync(msg); // we may be called from main thread, use async message
3397}
3398
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003399void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003400 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003401 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3402 this);
3403 int32_t type = hw->getDisplayType();
3404 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003405
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003406 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003407 return;
3408 }
3409
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003410 hw->setPowerMode(mode);
3411 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3412 ALOGW("Trying to set power mode for virtual display");
3413 return;
3414 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003415
Irvelffc9efc2016-07-27 15:16:37 -07003416 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003417 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003418 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3419 if (idx < 0) {
3420 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3421 return;
3422 }
3423 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3424 }
3425
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003426 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003427 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003428 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003429 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3430 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003431 // FIXME: eventthread only knows about the main display right now
3432 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003433 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003434 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003435
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003436 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003437 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003438 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003439
3440 struct sched_param param = {0};
3441 param.sched_priority = 1;
3442 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3443 ALOGW("Couldn't set SCHED_FIFO on display on");
3444 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003445 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003446 // Turn off the display
3447 struct sched_param param = {0};
3448 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3449 ALOGW("Couldn't set SCHED_OTHER on display off");
3450 }
3451
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003452 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3453 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003454 disableHardwareVsync(true); // also cancels any in-progress resync
3455
Mathias Agopiancde87a32012-09-13 14:09:01 -07003456 // FIXME: eventthread only knows about the main display right now
3457 mEventThread->onScreenReleased();
3458 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003459
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003460 getHwComposer().setPowerMode(type, mode);
3461 mVisibleRegionsDirty = true;
3462 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003463 } else if (mode == HWC_POWER_MODE_DOZE ||
3464 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003465 // Update display while dozing
3466 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003467 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3468 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003469 // FIXME: eventthread only knows about the main display right now
3470 mEventThread->onScreenAcquired();
3471 resyncToHardwareVsync(true);
3472 }
3473 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3474 // Leave display going to doze
3475 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3476 disableHardwareVsync(true); // also cancels any in-progress resync
3477 // FIXME: eventthread only knows about the main display right now
3478 mEventThread->onScreenReleased();
3479 }
3480 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003481 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003482 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003483 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003484 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003485}
3486
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003487void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3488 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003489 SurfaceFlinger& mFlinger;
3490 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003491 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003492 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003493 MessageSetPowerMode(SurfaceFlinger& flinger,
3494 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3495 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003496 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003497 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003498 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003499 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003500 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003501 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003502 ALOGW("Attempt to set power mode = %d for virtual display",
3503 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003504 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003505 mFlinger.setPowerModeInternal(
3506 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003507 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003508 return true;
3509 }
3510 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003511 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003512 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003513}
3514
3515// ---------------------------------------------------------------------------
3516
Vishnu Nair6a408532017-10-24 09:11:27 -07003517status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003519
Mathias Agopianbd115332013-04-18 16:41:04 -07003520 IPCThreadState* ipc = IPCThreadState::self();
3521 const int pid = ipc->getCallingPid();
3522 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003523
Mathias Agopianbd115332013-04-18 16:41:04 -07003524 if ((uid != AID_SHELL) &&
3525 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003526 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003527 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003529 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003530 // (this would indicate SF is stuck, but we want to be able to
3531 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003532 status_t err = mStateLock.timedLock(s2ns(1));
3533 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003534 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003535 result.appendFormat(
3536 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3537 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003538 }
3539
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003540 bool dumpAll = true;
3541 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003542 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003543
3544 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003545 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003546 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3547 dumpAll = false;
3548 }
3549
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003550 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003551 if ((index < numArgs) &&
3552 (args[index] == String16("--list"))) {
3553 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003554 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003555 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003556 }
3557
3558 if ((index < numArgs) &&
3559 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003560 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003561 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003562 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003563 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003564
3565 if ((index < numArgs) &&
3566 (args[index] == String16("--latency-clear"))) {
3567 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003568 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003569 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003570 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003571
3572 if ((index < numArgs) &&
3573 (args[index] == String16("--dispsync"))) {
3574 index++;
3575 mPrimaryDispSync.dump(result);
3576 dumpAll = false;
3577 }
Dan Stozab90cf072015-03-05 11:05:59 -08003578
3579 if ((index < numArgs) &&
3580 (args[index] == String16("--static-screen"))) {
3581 index++;
3582 dumpStaticScreenStats(result);
3583 dumpAll = false;
3584 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003585
3586 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003587 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003588 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003589 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003590 dumpAll = false;
3591 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003592
3593 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3594 index++;
3595 dumpWideColorInfo(result);
3596 dumpAll = false;
3597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003599
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003600 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003601 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003602 }
3603
Mathias Agopian9795c422009-08-26 16:36:26 -07003604 if (locked) {
3605 mStateLock.unlock();
3606 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 }
3608 write(fd, result.string(), result.size());
3609 return NO_ERROR;
3610}
3611
Dan Stozac7014012014-02-14 15:03:43 -08003612void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3613 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003614{
Robert Carr2047fae2016-11-28 14:09:09 -08003615 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003616 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003617 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003618}
3619
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003620void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003621 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003622{
3623 String8 name;
3624 if (index < args.size()) {
3625 name = String8(args[index]);
3626 index++;
3627 }
3628
David Sodman105b7dc2017-11-04 20:28:14 -07003629 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003630 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003631 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003632
3633 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003634 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003635 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003636 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003637 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003638 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003639 }
Robert Carr2047fae2016-11-28 14:09:09 -08003640 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003641 }
3642}
3643
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003644void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003645 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003646{
3647 String8 name;
3648 if (index < args.size()) {
3649 name = String8(args[index]);
3650 index++;
3651 }
3652
Robert Carr2047fae2016-11-28 14:09:09 -08003653 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003654 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003655 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003656 }
Robert Carr2047fae2016-11-28 14:09:09 -08003657 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003658
Svetoslavd85084b2014-03-20 10:28:31 -07003659 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003660}
3661
Jamie Gennis6547ff42013-07-16 20:12:42 -07003662// This should only be called from the main thread. Otherwise it would need
3663// the lock and should use mCurrentState rather than mDrawingState.
3664void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003665 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003666 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003667 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003668
3669 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3670}
3671
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003672void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003673{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003674 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003675 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3676
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003677 if (isLayerTripleBufferingDisabled())
3678 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003679
3680 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003681 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003682 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003683 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003684 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3685 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003686 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003687}
3688
Dan Stozab90cf072015-03-05 11:05:59 -08003689void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3690{
3691 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003692 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3693 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003694 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003695 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003696 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3697 b + 1, bucketTimeSec, percent);
3698 }
David Sodman4a36e932017-11-07 14:29:47 -08003699 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003700 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003701 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003702 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003703 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003704}
3705
Dan Stozae77c7662016-05-13 11:37:28 -07003706void SurfaceFlinger::recordBufferingStats(const char* layerName,
3707 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003708 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3709 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003710 for (const auto& segment : history) {
3711 if (!segment.usedThirdBuffer) {
3712 stats.twoBufferTime += segment.totalTime;
3713 }
3714 if (segment.occupancyAverage < 1.0f) {
3715 stats.doubleBufferedTime += segment.totalTime;
3716 } else if (segment.occupancyAverage < 2.0f) {
3717 stats.tripleBufferedTime += segment.totalTime;
3718 }
3719 ++stats.numSegments;
3720 stats.totalTime += segment.totalTime;
3721 }
3722}
3723
Brian Andersond6927fb2016-07-23 23:37:30 -07003724void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3725 result.appendFormat("Layer frame timestamps:\n");
3726
3727 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3728 const size_t count = currentLayers.size();
3729 for (size_t i=0 ; i<count ; i++) {
3730 currentLayers[i]->dumpFrameEvents(result);
3731 }
3732}
3733
Dan Stozae77c7662016-05-13 11:37:28 -07003734void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3735 result.append("Buffering stats:\n");
3736 result.append(" [Layer name] <Active time> <Two buffer> "
3737 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003738 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003739 typedef std::tuple<std::string, float, float, float> BufferTuple;
3740 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003741 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003742 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003743 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003744 if (stats.numSegments == 0) {
3745 continue;
3746 }
3747 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3748 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3749 stats.totalTime;
3750 float doubleBufferRatio = static_cast<float>(
3751 stats.doubleBufferedTime) / stats.totalTime;
3752 float tripleBufferRatio = static_cast<float>(
3753 stats.tripleBufferedTime) / stats.totalTime;
3754 sorted.insert({activeTime, {name, twoBufferRatio,
3755 doubleBufferRatio, tripleBufferRatio}});
3756 }
3757 for (const auto& sortedPair : sorted) {
3758 float activeTime = sortedPair.first;
3759 const BufferTuple& values = sortedPair.second;
3760 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3761 std::get<0>(values).c_str(), activeTime,
3762 std::get<1>(values), std::get<2>(values),
3763 std::get<3>(values));
3764 }
3765 result.append("\n");
3766}
3767
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003768void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3769 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003770 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003771
3772 // TODO: print out if wide-color mode is active or not
3773
3774 for (size_t d = 0; d < mDisplays.size(); d++) {
3775 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3776 int32_t hwcId = displayDevice->getHwcDisplayId();
3777 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3778 continue;
3779 }
3780
3781 result.appendFormat("Display %d color modes:\n", hwcId);
3782 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3783 for (auto&& mode : modes) {
3784 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3785 }
3786
3787 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3788 result.appendFormat(" Current color mode: %s (%d)\n",
3789 decodeColorMode(currentMode).c_str(), currentMode);
3790 }
3791 result.append("\n");
3792}
3793
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003794LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003795 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003796 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3797 const State& state = useDrawing ? mDrawingState : mCurrentState;
3798 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003799 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003800 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003801 });
3802
3803 return layersProto;
3804}
3805
Mathias Agopian74d211a2013-04-22 16:55:35 +02003806void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3807 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003808{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003809 bool colorize = false;
3810 if (index < args.size()
3811 && (args[index] == String16("--color"))) {
3812 colorize = true;
3813 index++;
3814 }
3815
3816 Colorizer colorizer(colorize);
3817
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818 // figure out if we're stuck somewhere
3819 const nsecs_t now = systemTime();
3820 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3821 const nsecs_t inTransaction(mDebugInTransaction);
3822 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3823 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3824
3825 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003826 * Dump library configuration.
3827 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003828
3829 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003830 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003831 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003832 appendSfConfigString(result);
3833 appendUiConfigString(result);
3834 appendGuiConfigString(result);
3835 result.append("\n");
3836
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003837 result.append("\nWide-Color information:\n");
3838 dumpWideColorInfo(result);
3839
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003840 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003841 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003842 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003843 result.append(SyncFeatures::getInstance().toString());
3844 result.append("\n");
3845
David Sodman105b7dc2017-11-04 20:28:14 -07003846 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003847
Andy McFadden41d67d72014-04-25 16:58:34 -07003848 colorizer.bold(result);
3849 result.append("DispSync configuration: ");
3850 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003851 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003852 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003853 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003854 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003855 result.append("\n");
3856
Dan Stozab90cf072015-03-05 11:05:59 -08003857 // Dump static screen stats
3858 result.append("\n");
3859 dumpStaticScreenStats(result);
3860 result.append("\n");
3861
Dan Stozae77c7662016-05-13 11:37:28 -07003862 dumpBufferingStats(result);
3863
Andy McFadden4803b742012-09-24 19:07:20 -07003864 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865 * Dump the visible layer list
3866 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003867 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003868 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003869 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003870
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003871 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003872 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3873 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003874
3875 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003876 * Dump Display state
3877 */
3878
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003879 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003880 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003881 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003882 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3883 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003884 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003885 }
3886
3887 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003888 * Dump SurfaceFlinger global state
3889 */
3890
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003891 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003892 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003893 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003894
Mathias Agopian888c8222012-08-04 21:10:38 -07003895 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003896 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003897
David Sodmanbc815282017-11-05 18:57:52 -08003898 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003899
Mathias Agopian42977342012-08-05 00:40:46 -07003900 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3902 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003903 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003904 " last eglSwapBuffers() time: %f us\n"
3905 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003906 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907 " refresh-rate : %f fps\n"
3908 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003909 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003910 " gpu_to_cpu_unsupported : %d\n"
3911 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 mLastSwapBufferTime/1000.0,
3913 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003914 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003915 1e9 / activeConfig->getVsyncPeriod(),
3916 activeConfig->getDpiX(),
3917 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003918 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003919
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003922
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003925
3926 /*
3927 * VSYNC state
3928 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003929 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003930 result.append("\n");
3931
3932 /*
3933 * HWC layer minidump
3934 */
3935 for (size_t d = 0; d < mDisplays.size(); d++) {
3936 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3937 int32_t hwcId = displayDevice->getHwcDisplayId();
3938 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3939 continue;
3940 }
3941
3942 result.appendFormat("Display %d HWC layers:\n", hwcId);
3943 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003944 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003945 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003946 });
Dan Stozae22aec72016-08-01 13:20:59 -07003947 result.append("\n");
3948 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949
3950 /*
3951 * Dump HWComposer state
3952 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003953 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003955 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003956 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003957 result.appendFormat(" h/w composer %s\n",
3958 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003959 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960
3961 /*
3962 * Dump gralloc state
3963 */
3964 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3965 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003966
3967 /*
3968 * Dump VrFlinger state if in use.
3969 */
3970 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3971 result.append("VrFlinger state:\n");
3972 result.append(mVrFlinger->Dump().c_str());
3973 result.append("\n");
3974 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975}
3976
Mathias Agopian13127d82013-03-05 17:47:11 -08003977const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003978SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003979 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003980 wp<IBinder> dpy;
3981 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3982 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3983 dpy = mDisplays.keyAt(i);
3984 break;
3985 }
3986 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08003987 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07003988 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3989 // Just use the primary display so we have something to return
3990 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3991 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003992 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003993}
3994
Keun young Park63f165f2012-08-31 10:53:36 -07003995bool SurfaceFlinger::startDdmConnection()
3996{
3997 void* libddmconnection_dso =
3998 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3999 if (!libddmconnection_dso) {
4000 return false;
4001 }
4002 void (*DdmConnection_start)(const char* name);
4003 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004004 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004005 if (!DdmConnection_start) {
4006 dlclose(libddmconnection_dso);
4007 return false;
4008 }
4009 (*DdmConnection_start)(getServiceName());
4010 return true;
4011}
4012
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004013status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004014 switch (code) {
4015 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004016 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004017 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004018 case CLEAR_ANIMATION_FRAME_STATS:
4019 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004020 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004021 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004022 case ENABLE_VSYNC_INJECTIONS:
4023 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024 {
4025 // codes that require permission check
4026 IPCThreadState* ipc = IPCThreadState::self();
4027 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004028 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004029 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004030 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004031 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004032 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004034 break;
4035 }
Robert Carr1db73f62016-12-21 12:58:51 -08004036 /*
4037 * Calling setTransactionState is safe, because you need to have been
4038 * granted a reference to Client* and Handle* to do anything with it.
4039 *
4040 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4041 */
4042 case SET_TRANSACTION_STATE:
4043 case CREATE_SCOPED_CONNECTION:
4044 {
4045 return OK;
4046 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004047 case CAPTURE_SCREEN:
4048 {
4049 // codes that require permission check
4050 IPCThreadState* ipc = IPCThreadState::self();
4051 const int pid = ipc->getCallingPid();
4052 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004053 if ((uid != AID_GRAPHICS) &&
4054 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004055 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004056 return PERMISSION_DENIED;
4057 }
4058 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 }
chaviwa76b2712017-09-20 12:02:26 -07004060 case CAPTURE_LAYERS: {
4061 IPCThreadState* ipc = IPCThreadState::self();
4062 const int pid = ipc->getCallingPid();
4063 const int uid = ipc->getCallingUid();
4064 if ((uid != AID_GRAPHICS) &&
4065 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4066 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4067 return PERMISSION_DENIED;
4068 }
4069 break;
4070 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004072 return OK;
4073}
4074
4075status_t SurfaceFlinger::onTransact(
4076 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4077{
4078 status_t credentialCheck = CheckTransactCodeCredentials(code);
4079 if (credentialCheck != OK) {
4080 return credentialCheck;
4081 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4084 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004085 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004086 IPCThreadState* ipc = IPCThreadState::self();
4087 const int uid = ipc->getCallingUid();
4088 if (CC_UNLIKELY(uid != AID_SYSTEM
4089 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004090 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004091 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004092 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 return PERMISSION_DENIED;
4094 }
4095 int n;
4096 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004097 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004098 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004099 return NO_ERROR;
4100 case 1002: // SHOW_UPDATES
4101 n = data.readInt32();
4102 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004103 invalidateHwcGeometry();
4104 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004105 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004106 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004107 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004108 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004110 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004111 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004112 setTransactionFlags(
4113 eTransactionNeeded|
4114 eDisplayTransactionNeeded|
4115 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004116 return NO_ERROR;
4117 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004118 case 1006:{ // send empty update
4119 signalRefresh();
4120 return NO_ERROR;
4121 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004122 case 1008: // toggle use of hw composer
4123 n = data.readInt32();
4124 mDebugDisableHWC = n ? 1 : 0;
4125 invalidateHwcGeometry();
4126 repaintEverything();
4127 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004128 case 1009: // toggle use of transform hint
4129 n = data.readInt32();
4130 mDebugDisableTransformHint = n ? 1 : 0;
4131 invalidateHwcGeometry();
4132 repaintEverything();
4133 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004135 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 reply->writeInt32(0);
4137 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004138 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004139 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 return NO_ERROR;
4141 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004142 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004143 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004144 return NO_ERROR;
4145 }
4146 case 1014: {
4147 // daltonize
4148 n = data.readInt32();
4149 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004150 case 1:
4151 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4152 break;
4153 case 2:
4154 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4155 break;
4156 case 3:
4157 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4158 break;
4159 default:
4160 mDaltonizer.setType(ColorBlindnessType::None);
4161 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004162 }
4163 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004164 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004165 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004166 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004167 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004168 invalidateHwcGeometry();
4169 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004170 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004171 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004172 case 1015: {
4173 // apply a color matrix
4174 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004175 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004176 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004177 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004178 for (size_t j = 0; j < 4; j++) {
4179 mColorMatrix[i][j] = data.readFloat();
4180 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004181 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004182 } else {
4183 mColorMatrix = mat4();
4184 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004185
4186 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4187 // the division by w in the fragment shader
4188 float4 lastRow(transpose(mColorMatrix)[3]);
4189 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4190 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4191 }
4192
Alan Viverette9c5a3332013-09-12 20:04:35 -07004193 invalidateHwcGeometry();
4194 repaintEverything();
4195 return NO_ERROR;
4196 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004197 // This is an experimental interface
4198 // Needs to be shifted to proper binder interface when we productize
4199 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004200 n = data.readInt32();
4201 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004202 return NO_ERROR;
4203 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004204 case 1017: {
4205 n = data.readInt32();
4206 mForceFullDamage = static_cast<bool>(n);
4207 return NO_ERROR;
4208 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004209 case 1018: { // Modify Choreographer's phase offset
4210 n = data.readInt32();
4211 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4212 return NO_ERROR;
4213 }
4214 case 1019: { // Modify SurfaceFlinger's phase offset
4215 n = data.readInt32();
4216 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4217 return NO_ERROR;
4218 }
Irvel468051e2016-06-13 16:44:44 -07004219 case 1020: { // Layer updates interceptor
4220 n = data.readInt32();
4221 if (n) {
4222 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004223 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004224 }
4225 else{
4226 ALOGV("Interceptor disabled");
4227 mInterceptor.disable();
4228 }
4229 return NO_ERROR;
4230 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004231 case 1021: { // Disable HWC virtual displays
4232 n = data.readInt32();
4233 mUseHwcVirtualDisplays = !n;
4234 return NO_ERROR;
4235 }
Romain Guy0147a172017-06-01 13:53:56 -07004236 case 1022: { // Set saturation boost
4237 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4238
4239 invalidateHwcGeometry();
4240 repaintEverything();
4241 return NO_ERROR;
4242 }
Romain Guy54f154a2017-10-24 21:40:32 +01004243 case 1023: { // Set native mode
4244 mForceNativeColorMode = data.readInt32() == 1;
4245
4246 invalidateHwcGeometry();
4247 repaintEverything();
4248 return NO_ERROR;
4249 }
4250 case 1024: { // Is wide color gamut rendering/color management supported?
4251 reply->writeBool(hasWideColorDisplay);
4252 return NO_ERROR;
4253 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004254 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004255 n = data.readInt32();
4256 if (n) {
4257 ALOGV("LayerTracing enabled");
4258 mTracing.enable();
4259 doTracing("tracing.enable");
4260 reply->writeInt32(NO_ERROR);
4261 } else {
4262 ALOGV("LayerTracing disabled");
4263 status_t err = mTracing.disable();
4264 reply->writeInt32(err);
4265 }
4266 return NO_ERROR;
4267 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004268 case 1026: { // Get layer tracing status
4269 reply->writeBool(mTracing.isEnabled());
4270 return NO_ERROR;
4271 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004272 }
4273 }
4274 return err;
4275}
4276
Steven Thomas6d8110b2017-08-31 18:24:21 -07004277void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004278 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004279 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004280}
4281
Steven Thomas6d8110b2017-08-31 18:24:21 -07004282void SurfaceFlinger::repaintEverything() {
4283 ConditionalLock _l(mStateLock,
4284 std::this_thread::get_id() != mMainThreadId);
4285 repaintEverythingLocked();
4286}
4287
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004288// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4289class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004290public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004291 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4292 ~WindowDisconnector() {
4293 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004294 }
4295
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004296private:
4297 ANativeWindow* mWindow;
4298 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004299};
4300
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004301status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4302 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4303 int32_t minLayerZ, int32_t maxLayerZ,
4304 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004305 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004306 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004307
chaviwa76b2712017-09-20 12:02:26 -07004308 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4309
4310 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4311 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4312
4313 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4314 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004315 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004316}
4317
4318status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004319 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004320 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004321 ATRACE_CALL();
4322
4323 class LayerRenderArea : public RenderArea {
4324 public:
chaviw7206d492017-11-10 16:16:12 -08004325 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004326 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004327 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004328 const Transform& getTransform() const override {
4329 // Make the top level transform the inverse the transform and it's parent so it sets
4330 // the whole capture back to 0,0
4331 return *new Transform(mLayer->getTransform().inverse());
4332 }
4333 Rect getBounds() const override {
4334 const Layer::State& layerState(mLayer->getDrawingState());
4335 return Rect(layerState.active.w, layerState.active.h);
4336 }
4337 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4338 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4339 bool isSecure() const override { return false; }
4340 bool needsFiltering() const override { return false; }
4341
chaviw7206d492017-11-10 16:16:12 -08004342 Rect getSourceCrop() const override {
4343 if (mCrop.isEmpty()) {
4344 return getBounds();
4345 } else {
4346 return mCrop;
4347 }
4348 }
chaviwa76b2712017-09-20 12:02:26 -07004349 bool getWideColorSupport() const override { return false; }
4350 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4351
4352 private:
chaviw7206d492017-11-10 16:16:12 -08004353 const sp<Layer> mLayer;
4354 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004355 };
4356
4357 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4358 auto parent = layerHandle->owner.promote();
4359
chaviw7206d492017-11-10 16:16:12 -08004360 if (parent == nullptr || parent->isPendingRemoval()) {
4361 ALOGE("captureLayers called with a removed parent");
4362 return NAME_NOT_FOUND;
4363 }
4364
4365 Rect crop(sourceCrop);
4366 if (sourceCrop.width() <= 0) {
4367 crop.left = 0;
4368 crop.right = parent->getCurrentState().active.w;
4369 }
4370
4371 if (sourceCrop.height() <= 0) {
4372 crop.top = 0;
4373 crop.bottom = parent->getCurrentState().active.h;
4374 }
4375
4376 int32_t reqWidth = crop.width() * frameScale;
4377 int32_t reqHeight = crop.height() * frameScale;
4378
4379 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4380
chaviwa76b2712017-09-20 12:02:26 -07004381 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4382 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4383 if (!layer->isVisible()) {
4384 return;
4385 }
4386 visitor(layer);
4387 });
4388 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004389 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004390}
4391
4392status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4393 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004394 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004395 bool useIdentityTransform) {
4396 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004397
chaviwa76b2712017-09-20 12:02:26 -07004398 renderArea.updateDimensions();
4399
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004400 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4401 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4402 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4403 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004404
4405 // This mutex protects syncFd and captureResult for communication of the return values from the
4406 // main thread back to this Binder thread
4407 std::mutex captureMutex;
4408 std::condition_variable captureCondition;
4409 std::unique_lock<std::mutex> captureLock(captureMutex);
4410 int syncFd = -1;
4411 std::optional<status_t> captureResult;
4412
Robert Carr03480e22018-01-04 16:02:06 -08004413 const int uid = IPCThreadState::self()->getCallingUid();
4414 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4415
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004416 sp<LambdaMessage> message = new LambdaMessage([&]() {
4417 // If there is a refresh pending, bug out early and tell the binder thread to try again
4418 // after the refresh.
4419 if (mRefreshPending) {
4420 ATRACE_NAME("Skipping screenshot for now");
4421 std::unique_lock<std::mutex> captureLock(captureMutex);
4422 captureResult = std::make_optional<status_t>(EAGAIN);
4423 captureCondition.notify_one();
4424 return;
4425 }
4426
4427 status_t result = NO_ERROR;
4428 int fd = -1;
4429 {
4430 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004431 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carr03480e22018-01-04 16:02:06 -08004432 useIdentityTransform, forSystem, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004433 }
4434
4435 {
4436 std::unique_lock<std::mutex> captureLock(captureMutex);
4437 syncFd = fd;
4438 captureResult = std::make_optional<status_t>(result);
4439 captureCondition.notify_one();
4440 }
4441 });
4442
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004443 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004444 if (result == NO_ERROR) {
4445 captureCondition.wait(captureLock, [&]() { return captureResult; });
4446 while (*captureResult == EAGAIN) {
4447 captureResult.reset();
4448 result = postMessageAsync(message);
4449 if (result != NO_ERROR) {
4450 return result;
4451 }
4452 captureCondition.wait(captureLock, [&]() { return captureResult; });
4453 }
4454 result = *captureResult;
4455 }
4456
4457 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004458 sync_wait(syncFd, -1);
4459 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004460 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004461
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004462 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004463}
4464
chaviwa76b2712017-09-20 12:02:26 -07004465void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4466 TraverseLayersFunction traverseLayers, bool yswap,
4467 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004468 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004469
Mathias Agopian3f844832013-08-07 21:24:32 -07004470 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004471
4472 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004473 const auto raWidth = renderArea.getWidth();
4474 const auto raHeight = renderArea.getHeight();
4475
4476 const auto reqWidth = renderArea.getReqWidth();
4477 const auto reqHeight = renderArea.getReqHeight();
4478 Rect sourceCrop = renderArea.getSourceCrop();
4479
4480 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4481 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004482
Dan Stozac1879002014-05-22 15:59:05 -07004483 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004484 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004485 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004486 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004487 }
4488
4489 // ensure that sourceCrop is inside screen
4490 if (sourceCrop.left < 0) {
4491 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4492 }
chaviwa76b2712017-09-20 12:02:26 -07004493 if (sourceCrop.right > raWidth) {
4494 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004495 }
4496 if (sourceCrop.top < 0) {
4497 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4498 }
chaviwa76b2712017-09-20 12:02:26 -07004499 if (sourceCrop.bottom > raHeight) {
4500 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004501 }
4502
chaviwa76b2712017-09-20 12:02:26 -07004503 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004504 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4505 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004506
Mathias Agopian180f10d2013-04-10 22:55:41 -07004507 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004508 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004509
4510 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004511 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4512 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004513 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004514
4515 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004516 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004517
chaviwa76b2712017-09-20 12:02:26 -07004518 traverseLayers([&](Layer* layer) {
4519 if (filtering) layer->setFiltering(true);
4520 layer->draw(renderArea, useIdentityTransform);
4521 if (filtering) layer->setFiltering(false);
4522 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004523}
4524
chaviwa76b2712017-09-20 12:02:26 -07004525status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4526 TraverseLayersFunction traverseLayers,
4527 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004528 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004529 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004530 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004531 ATRACE_CALL();
4532
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004533 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004534
4535 traverseLayers([&](Layer* layer) {
4536 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4537 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004538
Robert Carr03480e22018-01-04 16:02:06 -08004539 // We allow the system server to take screenshots of secure layers for
4540 // use in situations like the Screen-rotation animation and place
4541 // the impetus on WindowManager to not persist them.
4542 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004543 ALOGW("FB is protected: PERMISSION_DENIED");
4544 return PERMISSION_DENIED;
4545 }
4546
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004547 // this binds the given EGLImage as a framebuffer for the
4548 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004549 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4550 if (bufferBond.getStatus() != NO_ERROR) {
4551 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004552 return INVALID_OPERATION;
4553 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004554
Dan Stozaabcda352017-06-01 14:37:39 -07004555 // this will in fact render into our dequeued buffer
4556 // via an FBO, which means we didn't have to create
4557 // an EGLSurface and therefore we're not
4558 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004559 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004560
Dan Stozaabcda352017-06-01 14:37:39 -07004561 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004562 getRenderEngine().finish();
4563 *outSyncFd = -1;
4564
chaviwa76b2712017-09-20 12:02:26 -07004565 const auto reqWidth = renderArea.getReqWidth();
4566 const auto reqHeight = renderArea.getReqHeight();
4567
Dan Stozaabcda352017-06-01 14:37:39 -07004568 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4569 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004570 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004571 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004572 } else {
4573 base::unique_fd syncFd = getRenderEngine().flush();
4574 if (syncFd < 0) {
4575 getRenderEngine().finish();
4576 }
4577 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004578 }
4579
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004580 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004581}
4582
Mathias Agopiand5556842013-09-19 17:08:37 -07004583void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004584 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004585 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004586 for (size_t y = 0; y < h; y++) {
4587 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4588 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004589 if (p[x] != 0xFF000000) return;
4590 }
4591 }
chaviwa76b2712017-09-20 12:02:26 -07004592 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004593
Robert Carr2047fae2016-11-28 14:09:09 -08004594 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004595 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004596 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004597 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4598 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4599 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4600 static_cast<float>(state.color.a));
4601 i++;
4602 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004603 }
4604}
4605
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004606// ---------------------------------------------------------------------------
4607
Dan Stoza412903f2017-04-27 13:42:17 -07004608void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4609 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004610}
4611
Dan Stoza412903f2017-04-27 13:42:17 -07004612void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4613 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004614}
4615
chaviwa76b2712017-09-20 12:02:26 -07004616void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4617 int32_t maxLayerZ,
4618 const LayerVector::Visitor& visitor) {
4619 // We loop through the first level of layers without traversing,
4620 // as we need to interpret min/max layer Z in the top level Z space.
4621 for (const auto& layer : mDrawingState.layersSortedByZ) {
4622 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4623 continue;
4624 }
4625 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004626 // relative layers are traversed in Layer::traverseInZOrder
4627 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004628 continue;
4629 }
4630 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4631 if (!layer->isVisible()) {
4632 return;
4633 }
4634 visitor(layer);
4635 });
4636 }
4637}
4638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004639}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004640
4641
4642#if defined(__gl_h_)
4643#error "don't include gl/gl.h in this file"
4644#endif
4645
4646#if defined(__gl2_h_)
4647#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004648#endif