blob: a5b92b5f378b462e32557a743468d698c665f27b [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);
385 return NULL;
386 }
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
534 if (callback != NULL) {
535 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);
Jesse Hall692c7232012-11-08 15:41:56 -0800621
Steven Thomas050b2c82017-03-06 11:45:16 -0800622 if (useVrFlinger) {
623 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700624 // This callback is called from the vr flinger dispatch thread. We
625 // need to call signalTransaction(), which requires holding
626 // mStateLock when we're not on the main thread. Acquiring
627 // mStateLock from the vr flinger dispatch thread might trigger a
628 // deadlock in surface flinger (see b/66916578), so post a message
629 // to be handled on the main thread instead.
630 sp<LambdaMessage> message = new LambdaMessage([=]() {
631 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
632 mVrFlingerRequestsDisplay = requestDisplay;
633 signalTransaction();
634 });
635 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800636 };
David Sodman105b7dc2017-11-04 20:28:14 -0700637 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
638 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800639 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 if (!mVrFlinger) {
641 ALOGE("Failed to start vrflinger");
642 }
643 }
644
Jamie Gennisd1700752013-10-14 12:22:52 -0700645 mEventControlThread = new EventControlThread(this);
646 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
647
Mathias Agopian92a979a2012-08-02 18:32:23 -0700648 // initialize our drawing state
649 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700650
Andy McFadden13a082e2012-08-24 10:16:42 -0700651 // set initial conditions (e.g. unblank default device)
652 initializeDisplays();
653
David Sodmanbc815282017-11-05 18:57:52 -0800654 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700655
Wei Wangf9b05ee2017-07-19 20:59:39 -0700656 // Inform native graphics APIs whether the present timestamp is supported:
657 if (getHwComposer().hasCapability(
658 HWC2::Capability::PresentFenceIsNotReliable)) {
659 mStartPropertySetThread = new StartPropertySetThread(false);
660 } else {
661 mStartPropertySetThread = new StartPropertySetThread(true);
662 }
663
664 if (mStartPropertySetThread->Start() != NO_ERROR) {
665 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800666 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800667
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700669}
670
Romain Guy11d63f42017-07-20 12:47:14 -0700671void SurfaceFlinger::readPersistentProperties() {
672 char value[PROPERTY_VALUE_MAX];
673
674 property_get("persist.sys.sf.color_saturation", value, "1.0");
675 mSaturation = atof(value);
676 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100677
678 property_get("persist.sys.sf.native_mode", value, "0");
679 mForceNativeColorMode = atoi(value) == 1;
680 if (mForceNativeColorMode) {
681 ALOGV("Forcing native color mode");
682 }
Romain Guy11d63f42017-07-20 12:47:14 -0700683}
684
Mathias Agopiana67e4182012-06-19 17:26:12 -0700685void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800686 // Start boot animation service by setting a property mailbox
687 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800689 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 if (mStartPropertySetThread->join() != NO_ERROR) {
691 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800692 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700693}
694
Mathias Agopian875d8e12013-06-07 15:35:48 -0700695size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800696 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700697}
698
Mathias Agopian875d8e12013-06-07 15:35:48 -0700699size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800700 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700701}
702
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800704
Jamie Gennis582270d2011-08-17 18:19:00 -0700705bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800706 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800707 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800708 return authenticateSurfaceTextureLocked(bufferProducer);
709}
710
711bool SurfaceFlinger::authenticateSurfaceTextureLocked(
712 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800713 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700714 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800715}
716
Brian Anderson6b376712017-04-04 10:51:39 -0700717status_t SurfaceFlinger::getSupportedFrameTimestamps(
718 std::vector<FrameEvent>* outSupported) const {
719 *outSupported = {
720 FrameEvent::REQUESTED_PRESENT,
721 FrameEvent::ACQUIRE,
722 FrameEvent::LATCH,
723 FrameEvent::FIRST_REFRESH_START,
724 FrameEvent::LAST_REFRESH_START,
725 FrameEvent::GPU_COMPOSITION_DONE,
726 FrameEvent::DEQUEUE_READY,
727 FrameEvent::RELEASE,
728 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700729 ConditionalLock _l(mStateLock,
730 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700731 if (!getHwComposer().hasCapability(
732 HWC2::Capability::PresentFenceIsNotReliable)) {
733 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
734 }
735 return NO_ERROR;
736}
737
Dan Stoza7f7da322014-05-02 15:26:25 -0700738status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
739 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700740 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700741 return BAD_VALUE;
742 }
743
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500744 if (!display.get())
745 return NAME_NOT_FOUND;
746
Jesse Hall692c7232012-11-08 15:41:56 -0800747 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700748 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800749 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700750 type = i;
751 break;
752 }
753 }
754
755 if (type < 0) {
756 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700757 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 // TODO: Not sure if display density should handled by SF any longer
760 class Density {
761 static int getDensityFromProperty(char const* propName) {
762 char property[PROPERTY_VALUE_MAX];
763 int density = 0;
764 if (property_get(propName, property, NULL) > 0) {
765 density = atoi(property);
766 }
767 return density;
768 }
769 public:
770 static int getEmuDensity() {
771 return getDensityFromProperty("qemu.sf.lcd_density"); }
772 static int getBuildDensity() {
773 return getDensityFromProperty("ro.sf.lcd_density"); }
774 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700775
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700777
Steven Thomas6d8110b2017-08-31 18:24:21 -0700778 ConditionalLock _l(mStateLock,
779 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800780 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700781 DisplayInfo info = DisplayInfo();
782
Dan Stoza9e56aa02015-11-02 13:00:03 -0800783 float xdpi = hwConfig->getDpiX();
784 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700785
786 if (type == DisplayDevice::DISPLAY_PRIMARY) {
787 // The density of the device is provided by a build property
788 float density = Density::getBuildDensity() / 160.0f;
789 if (density == 0) {
790 // the build doesn't provide a density -- this is wrong!
791 // use xdpi instead
792 ALOGE("ro.sf.lcd_density must be defined as a build property");
793 density = xdpi / 160.0f;
794 }
795 if (Density::getEmuDensity()) {
796 // if "qemu.sf.lcd_density" is specified, it overrides everything
797 xdpi = ydpi = density = Density::getEmuDensity();
798 density /= 160.0f;
799 }
800 info.density = density;
801
802 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000804 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 } else {
806 // TODO: where should this value come from?
807 static const int TV_DENSITY = 213;
808 info.density = TV_DENSITY / 160.0f;
809 info.orientation = 0;
810 }
811
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812 info.w = hwConfig->getWidth();
813 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 info.xdpi = xdpi;
815 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900817 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800818
Andy McFadden91b2ca82014-06-13 14:04:23 -0700819 // This is how far in advance a buffer must be queued for
820 // presentation at a given time. If you want a buffer to appear
821 // on the screen at time N, you must submit the buffer before
822 // (N - presentationDeadline).
823 //
824 // Normally it's one full refresh period (to give SF a chance to
825 // latch the buffer), but this can be reduced by configuring a
826 // DispSync offset. Any additional delays introduced by the hardware
827 // composer or panel must be accounted for here.
828 //
829 // We add an additional 1ms to allow for processing time and
830 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800832 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700833
834 // All non-virtual displays are currently considered secure.
835 info.secure = true;
836
Michael Wright28f24d02016-07-12 13:30:53 -0700837 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 }
839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 return NO_ERROR;
841}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700842
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800843status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700844 DisplayStatInfo* stats) {
845 if (stats == NULL) {
846 return BAD_VALUE;
847 }
848
849 // FIXME for now we always return stats for the primary display
850 memset(stats, 0, sizeof(*stats));
851 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
852 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
853 return NO_ERROR;
854}
855
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700856int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800857 if (display == NULL) {
858 ALOGE("%s : display is NULL", __func__);
859 return BAD_VALUE;
860 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700861
862 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700863 if (device != NULL) {
864 return device->getActiveConfig();
865 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700866
Dan Stoza24a42e92015-03-09 10:04:11 -0700867 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700868}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700869
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700870void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
871 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
872 this);
873 int32_t type = hw->getDisplayType();
874 int currentMode = hw->getActiveConfig();
875
876 if (mode == currentMode) {
877 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
878 return;
879 }
880
881 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
882 ALOGW("Trying to set config for virtual display");
883 return;
884 }
885
886 hw->setActiveConfig(mode);
887 getHwComposer().setActiveConfig(type, mode);
888}
889
890status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
891 class MessageSetActiveConfig: public MessageBase {
892 SurfaceFlinger& mFlinger;
893 sp<IBinder> mDisplay;
894 int mMode;
895 public:
896 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
897 int mode) :
898 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
899 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700900 Vector<DisplayInfo> configs;
901 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700902 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700903 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700904 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700905 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700906 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700907 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
908 if (hw == NULL) {
909 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700910 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700911 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
912 ALOGW("Attempt to set active config = %d for virtual display",
913 mMode);
914 } else {
915 mFlinger.setActiveConfigInternal(hw, mMode);
916 }
917 return true;
918 }
919 };
920 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
921 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700922 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700923}
Michael Wright28f24d02016-07-12 13:30:53 -0700924status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
925 Vector<android_color_mode_t>* outColorModes) {
926 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
927 return BAD_VALUE;
928 }
929
930 if (!display.get()) {
931 return NAME_NOT_FOUND;
932 }
933
934 int32_t type = NAME_NOT_FOUND;
935 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
936 if (display == mBuiltinDisplays[i]) {
937 type = i;
938 break;
939 }
940 }
941
942 if (type < 0) {
943 return type;
944 }
945
Steven Thomas6d8110b2017-08-31 18:24:21 -0700946 std::vector<android_color_mode_t> modes;
947 {
948 ConditionalLock _l(mStateLock,
949 std::this_thread::get_id() != mMainThreadId);
950 modes = getHwComposer().getColorModes(type);
951 }
Michael Wright28f24d02016-07-12 13:30:53 -0700952 outColorModes->clear();
953 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
954
955 return NO_ERROR;
956}
957
958android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700959 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700960 if (device != nullptr) {
961 return device->getActiveColorMode();
962 }
963 return static_cast<android_color_mode_t>(BAD_VALUE);
964}
965
966void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
967 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700968 int32_t type = hw->getDisplayType();
969 android_color_mode_t currentMode = hw->getActiveColorMode();
970
971 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700972 return;
973 }
974
975 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
976 ALOGW("Trying to set config for virtual display");
977 return;
978 }
979
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600980 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
981 hw->getDisplayType());
982
Michael Wright28f24d02016-07-12 13:30:53 -0700983 hw->setActiveColorMode(mode);
984 getHwComposer().setActiveColorMode(type, mode);
985}
986
987
988status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
989 android_color_mode_t colorMode) {
990 class MessageSetActiveColorMode: public MessageBase {
991 SurfaceFlinger& mFlinger;
992 sp<IBinder> mDisplay;
993 android_color_mode_t mMode;
994 public:
995 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
996 android_color_mode_t mode) :
997 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
998 virtual bool handler() {
999 Vector<android_color_mode_t> modes;
1000 mFlinger.getDisplayColorModes(mDisplay, &modes);
1001 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1002 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1004 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001005 return true;
1006 }
1007 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1008 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001009 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1010 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001011 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001012 ALOGW("Attempt to set active color mode %s %d for virtual display",
1013 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001014 } else {
1015 mFlinger.setActiveColorModeInternal(hw, mMode);
1016 }
1017 return true;
1018 }
1019 };
1020 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1021 postMessageSync(msg);
1022 return NO_ERROR;
1023}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001024
Svetoslavd85084b2014-03-20 10:28:31 -07001025status_t SurfaceFlinger::clearAnimationFrameStats() {
1026 Mutex::Autolock _l(mStateLock);
1027 mAnimFrameTracker.clearStats();
1028 return NO_ERROR;
1029}
1030
1031status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1032 Mutex::Autolock _l(mStateLock);
1033 mAnimFrameTracker.getStats(outStats);
1034 return NO_ERROR;
1035}
1036
Dan Stozac4f471e2016-03-24 09:31:08 -07001037status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1038 HdrCapabilities* outCapabilities) const {
1039 Mutex::Autolock _l(mStateLock);
1040
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001041 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001042 if (displayDevice == nullptr) {
1043 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1044 return BAD_VALUE;
1045 }
1046
1047 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001048 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001049 if (capabilities) {
1050 std::swap(*outCapabilities, *capabilities);
1051 } else {
1052 return BAD_VALUE;
1053 }
1054
1055 return NO_ERROR;
1056}
1057
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001058status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001059 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1060 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061
Chia-I Wu90f669f2017-10-05 14:24:41 -07001062 if (mInjectVSyncs == enable) {
1063 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001064 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065
1066 if (enable) {
1067 ALOGV("VSync Injections enabled");
1068 if (mVSyncInjector.get() == nullptr) {
1069 mVSyncInjector = new InjectVSyncSource();
1070 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1071 }
1072 mEventQueue.setEventThread(mInjectorEventThread);
1073 } else {
1074 ALOGV("VSync Injections disabled");
1075 mEventQueue.setEventThread(mSFEventThread);
1076 }
1077
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079 });
1080 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081 return NO_ERROR;
1082}
1083
1084status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 Mutex::Autolock _l(mStateLock);
1086
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001087 if (!mInjectVSyncs) {
1088 ALOGE("VSync Injections not enabled");
1089 return BAD_VALUE;
1090 }
1091 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1092 ALOGV("Injecting VSync inside SurfaceFlinger");
1093 mVSyncInjector->onInjectSyncEvent(when);
1094 }
1095 return NO_ERROR;
1096}
1097
Kalle Raitaa099a242017-01-11 11:17:29 -08001098status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1099 IPCThreadState* ipc = IPCThreadState::self();
1100 const int pid = ipc->getCallingPid();
1101 const int uid = ipc->getCallingUid();
1102 if ((uid != AID_SHELL) &&
1103 !PermissionCache::checkPermission(sDump, pid, uid)) {
1104 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1105 return PERMISSION_DENIED;
1106 }
1107
1108 // Try to acquire a lock for 1s, fail gracefully
1109 const status_t err = mStateLock.timedLock(s2ns(1));
1110 const bool locked = (err == NO_ERROR);
1111 if (!locked) {
1112 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1113 return TIMED_OUT;
1114 }
1115
1116 outLayers->clear();
1117 mCurrentState.traverseInZOrder([&](Layer* layer) {
1118 outLayers->push_back(layer->getLayerDebugInfo());
1119 });
1120
1121 mStateLock.unlock();
1122 return NO_ERROR;
1123}
1124
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001125// ----------------------------------------------------------------------------
1126
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001127sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1128 ISurfaceComposer::VsyncSource vsyncSource) {
1129 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1130 return mSFEventThread->createEventConnection();
1131 } else {
1132 return mEventThread->createEventConnection();
1133 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001134}
1135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001137
1138void SurfaceFlinger::waitForEvent() {
1139 mEventQueue.waitMessage();
1140}
1141
1142void SurfaceFlinger::signalTransaction() {
1143 mEventQueue.invalidate();
1144}
1145
1146void SurfaceFlinger::signalLayerUpdate() {
1147 mEventQueue.invalidate();
1148}
1149
1150void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001151 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152 mEventQueue.refresh();
1153}
1154
1155status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001156 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001157 return mEventQueue.postMessage(msg, reltime);
1158}
1159
1160status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001161 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162 status_t res = mEventQueue.postMessage(msg, reltime);
1163 if (res == NO_ERROR) {
1164 msg->wait();
1165 }
1166 return res;
1167}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001168
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001169void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001170 do {
1171 waitForEvent();
1172 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001173}
1174
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175void SurfaceFlinger::enableHardwareVsync() {
1176 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001177 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001179 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1180 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001182 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183}
1184
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186 Mutex::Autolock _l(mHWVsyncLock);
1187
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188 if (makeAvailable) {
1189 mHWVsyncAvailable = true;
1190 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001191 // Hardware vsync is not currently available, so abort the resync
1192 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001193 return;
1194 }
1195
David Sodman105b7dc2017-11-04 20:28:14 -07001196 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001197 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198
1199 mPrimaryDispSync.reset();
1200 mPrimaryDispSync.setPeriod(period);
1201
1202 if (!mPrimaryHWVsyncEnabled) {
1203 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001204 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1205 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206 mPrimaryHWVsyncEnabled = true;
1207 }
1208}
1209
Jesse Hall948fe0c2013-10-14 12:56:09 -07001210void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 Mutex::Autolock _l(mHWVsyncLock);
1212 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001213 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1214 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215 mPrimaryDispSync.endResync();
1216 mPrimaryHWVsyncEnabled = false;
1217 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001218 if (makeUnavailable) {
1219 mHWVsyncAvailable = false;
1220 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221}
1222
Tim Murray4a4e4a22016-04-19 16:29:23 +00001223void SurfaceFlinger::resyncWithRateLimit() {
1224 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001225
1226 // No explicit locking is needed here since EventThread holds a lock while calling this method
1227 static nsecs_t sLastResyncAttempted = 0;
1228 const nsecs_t now = systemTime();
1229 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001230 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001231 }
Dan Stoza57164302017-05-08 14:03:54 -07001232 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001233}
1234
Steven Thomasb02664d2017-07-26 18:48:28 -07001235void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1236 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001237 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001238 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001239 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001240 return;
1241 }
1242
1243 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001244 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001245 return;
1246 }
1247
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 { // Scope for the lock
1251 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001252 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001255 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001256
1257 if (needsHwVsync) {
1258 enableHardwareVsync();
1259 } else {
1260 disableHardwareVsync(false);
1261 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001262}
1263
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001264void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001265 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1266 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001267}
1268
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001269void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001270 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001271 wp<IBinder> token = mBuiltinDisplays[type];
1272
1273 // All non-virtual displays are currently considered secure.
1274 const bool isSecure = true;
1275
1276 sp<IGraphicBufferProducer> producer;
1277 sp<IGraphicBufferConsumer> consumer;
1278 BufferQueue::createBufferQueue(&producer, &consumer);
1279
David Sodman105b7dc2017-11-04 20:28:14 -07001280 sp<FramebufferSurface> fbs = new FramebufferSurface(*getBE().mHwc, type, consumer);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001281
1282 bool hasWideColorModes = false;
1283 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1284 for (android_color_mode_t colorMode : modes) {
1285 switch (colorMode) {
1286 case HAL_COLOR_MODE_DISPLAY_P3:
1287 case HAL_COLOR_MODE_ADOBE_RGB:
1288 case HAL_COLOR_MODE_DCI_P3:
1289 hasWideColorModes = true;
1290 break;
1291 default:
1292 break;
1293 }
1294 }
Romain Guy54f154a2017-10-24 21:40:32 +01001295 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001296 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
Chia-I Wuc670d502017-11-09 23:17:51 -08001297 token, fbs, producer, useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001298 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001299 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001300 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001301 defaultColorMode = HAL_COLOR_MODE_SRGB;
1302 }
1303 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001304 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001305
1306 // Add the primary display token to mDrawingState so we don't try to
1307 // recreate the DisplayDevice for the primary display.
1308 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1309
1310 // make the GLContext current so that we can create textures when creating
1311 // Layers (which may happens before we render something)
Chia-I Wu7f402902017-11-09 12:51:10 -08001312 hw->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313}
1314
Steven Thomasb02664d2017-07-26 18:48:28 -07001315void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1316 hwc2_display_t display, HWC2::Connection connection,
1317 bool primaryDisplay) {
1318 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1319 sequenceId, display,
1320 connection == HWC2::Connection::Connected ?
1321 "connected" : "disconnected",
1322 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323
Steven Thomasb02664d2017-07-26 18:48:28 -07001324 // Only lock if we're not on the main thread. This function is normally
1325 // called on a hwbinder thread, but for the primary display it's called on
1326 // the main thread with the state lock already held, so don't attempt to
1327 // acquire it here.
1328 ConditionalLock lock(mStateLock,
1329 std::this_thread::get_id() != mMainThreadId);
1330
1331 if (primaryDisplay) {
David Sodman105b7dc2017-11-04 20:28:14 -07001332 getBE().mHwc->onHotplug(display, connection);
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1334 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001335 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001337 } else {
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 return;
1340 }
David Sodman105b7dc2017-11-04 20:28:14 -07001341 if (getBE().mHwc->isUsingVrComposer()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 ALOGE("External displays are not supported by the vr hardware composer.");
1343 return;
1344 }
David Sodman105b7dc2017-11-04 20:28:14 -07001345 getBE().mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001348 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001349 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001350 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1351 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001352 }
1353 setTransactionFlags(eDisplayTransactionNeeded);
1354
Andy McFadden9e9689c2012-10-10 18:17:51 -07001355 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001356 }
Mathias Agopian86303202012-07-24 22:46:10 -07001357}
1358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359void SurfaceFlinger::onRefreshReceived(int sequenceId,
1360 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001362 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001365 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001366}
1367
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 getHwComposer().setVsyncEnabled(disp,
1372 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001373}
1374
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001377 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378 // Clear the drawing state so that the logic inside of
1379 // handleTransactionLocked will fire. It will determine the delta between
1380 // mCurrentState and mDrawingState and re-apply all changes when we make the
1381 // transition.
1382 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001383 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384 mDisplays.clear();
1385}
1386
Steven Thomas050b2c82017-03-06 11:45:16 -08001387void SurfaceFlinger::updateVrFlinger() {
1388 if (!mVrFlinger)
1389 return;
1390 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001391 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001392 return;
1393 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 ALOGE("Vr flinger is only supported for remote hardware composer"
1397 " service connections. Ignoring request to transition to vr"
1398 " flinger.");
1399 mVrFlingerRequestsDisplay = false;
1400 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001401 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001403 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404
Steven Thomasb02664d2017-07-26 18:48:28 -07001405 int currentDisplayPowerMode = getDisplayDeviceLocked(
1406 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001413 getBE().mHwc.reset(); // Delete the current instance before creating the new one
David Sodmanbc815282017-11-05 18:57:52 -08001414 getBE().mHwc.reset(new HWComposer(vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
David Sodman105b7dc2017-11-04 20:28:14 -07001415 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416
David Sodman105b7dc2017-11-04 20:28:14 -07001417 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1418 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001419
1420 if (vrFlingerRequestsDisplay) {
1421 mVrFlinger->GrantDisplayOwnership();
1422 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425
1426 mVisibleRegionsDirty = true;
1427 invalidateHwcGeometry();
1428
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001429 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1431 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1432 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001435 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 const nsecs_t period = activeConfig->getVsyncPeriod();
1437 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 // Use phase of 0 since phase is not known.
1440 // Use latency of 0, which will snap to the ideal latency.
1441 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001442
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443 android_atomic_or(1, &mRepaintEverything);
1444 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445}
1446
Mathias Agopian4fec8732012-06-29 14:12:52 -07001447void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001448 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001449 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001451 bool frameMissed = !mHadClientComposition &&
1452 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001453 (mPreviousPresentFence->getSignalTime() ==
1454 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001455 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001456 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001457 signalLayerUpdate();
1458 break;
1459 }
1460
Steven Thomas050b2c82017-03-06 11:45:16 -08001461 // Now that we're going to make it to the handleMessageTransaction()
1462 // call below it's safe to call updateVrFlinger(), which will
1463 // potentially trigger a display handoff.
1464 updateVrFlinger();
1465
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 bool refreshNeeded = handleMessageTransaction();
1467 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001468 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001470 // Signal a refresh if a transaction modified the window state,
1471 // a new buffer was latched, or if HWC has requested a full
1472 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 signalRefresh();
1474 }
1475 break;
1476 }
1477 case MessageQueue::REFRESH: {
1478 handleMessageRefresh();
1479 break;
1480 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001481 }
1482}
1483
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001485 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001486 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001487 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001491}
1492
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496}
1497
1498void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001500
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001501 mRefreshPending = false;
1502
Pablo Ceballos40845df2016-01-25 17:41:15 -08001503 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001504
Brian Andersond6927fb2016-07-23 23:37:30 -07001505 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001506 rebuildLayerStacks();
1507 setUpHWComposer();
1508 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001509 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001510 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001511 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001512
David Sodman105b7dc2017-11-04 20:28:14 -07001513 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001514
1515 mHadClientComposition = false;
1516 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1517 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1518 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001519 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001520 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001521
Dan Stoza9e56aa02015-11-02 13:00:03 -08001522 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525void SurfaceFlinger::doDebugFlashRegions()
1526{
1527 // is debugging enabled
1528 if (CC_LIKELY(!mDebugRegion))
1529 return;
1530
1531 const bool repaintEverything = mRepaintEverything;
1532 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1533 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001534 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535 // transform the dirty region into this screen's coordinate space
1536 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1537 if (!dirtyRegion.isEmpty()) {
1538 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001539 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540
1541 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001543 RenderEngine& engine(getRenderEngine());
1544 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1545
Mathias Agopianda27af92012-09-13 18:17:13 -07001546 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 }
1548 }
1549 }
1550
1551 postFramebuffer();
1552
1553 if (mDebugRegion > 1) {
1554 usleep(mDebugRegion * 1000);
1555 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001556
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001558 auto& displayDevice = mDisplays[displayId];
1559 if (!displayDevice->isDisplayOn()) {
1560 continue;
1561 }
1562
David Sodman105b7dc2017-11-04 20:28:14 -07001563 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1564 ALOGE_IF(result != NO_ERROR,
1565 "prepareFrame for display %zd failed:"
1566 " %d (%s)",
1567 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001568 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569}
1570
Adrian Roos1e1a1282017-11-01 19:05:31 +01001571void SurfaceFlinger::doTracing(const char* where) {
1572 ATRACE_CALL();
1573 ATRACE_NAME(where);
1574 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001575 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001576 }
1577}
1578
Brian Andersond6927fb2016-07-23 23:37:30 -07001579void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001581 ATRACE_CALL();
1582 ALOGV("preComposition");
1583
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001585 mDrawingState.traverseInZOrder([&](Layer* layer) {
1586 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 needExtraInvalidate = true;
1588 }
Robert Carr2047fae2016-11-28 14:09:09 -08001589 });
1590
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591 if (needExtraInvalidate) {
1592 signalLayerUpdate();
1593 }
1594}
1595
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001596void SurfaceFlinger::updateCompositorTiming(
1597 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1598 std::shared_ptr<FenceTime>& presentFenceTime) {
1599 // Update queue of past composite+present times and determine the
1600 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001601 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001603 while (!getBE().mCompositePresentTimes.empty()) {
1604 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605 // Cached values should have been updated before calling this method,
1606 // which helps avoid duplicate syscalls.
1607 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1608 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1609 break;
1610 }
1611 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001612 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613 }
1614
1615 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001616 while (getBE().mCompositePresentTimes.size() > 16) {
1617 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001618 }
1619
Brian Andersond0010582017-03-07 13:20:31 -08001620 setCompositorTimingSnapped(
1621 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1622}
1623
1624void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1625 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 // Integer division and modulo round toward 0 not -inf, so we need to
1627 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001628 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1630 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1631
Brian Andersond0010582017-03-07 13:20:31 -08001632 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1633 if (idealLatency <= 0) {
1634 idealLatency = vsyncInterval;
1635 }
1636
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637 // Snap the latency to a value that removes scheduling jitter from the
1638 // composition and present times, which often have >1ms of jitter.
1639 // Reducing jitter is important if an app attempts to extrapolate
1640 // something (such as user input) to an accurate diasplay time.
1641 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1642 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001643 nsecs_t bias = vsyncInterval / 2;
1644 int64_t extraVsyncs =
1645 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1646 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1647 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648
David Sodman99974d22017-11-28 12:04:33 -08001649 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1650 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1651 getBE().mCompositorTiming.interval = vsyncInterval;
1652 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653}
1654
1655void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 ATRACE_CALL();
1658 ALOGV("postComposition");
1659
Brian Anderson3546a3f2016-07-14 11:51:14 -07001660 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001661 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001662 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001663 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001664 }
1665
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001666 // |mStateLock| not needed as we are on the main thread
1667 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668
David Sodman73beded2017-11-15 11:56:06 -08001669 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001670 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
David Sodman105b7dc2017-11-04 20:28:14 -07001671 if (getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001672 glCompositionDoneFenceTime =
1673 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001674 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675 } else {
1676 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1677 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001678
David Sodman73beded2017-11-15 11:56:06 -08001679 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001680 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001681 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001682 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001683
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1685 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1686
1687 // We use the refreshStartTime which might be sampled a little later than
1688 // when we started doing work for this frame, but that should be okay
1689 // since updateCompositorTiming has snapping logic.
1690 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001691 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001692 CompositorTiming compositorTiming;
1693 {
David Sodman99974d22017-11-28 12:04:33 -08001694 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1695 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001696 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697
Robert Carr2047fae2016-11-28 14:09:09 -08001698 mDrawingState.traverseInZOrder([&](Layer* layer) {
1699 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001700 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001701 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001702 recordBufferingStats(layer->getName().string(),
1703 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001704 }
Robert Carr2047fae2016-11-28 14:09:09 -08001705 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001706
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001707 if (presentFenceTime->isValid()) {
1708 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001709 enableHardwareVsync();
1710 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001711 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001712 }
1713 }
1714
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001715 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001716 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001717 enableHardwareVsync();
1718 }
1719 }
1720
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001721 if (mAnimCompositionPending) {
1722 mAnimCompositionPending = false;
1723
Brian Anderson4e606e32017-03-16 15:34:57 -07001724 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001725 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001726 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001727 } else {
1728 // The HWC doesn't support present fences, so use the refresh
1729 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001731 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001732 mAnimFrameTracker.setActualPresentTime(presentTime);
1733 }
1734 mAnimFrameTracker.advanceFrame();
1735 }
Dan Stozab90cf072015-03-05 11:05:59 -08001736
1737 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1738 return;
1739 }
1740
1741 nsecs_t currentTime = systemTime();
1742 if (mHasPoweredOff) {
1743 mHasPoweredOff = false;
1744 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001745 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001746 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001747 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1748 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001749 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001750 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001751 }
David Sodman4a36e932017-11-07 14:29:47 -08001752 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001753 }
David Sodman4a36e932017-11-07 14:29:47 -08001754 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001755}
1756
1757void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001758 ATRACE_CALL();
1759 ALOGV("rebuildLayerStacks");
1760
Mathias Agopiancd60f992012-08-16 16:28:27 -07001761 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001763 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 mVisibleRegionsDirty = false;
1765 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001766
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1768 Region opaqueRegion;
1769 Region dirtyRegion;
1770 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001771 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001772 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1773 const Transform& tr(displayDevice->getTransform());
1774 const Rect bounds(displayDevice->getBounds());
1775 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001776 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001777
Jeff Sharkey76488112017-02-27 14:15:18 -07001778 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001779 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001780 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1781 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001782 Region drawRegion(tr.transform(
1783 layer->visibleNonTransparentRegion));
1784 drawRegion.andSelf(bounds);
1785 if (!drawRegion.isEmpty()) {
1786 layersSortedByZ.add(layer);
1787 } else {
1788 // Clear out the HWC layer if this layer was
1789 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001790 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001791 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001793 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001794 // WM changes displayDevice->layerStack upon sleep/awake.
1795 // Here we make sure we delete the HWC layers even if
1796 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001797 hwcLayerDestroyed = layer->destroyHwcLayer(
1798 displayDevice->getHwcDisplayId());
1799 }
1800
1801 // If a layer is not going to get a release fence because
1802 // it is invisible, but it is also going to release its
1803 // old buffer, add it to the list of layers needing
1804 // fences.
1805 if (hwcLayerDestroyed) {
1806 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1807 mLayersWithQueuedFrames.cend(), layer);
1808 if (found != mLayersWithQueuedFrames.cend()) {
1809 layersNeedingFences.add(layer);
1810 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001811 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 });
1813 }
1814 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001815 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 displayDevice->undefinedRegion.set(bounds);
1817 displayDevice->undefinedRegion.subtractSelf(
1818 tr.transform(opaqueRegion));
1819 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001823
Romain Guy0147a172017-06-01 13:53:56 -07001824mat4 SurfaceFlinger::computeSaturationMatrix() const {
1825 if (mSaturation == 1.0f) {
1826 return mat4();
1827 }
1828
1829 // Rec.709 luma coefficients
1830 float3 luminance{0.213f, 0.715f, 0.072f};
1831 luminance *= 1.0f - mSaturation;
1832 return mat4(
1833 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1834 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1835 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1836 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1837 );
1838}
1839
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001840// pickColorMode translates a given dataspace into the best available color mode.
1841// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001842android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001843 if (mForceNativeColorMode) {
1844 return HAL_COLOR_MODE_NATIVE;
1845 }
1846
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001847 switch (dataSpace) {
1848 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1849 // system expects.
1850 case HAL_DATASPACE_UNKNOWN:
1851 case HAL_DATASPACE_SRGB:
1852 case HAL_DATASPACE_V0_SRGB:
1853 return HAL_COLOR_MODE_SRGB;
1854 break;
1855
1856 case HAL_DATASPACE_DISPLAY_P3:
1857 return HAL_COLOR_MODE_DISPLAY_P3;
1858 break;
1859
1860 default:
1861 // TODO (courtneygo): Do we want to assert an error here?
1862 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1863 dataSpace);
1864 return HAL_COLOR_MODE_SRGB;
1865 break;
1866 }
1867}
1868
Romain Guy0147a172017-06-01 13:53:56 -07001869android_dataspace SurfaceFlinger::bestTargetDataSpace(
1870 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001871 // Only support sRGB and Display-P3 right now.
1872 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1873 return HAL_DATASPACE_DISPLAY_P3;
1874 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001875 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1876 return HAL_DATASPACE_DISPLAY_P3;
1877 }
1878 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1879 return HAL_DATASPACE_DISPLAY_P3;
1880 }
1881
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001882 return HAL_DATASPACE_V0_SRGB;
1883}
1884
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 ATRACE_CALL();
1887 ALOGV("setUpHWComposer");
1888
Jesse Hall028dc8f2013-08-20 16:35:32 -07001889 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001890 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1891 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1892 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1893
1894 // If nothing has changed (!dirty), don't recompose.
1895 // If something changed, but we don't currently have any visible layers,
1896 // and didn't when we last did a composition, then skip it this time.
1897 // The second rule does two things:
1898 // - When all layers are removed from a display, we'll emit one black
1899 // frame, then nothing more until we get new layers.
1900 // - When a display is created with a private layer stack, we won't
1901 // emit any black frames until a layer is added to the layer stack.
1902 bool mustRecompose = dirty && !(empty && wasEmpty);
1903
1904 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1905 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1906 mustRecompose ? "doing" : "skipping",
1907 dirty ? "+" : "-",
1908 empty ? "+" : "-",
1909 wasEmpty ? "+" : "-");
1910
Dan Stoza71433162014-02-04 16:22:36 -08001911 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001912
1913 if (mustRecompose) {
1914 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1915 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001916 }
1917
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 // build the h/w work list
1919 if (CC_UNLIKELY(mGeometryInvalid)) {
1920 mGeometryInvalid = false;
1921 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1922 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1923 const auto hwcId = displayDevice->getHwcDisplayId();
1924 if (hwcId >= 0) {
1925 const Vector<sp<Layer>>& currentLayers(
1926 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001927 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001928 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001930 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001933 }
1934 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001935
Robert Carrae060832016-11-28 10:51:00 -08001936 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001937 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001939 }
1940 }
1941 }
1942 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 }
Riley Andrews03414a12014-07-01 14:22:59 -07001944
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001945
Romain Guy0147a172017-06-01 13:53:56 -07001946 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001947
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 // Set the per-frame data
1949 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1950 auto& displayDevice = mDisplays[displayId];
1951 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001952
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 if (hwcId < 0) {
1954 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001955 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001956 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001957 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001958 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1959 "display %zd: %d", displayId, result);
1960 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001962 if (layer->getForceClientComposition(hwcId)) {
1963 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1964 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1965 continue;
1966 }
1967
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 layer->setPerFrameData(displayDevice);
1969 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001970
1971 if (hasWideColorDisplay) {
1972 android_color_mode newColorMode;
1973 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1974
1975 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1976 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1977 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1978 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1979 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1980 }
1981 newColorMode = pickColorMode(newDataSpace);
1982
Thierry Strudel2924d012017-08-14 15:19:37 -07001983 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001984 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 }
1986
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001987 mPreviousColorMatrix = colorMatrix;
1988
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001990 auto& displayDevice = mDisplays[displayId];
1991 if (!displayDevice->isDisplayOn()) {
1992 continue;
1993 }
1994
David Sodman105b7dc2017-11-04 20:28:14 -07001995 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1997 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001998 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001999}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002000
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001void SurfaceFlinger::doComposition() {
2002 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 ALOGV("doComposition");
2004
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002005 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002006 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002007 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002008 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009 // transform the dirty region into this screen's coordinate space
2010 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002011
2012 // repaint the framebuffer (if needed)
2013 doDisplayComposition(hw, dirtyRegion);
2014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002016 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002017 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002018 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002019 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002020}
2021
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002022void SurfaceFlinger::postFramebuffer()
2023{
Mathias Agopian841cde52012-03-01 15:44:37 -08002024 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002025 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002026
Mathias Agopiana44b0412011-10-16 18:46:35 -07002027 const nsecs_t now = systemTime();
2028 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002029
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2031 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002032 if (!displayDevice->isDisplayOn()) {
2033 continue;
2034 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002035 const auto hwcId = displayDevice->getHwcDisplayId();
2036 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002037 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002038 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002039 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002040 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002042 // The layer buffer from the previous frame (if any) is released
2043 // by HWC only when the release fence from this frame (if any) is
2044 // signaled. Always get the release fence from HWC first.
2045 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002046 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002047
2048 // If the layer was client composited in the previous frame, we
2049 // need to merge with the previous client target acquire fence.
2050 // Since we do not track that, always merge with the current
2051 // client target acquire fence when it is available, even though
2052 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002054 releaseFence = Fence::merge("LayerRelease", releaseFence,
2055 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002056 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002057
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 layer->onLayerDisplayed(releaseFence);
2059 }
Chia-I Wu83806892017-11-16 10:50:20 -08002060
2061 // We've got a list of layers needing fences, that are disjoint with
2062 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2063 // supply them with the present fence.
2064 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002065 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002066 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2067 layer->onLayerDisplayed(presentFence);
2068 }
2069 }
2070
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002072 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002073 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002074 }
2075
Mathias Agopiana44b0412011-10-16 18:46:35 -07002076 mLastSwapBufferTime = systemTime() - now;
2077 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002078
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002079 // |mStateLock| not needed as we are on the main thread
2080 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002081 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2082 logFrameStats();
2083 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084}
2085
Mathias Agopian87baae12012-07-31 12:38:26 -07002086void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087{
Mathias Agopian841cde52012-03-01 15:44:37 -08002088 ATRACE_CALL();
2089
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002090 // here we keep a copy of the drawing state (that is the state that's
2091 // going to be overwritten by handleTransactionLocked()) outside of
2092 // mStateLock so that the side-effects of the State assignment
2093 // don't happen with mStateLock held (which can cause deadlocks).
2094 State drawingState(mDrawingState);
2095
Mathias Agopianca4d3602011-05-19 15:38:14 -07002096 Mutex::Autolock _l(mStateLock);
2097 const nsecs_t now = systemTime();
2098 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099
Mathias Agopianca4d3602011-05-19 15:38:14 -07002100 // Here we're guaranteed that some transaction flags are set
2101 // so we can call handleTransactionLocked() unconditionally.
2102 // We call getTransactionFlags(), which will also clear the flags,
2103 // with mStateLock held to guarantee that mCurrentState won't change
2104 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002105
Mathias Agopiane57f2922012-08-09 16:29:12 -07002106 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002107 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002108
Mathias Agopianca4d3602011-05-19 15:38:14 -07002109 mLastTransactionTime = systemTime() - now;
2110 mDebugInTransaction = 0;
2111 invalidateHwcGeometry();
2112 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002113}
2114
Mathias Agopian87baae12012-07-31 12:38:26 -07002115void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002116{
Dan Stoza7dde5992015-05-22 09:51:44 -07002117 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002118 mCurrentState.traverseInZOrder([](Layer* layer) {
2119 layer->notifyAvailableFrames();
2120 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122 /*
2123 * Traversal of the children
2124 * (perform the transaction for each of them if needed)
2125 */
2126
Mathias Agopian3559b072012-08-15 13:46:03 -07002127 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002128 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002130 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131
2132 const uint32_t flags = layer->doTransaction(0);
2133 if (flags & Layer::eVisibleRegion)
2134 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002135 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002136 }
2137
2138 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002139 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140 */
2141
Mathias Agopiane57f2922012-08-09 16:29:12 -07002142 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002143 // here we take advantage of Vector's copy-on-write semantics to
2144 // improve performance by skipping the transaction entirely when
2145 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002146 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2147 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002148 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002150 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002151 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002152
2153 // find the displays that were removed
2154 // (ie: in drawing state but not in current state)
2155 // also handle displays that changed
2156 // (ie: displays that are in both lists)
Ivan Lozano51a0b412017-12-06 17:07:27 -08002157 for (size_t i=0 ; i<dc ;) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002158 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2159 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002160 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002161 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002162 // Call makeCurrent() on the primary display so we can
2163 // be sure that nothing associated with this display
2164 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002165 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Chia-I Wu7f402902017-11-09 12:51:10 -08002166 defaultDisplay->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002167 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002168 if (hw != NULL)
2169 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002170 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002171 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002172 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002173 } else {
2174 ALOGW("trying to remove the main display");
2175 }
2176 } else {
2177 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002178 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002179 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002180 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2181 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002182 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002183 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002184 // recreating the DisplayDevice, so we just remove it
2185 // from the drawing state, so that it get re-added
2186 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002187 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002188 if (hw != NULL)
2189 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002190 mDisplays.removeItem(display);
2191 mDrawingState.displays.removeItemsAt(i);
Ivan Lozano51a0b412017-12-06 17:07:27 -08002192 dc--;
Mathias Agopian93997a82012-08-29 17:30:36 -07002193 // at this point we must loop to the next item
2194 continue;
2195 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002196
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002197 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002198 if (disp != NULL) {
2199 if (state.layerStack != draw[i].layerStack) {
2200 disp->setLayerStack(state.layerStack);
2201 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002202 if ((state.orientation != draw[i].orientation)
2203 || (state.viewport != draw[i].viewport)
2204 || (state.frame != draw[i].frame))
2205 {
2206 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002207 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002208 }
Michael Lentine47e45402014-07-18 15:34:25 -07002209 if (state.width != draw[i].width || state.height != draw[i].height) {
2210 disp->setDisplaySize(state.width, state.height);
2211 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002212 }
2213 }
Ivan Lozano51a0b412017-12-06 17:07:27 -08002214 ++i;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002215 }
2216
2217 // find displays that were added
2218 // (ie: in current state but not in drawing state)
2219 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002220 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002221 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002222
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002223 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002224 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002225 sp<IGraphicBufferProducer> bqProducer;
2226 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002227 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002228
Dan Stoza9e56aa02015-11-02 13:00:03 -08002229 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002230 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002231 // Virtual displays without a surface are dormant:
2232 // they have external state (layer stack, projection,
2233 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002234 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002235
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002236 // Allow VR composer to use virtual displays.
David Sodman105b7dc2017-11-04 20:28:14 -07002237 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002238 int width = 0;
2239 int status = state.surface->query(
2240 NATIVE_WINDOW_WIDTH, &width);
2241 ALOGE_IF(status != NO_ERROR,
2242 "Unable to query width (%d)", status);
2243 int height = 0;
2244 status = state.surface->query(
2245 NATIVE_WINDOW_HEIGHT, &height);
2246 ALOGE_IF(status != NO_ERROR,
2247 "Unable to query height (%d)", status);
2248 int intFormat = 0;
2249 status = state.surface->query(
2250 NATIVE_WINDOW_FORMAT, &intFormat);
2251 ALOGE_IF(status != NO_ERROR,
2252 "Unable to query format (%d)", status);
2253 auto format = static_cast<android_pixel_format_t>(
2254 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002255
David Sodman105b7dc2017-11-04 20:28:14 -07002256 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza8cf150a2016-08-02 10:27:31 -07002257 &hwcId);
2258 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259
Dan Stoza5cf424b2016-05-20 14:02:39 -07002260 // TODO: Plumb requested format back up to consumer
2261
Dan Stoza9e56aa02015-11-02 13:00:03 -08002262 sp<VirtualDisplaySurface> vds =
David Sodman105b7dc2017-11-04 20:28:14 -07002263 new VirtualDisplaySurface(*getBE().mHwc,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002264 hwcId, state.surface, bqProducer,
2265 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002266
2267 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002268 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002269 }
2270 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002271 ALOGE_IF(state.surface!=NULL,
2272 "adding a supported display, but rendering "
2273 "surface is provided (%p), ignoring it",
2274 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002275
2276 hwcId = state.type;
David Sodman105b7dc2017-11-04 20:28:14 -07002277 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002278 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002279 }
2280
2281 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002282 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002283 sp<DisplayDevice> hw =
2284 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
Chia-I Wuc670d502017-11-09 23:17:51 -08002285 dispSurface, producer, hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002286 hw->setLayerStack(state.layerStack);
2287 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002288 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002289 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002290 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002291 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002292 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002293 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002294 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002295 }
2296 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299
Mathias Agopian84300952012-11-21 16:02:13 -08002300 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2301 // The transform hint might have changed for some layers
2302 // (either because a display has changed, or because a layer
2303 // as changed).
2304 //
2305 // Walk through all the layers in currentLayers,
2306 // and update their transform hint.
2307 //
2308 // If a layer is visible only on a single display, then that
2309 // display is used to calculate the hint, otherwise we use the
2310 // default display.
2311 //
2312 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2313 // the hint is set before we acquire a buffer from the surface texture.
2314 //
2315 // NOTE: layer transactions have taken place already, so we use their
2316 // drawing state. However, SurfaceFlinger's own transaction has not
2317 // happened yet, so we must use the current state layer list
2318 // (soon to become the drawing state list).
2319 //
2320 sp<const DisplayDevice> disp;
2321 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002322 bool first = true;
2323 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002324 // NOTE: we rely on the fact that layers are sorted by
2325 // layerStack first (so we don't have to traverse the list
2326 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002327 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002328 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002329 currentlayerStack = layerStack;
2330 // figure out if this layerstack is mirrored
2331 // (more than one display) if so, pick the default display,
2332 // if not, pick the only display it's on.
2333 disp.clear();
2334 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2335 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002336 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002337 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002338 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002339 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002340 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002341 break;
2342 }
2343 }
2344 }
2345 }
Chet Haase91d25932013-04-11 15:24:55 -07002346 if (disp == NULL) {
2347 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2348 // redraw after transform hint changes. See bug 8508397.
2349
2350 // could be null when this layer is using a layerStack
2351 // that is not visible on any display. Also can occur at
2352 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002353 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002354 }
Chet Haase91d25932013-04-11 15:24:55 -07002355 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002356
2357 first = false;
2358 });
Mathias Agopian84300952012-11-21 16:02:13 -08002359 }
2360
2361
Mathias Agopian3559b072012-08-15 13:46:03 -07002362 /*
2363 * Perform our own transaction if needed
2364 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002365
2366 if (mLayersAdded) {
2367 mLayersAdded = false;
2368 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002369 mVisibleRegionsDirty = true;
2370 }
2371
2372 // some layers might have been removed, so
2373 // we need to update the regions they're exposing.
2374 if (mLayersRemoved) {
2375 mLayersRemoved = false;
2376 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002377 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002378 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002379 // this layer is not visible anymore
2380 // TODO: we could traverse the tree from front to back and
2381 // compute the actual visible region
2382 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002383 Region visibleReg;
2384 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002385 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002386 }
Robert Carr2047fae2016-11-28 14:09:09 -08002387 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388 }
2389
2390 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002391
2392 updateCursorAsync();
2393}
2394
2395void SurfaceFlinger::updateCursorAsync()
2396{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002397 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2398 auto& displayDevice = mDisplays[displayId];
2399 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002400 continue;
2401 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002402
2403 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2404 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002405 }
2406 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002407}
2408
2409void SurfaceFlinger::commitTransaction()
2410{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002411 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002412 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002413 for (const auto& l : mLayersPendingRemoval) {
2414 recordBufferingStats(l->getName().string(),
2415 l->getOccupancyHistory(true));
2416 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002417 }
2418 mLayersPendingRemoval.clear();
2419 }
2420
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002421 // If this transaction is part of a window animation then the next frame
2422 // we composite should be considered an animation as well.
2423 mAnimCompositionPending = mAnimTransactionPending;
2424
Mathias Agopian4fec8732012-06-29 14:12:52 -07002425 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002426 mDrawingState.traverseInZOrder([](Layer* layer) {
2427 layer->commitChildList();
2428 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002429 mTransactionPending = false;
2430 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432}
2433
Chia-I Wuab0c3192017-08-01 11:29:00 -07002434void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002435 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436{
Mathias Agopian841cde52012-03-01 15:44:37 -08002437 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002438 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002439
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440 Region aboveOpaqueLayers;
2441 Region aboveCoveredLayers;
2442 Region dirty;
2443
Mathias Agopian87baae12012-07-31 12:38:26 -07002444 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445
Robert Carr2047fae2016-11-28 14:09:09 -08002446 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002448 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449
Jesse Hall01e29052013-02-19 16:13:35 -08002450 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002451 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002452 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002453
Mathias Agopianab028732010-03-16 16:41:46 -07002454 /*
2455 * opaqueRegion: area of a surface that is fully opaque.
2456 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002458
2459 /*
2460 * visibleRegion: area of a surface that is visible on screen
2461 * and not fully transparent. This is essentially the layer's
2462 * footprint minus the opaque regions above it.
2463 * Areas covered by a translucent surface are considered visible.
2464 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002466
2467 /*
2468 * coveredRegion: area of a surface that is covered by all
2469 * visible regions above it (which includes the translucent areas).
2470 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002472
Jesse Halla8026d22012-09-25 13:25:04 -07002473 /*
2474 * transparentRegion: area of a surface that is hinted to be completely
2475 * transparent. This is only used to tell when the layer has no visible
2476 * non-transparent regions and can be removed from the layer list. It
2477 * does not affect the visibleRegion of this layer or any layers
2478 * beneath it. The hint may not be correct if apps don't respect the
2479 * SurfaceView restrictions (which, sadly, some don't).
2480 */
2481 Region transparentRegion;
2482
Mathias Agopianab028732010-03-16 16:41:46 -07002483
2484 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002485 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002486 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002487 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002489 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002490 if (!visibleRegion.isEmpty()) {
2491 // Remove the transparent area from the visible region
2492 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002493 if (tr.preserveRects()) {
2494 // transform the transparent region
2495 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002496 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002497 // transformation too complex, can't do the
2498 // transparent region optimization.
2499 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002500 }
Mathias Agopianab028732010-03-16 16:41:46 -07002501 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502
Mathias Agopianab028732010-03-16 16:41:46 -07002503 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002504 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002505 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002506 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2507 // the opaque region is the layer's footprint
2508 opaqueRegion = visibleRegion;
2509 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 }
2511 }
2512
Mathias Agopianab028732010-03-16 16:41:46 -07002513 // Clip the covered region to the visible region
2514 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2515
2516 // Update aboveCoveredLayers for next (lower) layer
2517 aboveCoveredLayers.orSelf(visibleRegion);
2518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 // subtract the opaque region covered by the layers above us
2520 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521
2522 // compute this layer's dirty region
2523 if (layer->contentDirty) {
2524 // we need to invalidate the whole region
2525 dirty = visibleRegion;
2526 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002527 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002528 layer->contentDirty = false;
2529 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002530 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002531 * the exposed region consists of two components:
2532 * 1) what's VISIBLE now and was COVERED before
2533 * 2) what's EXPOSED now less what was EXPOSED before
2534 *
2535 * note that (1) is conservative, we start with the whole
2536 * visible region but only keep what used to be covered by
2537 * something -- which mean it may have been exposed.
2538 *
2539 * (2) handles areas that were not covered by anything but got
2540 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002541 */
Mathias Agopianab028732010-03-16 16:41:46 -07002542 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002543 const Region oldVisibleRegion = layer->visibleRegion;
2544 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002545 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2546 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547 }
2548 dirty.subtractSelf(aboveOpaqueLayers);
2549
2550 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002551 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552
Mathias Agopianab028732010-03-16 16:41:46 -07002553 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002555
Jesse Halla8026d22012-09-25 13:25:04 -07002556 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 layer->setVisibleRegion(visibleRegion);
2558 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002559 layer->setVisibleNonTransparentRegion(
2560 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002561 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562
Mathias Agopian87baae12012-07-31 12:38:26 -07002563 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564}
2565
Chia-I Wuab0c3192017-08-01 11:29:00 -07002566void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002567 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002568 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002569 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002570 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002571 }
2572 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002573}
2574
Dan Stoza6b9454d2014-11-07 16:00:59 -08002575bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 ALOGV("handlePageFlip");
2578
Brian Andersond6927fb2016-07-23 23:37:30 -07002579 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580
Mathias Agopian4fec8732012-06-29 14:12:52 -07002581 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002582 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002583 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002584
2585 // Store the set of layers that need updates. This set must not change as
2586 // buffers are being latched, as this could result in a deadlock.
2587 // Example: Two producers share the same command stream and:
2588 // 1.) Layer 0 is latched
2589 // 2.) Layer 0 gets a new frame
2590 // 2.) Layer 1 gets a new frame
2591 // 3.) Layer 1 is latched.
2592 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2593 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002594 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002595 if (layer->hasQueuedFrame()) {
2596 frameQueued = true;
2597 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002598 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002599 } else {
2600 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002601 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002602 } else {
2603 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002604 }
Robert Carr2047fae2016-11-28 14:09:09 -08002605 });
2606
Dan Stoza9e56aa02015-11-02 13:00:03 -08002607 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002608 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002609 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002610 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002611 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002612 newDataLatched = true;
2613 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002614 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002615
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002616 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002617
2618 // If we will need to wake up at some time in the future to deal with a
2619 // queued frame that shouldn't be displayed during this vsync period, wake
2620 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002621 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002622 signalLayerUpdate();
2623 }
2624
2625 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002626 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627}
2628
Mathias Agopianad456f92011-01-13 17:53:01 -08002629void SurfaceFlinger::invalidateHwcGeometry()
2630{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002631 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002632}
2633
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002634
Fabien Sanglard830b8472016-11-30 16:35:58 -08002635void SurfaceFlinger::doDisplayComposition(
2636 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002637 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638{
Dan Stoza71433162014-02-04 16:22:36 -08002639 // We only need to actually compose the display if:
2640 // 1) It is being handled by hardware composer, which may need this to
2641 // keep its virtual display state machine in sync, or
2642 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002643 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002644 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002646 return;
2647 }
2648
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002650 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002651
2652 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002653 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654}
2655
Chia-I Wub02087d2017-11-09 10:19:54 -08002656bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002657{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002659
Chia-I Wub02087d2017-11-09 10:19:54 -08002660 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002661 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002663
2664 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002665 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2666 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002667 if (applyColorMatrix) {
2668 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2669 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2670 }
2671
David Sodman105b7dc2017-11-04 20:28:14 -07002672 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 if (hasClientComposition) {
2674 ALOGV("hasClientComposition");
2675
David Sodmanbc815282017-11-05 18:57:52 -08002676 getBE().mRenderEngine->setWideColor(
Romain Guy54f154a2017-10-24 21:40:32 +01002677 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
David Sodmanbc815282017-11-05 18:57:52 -08002678 getBE().mRenderEngine->setColorMode(mForceNativeColorMode ?
Romain Guy54f154a2017-10-24 21:40:32 +01002679 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002680 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002681 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002683 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002684
2685 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002686 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002687 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2688 }
2689 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002690 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002691
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002692 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002693 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002695 // when using overlays, we assume a fully transparent framebuffer
2696 // NOTE: we could reduce how much we need to clear, for instance
2697 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002698 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002699 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002700 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002701 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002702 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002703 // we're left with the letterbox region
2704 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002706
2707 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002709
Mathias Agopianb9494d52012-04-18 02:28:45 -07002710 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002711 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002712 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002714 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002715 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002716
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002718 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002719 // scissor on the main display. It should never be needed
2720 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 const Rect& bounds(displayDevice->getBounds());
2722 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002723 if (scissor != bounds) {
2724 // scissor doesn't match the screen's dimensions, so we
2725 // need to clear everything outside of it and enable
2726 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002727
Mathias Agopianf45c5102012-10-24 16:29:17 -07002728 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002730 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002731 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002732 }
2733 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002735
Mathias Agopian85d751c2012-08-29 16:59:24 -07002736 /*
2737 * and then, render the layers targeted at the framebuffer
2738 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002739
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 ALOGV("Rendering client layers");
2741 const Transform& displayTransform = displayDevice->getTransform();
2742 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002743 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 bool firstLayer = true;
2745 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002746 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 displayTransform.transform(layer->visibleRegion)));
2748 ALOGV("Layer: %s", layer->getName().string());
2749 ALOGV(" Composition type: %s",
2750 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002751 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 switch (layer->getCompositionType(hwcId)) {
2753 case HWC2::Composition::Cursor:
2754 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002755 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002756 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002757 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002758 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002759 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002760 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002761 // never clear the very first layer since we're
2762 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002763 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002764 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002765 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002766 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002768 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002769 break;
2770 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002772 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002773 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 } else {
2775 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002776 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002778 }
2779 } else {
2780 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002781 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002782 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002783 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002784 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002785 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002786 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002787 }
2788 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002789
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002790 if (applyColorMatrix) {
2791 getRenderEngine().setupColorTransform(oldColorMatrix);
2792 }
2793
Mathias Agopianf45c5102012-10-24 16:29:17 -07002794 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002795 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002796 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797}
2798
Fabien Sanglard830b8472016-11-30 16:35:58 -08002799void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2800 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002801 RenderEngine& engine(getRenderEngine());
2802 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803}
2804
Dan Stoza7d89d062015-04-30 13:29:25 -07002805status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002806 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002807 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 const sp<Layer>& lbc,
2809 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002810{
Dan Stoza7d89d062015-04-30 13:29:25 -07002811 // add this layer to the current state list
2812 {
2813 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002815 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2816 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002817 return NO_MEMORY;
2818 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 if (parent == nullptr) {
2820 mCurrentState.layersSortedByZ.add(lbc);
2821 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002822 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002823 ALOGE("addClientLayer called with a removed parent");
2824 return NAME_NOT_FOUND;
2825 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 parent->addChild(lbc);
2827 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002828
Dan Stoza7d89d062015-04-30 13:29:25 -07002829 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002830 mLayersAdded = true;
2831 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002832 }
2833
Mathias Agopian96f08192010-06-02 23:28:45 -07002834 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002835 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002836
Dan Stoza7d89d062015-04-30 13:29:25 -07002837 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002838}
2839
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002840status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002841 Mutex::Autolock _l(mStateLock);
2842
chaviw8b3871a2017-11-01 17:41:01 -07002843 if (layer->isPendingRemoval()) {
2844 return NO_ERROR;
2845 }
2846
Robert Carr1f0a16a2016-10-24 16:27:39 -07002847 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002848 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002849 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002850 if (topLevelOnly) {
2851 return NO_ERROR;
2852 }
2853
Chia-I Wu98f1c102017-05-30 14:54:08 -07002854 sp<Layer> ancestor = p;
2855 while (ancestor->getParent() != nullptr) {
2856 ancestor = ancestor->getParent();
2857 }
2858 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2859 ALOGE("removeLayer called with a layer whose parent has been removed");
2860 return NAME_NOT_FOUND;
2861 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002862
2863 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002864 } else {
2865 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002866 }
2867
Robert Carr136e2f62017-02-08 17:54:29 -08002868 // As a matter of normal operation, the LayerCleaner will produce a second
2869 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2870 // so we will succeed in promoting it, but it's already been removed
2871 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2872 // otherwise something has gone wrong and we are leaking the layer.
2873 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002874 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2875 layer->getName().string(),
2876 (p != nullptr) ? p->getName().string() : "no-parent");
2877 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002878 } else if (index < 0) {
2879 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002880 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881
Chia-I Wuc6657022017-08-15 11:18:17 -07002882 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 mLayersPendingRemoval.add(layer);
2884 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002885 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 setTransactionFlags(eTransactionNeeded);
2887 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888}
2889
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002890uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002891 return android_atomic_release_load(&mTransactionFlags);
2892}
2893
Mathias Agopian3f844832013-08-07 21:24:32 -07002894uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2896}
2897
Mathias Agopian3f844832013-08-07 21:24:32 -07002898uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2900 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002901 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902 }
2903 return old;
2904}
2905
Mathias Agopian8b33f032012-07-24 20:43:54 -07002906void SurfaceFlinger::setTransactionState(
2907 const Vector<ComposerState>& state,
2908 const Vector<DisplayState>& displays,
2909 uint32_t flags)
2910{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002911 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002912 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002913 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002914
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002915 if (flags & eAnimation) {
2916 // For window updates that are part of an animation we must wait for
2917 // previous animation "frames" to be handled.
2918 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002919 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002920 if (CC_UNLIKELY(err != NO_ERROR)) {
2921 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002922 // caller after a few seconds.
2923 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2924 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002925 mAnimTransactionPending = false;
2926 break;
2927 }
2928 }
2929 }
2930
Mathias Agopiane57f2922012-08-09 16:29:12 -07002931 size_t count = displays.size();
2932 for (size_t i=0 ; i<count ; i++) {
2933 const DisplayState& s(displays[i]);
2934 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002935 }
2936
Mathias Agopiane57f2922012-08-09 16:29:12 -07002937 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002938 for (size_t i=0 ; i<count ; i++) {
2939 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002940 // Here we need to check that the interface we're given is indeed
2941 // one of our own. A malicious client could give us a NULL
2942 // IInterface, or one of its own or even one of our own but a
2943 // different type. All these situations would cause us to crash.
2944 //
2945 // NOTE: it would be better to use RTTI as we could directly check
2946 // that we have a Client*. however, RTTI is disabled in Android.
2947 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002948 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002949 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002950 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002951 sp<Client> client( static_cast<Client *>(s.client.get()) );
2952 transactionFlags |= setClientStateLocked(client, s.state);
2953 }
2954 }
2955 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002956 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002957
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002958 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2959 // anyway. This can be used as a flush mechanism for previous async transactions.
2960 // Empty animation transaction can be used to simulate back-pressure, so also force a
2961 // transaction for empty animation transactions.
2962 if (transactionFlags == 0 &&
2963 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002964 transactionFlags = eTransactionNeeded;
2965 }
2966
Mathias Agopian386aa982011-11-07 21:58:03 -08002967 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002968 if (mInterceptor.isEnabled()) {
2969 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2970 }
Irvel468051e2016-06-13 16:44:44 -07002971
Mathias Agopian386aa982011-11-07 21:58:03 -08002972 // this triggers the transaction
2973 setTransactionFlags(transactionFlags);
2974
2975 // if this is a synchronous transaction, wait for it to take effect
2976 // before returning.
2977 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002978 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002979 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002980 if (flags & eAnimation) {
2981 mAnimTransactionPending = true;
2982 }
2983 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002984 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2985 if (CC_UNLIKELY(err != NO_ERROR)) {
2986 // just in case something goes wrong in SF, return to the
2987 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002988 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2989 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002990 break;
2991 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002992 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993 }
2994}
2995
Mathias Agopiane57f2922012-08-09 16:29:12 -07002996uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2997{
Jesse Hall9a143922012-10-04 16:29:19 -07002998 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2999 if (dpyIdx < 0)
3000 return 0;
3001
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003003 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003004 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003005 const uint32_t what = s.what;
3006 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003007 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 disp.surface = s.surface;
3009 flags |= eDisplayTransactionNeeded;
3010 }
3011 }
3012 if (what & DisplayState::eLayerStackChanged) {
3013 if (disp.layerStack != s.layerStack) {
3014 disp.layerStack = s.layerStack;
3015 flags |= eDisplayTransactionNeeded;
3016 }
3017 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003018 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003019 if (disp.orientation != s.orientation) {
3020 disp.orientation = s.orientation;
3021 flags |= eDisplayTransactionNeeded;
3022 }
3023 if (disp.frame != s.frame) {
3024 disp.frame = s.frame;
3025 flags |= eDisplayTransactionNeeded;
3026 }
3027 if (disp.viewport != s.viewport) {
3028 disp.viewport = s.viewport;
3029 flags |= eDisplayTransactionNeeded;
3030 }
3031 }
Michael Lentine47e45402014-07-18 15:34:25 -07003032 if (what & DisplayState::eDisplaySizeChanged) {
3033 if (disp.width != s.width) {
3034 disp.width = s.width;
3035 flags |= eDisplayTransactionNeeded;
3036 }
3037 if (disp.height != s.height) {
3038 disp.height = s.height;
3039 flags |= eDisplayTransactionNeeded;
3040 }
3041 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003042 }
3043 return flags;
3044}
3045
3046uint32_t SurfaceFlinger::setClientStateLocked(
3047 const sp<Client>& client,
3048 const layer_state_t& s)
3049{
Mathias Agopian13127d82013-03-05 17:47:11 -08003050 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003051 if (layer == nullptr) {
3052 return 0;
3053 }
3054
3055 if (layer->isPendingRemoval()) {
3056 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3057 return 0;
3058 }
3059
3060 uint32_t flags = 0;
3061
3062 const uint32_t what = s.what;
3063 bool geometryAppliesWithResize =
3064 what & layer_state_t::eGeometryAppliesWithResize;
3065 if (what & layer_state_t::ePositionChanged) {
3066 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3067 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003068 }
chaviw8b3871a2017-11-01 17:41:01 -07003069 }
3070 if (what & layer_state_t::eLayerChanged) {
3071 // NOTE: index needs to be calculated before we update the state
3072 const auto& p = layer->getParent();
3073 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003074 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003075 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003076 mCurrentState.layersSortedByZ.removeAt(idx);
3077 mCurrentState.layersSortedByZ.add(layer);
3078 // we need traversal (state changed)
3079 // AND transaction (list changed)
3080 flags |= eTransactionNeeded|eTraversalNeeded;
3081 }
chaviw8b3871a2017-11-01 17:41:01 -07003082 } else {
3083 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003084 flags |= eTransactionNeeded|eTraversalNeeded;
3085 }
3086 }
chaviw8b3871a2017-11-01 17:41:01 -07003087 }
3088 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003089 // NOTE: index needs to be calculated before we update the state
3090 const auto& p = layer->getParent();
3091 if (p == nullptr) {
3092 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3093 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3094 mCurrentState.layersSortedByZ.removeAt(idx);
3095 mCurrentState.layersSortedByZ.add(layer);
3096 // we need traversal (state changed)
3097 // AND transaction (list changed)
3098 flags |= eTransactionNeeded|eTraversalNeeded;
3099 }
3100 } else {
3101 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3102 flags |= eTransactionNeeded|eTraversalNeeded;
3103 }
chaviw8b3871a2017-11-01 17:41:01 -07003104 }
3105 }
3106 if (what & layer_state_t::eSizeChanged) {
3107 if (layer->setSize(s.w, s.h)) {
3108 flags |= eTraversalNeeded;
3109 }
3110 }
3111 if (what & layer_state_t::eAlphaChanged) {
3112 if (layer->setAlpha(s.alpha))
3113 flags |= eTraversalNeeded;
3114 }
3115 if (what & layer_state_t::eColorChanged) {
3116 if (layer->setColor(s.color))
3117 flags |= eTraversalNeeded;
3118 }
3119 if (what & layer_state_t::eMatrixChanged) {
3120 if (layer->setMatrix(s.matrix))
3121 flags |= eTraversalNeeded;
3122 }
3123 if (what & layer_state_t::eTransparentRegionChanged) {
3124 if (layer->setTransparentRegionHint(s.transparentRegion))
3125 flags |= eTraversalNeeded;
3126 }
3127 if (what & layer_state_t::eFlagsChanged) {
3128 if (layer->setFlags(s.flags, s.mask))
3129 flags |= eTraversalNeeded;
3130 }
3131 if (what & layer_state_t::eCropChanged) {
3132 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3133 flags |= eTraversalNeeded;
3134 }
3135 if (what & layer_state_t::eFinalCropChanged) {
3136 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3137 flags |= eTraversalNeeded;
3138 }
3139 if (what & layer_state_t::eLayerStackChanged) {
3140 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3141 // We only allow setting layer stacks for top level layers,
3142 // everything else inherits layer stack from its parent.
3143 if (layer->hasParent()) {
3144 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3145 layer->getName().string());
3146 } else if (idx < 0) {
3147 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3148 "that also does not appear in the top level layer list. Something"
3149 " has gone wrong.", layer->getName().string());
3150 } else if (layer->setLayerStack(s.layerStack)) {
3151 mCurrentState.layersSortedByZ.removeAt(idx);
3152 mCurrentState.layersSortedByZ.add(layer);
3153 // we need traversal (state changed)
3154 // AND transaction (list changed)
3155 flags |= eTransactionNeeded|eTraversalNeeded;
3156 }
3157 }
3158 if (what & layer_state_t::eDeferTransaction) {
3159 if (s.barrierHandle != nullptr) {
3160 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3161 } else if (s.barrierGbp != nullptr) {
3162 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3163 if (authenticateSurfaceTextureLocked(gbp)) {
3164 const auto& otherLayer =
3165 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3166 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3167 } else {
3168 ALOGE("Attempt to defer transaction to to an"
3169 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003170 }
3171 }
chaviw8b3871a2017-11-01 17:41:01 -07003172 // We don't trigger a traversal here because if no other state is
3173 // changed, we don't want this to cause any more work
3174 }
3175 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003176 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003177 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003178 if (!hadParent) {
3179 mCurrentState.layersSortedByZ.remove(layer);
3180 }
chaviw8b3871a2017-11-01 17:41:01 -07003181 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003182 }
chaviw8b3871a2017-11-01 17:41:01 -07003183 }
3184 if (what & layer_state_t::eReparentChildren) {
3185 if (layer->reparentChildren(s.reparentHandle)) {
3186 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003187 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003188 }
chaviw8b3871a2017-11-01 17:41:01 -07003189 if (what & layer_state_t::eDetachChildren) {
3190 layer->detachChildren();
3191 }
3192 if (what & layer_state_t::eOverrideScalingModeChanged) {
3193 layer->setOverrideScalingMode(s.overrideScalingMode);
3194 // We don't trigger a traversal here because if no other state is
3195 // changed, we don't want this to cause any more work
3196 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003197 return flags;
3198}
3199
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003200status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003201 const String8& name,
3202 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003203 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003204 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3205 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003207 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003208 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003209 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003210 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003211 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003212
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003213 status_t result = NO_ERROR;
3214
3215 sp<Layer> layer;
3216
Cody Northropbc755282017-03-31 12:00:08 -06003217 String8 uniqueName = getUniqueLayerName(name);
3218
Mathias Agopian3165cc22012-08-08 19:42:09 -07003219 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3220 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003221 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003222 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003223 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 break;
chaviw13fdc492017-06-27 12:40:18 -07003226 case ISurfaceComposerClient::eFXSurfaceColor:
3227 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003228 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003229 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003230 break;
3231 default:
3232 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 break;
3234 }
3235
Dan Stoza7d89d062015-04-30 13:29:25 -07003236 if (result != NO_ERROR) {
3237 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003239
Chia-I Wuab0c3192017-08-01 11:29:00 -07003240 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3241 // TODO b/64227542
3242 if (windowType == 441731) {
3243 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3244 layer->setPrimaryDisplayOnly();
3245 }
3246
Albert Chaulk479c60c2017-01-27 14:21:34 -05003247 layer->setInfo(windowType, ownerUid);
3248
Robert Carr1f0a16a2016-10-24 16:27:39 -07003249 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003250 if (result != NO_ERROR) {
3251 return result;
3252 }
Irvelffc9efc2016-07-27 15:16:37 -07003253 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003254
3255 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003256 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257}
3258
Cody Northropbc755282017-03-31 12:00:08 -06003259String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3260{
3261 bool matchFound = true;
3262 uint32_t dupeCounter = 0;
3263
3264 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3265 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3266
3267 // Loop over layers until we're sure there is no matching name
3268 while (matchFound) {
3269 matchFound = false;
3270 mDrawingState.traverseInZOrder([&](Layer* layer) {
3271 if (layer->getName() == uniqueName) {
3272 matchFound = true;
3273 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3274 }
3275 });
3276 }
3277
3278 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3279
3280 return uniqueName;
3281}
3282
David Sodman0c69cad2017-08-21 12:12:51 -07003283status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003284 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3285 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286{
3287 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003288 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 case PIXEL_FORMAT_TRANSPARENT:
3290 case PIXEL_FORMAT_TRANSLUCENT:
3291 format = PIXEL_FORMAT_RGBA_8888;
3292 break;
3293 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003294 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295 break;
3296 }
3297
David Sodman0c69cad2017-08-21 12:12:51 -07003298 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3299 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003300 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003301 *handle = layer->getHandle();
3302 *gbp = layer->getProducer();
3303 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003305
David Sodman0c69cad2017-08-21 12:12:51 -07003306 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003307 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003308}
3309
chaviw13fdc492017-06-27 12:40:18 -07003310status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003311 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003312 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313{
chaviw13fdc492017-06-27 12:40:18 -07003314 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003315 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003316 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003317}
3318
Mathias Agopianac9fa422013-02-11 16:40:36 -08003319status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003320{
Robert Carr9524cb32017-02-13 11:32:32 -08003321 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003322 status_t err = NO_ERROR;
3323 sp<Layer> l(client->getLayerUser(handle));
3324 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003325 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003326 err = removeLayer(l);
3327 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3328 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003329 }
3330 return err;
3331}
3332
Mathias Agopian13127d82013-03-05 17:47:11 -08003333status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003334{
Mathias Agopian67106042013-03-14 19:18:13 -07003335 // called by ~LayerCleaner() when all references to the IBinder (handle)
3336 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003337 sp<Layer> l = layer.promote();
3338 if (l == nullptr) {
3339 // The layer has already been removed, carry on
3340 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003341 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003342 // If we have a parent, then we can continue to live as long as it does.
3343 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344}
3345
Mathias Agopianb60314a2012-04-10 22:09:54 -07003346// ---------------------------------------------------------------------------
3347
Andy McFadden13a082e2012-08-24 10:16:42 -07003348void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003349 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003350 Vector<ComposerState> state;
3351 Vector<DisplayState> displays;
3352 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003353 d.what = DisplayState::eDisplayProjectionChanged |
3354 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003355 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003356 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003357 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003358 d.frame.makeInvalid();
3359 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003360 d.width = 0;
3361 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003362 displays.add(d);
3363 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003364 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3365 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003366
David Sodman105b7dc2017-11-04 20:28:14 -07003367 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003368 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003369 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003370
Brian Andersond0010582017-03-07 13:20:31 -08003371 // Use phase of 0 since phase is not known.
3372 // Use latency of 0, which will snap to the ideal latency.
3373 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003374}
3375
3376void SurfaceFlinger::initializeDisplays() {
3377 class MessageScreenInitialized : public MessageBase {
3378 SurfaceFlinger* flinger;
3379 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003380 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003381 virtual bool handler() {
3382 flinger->onInitializeDisplays();
3383 return true;
3384 }
3385 };
3386 sp<MessageBase> msg = new MessageScreenInitialized(this);
3387 postMessageAsync(msg); // we may be called from main thread, use async message
3388}
3389
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003390void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003391 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003392 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3393 this);
3394 int32_t type = hw->getDisplayType();
3395 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003396
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003397 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003398 return;
3399 }
3400
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003401 hw->setPowerMode(mode);
3402 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3403 ALOGW("Trying to set power mode for virtual display");
3404 return;
3405 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003406
Irvelffc9efc2016-07-27 15:16:37 -07003407 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003408 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003409 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3410 if (idx < 0) {
3411 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3412 return;
3413 }
3414 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3415 }
3416
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003417 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003418 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003419 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003420 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3421 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003422 // FIXME: eventthread only knows about the main display right now
3423 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003424 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003425 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003426
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003427 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003428 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003429 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003430
3431 struct sched_param param = {0};
3432 param.sched_priority = 1;
3433 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3434 ALOGW("Couldn't set SCHED_FIFO on display on");
3435 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003436 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003437 // Turn off the display
3438 struct sched_param param = {0};
3439 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3440 ALOGW("Couldn't set SCHED_OTHER on display off");
3441 }
3442
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003443 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3444 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003445 disableHardwareVsync(true); // also cancels any in-progress resync
3446
Mathias Agopiancde87a32012-09-13 14:09:01 -07003447 // FIXME: eventthread only knows about the main display right now
3448 mEventThread->onScreenReleased();
3449 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003450
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003451 getHwComposer().setPowerMode(type, mode);
3452 mVisibleRegionsDirty = true;
3453 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003454 } else if (mode == HWC_POWER_MODE_DOZE ||
3455 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003456 // Update display while dozing
3457 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003458 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3459 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003460 // FIXME: eventthread only knows about the main display right now
3461 mEventThread->onScreenAcquired();
3462 resyncToHardwareVsync(true);
3463 }
3464 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3465 // Leave display going to doze
3466 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3467 disableHardwareVsync(true); // also cancels any in-progress resync
3468 // FIXME: eventthread only knows about the main display right now
3469 mEventThread->onScreenReleased();
3470 }
3471 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003472 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003473 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003474 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003475 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003476}
3477
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003478void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3479 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003480 SurfaceFlinger& mFlinger;
3481 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003482 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003483 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003484 MessageSetPowerMode(SurfaceFlinger& flinger,
3485 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3486 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003487 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003488 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003489 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003490 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003491 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003492 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003493 ALOGW("Attempt to set power mode = %d for virtual display",
3494 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003495 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003496 mFlinger.setPowerModeInternal(
3497 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003498 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003499 return true;
3500 }
3501 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003502 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003503 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003504}
3505
3506// ---------------------------------------------------------------------------
3507
Vishnu Nair6a408532017-10-24 09:11:27 -07003508status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003510
Mathias Agopianbd115332013-04-18 16:41:04 -07003511 IPCThreadState* ipc = IPCThreadState::self();
3512 const int pid = ipc->getCallingPid();
3513 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003514
Mathias Agopianbd115332013-04-18 16:41:04 -07003515 if ((uid != AID_SHELL) &&
3516 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003517 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003518 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003520 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003521 // (this would indicate SF is stuck, but we want to be able to
3522 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003523 status_t err = mStateLock.timedLock(s2ns(1));
3524 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003525 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003526 result.appendFormat(
3527 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3528 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003529 }
3530
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003531 bool dumpAll = true;
3532 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003533 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003534
3535 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003536 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003537 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3538 dumpAll = false;
3539 }
3540
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003541 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003542 if ((index < numArgs) &&
3543 (args[index] == String16("--list"))) {
3544 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003545 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003546 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003547 }
3548
3549 if ((index < numArgs) &&
3550 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003551 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003552 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003553 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003554 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003555
3556 if ((index < numArgs) &&
3557 (args[index] == String16("--latency-clear"))) {
3558 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003559 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003560 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003561 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003562
3563 if ((index < numArgs) &&
3564 (args[index] == String16("--dispsync"))) {
3565 index++;
3566 mPrimaryDispSync.dump(result);
3567 dumpAll = false;
3568 }
Dan Stozab90cf072015-03-05 11:05:59 -08003569
3570 if ((index < numArgs) &&
3571 (args[index] == String16("--static-screen"))) {
3572 index++;
3573 dumpStaticScreenStats(result);
3574 dumpAll = false;
3575 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003576
3577 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003578 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003579 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003580 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003581 dumpAll = false;
3582 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003583
3584 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3585 index++;
3586 dumpWideColorInfo(result);
3587 dumpAll = false;
3588 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003590
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003591 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003592 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003593 }
3594
Mathias Agopian9795c422009-08-26 16:36:26 -07003595 if (locked) {
3596 mStateLock.unlock();
3597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 }
3599 write(fd, result.string(), result.size());
3600 return NO_ERROR;
3601}
3602
Dan Stozac7014012014-02-14 15:03:43 -08003603void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3604 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003605{
Robert Carr2047fae2016-11-28 14:09:09 -08003606 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003607 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003608 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003609}
3610
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003612 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003613{
3614 String8 name;
3615 if (index < args.size()) {
3616 name = String8(args[index]);
3617 index++;
3618 }
3619
David Sodman105b7dc2017-11-04 20:28:14 -07003620 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003621 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003622 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003623
3624 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003625 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003626 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003627 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003628 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003629 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003630 }
Robert Carr2047fae2016-11-28 14:09:09 -08003631 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003632 }
3633}
3634
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003635void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003636 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003637{
3638 String8 name;
3639 if (index < args.size()) {
3640 name = String8(args[index]);
3641 index++;
3642 }
3643
Robert Carr2047fae2016-11-28 14:09:09 -08003644 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003645 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003646 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003647 }
Robert Carr2047fae2016-11-28 14:09:09 -08003648 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003649
Svetoslavd85084b2014-03-20 10:28:31 -07003650 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003651}
3652
Jamie Gennis6547ff42013-07-16 20:12:42 -07003653// This should only be called from the main thread. Otherwise it would need
3654// the lock and should use mCurrentState rather than mDrawingState.
3655void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003656 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003657 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003658 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003659
3660 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3661}
3662
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003663void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003664{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003665 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003666 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3667
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003668 if (isLayerTripleBufferingDisabled())
3669 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003670
3671 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003672 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003673 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003674 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003675 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3676 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003677 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003678}
3679
Dan Stozab90cf072015-03-05 11:05:59 -08003680void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3681{
3682 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003683 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3684 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003685 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003686 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003687 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3688 b + 1, bucketTimeSec, percent);
3689 }
David Sodman4a36e932017-11-07 14:29:47 -08003690 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003691 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003692 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003693 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003694 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003695}
3696
Dan Stozae77c7662016-05-13 11:37:28 -07003697void SurfaceFlinger::recordBufferingStats(const char* layerName,
3698 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003699 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3700 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003701 for (const auto& segment : history) {
3702 if (!segment.usedThirdBuffer) {
3703 stats.twoBufferTime += segment.totalTime;
3704 }
3705 if (segment.occupancyAverage < 1.0f) {
3706 stats.doubleBufferedTime += segment.totalTime;
3707 } else if (segment.occupancyAverage < 2.0f) {
3708 stats.tripleBufferedTime += segment.totalTime;
3709 }
3710 ++stats.numSegments;
3711 stats.totalTime += segment.totalTime;
3712 }
3713}
3714
Brian Andersond6927fb2016-07-23 23:37:30 -07003715void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3716 result.appendFormat("Layer frame timestamps:\n");
3717
3718 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3719 const size_t count = currentLayers.size();
3720 for (size_t i=0 ; i<count ; i++) {
3721 currentLayers[i]->dumpFrameEvents(result);
3722 }
3723}
3724
Dan Stozae77c7662016-05-13 11:37:28 -07003725void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3726 result.append("Buffering stats:\n");
3727 result.append(" [Layer name] <Active time> <Two buffer> "
3728 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003729 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003730 typedef std::tuple<std::string, float, float, float> BufferTuple;
3731 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003732 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003733 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003734 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003735 if (stats.numSegments == 0) {
3736 continue;
3737 }
3738 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3739 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3740 stats.totalTime;
3741 float doubleBufferRatio = static_cast<float>(
3742 stats.doubleBufferedTime) / stats.totalTime;
3743 float tripleBufferRatio = static_cast<float>(
3744 stats.tripleBufferedTime) / stats.totalTime;
3745 sorted.insert({activeTime, {name, twoBufferRatio,
3746 doubleBufferRatio, tripleBufferRatio}});
3747 }
3748 for (const auto& sortedPair : sorted) {
3749 float activeTime = sortedPair.first;
3750 const BufferTuple& values = sortedPair.second;
3751 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3752 std::get<0>(values).c_str(), activeTime,
3753 std::get<1>(values), std::get<2>(values),
3754 std::get<3>(values));
3755 }
3756 result.append("\n");
3757}
3758
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003759void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3760 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003761 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003762
3763 // TODO: print out if wide-color mode is active or not
3764
3765 for (size_t d = 0; d < mDisplays.size(); d++) {
3766 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3767 int32_t hwcId = displayDevice->getHwcDisplayId();
3768 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3769 continue;
3770 }
3771
3772 result.appendFormat("Display %d color modes:\n", hwcId);
3773 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3774 for (auto&& mode : modes) {
3775 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3776 }
3777
3778 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3779 result.appendFormat(" Current color mode: %s (%d)\n",
3780 decodeColorMode(currentMode).c_str(), currentMode);
3781 }
3782 result.append("\n");
3783}
3784
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003785LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003786 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003787 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3788 const State& state = useDrawing ? mDrawingState : mCurrentState;
3789 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003790 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003791 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003792 });
3793
3794 return layersProto;
3795}
3796
Mathias Agopian74d211a2013-04-22 16:55:35 +02003797void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3798 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003799{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003800 bool colorize = false;
3801 if (index < args.size()
3802 && (args[index] == String16("--color"))) {
3803 colorize = true;
3804 index++;
3805 }
3806
3807 Colorizer colorizer(colorize);
3808
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003809 // figure out if we're stuck somewhere
3810 const nsecs_t now = systemTime();
3811 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3812 const nsecs_t inTransaction(mDebugInTransaction);
3813 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3814 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3815
3816 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003817 * Dump library configuration.
3818 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003819
3820 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003821 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003822 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003823 appendSfConfigString(result);
3824 appendUiConfigString(result);
3825 appendGuiConfigString(result);
3826 result.append("\n");
3827
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003828 result.append("\nWide-Color information:\n");
3829 dumpWideColorInfo(result);
3830
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003831 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003832 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003833 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003834 result.append(SyncFeatures::getInstance().toString());
3835 result.append("\n");
3836
David Sodman105b7dc2017-11-04 20:28:14 -07003837 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003838
Andy McFadden41d67d72014-04-25 16:58:34 -07003839 colorizer.bold(result);
3840 result.append("DispSync configuration: ");
3841 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003842 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003843 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003844 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003845 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003846 result.append("\n");
3847
Dan Stozab90cf072015-03-05 11:05:59 -08003848 // Dump static screen stats
3849 result.append("\n");
3850 dumpStaticScreenStats(result);
3851 result.append("\n");
3852
Dan Stozae77c7662016-05-13 11:37:28 -07003853 dumpBufferingStats(result);
3854
Andy McFadden4803b742012-09-24 19:07:20 -07003855 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856 * Dump the visible layer list
3857 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003858 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003859 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003861
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003862 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003863 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3864 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865
3866 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003867 * Dump Display state
3868 */
3869
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003870 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003871 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003872 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003873 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3874 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003875 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003876 }
3877
3878 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003879 * Dump SurfaceFlinger global state
3880 */
3881
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003882 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003883 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003884 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003885
Mathias Agopian888c8222012-08-04 21:10:38 -07003886 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003887 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003888
David Sodmanbc815282017-11-05 18:57:52 -08003889 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003890
Mathias Agopian42977342012-08-05 00:40:46 -07003891 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003892 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3893 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003894 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003895 " last eglSwapBuffers() time: %f us\n"
3896 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003897 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003898 " refresh-rate : %f fps\n"
3899 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003900 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003901 " gpu_to_cpu_unsupported : %d\n"
3902 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003903 mLastSwapBufferTime/1000.0,
3904 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003905 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003906 1e9 / activeConfig->getVsyncPeriod(),
3907 activeConfig->getDpiX(),
3908 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003909 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910
Mathias Agopian74d211a2013-04-22 16:55:35 +02003911 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003913
Mathias Agopian74d211a2013-04-22 16:55:35 +02003914 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003915 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003916
3917 /*
3918 * VSYNC state
3919 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003921 result.append("\n");
3922
3923 /*
3924 * HWC layer minidump
3925 */
3926 for (size_t d = 0; d < mDisplays.size(); d++) {
3927 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3928 int32_t hwcId = displayDevice->getHwcDisplayId();
3929 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3930 continue;
3931 }
3932
3933 result.appendFormat("Display %d HWC layers:\n", hwcId);
3934 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003935 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003936 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003937 });
Dan Stozae22aec72016-08-01 13:20:59 -07003938 result.append("\n");
3939 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940
3941 /*
3942 * Dump HWComposer state
3943 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003944 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003945 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003946 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003947 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003948 result.appendFormat(" h/w composer %s\n",
3949 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003950 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003951
3952 /*
3953 * Dump gralloc state
3954 */
3955 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3956 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003957
3958 /*
3959 * Dump VrFlinger state if in use.
3960 */
3961 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3962 result.append("VrFlinger state:\n");
3963 result.append(mVrFlinger->Dump().c_str());
3964 result.append("\n");
3965 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966}
3967
Mathias Agopian13127d82013-03-05 17:47:11 -08003968const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003969SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003970 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003971 wp<IBinder> dpy;
3972 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3973 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3974 dpy = mDisplays.keyAt(i);
3975 break;
3976 }
3977 }
3978 if (dpy == NULL) {
3979 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3980 // Just use the primary display so we have something to return
3981 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3982 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003983 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003984}
3985
Keun young Park63f165f2012-08-31 10:53:36 -07003986bool SurfaceFlinger::startDdmConnection()
3987{
3988 void* libddmconnection_dso =
3989 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3990 if (!libddmconnection_dso) {
3991 return false;
3992 }
3993 void (*DdmConnection_start)(const char* name);
3994 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003995 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003996 if (!DdmConnection_start) {
3997 dlclose(libddmconnection_dso);
3998 return false;
3999 }
4000 (*DdmConnection_start)(getServiceName());
4001 return true;
4002}
4003
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004004status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005 switch (code) {
4006 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004007 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004009 case CLEAR_ANIMATION_FRAME_STATS:
4010 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004011 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004012 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004013 case ENABLE_VSYNC_INJECTIONS:
4014 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 {
4016 // codes that require permission check
4017 IPCThreadState* ipc = IPCThreadState::self();
4018 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004019 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004020 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004021 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004022 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004023 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004024 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004025 break;
4026 }
Robert Carr1db73f62016-12-21 12:58:51 -08004027 /*
4028 * Calling setTransactionState is safe, because you need to have been
4029 * granted a reference to Client* and Handle* to do anything with it.
4030 *
4031 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4032 */
4033 case SET_TRANSACTION_STATE:
4034 case CREATE_SCOPED_CONNECTION:
4035 {
4036 return OK;
4037 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004038 case CAPTURE_SCREEN:
4039 {
4040 // codes that require permission check
4041 IPCThreadState* ipc = IPCThreadState::self();
4042 const int pid = ipc->getCallingPid();
4043 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004044 if ((uid != AID_GRAPHICS) &&
4045 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004046 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004047 return PERMISSION_DENIED;
4048 }
4049 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004050 }
chaviwa76b2712017-09-20 12:02:26 -07004051 case CAPTURE_LAYERS: {
4052 IPCThreadState* ipc = IPCThreadState::self();
4053 const int pid = ipc->getCallingPid();
4054 const int uid = ipc->getCallingUid();
4055 if ((uid != AID_GRAPHICS) &&
4056 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4057 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4058 return PERMISSION_DENIED;
4059 }
4060 break;
4061 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004063 return OK;
4064}
4065
4066status_t SurfaceFlinger::onTransact(
4067 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4068{
4069 status_t credentialCheck = CheckTransactCodeCredentials(code);
4070 if (credentialCheck != OK) {
4071 return credentialCheck;
4072 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4075 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004076 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004077 IPCThreadState* ipc = IPCThreadState::self();
4078 const int uid = ipc->getCallingUid();
4079 if (CC_UNLIKELY(uid != AID_SYSTEM
4080 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004081 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004082 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004083 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004084 return PERMISSION_DENIED;
4085 }
4086 int n;
4087 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004088 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004089 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 return NO_ERROR;
4091 case 1002: // SHOW_UPDATES
4092 n = data.readInt32();
4093 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004094 invalidateHwcGeometry();
4095 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004097 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004098 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004099 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004100 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004101 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004102 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004103 setTransactionFlags(
4104 eTransactionNeeded|
4105 eDisplayTransactionNeeded|
4106 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004107 return NO_ERROR;
4108 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004109 case 1006:{ // send empty update
4110 signalRefresh();
4111 return NO_ERROR;
4112 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004113 case 1008: // toggle use of hw composer
4114 n = data.readInt32();
4115 mDebugDisableHWC = n ? 1 : 0;
4116 invalidateHwcGeometry();
4117 repaintEverything();
4118 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004119 case 1009: // toggle use of transform hint
4120 n = data.readInt32();
4121 mDebugDisableTransformHint = n ? 1 : 0;
4122 invalidateHwcGeometry();
4123 repaintEverything();
4124 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004126 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 reply->writeInt32(0);
4128 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004129 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004130 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004131 return NO_ERROR;
4132 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004133 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004134 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004135 return NO_ERROR;
4136 }
4137 case 1014: {
4138 // daltonize
4139 n = data.readInt32();
4140 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004141 case 1:
4142 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4143 break;
4144 case 2:
4145 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4146 break;
4147 case 3:
4148 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4149 break;
4150 default:
4151 mDaltonizer.setType(ColorBlindnessType::None);
4152 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004153 }
4154 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004155 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004156 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004157 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004158 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004159 invalidateHwcGeometry();
4160 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004161 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004162 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004163 case 1015: {
4164 // apply a color matrix
4165 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004166 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004167 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004168 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004169 for (size_t j = 0; j < 4; j++) {
4170 mColorMatrix[i][j] = data.readFloat();
4171 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004172 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004173 } else {
4174 mColorMatrix = mat4();
4175 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004176
4177 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4178 // the division by w in the fragment shader
4179 float4 lastRow(transpose(mColorMatrix)[3]);
4180 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4181 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4182 }
4183
Alan Viverette9c5a3332013-09-12 20:04:35 -07004184 invalidateHwcGeometry();
4185 repaintEverything();
4186 return NO_ERROR;
4187 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004188 // This is an experimental interface
4189 // Needs to be shifted to proper binder interface when we productize
4190 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004191 n = data.readInt32();
4192 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004193 return NO_ERROR;
4194 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004195 case 1017: {
4196 n = data.readInt32();
4197 mForceFullDamage = static_cast<bool>(n);
4198 return NO_ERROR;
4199 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004200 case 1018: { // Modify Choreographer's phase offset
4201 n = data.readInt32();
4202 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4203 return NO_ERROR;
4204 }
4205 case 1019: { // Modify SurfaceFlinger's phase offset
4206 n = data.readInt32();
4207 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4208 return NO_ERROR;
4209 }
Irvel468051e2016-06-13 16:44:44 -07004210 case 1020: { // Layer updates interceptor
4211 n = data.readInt32();
4212 if (n) {
4213 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004214 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004215 }
4216 else{
4217 ALOGV("Interceptor disabled");
4218 mInterceptor.disable();
4219 }
4220 return NO_ERROR;
4221 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004222 case 1021: { // Disable HWC virtual displays
4223 n = data.readInt32();
4224 mUseHwcVirtualDisplays = !n;
4225 return NO_ERROR;
4226 }
Romain Guy0147a172017-06-01 13:53:56 -07004227 case 1022: { // Set saturation boost
4228 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4229
4230 invalidateHwcGeometry();
4231 repaintEverything();
4232 return NO_ERROR;
4233 }
Romain Guy54f154a2017-10-24 21:40:32 +01004234 case 1023: { // Set native mode
4235 mForceNativeColorMode = data.readInt32() == 1;
4236
4237 invalidateHwcGeometry();
4238 repaintEverything();
4239 return NO_ERROR;
4240 }
4241 case 1024: { // Is wide color gamut rendering/color management supported?
4242 reply->writeBool(hasWideColorDisplay);
4243 return NO_ERROR;
4244 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004245 case 1025: { // tracing
4246 n = data.readInt32();
4247 if (n) {
4248 ALOGV("LayerTracing enabled");
4249 mTracing.enable();
4250 doTracing("tracing.enable");
4251 reply->writeInt32(NO_ERROR);
4252 } else {
4253 ALOGV("LayerTracing disabled");
4254 status_t err = mTracing.disable();
4255 reply->writeInt32(err);
4256 }
4257 return NO_ERROR;
4258 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004259 }
4260 }
4261 return err;
4262}
4263
Steven Thomas6d8110b2017-08-31 18:24:21 -07004264void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004265 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004266 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004267}
4268
Steven Thomas6d8110b2017-08-31 18:24:21 -07004269void SurfaceFlinger::repaintEverything() {
4270 ConditionalLock _l(mStateLock,
4271 std::this_thread::get_id() != mMainThreadId);
4272 repaintEverythingLocked();
4273}
4274
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004275// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4276class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004277public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004278 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4279 ~WindowDisconnector() {
4280 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004281 }
4282
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004283private:
4284 ANativeWindow* mWindow;
4285 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004286};
4287
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004288status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4289 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4290 int32_t minLayerZ, int32_t maxLayerZ,
4291 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004292 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004293 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004294
chaviwa76b2712017-09-20 12:02:26 -07004295 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4296
4297 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4298 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4299
4300 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4301 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004302 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004303}
4304
4305status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004306 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
4307 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004308 ATRACE_CALL();
4309
4310 class LayerRenderArea : public RenderArea {
4311 public:
chaviw7206d492017-11-10 16:16:12 -08004312 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004313 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004314 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004315 const Transform& getTransform() const override {
4316 // Make the top level transform the inverse the transform and it's parent so it sets
4317 // the whole capture back to 0,0
4318 return *new Transform(mLayer->getTransform().inverse());
4319 }
4320 Rect getBounds() const override {
4321 const Layer::State& layerState(mLayer->getDrawingState());
4322 return Rect(layerState.active.w, layerState.active.h);
4323 }
4324 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4325 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4326 bool isSecure() const override { return false; }
4327 bool needsFiltering() const override { return false; }
4328
chaviw7206d492017-11-10 16:16:12 -08004329 Rect getSourceCrop() const override {
4330 if (mCrop.isEmpty()) {
4331 return getBounds();
4332 } else {
4333 return mCrop;
4334 }
4335 }
chaviwa76b2712017-09-20 12:02:26 -07004336 bool getWideColorSupport() const override { return false; }
4337 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4338
4339 private:
chaviw7206d492017-11-10 16:16:12 -08004340 const sp<Layer> mLayer;
4341 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004342 };
4343
4344 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4345 auto parent = layerHandle->owner.promote();
4346
chaviw7206d492017-11-10 16:16:12 -08004347 if (parent == nullptr || parent->isPendingRemoval()) {
4348 ALOGE("captureLayers called with a removed parent");
4349 return NAME_NOT_FOUND;
4350 }
4351
4352 Rect crop(sourceCrop);
4353 if (sourceCrop.width() <= 0) {
4354 crop.left = 0;
4355 crop.right = parent->getCurrentState().active.w;
4356 }
4357
4358 if (sourceCrop.height() <= 0) {
4359 crop.top = 0;
4360 crop.bottom = parent->getCurrentState().active.h;
4361 }
4362
4363 int32_t reqWidth = crop.width() * frameScale;
4364 int32_t reqHeight = crop.height() * frameScale;
4365
4366 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4367
chaviwa76b2712017-09-20 12:02:26 -07004368 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4369 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4370 if (!layer->isVisible()) {
4371 return;
4372 }
4373 visitor(layer);
4374 });
4375 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004376 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004377}
4378
4379status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4380 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004381 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004382 bool useIdentityTransform) {
4383 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004384
chaviwa76b2712017-09-20 12:02:26 -07004385 renderArea.updateDimensions();
4386
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004387 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4388 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4389 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4390 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004391
4392 // This mutex protects syncFd and captureResult for communication of the return values from the
4393 // main thread back to this Binder thread
4394 std::mutex captureMutex;
4395 std::condition_variable captureCondition;
4396 std::unique_lock<std::mutex> captureLock(captureMutex);
4397 int syncFd = -1;
4398 std::optional<status_t> captureResult;
4399
4400 sp<LambdaMessage> message = new LambdaMessage([&]() {
4401 // If there is a refresh pending, bug out early and tell the binder thread to try again
4402 // after the refresh.
4403 if (mRefreshPending) {
4404 ATRACE_NAME("Skipping screenshot for now");
4405 std::unique_lock<std::mutex> captureLock(captureMutex);
4406 captureResult = std::make_optional<status_t>(EAGAIN);
4407 captureCondition.notify_one();
4408 return;
4409 }
4410
4411 status_t result = NO_ERROR;
4412 int fd = -1;
4413 {
4414 Mutex::Autolock _l(mStateLock);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004415 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4416 useIdentityTransform, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004417 }
4418
4419 {
4420 std::unique_lock<std::mutex> captureLock(captureMutex);
4421 syncFd = fd;
4422 captureResult = std::make_optional<status_t>(result);
4423 captureCondition.notify_one();
4424 }
4425 });
4426
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004427 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004428 if (result == NO_ERROR) {
4429 captureCondition.wait(captureLock, [&]() { return captureResult; });
4430 while (*captureResult == EAGAIN) {
4431 captureResult.reset();
4432 result = postMessageAsync(message);
4433 if (result != NO_ERROR) {
4434 return result;
4435 }
4436 captureCondition.wait(captureLock, [&]() { return captureResult; });
4437 }
4438 result = *captureResult;
4439 }
4440
4441 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004442 sync_wait(syncFd, -1);
4443 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004444 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004445
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004446 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004447}
4448
chaviwa76b2712017-09-20 12:02:26 -07004449void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4450 TraverseLayersFunction traverseLayers, bool yswap,
4451 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004452 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004453
Mathias Agopian3f844832013-08-07 21:24:32 -07004454 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004455
4456 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004457 const auto raWidth = renderArea.getWidth();
4458 const auto raHeight = renderArea.getHeight();
4459
4460 const auto reqWidth = renderArea.getReqWidth();
4461 const auto reqHeight = renderArea.getReqHeight();
4462 Rect sourceCrop = renderArea.getSourceCrop();
4463
4464 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4465 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004466
Dan Stozac1879002014-05-22 15:59:05 -07004467 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004468 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004469 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004470 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004471 }
4472
4473 // ensure that sourceCrop is inside screen
4474 if (sourceCrop.left < 0) {
4475 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4476 }
chaviwa76b2712017-09-20 12:02:26 -07004477 if (sourceCrop.right > raWidth) {
4478 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004479 }
4480 if (sourceCrop.top < 0) {
4481 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4482 }
chaviwa76b2712017-09-20 12:02:26 -07004483 if (sourceCrop.bottom > raHeight) {
4484 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004485 }
4486
chaviwa76b2712017-09-20 12:02:26 -07004487 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004488 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4489 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004490
Mathias Agopian180f10d2013-04-10 22:55:41 -07004491 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004492 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004493
4494 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004495 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4496 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004497 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004498
4499 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004500 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004501
chaviwa76b2712017-09-20 12:02:26 -07004502 traverseLayers([&](Layer* layer) {
4503 if (filtering) layer->setFiltering(true);
4504 layer->draw(renderArea, useIdentityTransform);
4505 if (filtering) layer->setFiltering(false);
4506 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004507}
4508
chaviwa76b2712017-09-20 12:02:26 -07004509status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4510 TraverseLayersFunction traverseLayers,
4511 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004512 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004513 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004514 ATRACE_CALL();
4515
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004516 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004517
4518 traverseLayers([&](Layer* layer) {
4519 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4520 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004521
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004522 if (secureLayerIsVisible) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004523 ALOGW("FB is protected: PERMISSION_DENIED");
4524 return PERMISSION_DENIED;
4525 }
4526
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004527 // this binds the given EGLImage as a framebuffer for the
4528 // duration of this scope.
Chia-I Wueadbaa62017-11-09 11:26:15 -08004529 RenderEngine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
4530 if (bufferBond.getStatus() != NO_ERROR) {
4531 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004532 return INVALID_OPERATION;
4533 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004534
Dan Stozaabcda352017-06-01 14:37:39 -07004535 // this will in fact render into our dequeued buffer
4536 // via an FBO, which means we didn't have to create
4537 // an EGLSurface and therefore we're not
4538 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004539 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004540
Dan Stozaabcda352017-06-01 14:37:39 -07004541 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004542 getRenderEngine().finish();
4543 *outSyncFd = -1;
4544
chaviwa76b2712017-09-20 12:02:26 -07004545 const auto reqWidth = renderArea.getReqWidth();
4546 const auto reqHeight = renderArea.getReqHeight();
4547
Dan Stozaabcda352017-06-01 14:37:39 -07004548 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4549 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004550 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004551 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004552 } else {
4553 base::unique_fd syncFd = getRenderEngine().flush();
4554 if (syncFd < 0) {
4555 getRenderEngine().finish();
4556 }
4557 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004558 }
4559
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004560 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004561}
4562
Mathias Agopiand5556842013-09-19 17:08:37 -07004563void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004564 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004565 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004566 for (size_t y = 0; y < h; y++) {
4567 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4568 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004569 if (p[x] != 0xFF000000) return;
4570 }
4571 }
chaviwa76b2712017-09-20 12:02:26 -07004572 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004573
Robert Carr2047fae2016-11-28 14:09:09 -08004574 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004575 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004576 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004577 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4578 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4579 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4580 static_cast<float>(state.color.a));
4581 i++;
4582 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004583 }
4584}
4585
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004586// ---------------------------------------------------------------------------
4587
Dan Stoza412903f2017-04-27 13:42:17 -07004588void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4589 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004590}
4591
Dan Stoza412903f2017-04-27 13:42:17 -07004592void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4593 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004594}
4595
chaviwa76b2712017-09-20 12:02:26 -07004596void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4597 int32_t maxLayerZ,
4598 const LayerVector::Visitor& visitor) {
4599 // We loop through the first level of layers without traversing,
4600 // as we need to interpret min/max layer Z in the top level Z space.
4601 for (const auto& layer : mDrawingState.layersSortedByZ) {
4602 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4603 continue;
4604 }
4605 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004606 // relative layers are traversed in Layer::traverseInZOrder
4607 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004608 continue;
4609 }
4610 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4611 if (!layer->isVisible()) {
4612 return;
4613 }
4614 visitor(layer);
4615 });
4616 }
4617}
4618
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004619}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004620
4621
4622#if defined(__gl_h_)
4623#error "don't include gl/gl.h in this file"
4624#endif
4625
4626#if defined(__gl2_h_)
4627#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004628#endif